context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.DataMappers;
using Glass.Mapper.Sc.Fields;
using NUnit.Framework;
using Sitecore.Data;
namespace Glass.Mapper.Sc.Integration.DataMappers
{
[TestFixture]
public class SitecoreFieldLinkMapperFixture: AbstractMapperFixture
{
#region Method - GetField
[Test]
public void GetField_FieldContainsAnchor_ReturnsAnchorLink()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"anchor\" url=\"testAnchor\" anchor=\"testAnchor\" title=\"test alternate\" class=\"testClass\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/GetField");
var field = item.Fields[FieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as Link;
//Assert
Assert.AreEqual("testAnchor", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("", result.Query);
Assert.AreEqual("", result.Target);
Assert.AreEqual(Guid.Empty, result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternate", result.Title);
Assert.AreEqual(LinkType.Anchor, result.Type);
Assert.AreEqual("testAnchor", result.Url);
}
[Test]
public void GetField_FieldContainsExternal_ReturnsExternalLink()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"external\" url=\"http://www.google.com\" anchor=\"\" title=\"test alternative\" class=\"testClass\" target=\"_blank\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/GetField");
var field = item.Fields[FieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as Link;
//Assert
Assert.AreEqual("", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("", result.Query);
Assert.AreEqual("_blank", result.Target);
Assert.AreEqual(Guid.Empty, result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.External, result.Type);
Assert.AreEqual("http://www.google.com", result.Url);
}
[Test]
public void GetField_FieldContainsJavaScript_ReturnsJavascriptLink()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"javascript\" url=\"javascript:alert('hello world');\" anchor=\"\" title=\"test alternate\" class=\"testClass\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/GetField");
var field = item.Fields[FieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as Link;
//Assert
Assert.AreEqual("", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("", result.Query);
Assert.AreEqual("", result.Target);
Assert.AreEqual(Guid.Empty, result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternate", result.Title);
Assert.AreEqual(LinkType.JavaScript, result.Type);
Assert.AreEqual("javascript:alert('hello world');", result.Url);
}
[Test]
public void GetField_FieldContainsMailto_ReturnsMailtoLink()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"mailto\" url=\"mailto:test@test.com\" anchor=\"\" title=\"test alternate\" class=\"testClass\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/GetField");
var field = item.Fields[FieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, new SitecoreFieldConfiguration(), null) as Link;
//Assert
Assert.AreEqual("", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("", result.Query);
Assert.AreEqual("", result.Target);
Assert.AreEqual(Guid.Empty, result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternate", result.Title);
Assert.AreEqual(LinkType.MailTo, result.Type);
Assert.AreEqual("mailto:test@test.com", result.Url);
}
[Test]
public void GetField_FieldContainsInternal_ReturnsInternalLink()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"internal\" url=\"/Tests/DataMappers/SitecoreFieldLinkMapper/Target.aspx\" anchor=\"testAnchor\" querystring=\"q=s\" title=\"test alternative\" class=\"testClass\" target=\"testTarget\" id=\"{1AE37F34-3B6F-4F5F-A5C2-FD2B9D5A47A0}\" />";
Sitecore.Context.Site = null;
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/GetField");
var field = item.Fields[FieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, new SitecoreFieldConfiguration(), null) as Link;
//Assert
Assert.AreEqual("testAnchor", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("q=s", result.Query);
Assert.AreEqual("testTarget", result.Target);
Assert.AreEqual(new Guid("{1AE37F34-3B6F-4F5F-A5C2-FD2B9D5A47A0}"), result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.Internal, result.Type);
Assert.AreEqual("/en/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/Target.aspx", result.Url);
}
[Test]
public void GetField_FieldContainsInternalButItemMissing_ReturnsEmptyUrl()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"internal\" url=\"/Tests/DataMappers/SitecoreFieldLinkMapper/Target.aspx\" anchor=\"testAnchor\" querystring=\"q=s\" title=\"test alternative\" class=\"testClass\" target=\"testTarget\" id=\"{AAAAAAAA-3B6F-4F5F-A5C2-FD2B9D5A47A0}\" />";
Sitecore.Context.Site = null;
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/GetField");
var field = item.Fields[FieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, new SitecoreFieldConfiguration(), null) as Link;
//Assert
Assert.AreEqual("testAnchor", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("q=s", result.Query);
Assert.AreEqual("testTarget", result.Target);
Assert.AreEqual(new Guid("{AAAAAAAA-3B6F-4F5F-A5C2-FD2B9D5A47A0}"), result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.Internal, result.Type);
Assert.AreEqual(string.Empty, result.Url);
}
[Test]
public void GetField_FieldContainsInternalAbsoluteUrl_ReturnsInternalLink()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"internal\" url=\"/Tests/DataMappers/SitecoreFieldLinkMapper/Target.aspx\" anchor=\"testAnchor\" querystring=\"q=s\" title=\"test alternative\" class=\"testClass\" target=\"testTarget\" id=\"{1AE37F34-3B6F-4F5F-A5C2-FD2B9D5A47A0}\" />";
Sitecore.Context.Site = null;
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/GetField");
var field = item.Fields[FieldName];
var config = new SitecoreFieldConfiguration();
config.UrlOptions = SitecoreInfoUrlOptions.LanguageEmbeddingNever;
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, config, null) as Link;
//Assert
Assert.AreEqual("testAnchor", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("q=s", result.Query);
Assert.AreEqual("testTarget", result.Target);
Assert.AreEqual(new Guid("{1AE37F34-3B6F-4F5F-A5C2-FD2B9D5A47A0}"), result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.Internal, result.Type);
Assert.AreEqual("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/Target.aspx", result.Url);
}
[Test]
public void GetField_FieldContainsInternalMissingItem_ReturnsNotSetLink()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"internal\" url=\"/Tests/DataMappers/SitecoreFieldLinkMapper/Target.aspx\" anchor=\"testAnchor\" querystring=\"q=s\" title=\"test alternative\" class=\"testClass\" target=\"testTarget\" id=\"{11111111-3B6F-4F5F-A5C2-FD2B9D5A47A0}\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/GetField");
var field = item.Fields[FieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, new SitecoreFieldConfiguration(), null) as Link;
//Assert
Assert.AreEqual("testAnchor", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("q=s", result.Query);
Assert.AreEqual("testTarget", result.Target);
Assert.AreEqual(new Guid("{11111111-3B6F-4F5F-A5C2-FD2B9D5A47A0}"), result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.Internal, result.Type);
Assert.AreEqual("", result.Url);
}
[Test]
public void GetField_FieldContainsMediaLink_ReturnsMediaLink()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"media\" url=\"/Files/20121222_001405\" title=\"test alternative\" class=\"testClass\" target=\"_blank\" id=\"{8E1C32F3-CF15-4067-A3F4-85148606F9CD}\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/GetField");
var field = item.Fields[FieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as Link;
//Assert
Assert.AreEqual("", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("", result.Query);
Assert.AreEqual("_blank", result.Target);
Assert.AreEqual(new Guid("{8E1C32F3-CF15-4067-A3F4-85148606F9CD}"), result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.Media, result.Type);
Assert.AreEqual("/~/media/8E1C32F3CF154067A3F485148606F9CD.ashx", result.Url);
}
[Test]
public void GetField_FieldContainsMediaLinkMissingItem_ReturnsNotSetLink()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var fieldValue =
"<link text=\"Test description\" linktype=\"media\" url=\"/Files/20121222_001405\" title=\"test alternative\" class=\"testClass\" target=\"_blank\" id=\"{11111111-CF15-4067-A3F4-85148606F9CD}\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/GetField");
var field = item.Fields[FieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as Link;
//Assert
Assert.AreEqual("", result.Anchor);
Assert.AreEqual("testClass", result.Class);
Assert.AreEqual("", result.Query);
Assert.AreEqual("_blank", result.Target);
Assert.AreEqual(new Guid("{11111111-CF15-4067-A3F4-85148606F9CD}"), result.TargetId);
Assert.AreEqual("Test description", result.Text);
Assert.AreEqual("test alternative", result.Title);
Assert.AreEqual(LinkType.Media, result.Type);
Assert.AreEqual("", result.Url);
}
#endregion
#region Method - SetField
[Test]
public void SetField_AnchorLink_AnchorLinkSetOnField()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var expected =
"<link title=\"test alternative\" linktype=\"anchor\" url=\"testAnchor\" anchor=\"testAnchor\" class=\"testClass\" text=\"Test description\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/SetField");
var field = item.Fields[FieldName];
var value = new Link()
{
Anchor = "testAnchor",
Class = "testClass",
Query = "",
Target = "",
TargetId = Guid.Empty,
Text = "Test description",
Title = "test alternative",
Type = LinkType.Anchor,
Url = "testAnchor"
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
Assert.AreEqual(expected, field.Value);
}
[Test]
public void SetField_ExternalLink_ExternalLinkSetOnField()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var expected =
"<link url=\"http://www.google.com\" text=\"Test description\" class=\"testClass\" title=\"test alternative\" linktype=\"external\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/SetField");
var field = item.Fields[FieldName];
var value = new Link()
{
Anchor = "",
Class = "testClass",
Query = "",
Target = "",
TargetId = Guid.Empty,
Text = "Test description",
Title = "test alternative",
Type = LinkType.External,
Url = "http://www.google.com"
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
Assert.AreEqual(expected, field.Value);
}
[Test]
public void SetField_JavaScriptLink_JavaScriptLinkSetOnField()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var expected =
"<link url=\"javascript:alert('hello world');\" text=\"Test description\" class=\"testClass\" title=\"test alternative\" linktype=\"javascript\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/SetField");
var field = item.Fields[FieldName];
var value = new Link()
{
Anchor = "",
Class = "testClass",
Query = "",
Target = "",
TargetId = Guid.Empty,
Text = "Test description",
Title = "test alternative",
Type = LinkType.JavaScript,
Url = "javascript:alert('hello world');"
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
Assert.AreEqual(expected, field.Value);
}
[Test]
public void SetField_MailToLink_MailToLinkSetOnField()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var expected =
"<link url=\"mailto:test@test.com\" text=\"Test description\" class=\"testClass\" title=\"test alternative\" linktype=\"mailto\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/SetField");
var field = item.Fields[FieldName];
var value = new Link()
{
Anchor = "",
Class = "testClass",
Query = "",
Target = "",
TargetId = Guid.Empty,
Text = "Test description",
Title = "test alternative",
Type = LinkType.MailTo,
Url = "mailto:test@test.com"
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
Assert.AreEqual(expected, field.Value);
}
[Test]
public void SetField_InternalLink_InternalLinkSetOnField()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var expected =
"<link target=\"testTarget\" title=\"test alternative\" querystring=\"q=s\" linktype=\"internal\" id=\"{1AE37F34-3B6F-4F5F-A5C2-FD2B9D5A47A0}\" anchor=\"testAnchor\" url=\"/en/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/Target.aspx\" class=\"testClass\" text=\"Test description\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/SetField");
var field = item.Fields[FieldName];
var value = new Link()
{
Anchor = "testAnchor",
Class = "testClass",
Query = "q=s",
Target = "testTarget",
TargetId = new Guid("{1AE37F34-3B6F-4F5F-A5C2-FD2B9D5A47A0}"),
Text = "Test description",
Title = "test alternative",
Type = LinkType.Internal,
Url = ""
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
Assert.AreEqual(expected, field.Value);
}
[Test]
[ExpectedException(typeof(MapperException))]
public void SetField_InternalLinkMissingTarget_ThorwsException()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/SetField");
var field = item.Fields[FieldName];
var value = new Link()
{
Anchor = "testAnchor",
Class = "testClass",
Query = "q=s",
Target = "testTarget",
TargetId = new Guid("{11111111-3B6F-4F5F-A5C2-FD2B9D5A47A0}"),
Text = "Test description",
Title = "test alternative",
Type = LinkType.Internal,
Url = ""
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
}
[Test]
public void SetField_MedialLink_MediaLinkSetOnField()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var expected =
"<link target=\"_blank\" title=\"test alternative\" linktype=\"media\" id=\"{8E1C32F3-CF15-4067-A3F4-85148606F9CD}\" url=\"/~/media/8E1C32F3CF154067A3F485148606F9CD.ashx\" class=\"testClass\" text=\"Test description\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/SetField");
var field = item.Fields[FieldName];
var value = new Link()
{
Anchor = "",
Class = "testClass",
Query = "",
Target = "_blank",
TargetId = new Guid("{8E1C32F3-CF15-4067-A3F4-85148606F9CD}"),
Text = "Test description",
Title = "test alternative",
Type = LinkType.Media,
Url = ""
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
Assert.AreEqual(expected, field.Value);
}
[Test]
[ExpectedException(typeof(MapperException))]
public void SetField_MedialLinkMissingItem_ThrowsException()
{
//Assign
var mapper = new SitecoreFieldLinkMapper();
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldLinkMapper/SetField");
var field = item.Fields[FieldName];
var value = new Link()
{
Anchor = "",
Class = "testClass",
Query = "",
Target = "_blank",
TargetId = new Guid("{11111111-CF15-4067-A3F4-85148606F9CD}"),
Text = "Test description",
Title = "test alternative",
Type = LinkType.Media,
Url = ""
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, value, null, null);
}
//Assert
}
#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.Threading;
namespace System.Net
{
// This is used by ContextAwareResult to cache callback closures between similar calls. Create one of these and
// pass it in to FinishPostingAsyncOp() to prevent the context from being captured in every iteration of a looped async call.
//
// It was decided not to make the delegate and state into weak references because:
// - The delegate is very likely to be abandoned by the user right after calling BeginXxx, making caching it useless. There's
// no easy way to weakly reference just the target.
// - We want to support identifying state via object.Equals() (especially value types), which means we need to keep a
// reference to the original. Plus, if we're holding the target, might as well hold the state too.
// The user will need to disable caching if they want their target/state to be instantly collected.
//
// For now the state is not included as part of the closure. It is too common a pattern (for example with socket receive)
// to have several pending IOs differentiated by their state object. We don't want that pattern to break the cache.
internal class CallbackClosure
{
private readonly AsyncCallback _savedCallback;
private readonly ExecutionContext _savedContext;
internal CallbackClosure(ExecutionContext context, AsyncCallback callback)
{
if (callback != null)
{
_savedCallback = callback;
_savedContext = context;
}
}
internal bool IsCompatible(AsyncCallback callback)
{
if (callback == null || _savedCallback == null)
{
return false;
}
// Delegates handle this ok. AsyncCallback is sealed and immutable, so if this succeeds, we are safe to use
// the passed-in instance.
if (!object.Equals(_savedCallback, callback))
{
return false;
}
return true;
}
internal AsyncCallback AsyncCallback
{
get
{
return _savedCallback;
}
}
internal ExecutionContext Context
{
get
{
return _savedContext;
}
}
}
// This class will ensure that the correct context is restored on the thread before invoking
// a user callback.
internal partial class ContextAwareResult : LazyAsyncResult
{
[Flags]
private enum StateFlags : byte
{
None = 0x00,
CaptureIdentity = 0x01,
CaptureContext = 0x02,
ThreadSafeContextCopy = 0x04,
PostBlockStarted = 0x08,
PostBlockFinished = 0x10,
}
// This needs to be volatile so it's sure to make it over to the completion thread in time.
private volatile ExecutionContext _context;
private object _lock;
private StateFlags _flags;
internal ContextAwareResult(object myObject, object myState, AsyncCallback myCallBack) :
this(false, false, myObject, myState, myCallBack)
{ }
// Setting captureIdentity enables the Identity property. This will be available even if ContextCopy isn't, either because
// flow is suppressed or it wasn't needed. (If ContextCopy isn't available, Identity may or may not be. But if it is, it
// should be used instead of ContextCopy for impersonation - ContextCopy might not include the identity.)
//
// Setting forceCaptureContext enables the ContextCopy property even when a null callback is specified. (The context is
// always captured if a callback is given.)
internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, object myObject, object myState, AsyncCallback myCallBack) :
this(captureIdentity, forceCaptureContext, false, myObject, myState, myCallBack)
{ }
internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, bool threadSafeContextCopy, object myObject, object myState, AsyncCallback myCallBack) :
base(myObject, myState, myCallBack)
{
if (forceCaptureContext)
{
_flags = StateFlags.CaptureContext;
}
if (captureIdentity)
{
_flags |= StateFlags.CaptureIdentity;
}
if (threadSafeContextCopy)
{
_flags |= StateFlags.ThreadSafeContextCopy;
}
}
// This can be used to establish a context during an async op for something like calling a delegate or demanding a permission.
// May block briefly if the context is still being produced.
//
// Returns null if called from the posting thread.
internal ExecutionContext ContextCopy
{
get
{
if (InternalPeekCompleted)
{
if ((_flags & StateFlags.ThreadSafeContextCopy) == 0)
{
NetEventSource.Fail(this, "Called on completed result.");
}
throw new InvalidOperationException(SR.net_completed_result);
}
ExecutionContext context = _context;
if (context != null)
{
return context; // No need to copy on CoreCLR; ExecutionContext is immutable
}
// Make sure the context was requested.
if (AsyncCallback == null && (_flags & StateFlags.CaptureContext) == 0)
{
NetEventSource.Fail(this, "No context captured - specify a callback or forceCaptureContext.");
}
// Just use the lock to block. We might be on the thread that owns the lock which is great, it means we
// don't need a context anyway.
if ((_flags & StateFlags.PostBlockFinished) == 0)
{
if (_lock == null)
{
NetEventSource.Fail(this, "Must lock (StartPostingAsyncOp()) { ... FinishPostingAsyncOp(); } when calling ContextCopy (unless it's only called after FinishPostingAsyncOp).");
}
lock (_lock) { }
}
if (InternalPeekCompleted)
{
if ((_flags & StateFlags.ThreadSafeContextCopy) == 0)
{
NetEventSource.Fail(this, "Result became completed during call.");
}
throw new InvalidOperationException(SR.net_completed_result);
}
return _context; // No need to copy on CoreCLR; ExecutionContext is immutable
}
}
#if DEBUG
// Want to be able to verify that the Identity was requested. If it was requested but isn't available
// on the Identity property, it's either available via ContextCopy or wasn't needed (synchronous).
internal bool IdentityRequested
{
get
{
return (_flags & StateFlags.CaptureIdentity) != 0;
}
}
#endif
internal object StartPostingAsyncOp()
{
return StartPostingAsyncOp(true);
}
// If ContextCopy or Identity will be used, the return value should be locked until FinishPostingAsyncOp() is called
// or the operation has been aborted (e.g. by BeginXxx throwing). Otherwise, this can be called with false to prevent the lock
// object from being created.
internal object StartPostingAsyncOp(bool lockCapture)
{
if (InternalPeekCompleted)
{
NetEventSource.Fail(this, "Called on completed result.");
}
DebugProtectState(true);
_lock = lockCapture ? new object() : null;
_flags |= StateFlags.PostBlockStarted;
return _lock;
}
// Call this when returning control to the user.
internal bool FinishPostingAsyncOp()
{
// Ignore this call if StartPostingAsyncOp() failed or wasn't called, or this has already been called.
if ((_flags & (StateFlags.PostBlockStarted | StateFlags.PostBlockFinished)) != StateFlags.PostBlockStarted)
{
return false;
}
_flags |= StateFlags.PostBlockFinished;
ExecutionContext cachedContext = null;
return CaptureOrComplete(ref cachedContext, false);
}
// Call this when returning control to the user. Allows a cached Callback Closure to be supplied and used
// as appropriate, and replaced with a new one.
internal bool FinishPostingAsyncOp(ref CallbackClosure closure)
{
// Ignore this call if StartPostingAsyncOp() failed or wasn't called, or this has already been called.
if ((_flags & (StateFlags.PostBlockStarted | StateFlags.PostBlockFinished)) != StateFlags.PostBlockStarted)
{
return false;
}
_flags |= StateFlags.PostBlockFinished;
// Need a copy of this ref argument since it can be used in many of these calls simultaneously.
CallbackClosure closureCopy = closure;
ExecutionContext cachedContext;
if (closureCopy == null)
{
cachedContext = null;
}
else
{
if (!closureCopy.IsCompatible(AsyncCallback))
{
// Clear the cache as soon as a method is called with incompatible parameters.
closure = null;
cachedContext = null;
}
else
{
// If it succeeded, we want to replace our context/callback with the one from the closure.
// Using the closure's instance of the callback is probably overkill, but safer.
AsyncCallback = closureCopy.AsyncCallback;
cachedContext = closureCopy.Context;
}
}
bool calledCallback = CaptureOrComplete(ref cachedContext, true);
// Set up new cached context if we didn't use the previous one.
if (closure == null && AsyncCallback != null && cachedContext != null)
{
closure = new CallbackClosure(cachedContext, AsyncCallback);
}
return calledCallback;
}
protected override void Cleanup()
{
base.Cleanup();
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
CleanupInternal();
}
// This must be called right before returning the result to the user. It might call the callback itself,
// to avoid flowing context. Even if the operation completes before this call, the callback won't have been
// called.
//
// Returns whether the operation completed sync or not.
private bool CaptureOrComplete(ref ExecutionContext cachedContext, bool returnContext)
{
if ((_flags & StateFlags.PostBlockStarted) == 0)
{
NetEventSource.Fail(this, "Called without calling StartPostingAsyncOp.");
}
// See if we're going to need to capture the context.
bool capturingContext = AsyncCallback != null || (_flags & StateFlags.CaptureContext) != 0;
// Peek if we've already completed, but don't fix CompletedSynchronously yet
// Capture the identity if requested, unless we're going to capture the context anyway, unless
// capturing the context won't be sufficient.
if ((_flags & StateFlags.CaptureIdentity) != 0 && !InternalPeekCompleted && (!capturingContext))
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "starting identity capture");
SafeCaptureIdentity();
}
// No need to flow if there's no callback, unless it's been specifically requested.
// Note that Capture() can return null, for example if SuppressFlow() is in effect.
if (capturingContext && !InternalPeekCompleted)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "starting capture");
if (cachedContext == null)
{
cachedContext = ExecutionContext.Capture();
}
if (cachedContext != null)
{
if (!returnContext)
{
_context = cachedContext;
cachedContext = null;
}
else
{
_context = cachedContext;
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_context:{_context}");
}
else
{
// Otherwise we have to have completed synchronously, or not needed the context.
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Skipping capture");
cachedContext = null;
if (AsyncCallback != null && !CompletedSynchronously)
{
NetEventSource.Fail(this, "Didn't capture context, but didn't complete synchronously!");
}
}
// Now we want to see for sure what to do. We might have just captured the context for no reason.
// This has to be the first time the state has been queried "for real" (apart from InvokeCallback)
// to guarantee synchronization with Complete() (otherwise, Complete() could try to call the
// callback without the context having been gotten).
DebugProtectState(false);
if (CompletedSynchronously)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Completing synchronously");
base.Complete(IntPtr.Zero);
return true;
}
return false;
}
// This method is guaranteed to be called only once. If called with a non-zero userToken, the context is not flowed.
protected override void Complete(IntPtr userToken)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_context(set):{_context != null} userToken:{userToken}");
// If no flowing, just complete regularly.
if ((_flags & StateFlags.PostBlockStarted) == 0)
{
base.Complete(userToken);
return;
}
// At this point, IsCompleted is set and CompletedSynchronously is fixed. If it's synchronous, then we want to hold
// the completion for the CaptureOrComplete() call to avoid the context flow. If not, we know CaptureOrComplete() has completed.
if (CompletedSynchronously)
{
return;
}
ExecutionContext context = _context;
// If the context is being abandoned or wasn't captured (SuppressFlow, null AsyncCallback), just
// complete regularly, as long as CaptureOrComplete() has finished.
//
if (userToken != IntPtr.Zero || context == null)
{
base.Complete(userToken);
return;
}
ExecutionContext.Run(context, s => ((ContextAwareResult)s).CompleteCallback(), this);
}
private void CompleteCallback()
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Context set, calling callback.");
base.Complete(IntPtr.Zero);
}
internal virtual EndPoint RemoteEndPoint => null;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public abstract class HttpContent : IDisposable
{
private HttpContentHeaders _headers;
private MemoryStream _bufferedContent;
private object _contentReadStream; // Stream or Task<Stream>
private bool _disposed;
private bool _canCalculateLength;
internal const int MaxBufferSize = int.MaxValue;
internal static readonly Encoding DefaultStringEncoding = Encoding.UTF8;
private const int UTF8CodePage = 65001;
private const int UTF8PreambleLength = 3;
private const byte UTF8PreambleByte0 = 0xEF;
private const byte UTF8PreambleByte1 = 0xBB;
private const byte UTF8PreambleByte2 = 0xBF;
private const int UTF8PreambleFirst2Bytes = 0xEFBB;
#if !uap
// UTF32 not supported on Phone
private const int UTF32CodePage = 12000;
private const int UTF32PreambleLength = 4;
private const byte UTF32PreambleByte0 = 0xFF;
private const byte UTF32PreambleByte1 = 0xFE;
private const byte UTF32PreambleByte2 = 0x00;
private const byte UTF32PreambleByte3 = 0x00;
#endif
private const int UTF32OrUnicodePreambleFirst2Bytes = 0xFFFE;
private const int UnicodeCodePage = 1200;
private const int UnicodePreambleLength = 2;
private const byte UnicodePreambleByte0 = 0xFF;
private const byte UnicodePreambleByte1 = 0xFE;
private const int BigEndianUnicodeCodePage = 1201;
private const int BigEndianUnicodePreambleLength = 2;
private const byte BigEndianUnicodePreambleByte0 = 0xFE;
private const byte BigEndianUnicodePreambleByte1 = 0xFF;
private const int BigEndianUnicodePreambleFirst2Bytes = 0xFEFF;
#if DEBUG
static HttpContent()
{
// Ensure the encoding constants used in this class match the actual data from the Encoding class
AssertEncodingConstants(Encoding.UTF8, UTF8CodePage, UTF8PreambleLength, UTF8PreambleFirst2Bytes,
UTF8PreambleByte0,
UTF8PreambleByte1,
UTF8PreambleByte2);
#if !uap
// UTF32 not supported on Phone
AssertEncodingConstants(Encoding.UTF32, UTF32CodePage, UTF32PreambleLength, UTF32OrUnicodePreambleFirst2Bytes,
UTF32PreambleByte0,
UTF32PreambleByte1,
UTF32PreambleByte2,
UTF32PreambleByte3);
#endif
AssertEncodingConstants(Encoding.Unicode, UnicodeCodePage, UnicodePreambleLength, UTF32OrUnicodePreambleFirst2Bytes,
UnicodePreambleByte0,
UnicodePreambleByte1);
AssertEncodingConstants(Encoding.BigEndianUnicode, BigEndianUnicodeCodePage, BigEndianUnicodePreambleLength, BigEndianUnicodePreambleFirst2Bytes,
BigEndianUnicodePreambleByte0,
BigEndianUnicodePreambleByte1);
}
private static void AssertEncodingConstants(Encoding encoding, int codePage, int preambleLength, int first2Bytes, params byte[] preamble)
{
Debug.Assert(encoding != null);
Debug.Assert(preamble != null);
Debug.Assert(codePage == encoding.CodePage,
"Encoding code page mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual (Encoding.CodePage): {1}", codePage, encoding.CodePage);
byte[] actualPreamble = encoding.GetPreamble();
Debug.Assert(preambleLength == actualPreamble.Length,
"Encoding preamble length mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual (Encoding.GetPreamble().Length): {1}", preambleLength, actualPreamble.Length);
Debug.Assert(actualPreamble.Length >= 2);
int actualFirst2Bytes = actualPreamble[0] << 8 | actualPreamble[1];
Debug.Assert(first2Bytes == actualFirst2Bytes,
"Encoding preamble first 2 bytes mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual: {1}", first2Bytes, actualFirst2Bytes);
Debug.Assert(preamble.Length == actualPreamble.Length,
"Encoding preamble mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}",
BitConverter.ToString(preamble),
BitConverter.ToString(actualPreamble));
for (int i = 0; i < preamble.Length; i++)
{
Debug.Assert(preamble[i] == actualPreamble[i],
"Encoding preamble mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}",
BitConverter.ToString(preamble),
BitConverter.ToString(actualPreamble));
}
}
#endif
public HttpContentHeaders Headers
{
get
{
if (_headers == null)
{
_headers = new HttpContentHeaders(this);
}
return _headers;
}
}
private bool IsBuffered
{
get { return _bufferedContent != null; }
}
internal void SetBuffer(byte[] buffer, int offset, int count)
{
_bufferedContent = new MemoryStream(buffer, offset, count, writable: false, publiclyVisible: true);
}
internal bool TryGetBuffer(out ArraySegment<byte> buffer)
{
if (_bufferedContent != null)
{
return _bufferedContent.TryGetBuffer(out buffer);
}
buffer = default;
return false;
}
protected HttpContent()
{
// Log to get an ID for the current content. This ID is used when the content gets associated to a message.
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
// We start with the assumption that we can calculate the content length.
_canCalculateLength = true;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
public Task<string> ReadAsStringAsync()
{
CheckDisposed();
return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => s.ReadBufferedContentAsString());
}
private string ReadBufferedContentAsString()
{
Debug.Assert(IsBuffered);
if (_bufferedContent.Length == 0)
{
return string.Empty;
}
ArraySegment<byte> buffer;
if (!TryGetBuffer(out buffer))
{
buffer = new ArraySegment<byte>(_bufferedContent.ToArray());
}
return ReadBufferAsString(buffer, Headers);
}
internal static string ReadBufferAsString(ArraySegment<byte> buffer, HttpContentHeaders headers)
{
// We don't validate the Content-Encoding header: If the content was encoded, it's the caller's
// responsibility to make sure to only call ReadAsString() on already decoded content. E.g. if the
// Content-Encoding is 'gzip' the user should set HttpClientHandler.AutomaticDecompression to get a
// decoded response stream.
Encoding encoding = null;
int bomLength = -1;
string charset = headers.ContentType?.CharSet;
// If we do have encoding information in the 'Content-Type' header, use that information to convert
// the content to a string.
if (charset != null)
{
try
{
// Remove at most a single set of quotes.
if (charset.Length > 2 &&
charset[0] == '\"' &&
charset[charset.Length - 1] == '\"')
{
encoding = Encoding.GetEncoding(charset.Substring(1, charset.Length - 2));
}
else
{
encoding = Encoding.GetEncoding(charset);
}
// Byte-order-mark (BOM) characters may be present even if a charset was specified.
bomLength = GetPreambleLength(buffer, encoding);
}
catch (ArgumentException e)
{
throw new InvalidOperationException(SR.net_http_content_invalid_charset, e);
}
}
// If no content encoding is listed in the ContentType HTTP header, or no Content-Type header present,
// then check for a BOM in the data to figure out the encoding.
if (encoding == null)
{
if (!TryDetectEncoding(buffer, out encoding, out bomLength))
{
// Use the default encoding (UTF8) if we couldn't detect one.
encoding = DefaultStringEncoding;
// We already checked to see if the data had a UTF8 BOM in TryDetectEncoding
// and DefaultStringEncoding is UTF8, so the bomLength is 0.
bomLength = 0;
}
}
// Drop the BOM when decoding the data.
return encoding.GetString(buffer.Array, buffer.Offset + bomLength, buffer.Count - bomLength);
}
public Task<byte[]> ReadAsByteArrayAsync()
{
CheckDisposed();
return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => s.ReadBufferedContentAsByteArray());
}
internal byte[] ReadBufferedContentAsByteArray()
{
// The returned array is exposed out of the library, so use ToArray rather
// than TryGetBuffer in order to make a copy.
return _bufferedContent.ToArray();
}
public Task<Stream> ReadAsStreamAsync()
{
CheckDisposed();
// _contentReadStream will be either null (nothing yet initialized), a Stream (it was previously
// initialized in TryReadAsStream), or a Task<Stream> (it was previously initialized here
// in ReadAsStreamAsync).
if (_contentReadStream == null) // don't yet have a Stream
{
Task<Stream> t = TryGetBuffer(out ArraySegment<byte> buffer) ?
Task.FromResult<Stream>(new MemoryStream(buffer.Array, buffer.Offset, buffer.Count, writable: false)) :
CreateContentReadStreamAsync();
_contentReadStream = t;
return t;
}
else if (_contentReadStream is Task<Stream> t) // have a Task<Stream>
{
return t;
}
else
{
Debug.Assert(_contentReadStream is Stream, $"Expected a Stream, got ${_contentReadStream}");
Task<Stream> ts = Task.FromResult((Stream)_contentReadStream);
_contentReadStream = ts;
return ts;
}
}
internal Stream TryReadAsStream()
{
CheckDisposed();
// _contentReadStream will be either null (nothing yet initialized), a Stream (it was previously
// initialized here in TryReadAsStream), or a Task<Stream> (it was previously initialized
// in ReadAsStreamAsync).
if (_contentReadStream == null) // don't yet have a Stream
{
Stream s = TryGetBuffer(out ArraySegment<byte> buffer) ?
new MemoryStream(buffer.Array, buffer.Offset, buffer.Count, writable: false) :
TryCreateContentReadStream();
_contentReadStream = s;
return s;
}
else if (_contentReadStream is Stream s) // have a Stream
{
return s;
}
else // have a Task<Stream>
{
Debug.Assert(_contentReadStream is Task<Stream>, $"Expected a Task<Stream>, got ${_contentReadStream}");
Task<Stream> t = (Task<Stream>)_contentReadStream;
return t.Status == TaskStatus.RanToCompletion ? t.Result : null;
}
}
protected abstract Task SerializeToStreamAsync(Stream stream, TransportContext context);
// TODO #9071: Expose this publicly. Until it's public, only sealed or internal types should override it, and then change
// their SerializeToStreamAsync implementation to delegate to this one. They need to be sealed as otherwise an external
// type could derive from it and override SerializeToStreamAsync(stream, context) further, at which point when
// HttpClient calls SerializeToStreamAsync(stream, context, cancellationToken), their custom override will be skipped.
internal virtual Task SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken) =>
SerializeToStreamAsync(stream, context);
public Task CopyToAsync(Stream stream, TransportContext context) =>
CopyToAsync(stream, context, CancellationToken.None);
// TODO #9071: Expose this publicly.
internal Task CopyToAsync(Stream stream, TransportContext context, CancellationToken cancellationToken)
{
CheckDisposed();
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
try
{
ArraySegment<byte> buffer;
if (TryGetBuffer(out buffer))
{
return CopyToAsyncCore(stream.WriteAsync(new ReadOnlyMemory<byte>(buffer.Array, buffer.Offset, buffer.Count), cancellationToken));
}
else
{
Task task = SerializeToStreamAsync(stream, context, cancellationToken);
CheckTaskNotNull(task);
return CopyToAsyncCore(new ValueTask(task));
}
}
catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e))
{
return Task.FromException(GetStreamCopyException(e));
}
}
private static async Task CopyToAsyncCore(ValueTask copyTask)
{
try
{
await copyTask.ConfigureAwait(false);
}
catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e))
{
throw GetStreamCopyException(e);
}
}
public Task CopyToAsync(Stream stream)
{
return CopyToAsync(stream, null);
}
public Task LoadIntoBufferAsync()
{
return LoadIntoBufferAsync(MaxBufferSize);
}
// No "CancellationToken" parameter needed since canceling the CTS will close the connection, resulting
// in an exception being thrown while we're buffering.
// If buffering is used without a connection, it is supposed to be fast, thus no cancellation required.
public Task LoadIntoBufferAsync(long maxBufferSize) =>
LoadIntoBufferAsync(maxBufferSize, CancellationToken.None);
internal Task LoadIntoBufferAsync(long maxBufferSize, CancellationToken cancellationToken)
{
CheckDisposed();
if (maxBufferSize > HttpContent.MaxBufferSize)
{
// This should only be hit when called directly; HttpClient/HttpClientHandler
// will not exceed this limit.
throw new ArgumentOutOfRangeException(nameof(maxBufferSize), maxBufferSize,
SR.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize));
}
if (IsBuffered)
{
// If we already buffered the content, just return a completed task.
return Task.CompletedTask;
}
Exception error = null;
MemoryStream tempBuffer = CreateMemoryStream(maxBufferSize, out error);
if (tempBuffer == null)
{
// We don't throw in LoadIntoBufferAsync(): return a faulted task.
return Task.FromException(error);
}
try
{
Task task = SerializeToStreamAsync(tempBuffer, null, cancellationToken);
CheckTaskNotNull(task);
return LoadIntoBufferAsyncCore(task, tempBuffer);
}
catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e))
{
return Task.FromException(GetStreamCopyException(e));
}
// other synchronous exceptions from SerializeToStreamAsync/CheckTaskNotNull will propagate
}
private async Task LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)
{
try
{
await serializeToStreamTask.ConfigureAwait(false);
}
catch (Exception e)
{
tempBuffer.Dispose(); // Cleanup partially filled stream.
Exception we = GetStreamCopyException(e);
if (we != e) throw we;
throw;
}
try
{
tempBuffer.Seek(0, SeekOrigin.Begin); // Rewind after writing data.
_bufferedContent = tempBuffer;
}
catch (Exception e)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, e);
throw;
}
}
protected virtual Task<Stream> CreateContentReadStreamAsync()
{
// By default just buffer the content to a memory stream. Derived classes can override this behavior
// if there is a better way to retrieve the content as stream (e.g. byte array/string use a more efficient
// way, like wrapping a read-only MemoryStream around the bytes/string)
return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => (Stream)s._bufferedContent);
}
// As an optimization for internal consumers of HttpContent (e.g. HttpClient.GetStreamAsync), and for
// HttpContent-derived implementations that override CreateContentReadStreamAsync in a way that always
// or frequently returns synchronously-completed tasks, we can avoid the task allocation by enabling
// callers to try to get the Stream first synchronously.
internal virtual Stream TryCreateContentReadStream() => null;
// Derived types return true if they're able to compute the length. It's OK if derived types return false to
// indicate that they're not able to compute the length. The transport channel needs to decide what to do in
// that case (send chunked, buffer first, etc.).
protected internal abstract bool TryComputeLength(out long length);
internal long? GetComputedOrBufferLength()
{
CheckDisposed();
if (IsBuffered)
{
return _bufferedContent.Length;
}
// If we already tried to calculate the length, but the derived class returned 'false', then don't try
// again; just return null.
if (_canCalculateLength)
{
long length = 0;
if (TryComputeLength(out length))
{
return length;
}
// Set flag to make sure next time we don't try to compute the length, since we know that we're unable
// to do so.
_canCalculateLength = false;
}
return null;
}
private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error)
{
error = null;
// If we have a Content-Length allocate the right amount of buffer up-front. Also check whether the
// content length exceeds the max. buffer size.
long? contentLength = Headers.ContentLength;
if (contentLength != null)
{
Debug.Assert(contentLength >= 0);
if (contentLength > maxBufferSize)
{
error = new HttpRequestException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize));
return null;
}
// We can safely cast contentLength to (int) since we just checked that it is <= maxBufferSize.
return new LimitMemoryStream((int)maxBufferSize, (int)contentLength);
}
// We couldn't determine the length of the buffer. Create a memory stream with an empty buffer.
return new LimitMemoryStream((int)maxBufferSize, 0);
}
#region IDisposable Members
protected virtual void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
if (_contentReadStream != null)
{
Stream s = _contentReadStream as Stream ??
(_contentReadStream is Task<Stream> t && t.Status == TaskStatus.RanToCompletion ? t.Result : null);
s?.Dispose();
_contentReadStream = null;
}
if (IsBuffered)
{
_bufferedContent.Dispose();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Helpers
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().ToString());
}
}
private void CheckTaskNotNull(Task task)
{
if (task == null)
{
var e = new InvalidOperationException(SR.net_http_content_no_task_returned);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, e);
throw e;
}
}
private static bool StreamCopyExceptionNeedsWrapping(Exception e) => e is IOException || e is ObjectDisposedException;
private static Exception GetStreamCopyException(Exception originalException)
{
// HttpContent derived types should throw HttpRequestExceptions if there is an error. However, since the stream
// provided by CopyToAsync() can also throw, we wrap such exceptions in HttpRequestException. This way custom content
// types don't have to worry about it. The goal is that users of HttpContent don't have to catch multiple
// exceptions (depending on the underlying transport), but just HttpRequestExceptions
// Custom stream should throw either IOException or HttpRequestException.
// We don't want to wrap other exceptions thrown by Stream (e.g. InvalidOperationException), since we
// don't want to hide such "usage error" exceptions in HttpRequestException.
// ObjectDisposedException is also wrapped, since aborting HWR after a request is complete will result in
// the response stream being closed.
return StreamCopyExceptionNeedsWrapping(originalException) ?
new HttpRequestException(SR.net_http_content_stream_copy_error, originalException) :
originalException;
}
private static int GetPreambleLength(ArraySegment<byte> buffer, Encoding encoding)
{
byte[] data = buffer.Array;
int offset = buffer.Offset;
int dataLength = buffer.Count;
Debug.Assert(data != null);
Debug.Assert(encoding != null);
switch (encoding.CodePage)
{
case UTF8CodePage:
return (dataLength >= UTF8PreambleLength
&& data[offset + 0] == UTF8PreambleByte0
&& data[offset + 1] == UTF8PreambleByte1
&& data[offset + 2] == UTF8PreambleByte2) ? UTF8PreambleLength : 0;
#if !uap
// UTF32 not supported on Phone
case UTF32CodePage:
return (dataLength >= UTF32PreambleLength
&& data[offset + 0] == UTF32PreambleByte0
&& data[offset + 1] == UTF32PreambleByte1
&& data[offset + 2] == UTF32PreambleByte2
&& data[offset + 3] == UTF32PreambleByte3) ? UTF32PreambleLength : 0;
#endif
case UnicodeCodePage:
return (dataLength >= UnicodePreambleLength
&& data[offset + 0] == UnicodePreambleByte0
&& data[offset + 1] == UnicodePreambleByte1) ? UnicodePreambleLength : 0;
case BigEndianUnicodeCodePage:
return (dataLength >= BigEndianUnicodePreambleLength
&& data[offset + 0] == BigEndianUnicodePreambleByte0
&& data[offset + 1] == BigEndianUnicodePreambleByte1) ? BigEndianUnicodePreambleLength : 0;
default:
byte[] preamble = encoding.GetPreamble();
return BufferHasPrefix(buffer, preamble) ? preamble.Length : 0;
}
}
private static bool TryDetectEncoding(ArraySegment<byte> buffer, out Encoding encoding, out int preambleLength)
{
byte[] data = buffer.Array;
int offset = buffer.Offset;
int dataLength = buffer.Count;
Debug.Assert(data != null);
if (dataLength >= 2)
{
int first2Bytes = data[offset + 0] << 8 | data[offset + 1];
switch (first2Bytes)
{
case UTF8PreambleFirst2Bytes:
if (dataLength >= UTF8PreambleLength && data[offset + 2] == UTF8PreambleByte2)
{
encoding = Encoding.UTF8;
preambleLength = UTF8PreambleLength;
return true;
}
break;
case UTF32OrUnicodePreambleFirst2Bytes:
#if !uap
// UTF32 not supported on Phone
if (dataLength >= UTF32PreambleLength && data[offset + 2] == UTF32PreambleByte2 && data[offset + 3] == UTF32PreambleByte3)
{
encoding = Encoding.UTF32;
preambleLength = UTF32PreambleLength;
}
else
#endif
{
encoding = Encoding.Unicode;
preambleLength = UnicodePreambleLength;
}
return true;
case BigEndianUnicodePreambleFirst2Bytes:
encoding = Encoding.BigEndianUnicode;
preambleLength = BigEndianUnicodePreambleLength;
return true;
}
}
encoding = null;
preambleLength = 0;
return false;
}
private static bool BufferHasPrefix(ArraySegment<byte> buffer, byte[] prefix)
{
byte[] byteArray = buffer.Array;
if (prefix == null || byteArray == null || prefix.Length > buffer.Count || prefix.Length == 0)
return false;
for (int i = 0, j = buffer.Offset; i < prefix.Length; i++, j++)
{
if (prefix[i] != byteArray[j])
return false;
}
return true;
}
#endregion Helpers
private static async Task<TResult> WaitAndReturnAsync<TState, TResult>(Task waitTask, TState state, Func<TState, TResult> returnFunc)
{
await waitTask.ConfigureAwait(false);
return returnFunc(state);
}
private static Exception CreateOverCapacityException(int maxBufferSize)
{
return new HttpRequestException(SR.Format(SR.net_http_content_buffersize_exceeded, maxBufferSize));
}
internal sealed class LimitMemoryStream : MemoryStream
{
private readonly int _maxSize;
public LimitMemoryStream(int maxSize, int capacity)
: base(capacity)
{
Debug.Assert(capacity <= maxSize);
_maxSize = maxSize;
}
public byte[] GetSizedBuffer()
{
ArraySegment<byte> buffer;
return TryGetBuffer(out buffer) && buffer.Offset == 0 && buffer.Count == buffer.Array.Length ?
buffer.Array :
ToArray();
}
public override void Write(byte[] buffer, int offset, int count)
{
CheckSize(count);
base.Write(buffer, offset, count);
}
public override void WriteByte(byte value)
{
CheckSize(1);
base.WriteByte(value);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckSize(count);
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
CheckSize(buffer.Length);
return base.WriteAsync(buffer, cancellationToken);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
CheckSize(count);
return base.BeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
base.EndWrite(asyncResult);
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
ArraySegment<byte> buffer;
if (TryGetBuffer(out buffer))
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
long pos = Position;
long length = Length;
Position = length;
long bytesToWrite = length - pos;
return destination.WriteAsync(buffer.Array, (int)(buffer.Offset + pos), (int)bytesToWrite, cancellationToken);
}
return base.CopyToAsync(destination, bufferSize, cancellationToken);
}
private void CheckSize(int countToAdd)
{
if (_maxSize - Length < countToAdd)
{
throw CreateOverCapacityException(_maxSize);
}
}
}
internal sealed class LimitArrayPoolWriteStream : Stream
{
private const int MaxByteArrayLength = 0x7FFFFFC7;
private const int InitialLength = 256;
private readonly int _maxBufferSize;
private byte[] _buffer;
private int _length;
public LimitArrayPoolWriteStream(int maxBufferSize) : this(maxBufferSize, InitialLength) { }
public LimitArrayPoolWriteStream(int maxBufferSize, long capacity)
{
if (capacity < InitialLength)
{
capacity = InitialLength;
}
else if (capacity > maxBufferSize)
{
throw CreateOverCapacityException(maxBufferSize);
}
_maxBufferSize = maxBufferSize;
_buffer = ArrayPool<byte>.Shared.Rent((int)capacity);
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_buffer != null);
ArrayPool<byte>.Shared.Return(_buffer);
_buffer = null;
base.Dispose(disposing);
}
public ArraySegment<byte> GetBuffer() => new ArraySegment<byte>(_buffer, 0, _length);
public byte[] ToArray()
{
var arr = new byte[_length];
Buffer.BlockCopy(_buffer, 0, arr, 0, _length);
return arr;
}
private void EnsureCapacity(int value)
{
if ((uint)value > (uint)_maxBufferSize) // value cast handles overflow to negative as well
{
throw CreateOverCapacityException(_maxBufferSize);
}
else if (value > _buffer.Length)
{
Grow(value);
}
}
private void Grow(int value)
{
Debug.Assert(value > _buffer.Length);
// Extract the current buffer to be replaced.
byte[] currentBuffer = _buffer;
_buffer = null;
// Determine the capacity to request for the new buffer. It should be
// at least twice as long as the current one, if not more if the requested
// value is more than that. If the new value would put it longer than the max
// allowed byte array, than shrink to that (and if the required length is actually
// longer than that, we'll let the runtime throw).
uint twiceLength = 2 * (uint)currentBuffer.Length;
int newCapacity = twiceLength > MaxByteArrayLength ?
(value > MaxByteArrayLength ? value : MaxByteArrayLength) :
Math.Max(value, (int)twiceLength);
// Get a new buffer, copy the current one to it, return the current one, and
// set the new buffer as current.
byte[] newBuffer = ArrayPool<byte>.Shared.Rent(newCapacity);
Buffer.BlockCopy(currentBuffer, 0, newBuffer, 0, _length);
ArrayPool<byte>.Shared.Return(currentBuffer);
_buffer = newBuffer;
}
public override void Write(byte[] buffer, int offset, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
EnsureCapacity(_length + count);
Buffer.BlockCopy(buffer, offset, _buffer, _length, count);
_length += count;
}
public override void Write(ReadOnlySpan<byte> buffer)
{
EnsureCapacity(_length + buffer.Length);
buffer.CopyTo(new Span<byte>(_buffer, _length, buffer.Length));
_length += buffer.Length;
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
Write(buffer, offset, count);
return Task.CompletedTask;
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
Write(buffer.Span);
return default;
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) =>
TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
public override void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
public override void WriteByte(byte value)
{
int newLength = _length + 1;
EnsureCapacity(newLength);
_buffer[_length] = value;
_length = newLength;
}
public override void Flush() { }
public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public override long Length => _length;
public override bool CanWrite => true;
public override bool CanRead => false;
public override bool CanSeek => false;
public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }
public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
public override void SetLength(long value) { throw new NotSupportedException(); }
}
}
}
| |
// 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.
#define EF5
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Linq;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.Research.CodeAnalysis.Caching.Models;
using System.Data.Entity;
using Microsoft.Research.DataStructures;
using System.Data.SqlClient;
using Microsoft.Research.CodeAnalysis;
//temp
using System.Data.Entity.Migrations;
using System.Data.Entity.Infrastructure;
// Entityframework v5:
#if EF5
using System.Data.Objects;
#else
// Entity Framework v6
using System.Data.Entity.Core.Objects;
#endif
using System.Linq.Expressions;
using System.Diagnostics.Contracts;
using System.IO;
namespace Microsoft.Research.CodeAnalysis.Caching
{
using Microsoft.Win32;
static class IndexExtension
{
public static void CreateUniqueIndex<TModel>(this DbContext context, Expression<Func<TModel, object>> expression)
{
Contract.Requires(context != null);
Contract.Requires(expression != null);
// Assumes singular table name matching the name of the Model type
var tableName = typeof(TModel).Name + "s"; // hack. No way to read the configuration back? IF we use non-standard table names, this won't work
var columnName = GetLambdaExpressionName(expression.Body);
var indexName = string.Format("IX_{0}_{1}", tableName, columnName);
var createIndexSql = string.Format("CREATE INDEX {0} ON {1} ({2})", indexName, tableName, columnName);
try
{
Contract.Assume(context.Database != null);
context.Database.ExecuteSqlCommand(createIndexSql);
}
catch
{ }
}
public static string GetLambdaExpressionName(Expression expression)
{
MemberExpression memberExp = expression as MemberExpression;
if (memberExp == null)
{
// Check if it is an UnaryExpression and unwrap it
var unaryExp = expression as UnaryExpression;
if (unaryExp != null)
memberExp = unaryExp.Operand as MemberExpression;
}
if (memberExp == null)
throw new ArgumentException("Cannot get name from expression", "expression");
return memberExp.Member.Name;
}
}
public abstract class SQLCacheModel : ClousotCacheContext, ICacheModel
{
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(cachename != null);
}
private bool isFresh;
private int nbWaitingChanges = 0;
const int MaxWaitingChanges = 500;
private DateTime lastSave;
const int MaxWaitTime = 30; // seconds
readonly private bool trace;
readonly protected string cachename;
public SQLCacheModel(string connection, string cachename, bool trace = false)
: base(connection)
{
Contract.Requires(cachename != null);
this.trace = trace;
Contract.Assume(this.Configuration != null);
this.Configuration.AutoDetectChangesEnabled = false;
this.Configuration.ValidateOnSaveEnabled = false;
lastSave = DateTime.Now;
this.cachename = cachename;
}
/// <summary>
/// Called when created for first time
/// </summary>
protected void Initialize()
{
this.isFresh = true;
this.CreateUniqueIndex<Method>(x => x.Hash);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public new IEnumerable<Method> Methods
{
get
{
return base.Methods;
}
}
public new IEnumerable<Metadata> Metadatas
{
get
{
return base.Metadatas;
}
}
public new IEnumerable<AssemblyInfo> AssemblyInfoes
{
get
{
return base.AssemblyInfoes;
}
}
public Metadata MetadataByKey(string key)
{
try
{
return base.Metadatas.Find(key);
}
catch (Exception e)
{
if (this.trace)
{
Console.WriteLine("[cache] SqlCacheModel: MetadataByKey failed: {0}", e.Message);
}
return default(Metadata);
}
}
public Method MethodByHash(byte[] hash)
{
try
{
var query = base.Methods.Where(m => m.Hash.Equals(hash));
return query.FirstOrDefault();
}
catch (Exception e)
{
if (this.trace)
{
Console.WriteLine("[cache] SqlCacheModel: MethodByHash failed: {0}", e.Message);
}
return null;
}
}
public Method BaselineByName(byte[] methodNameHash, string baselineName)
{
try
{
var candidate = base.BaselineMethods.Find(methodNameHash, baselineName);
//var candidate = base.BaselineMethods.Where(m => m.MethodFullName == methodName && m.BaselineId == baselineName).FirstOrDefault();
if (candidate != null) return candidate.Method;
return null;
}
catch (Exception e)
{
if (this.trace)
{
Console.WriteLine("[cache] SqlCacheModel: MethodByName failed: {0}", e.Message);
}
return null;
}
}
public Metadata NewMetadata()
{
return new Metadata();
}
public Method NewMethod()
{
return new Method();
}
public Outcome NewOutcome(Method method)
{
var result = new Outcome() { Method = method };
if (ValidMethodModel(method))
{
method.Outcomes.AssumeNotNull().Add(result);
}
return result;
}
public Suggestion NewSuggestion(Method method)
{
var result = new Suggestion() { Method = method };
if (ValidMethodModel(method))
{
method.Suggestions.AssumeNotNull().Add(result);
}
return result;
}
public OutcomeContext NewOutcomeContext(Outcome outcome)
{
var result = new OutcomeContext();
if (ValidMethodModel(outcome.Method))
{
outcome.OutcomeContexts.Add(result);
}
return result;
}
public ContextEdge NewContextEdge(OutcomeOrSuggestion item)
{
// TODO: this might now work if the underlying DfContext generates proxies.
Outcome outcome = item as Outcome;
if (outcome != null)
{
var result = new OutcomeContextEdge();
Contract.Assume(outcome.Method != null);
if (ValidMethodModel(outcome.Method))
{
outcome.OutcomeContextEdges.Add(result);
}
return result;
}
Suggestion sugg = item as Suggestion;
if (sugg != null)
{
Contract.Assume(sugg.Method != null);
var result = new SuggestionContextEdge();
if (ValidMethodModel(sugg.Method))
{
sugg.SuggestionContextEdges.Add(result);
}
return result;
}
return null;
}
public void DeleteMethodModel(Method methodModel)
{
try
{
base.Methods.Remove(methodModel);
}
catch (Exception e)
{
if (this.trace)
{
Console.WriteLine("[cache] SqlCacheModel: DeleteMethodModel failed: {0}", e.Message);
}
}
}
public AssemblyInfo GetOrCreateAssemblyInfo(Guid guid)
{
var result = base.AssemblyInfoes.Find(guid);
if (result == null)
{
result = base.AssemblyInfoes.Create();
Contract.Assume(result != null);
result.AssemblyId = guid;
base.AssemblyInfoes.Add(result);
}
return result;
}
public IdHashTimeToMethod NewHashDateBindingForNow(ByteArray methodIdHash, Method methodModel)
{
var result = new IdHashTimeToMethod { Method = methodModel, MethodIdHash = methodIdHash.Bytes, Time = DateTime.Now };
return result;
}
public ByteArray GetHashForDate(ByteArray methodIdHash, DateTime t, bool afterT)
{
try
{
var methodIdHashBytes = methodIdHash.Bytes;
var latest = base.IdHashTimeToMethods
// .Where(b => b.MethodIdHash.Equals(methodIdHashBytes) && (afterT? b.Time >= t : b.Time <= t))
.Where(b => b.MethodIdHash.Equals(methodIdHashBytes))
.OrderByDescending(b => b.Time)
.FirstOrDefault();
if (latest == null)
return null;
return latest.Method.AssumeNotNull().Hash;
}
catch (Exception e)
{
if (this.trace)
{
Console.WriteLine("[cache] SqlCacheModel: GetHashForDate failed: {0}", e.Message);
}
return null;
}
}
public bool IsValid
{
get
{
try {
return base.Database != null
&& base.Database.Connection != null
&& base.Database.Connection.State != System.Data.ConnectionState.Broken;
}
catch (Exception e)
{
if (this.trace)
{
Console.WriteLine("[cache] SqlCacheModel: IsValid failed: {0}", e.Message);
}
return false;
}
}
}
public bool IsFresh { get { return this.isFresh; } }
public void SaveChanges(bool now)
{
if (!now && ++this.nbWaitingChanges <= MaxWaitingChanges && (DateTime.Now - this.lastSave).Seconds < MaxWaitTime)
return;
this.lastSave = DateTime.Now;
for (var i = 0; i < 3; i++)
{
try
{
if (this.trace)
{
Console.WriteLine("[cache] SqlCacheModel: SaveChanges saving...");
}
Contract.Assume(this.Configuration != null);
this.Configuration.AutoDetectChangesEnabled = true;
base.SaveChanges();
Contract.Assume(this.Configuration != null);
this.Configuration.AutoDetectChangesEnabled = false;
this.nbWaitingChanges = 0;
}
catch (Exception e)
{
if (this.trace || i == 2)
{
Console.WriteLine("[cache] SqlCacheModel: SaveChanges failed: {0}", e.Message);
foreach (var result in this.GetValidationErrors())
{
foreach (var error in result.ValidationErrors)
{
Console.WriteLine("validation error: {0}", error.ErrorMessage);
}
}
for (var inner = e.InnerException; inner != null; inner = inner.InnerException)
{
Console.WriteLine("Innner exception: {0}", inner.Message);
}
}
FixupPendingChanges();
continue;
}
break;
}
}
private void FixupPendingChanges()
{
var objContext = (this as IObjectContextAdapter).ObjectContext;
Contract.Assume(objContext != null);
RemoveDuplicateAdds<AssemblyInfo>(objContext, ai => base.AssemblyInfoes.Find(ai.AssemblyId));
RemoveDuplicateAdds<Method>(objContext, method => this.MethodByHash(method.Hash));
}
private void RemoveDuplicateAdds<T>(ObjectContext objContext, Func<T,T> getStored) where T:class
{
Contract.Requires(objContext != null);
Contract.Requires(getStored != null);
Contract.Assume(this.ChangeTracker != null);
Contract.Assume(this.ChangeTracker.Entries<T>() != null);
#if EF5
var pendingAssemblyInfo = this.ChangeTracker.Entries<T>().AssumeNotNull().Where(a => a.State == System.Data.EntityState.Added);
#else
var pendingAssemblyInfo = this.ChangeTracker.Entries<T>().AssumeNotNull().Where(a => a.State == System.Data.Entity.EntityState.Added);
#endif
foreach (var p in pendingAssemblyInfo)
{
Contract.Assume(p != null);
if (getStored(p.Entity) != null) {
objContext.Detach(p.Entity);
}
}
}
public void AddOrUpdate(Metadata value)
{
try
{
base.Metadatas.AddOrUpdate(value);
}
catch (Exception e)
{
if (this.trace)
{
Console.WriteLine("[cache] SqlCacheModel: AddOrUpdate Metadata failed: {0}", e.Message);
}
}
}
public void AddOrUpdate(AssemblyInfo ainfo)
{
return; // nothing to do if we go through our construction.
//try
//{
// base.AssemblyInfoes.AddOrUpdate(ainfo);
//}
//catch (Exception e)
//{
// if (this.trace)
// {
// Console.WriteLine("[cache] SqlCacheModel: AddOrUpdate AssemblyInfo failed: {0}", e.Message);
// }
//}
}
private bool ValidMethodModel(Method methodModel, bool warn = false)
{
if (methodModel.FullName == null) return true; // not set yet?
if (methodModel.FullName.Length > CacheUtils.MaxMethodLength)
{
Console.WriteLine("[cache] Won't cache Method {0}. FullName is too long: {1} > {2}", methodModel.FullName, methodModel.FullName.Length, CacheUtils.MaxMethodLength);
return false;
}
return true;
}
public void AddOrUpdate(Method methodModel)
{
if (!ValidMethodModel(methodModel, warn:true)) return;
try
{
// don't use Migrations.AddOrUpdate method. It is really slow. Assume we can update (no cache hit)
base.Methods.Add(methodModel);
}
catch (Exception e)
{
if (this.trace)
{
Console.WriteLine("[cache] SqlCacheModel: AddOrUpdate MethodModel failed: {0}", e.Message);
}
}
}
public void AddOrUpdate(IdHashTimeToMethod idhash)
{
if (!ValidMethodModel(idhash.Method)) return;
try
{
// assume no duplicates
base.IdHashTimeToMethods.Add(idhash);
}
catch (Exception e)
{
if (this.trace)
{
Console.WriteLine("[cache] SqlCacheModel: AddOrUpdate IdHashTimeToMethod failed: {0}", e.Message);
}
}
}
public void AddOrUpdate(Method method, AssemblyInfo assemblyInfo)
{
if (!ValidMethodModel(method)) return;
try
{
if (!method.Assemblies.AssumeNotNull()
.Where(a => a.AssemblyId == assemblyInfo.AssemblyId).AssumeNotNull()
.Any())
{
method.Assemblies.Add(assemblyInfo);
}
}
catch (Exception e)
{
if (this.trace)
{
Console.WriteLine("[cache] SqlCacheModel: AddOrUpdate method assembly binding failed: {0}", e.Message);
}
}
}
public void AddOrUpdate(BaselineMethod baseline)
{
try
{
var candidate = base.BaselineMethods.Find(baseline.MethodFullNameHash, baseline.BaselineId);
if (candidate != null)
{
candidate.Method = baseline.Method;
}
else
{
base.BaselineMethods.Add(baseline);
}
}
catch (Exception e)
{
if (this.trace)
{
Console.WriteLine("[cache] SqlCacheModel: AddOrUpdate baseline binding failed: {0}", e.Message);
}
}
}
public string CacheName
{
get { return this.cachename; }
}
protected void DetachDeletedDb(string connection)
{
// If anyone has manually deleted the cache file, it might be still registered with LocalDB.
// If this is the case, we can't create a new database and the user is stuck unless he knows the tricky internals of LocalDB and how to get rid of the registration.
// => If we use LocalDB and the file does not exist, we try to detach it.
try
{
var connectionString = new DbConnectionStringBuilder { ConnectionString = connection };
var fileName = (string)connectionString["AttachDbFileName"];
if (File.Exists(fileName))
return;
var catalog = (string)connectionString["Initial Catalog"];
var dataSource = (string)connectionString["Data Source"];
using (var master = new DataContext(string.Format(CultureInfo.InvariantCulture, @"Data Source={0};Initial Catalog=master;Integrated Security=True", dataSource)))
{
master.ExecuteCommand(@"exec sp_detach_db {0}", catalog);
}
}
catch (ArgumentException)
{
// Not using LocalDB at all (any of the connection string parameters did not exist).
}
catch (SqlException)
{
// The file was never registered (first time used) or is already detached.
}
catch (Exception ex)
{
// Ignore other errors, could be any DbProvider specific exception.
// Usually we won't get here, but the active provider might not be LocalDB, in this case we know nothing about the provider and the exceptions it might raise.
if (this.trace)
{
Console.WriteLine("[cache] DetachDeletedDb failed: {0}", ex.Message);
}
}
}
}
public class SqlCacheModelNoCreate : SQLCacheModel
{
static SqlCacheModelNoCreate()
{
Database.SetInitializer<SqlCacheModelNoCreate>(null);
}
public SqlCacheModelNoCreate(string connection, string cacheName, bool trace) : base(connection, cacheName, trace) {
Contract.Requires(cacheName != null);
}
}
public class SqlCacheModelUseExisting : SQLCacheModel
{
class Policy : CreateDatabaseIfNotExists<SqlCacheModelUseExisting>
{
protected override void Seed(SqlCacheModelUseExisting context)
{
context.Initialize();
base.Seed(context);
}
}
static SqlCacheModelUseExisting() {
Database.SetInitializer<SqlCacheModelUseExisting>(new Policy());
}
public SqlCacheModelUseExisting(string connection, string cachename, bool trace)
: base(connection, cachename, trace)
{
Contract.Requires(cachename != null);
}
}
public class SqlCacheModelClearExisting : SQLCacheModel
{
class Policy : DropCreateDatabaseAlways<SqlCacheModelClearExisting>
{
protected override void Seed(SqlCacheModelClearExisting context)
{
context.Initialize();
base.Seed(context);
}
}
static SqlCacheModelClearExisting()
{
Database.SetInitializer<SqlCacheModelClearExisting>(new Policy());
}
public SqlCacheModelClearExisting(string connection, string cachename, bool trace)
: base(connection, cachename, trace)
{
Contract.Requires(cachename != null);
DetachDeletedDb(connection);
}
}
public class SqlCacheModelDropOnModelChange : SQLCacheModel
{
class Policy : DropCreateDatabaseIfModelChanges<SqlCacheModelDropOnModelChange>
{
protected override void Seed(SqlCacheModelDropOnModelChange context)
{
context.Initialize();
base.Seed(context);
}
}
static SqlCacheModelDropOnModelChange()
{
Database.SetInitializer<SqlCacheModelDropOnModelChange>(new Policy());
}
public SqlCacheModelDropOnModelChange(string connection, string cachename, bool trace)
: base(connection, cachename, trace)
{
Contract.Requires(cachename != null);
DetachDeletedDb(connection);
}
}
public class SQLClousotCacheFactory : IClousotCacheFactory
{
public const int DefaultMinPoolSize = 0;
/// <summary>
/// Specifying MinPoolSize increases degree of parallelism for concurrent connections to the sql database.
/// With default value (that is 0) there is no way to connect to different local db instances simultaneously.
/// </summary>
readonly protected int minPoolSize;
readonly protected string DbName;
readonly protected bool deleteOnModelChange;
public SQLClousotCacheFactory(string DbName, bool deleteOnModelChange = false, int minPoolSize = DefaultMinPoolSize)
{
this.deleteOnModelChange = deleteOnModelChange;
this.DbName = DbName;
this.minPoolSize = minPoolSize;
}
public virtual IClousotCache Create(IClousotCacheOptions options)
{
if (String.IsNullOrWhiteSpace(DbName) || options == null) { return null; }
var connection = BuildConnectionString(options).ToString();
Contract.Assert(DbName != null, "Helping cccheck");
SQLCacheModel model;
if (options.ClearCache)
{
model = new SqlCacheModelClearExisting(connection, DbName, options.Trace);
}
else if (options.SaveToCache)
{
if (this.deleteOnModelChange)
{
model = new SqlCacheModelDropOnModelChange(connection, DbName, options.Trace);
}
else
{
model = new SqlCacheModelUseExisting(connection, DbName, options.Trace);
}
}
else
{
model = new SqlCacheModelNoCreate(connection, DbName, options.Trace);
}
return new ClousotCache(model, options);
}
[Pure]
protected virtual SqlConnectionStringBuilder BuildConnectionString(IClousotCacheOptions options)
{
Contract.Requires(options != null);
Contract.Ensures(Contract.Result<SqlConnectionStringBuilder>() != null);
return new SqlConnectionStringBuilder
{
IntegratedSecurity = true,
InitialCatalog = options.GetCacheDBName(),
DataSource = this.DbName,
UserInstance = false,
MultipleActiveResultSets = true,
ConnectTimeout = options.CacheServerTimeout,
MinPoolSize = minPoolSize,
};
}
}
public class LocalDbClousotCacheFactory : SQLClousotCacheFactory
{
public LocalDbClousotCacheFactory(int minPoolSize = DefaultMinPoolSize)
: this(GetDesiredDbName(), minPoolSize)
{}
public LocalDbClousotCacheFactory(string dbName, int minPoolSize = DefaultMinPoolSize)
: base(dbName, true, minPoolSize)
{}
protected override SqlConnectionStringBuilder BuildConnectionString(IClousotCacheOptions options)
{
if (!string.IsNullOrWhiteSpace(options.CacheDirectory))
{
var name = options.GetCacheDBName();
return new SqlConnectionStringBuilder
{
IntegratedSecurity = true,
InitialCatalog = name,
DataSource = this.DbName,
UserInstance = false,
MultipleActiveResultSets = true,
ConnectTimeout = options.CacheServerTimeout,
MinPoolSize = minPoolSize,
AttachDBFilename = Path.Combine(options.CacheDirectory.AssumeNotNull(), name + ".mdf")
};
}
return base.BuildConnectionString(options);
}
public static string GetDesiredDbName()
{
const string registryKeyPath = @"SOFTWARE\Microsoft\Microsoft SQL Server Local DB\Installed Versions";
var versionKeyFileMapping = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ @"11.0", @"(LocalDb)\v11.0" },
{ @"12.0", @"(LocalDb)\MSSQLLocalDB" },
};
using (var rootKey = Registry.LocalMachine.OpenSubKey(registryKeyPath))
{
if (rootKey == null)
return null;
return rootKey.GetSubKeyNames()
.OrderByDescending(name => name.ToUpperInvariant()) // use latest version available.
.Select(versionKey => GetValueOrDefault(versionKeyFileMapping, versionKey))
.FirstOrDefault(entry => entry != null);
}
}
private static TValue GetValueOrDefault<TKey, TValue>(IDictionary<TKey, TValue> dict, TKey key)
{
Contract.Requires(!ReferenceEquals(key, null));
TValue value;
return dict.TryGetValue(key, out value) ? value : default(TValue);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
namespace System.Net.Sockets
{
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
// Buffer,Offset,Count property variables.
private WSABuffer _wsaBuffer;
private IntPtr _ptrSingleBuffer;
// BufferList property variables.
private WSABuffer[] _wsaBufferArray;
// Internal buffers for WSARecvMsg
private byte[] _wsaMessageBuffer;
private GCHandle _wsaMessageBufferGCHandle;
private IntPtr _ptrWSAMessageBuffer;
private byte[] _controlBuffer;
private GCHandle _controlBufferGCHandle;
private IntPtr _ptrControlBuffer;
private WSABuffer[] _wsaRecvMsgWSABufferArray;
private GCHandle _wsaRecvMsgWSABufferArrayGCHandle;
private IntPtr _ptrWSARecvMsgWSABufferArray;
// Internal buffer for AcceptEx when Buffer not supplied.
private IntPtr _ptrAcceptBuffer;
// Internal SocketAddress buffer
private GCHandle _socketAddressGCHandle;
private Internals.SocketAddress _pinnedSocketAddress;
private IntPtr _ptrSocketAddressBuffer;
private IntPtr _ptrSocketAddressBufferSize;
// SendPacketsElements property variables.
private SendPacketsElement[] _sendPacketsElementsInternal;
private Interop.Winsock.TransmitPacketsElement[] _sendPacketsDescriptor;
private int _sendPacketsElementsFileCount;
private int _sendPacketsElementsBufferCount;
// Internal variables for SendPackets
private FileStream[] _sendPacketsFileStreams;
private SafeHandle[] _sendPacketsFileHandles;
private IntPtr _ptrSendPacketsDescriptor;
// Overlapped object related variables.
private SafeNativeOverlapped _ptrNativeOverlapped;
private PreAllocatedOverlapped _preAllocatedOverlapped;
private object[] _objectsToPin;
private enum PinState
{
None = 0,
NoBuffer,
SingleAcceptBuffer,
SingleBuffer,
MultipleBuffer,
SendPackets
}
private PinState _pinState;
private byte[] _pinnedAcceptBuffer;
private byte[] _pinnedSingleBuffer;
private int _pinnedSingleBufferOffset;
private int _pinnedSingleBufferCount;
internal int? SendPacketsDescriptorCount
{
get
{
return _sendPacketsDescriptor == null ? null : (int?)_sendPacketsDescriptor.Length;
}
}
private void InitializeInternals()
{
// Zero tells TransmitPackets to select a default send size.
_sendPacketsSendSize = 0;
}
private void FreeInternals(bool calledFromFinalizer)
{
// Free native overlapped data.
FreeOverlapped(calledFromFinalizer);
}
private void SetupSingleBuffer()
{
CheckPinSingleBuffer(true);
}
private void SetupMultipleBuffers()
{
CheckPinMultipleBuffers();
}
private void SetupSendPacketsElements()
{
_sendPacketsElementsInternal = null;
}
private void InnerComplete()
{
CompleteIOCPOperation();
}
private unsafe void PrepareIOCPOperation()
{
Debug.Assert(_currentSocket != null, "_currentSocket is null");
Debug.Assert(_currentSocket.SafeHandle != null, "_currentSocket.SafeHandle is null");
Debug.Assert(!_currentSocket.SafeHandle.IsInvalid, "_currentSocket.SafeHandle is invalid");
ThreadPoolBoundHandle boundHandle = _currentSocket.GetOrAllocateThreadPoolBoundHandle();
NativeOverlapped* overlapped = null;
if (_preAllocatedOverlapped != null)
{
overlapped = boundHandle.AllocateNativeOverlapped(_preAllocatedOverlapped);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"boundHandle:{boundHandle}, PreAllocatedOverlapped:{_preAllocatedOverlapped}, Returned:{(IntPtr)overlapped}");
}
else
{
overlapped = boundHandle.AllocateNativeOverlapped(CompletionPortCallback, this, null);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"boundHandle:{boundHandle}, AllocateNativeOverlapped(pinData=null), Returned:{(IntPtr)overlapped}");
}
Debug.Assert(overlapped != null, "NativeOverlapped is null.");
// If we already have a SafeNativeOverlapped SafeHandle and it's associated with the same
// socket (due to the last operation that used this SocketAsyncEventArgs using the same socket),
// then we can reuse the same SafeHandle object. Otherwise, this is either the first operation
// or the last operation was with a different socket, so create a new SafeHandle.
if (_ptrNativeOverlapped?.SocketHandle == _currentSocket.SafeHandle)
{
_ptrNativeOverlapped.ReplaceHandle(overlapped);
}
else
{
_ptrNativeOverlapped?.Dispose();
_ptrNativeOverlapped = new SafeNativeOverlapped(_currentSocket.SafeHandle, overlapped);
}
}
private SocketError ProcessIOCPResult(bool success, int bytesTransferred)
{
if (success)
{
// Synchronous success.
if (_currentSocket.SafeHandle.SkipCompletionPortOnSuccess)
{
// The socket handle is configured to skip completion on success,
// so we can set the results right now.
FinishOperationSyncSuccess(bytesTransferred, SocketFlags.None);
return SocketError.Success;
}
// Socket handle is going to post a completion to the completion port (may have done so already).
// Return pending and we will continue in the completion port callback.
return SocketError.IOPending;
}
// Get the socket error (which may be IOPending)
SocketError errorCode = SocketPal.GetLastSocketError();
if (errorCode == SocketError.IOPending)
{
return errorCode;
}
FinishOperationSyncFailure(errorCode, bytesTransferred, SocketFlags.None);
// Note, the overlapped will be release in CompleteIOCPOperation below, for either success or failure
return errorCode;
}
private void CompleteIOCPOperation()
{
// Required to allow another IOCP operation for the same handle. We release the native overlapped
// in the safe handle, but keep the safe handle object around so as to be able to reuse it
// for other operations.
_ptrNativeOverlapped?.FreeNativeOverlapped();
}
private void InnerStartOperationAccept(bool userSuppliedBuffer)
{
if (!userSuppliedBuffer)
{
CheckPinSingleBuffer(false);
}
}
internal unsafe SocketError DoOperationAccept(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle)
{
PrepareIOCPOperation();
int bytesTransferred;
bool success = socket.AcceptEx(
handle,
acceptHandle,
(_ptrSingleBuffer != IntPtr.Zero) ? _ptrSingleBuffer : _ptrAcceptBuffer,
(_ptrSingleBuffer != IntPtr.Zero) ? Count - _acceptAddressBufferCount : 0,
_acceptAddressBufferCount / 2,
_acceptAddressBufferCount / 2,
out bytesTransferred,
_ptrNativeOverlapped);
return ProcessIOCPResult(success, bytesTransferred);
}
private void InnerStartOperationConnect()
{
// ConnectEx uses a sockaddr buffer containing he remote address to which to connect.
// It can also optionally take a single buffer of data to send after the connection is complete.
//
// The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack.
// The optional buffer is pinned using the Overlapped.UnsafePack method that takes a single object to pin.
PinSocketAddressBuffer();
CheckPinNoBuffer();
}
internal unsafe SocketError DoOperationConnect(Socket socket, SafeCloseSocket handle)
{
PrepareIOCPOperation();
int bytesTransferred;
bool success = socket.ConnectEx(
handle,
_ptrSocketAddressBuffer,
_socketAddress.Size,
_ptrSingleBuffer,
Count,
out bytesTransferred,
_ptrNativeOverlapped);
return ProcessIOCPResult(success, bytesTransferred);
}
private void InnerStartOperationDisconnect()
{
CheckPinNoBuffer();
}
internal SocketError DoOperationDisconnect(Socket socket, SafeCloseSocket handle)
{
PrepareIOCPOperation();
bool success = socket.DisconnectEx(
handle,
_ptrNativeOverlapped,
(int)(DisconnectReuseSocket ? TransmitFileOptions.ReuseSocket : 0),
0);
return ProcessIOCPResult(success, 0);
}
private void InnerStartOperationReceive()
{
// WWSARecv uses a WSABuffer array describing buffers of data to send.
//
// Single and multiple buffers are handled differently so as to optimize
// performance for the more common single buffer case.
//
// For a single buffer:
// The Overlapped.UnsafePack method is used that takes a single object to pin.
// A single WSABuffer that pre-exists in SocketAsyncEventArgs is used.
//
// For multiple buffers:
// The Overlapped.UnsafePack method is used that takes an array of objects to pin.
// An array to reference the multiple buffer is allocated.
// An array of WSABuffer descriptors is allocated.
}
internal unsafe SocketError DoOperationReceive(SafeCloseSocket handle, out SocketFlags flags)
{
PrepareIOCPOperation();
flags = _socketFlags;
int bytesTransferred;
SocketError socketError;
if (_buffer != null)
{
// Single buffer case.
socketError = Interop.Winsock.WSARecv(
handle,
ref _wsaBuffer,
1,
out bytesTransferred,
ref flags,
_ptrNativeOverlapped,
IntPtr.Zero);
}
else
{
// Multi buffer case.
socketError = Interop.Winsock.WSARecv(
handle,
_wsaBufferArray,
_wsaBufferArray.Length,
out bytesTransferred,
ref flags,
_ptrNativeOverlapped,
IntPtr.Zero);
}
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred);
}
private void InnerStartOperationReceiveFrom()
{
// WSARecvFrom uses e a WSABuffer array describing buffers in which to
// receive data and from which to send data respectively. Single and multiple buffers
// are handled differently so as to optimize performance for the more common single buffer case.
//
// For a single buffer:
// The Overlapped.UnsafePack method is used that takes a single object to pin.
// A single WSABuffer that pre-exists in SocketAsyncEventArgs is used.
//
// For multiple buffers:
// The Overlapped.UnsafePack method is used that takes an array of objects to pin.
// An array to reference the multiple buffer is allocated.
// An array of WSABuffer descriptors is allocated.
//
// WSARecvFrom and WSASendTo also uses a sockaddr buffer in which to store the address from which the data was received.
// The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack.
PinSocketAddressBuffer();
}
internal unsafe SocketError DoOperationReceiveFrom(SafeCloseSocket handle, out SocketFlags flags)
{
PrepareIOCPOperation();
flags = _socketFlags;
int bytesTransferred;
SocketError socketError;
if (_buffer != null)
{
socketError = Interop.Winsock.WSARecvFrom(
handle,
ref _wsaBuffer,
1,
out bytesTransferred,
ref flags,
_ptrSocketAddressBuffer,
_ptrSocketAddressBufferSize,
_ptrNativeOverlapped,
IntPtr.Zero);
}
else
{
socketError = Interop.Winsock.WSARecvFrom(
handle,
_wsaBufferArray,
_wsaBufferArray.Length,
out bytesTransferred,
ref flags,
_ptrSocketAddressBuffer,
_ptrSocketAddressBufferSize,
_ptrNativeOverlapped,
IntPtr.Zero);
}
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred);
}
private unsafe void InnerStartOperationReceiveMessageFrom()
{
// WSARecvMsg uses a WSAMsg descriptor.
// The WSAMsg buffer is pinned with a GCHandle to avoid complicating the use of Overlapped.
// WSAMsg contains a pointer to a sockaddr.
// The sockaddr is pinned with a GCHandle to avoid complicating the use of Overlapped.
// WSAMsg contains a pointer to a WSABuffer array describing data buffers.
// WSAMsg also contains a single WSABuffer describing a control buffer.
PinSocketAddressBuffer();
// Create and pin a WSAMessageBuffer if none already.
if (_wsaMessageBuffer == null)
{
_wsaMessageBuffer = new byte[sizeof(Interop.Winsock.WSAMsg)];
_wsaMessageBufferGCHandle = GCHandle.Alloc(_wsaMessageBuffer, GCHandleType.Pinned);
_ptrWSAMessageBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0);
}
// Create and pin an appropriately sized control buffer if none already
IPAddress ipAddress = (_socketAddress.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null);
bool ipv4 = (_currentSocket.AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode
bool ipv6 = _currentSocket.AddressFamily == AddressFamily.InterNetworkV6;
if (ipv4 && (_controlBuffer == null || _controlBuffer.Length != sizeof(Interop.Winsock.ControlData)))
{
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
}
_controlBuffer = new byte[sizeof(Interop.Winsock.ControlData)];
}
else if (ipv6 && (_controlBuffer == null || _controlBuffer.Length != sizeof(Interop.Winsock.ControlDataIPv6)))
{
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
}
_controlBuffer = new byte[sizeof(Interop.Winsock.ControlDataIPv6)];
}
if (!_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle = GCHandle.Alloc(_controlBuffer, GCHandleType.Pinned);
_ptrControlBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_controlBuffer, 0);
}
// If single buffer we need a pinned 1 element WSABuffer.
if (_buffer != null)
{
if (_wsaRecvMsgWSABufferArray == null)
{
_wsaRecvMsgWSABufferArray = new WSABuffer[1];
}
_wsaRecvMsgWSABufferArray[0].Pointer = _ptrSingleBuffer;
_wsaRecvMsgWSABufferArray[0].Length = _count;
_wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaRecvMsgWSABufferArray, GCHandleType.Pinned);
_ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaRecvMsgWSABufferArray, 0);
}
else
{
// Just pin the multi-buffer WSABuffer.
_wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaBufferArray, GCHandleType.Pinned);
_ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaBufferArray, 0);
}
// Fill in WSAMessageBuffer.
unsafe
{
Interop.Winsock.WSAMsg* pMessage = (Interop.Winsock.WSAMsg*)_ptrWSAMessageBuffer; ;
pMessage->socketAddress = _ptrSocketAddressBuffer;
pMessage->addressLength = (uint)_socketAddress.Size;
pMessage->buffers = _ptrWSARecvMsgWSABufferArray;
if (_buffer != null)
{
pMessage->count = (uint)1;
}
else
{
pMessage->count = (uint)_wsaBufferArray.Length;
}
if (_controlBuffer != null)
{
pMessage->controlBuffer.Pointer = _ptrControlBuffer;
pMessage->controlBuffer.Length = _controlBuffer.Length;
}
pMessage->flags = _socketFlags;
}
}
internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeCloseSocket handle)
{
PrepareIOCPOperation();
int bytesTransferred;
SocketError socketError = socket.WSARecvMsg(
handle,
_ptrWSAMessageBuffer,
out bytesTransferred,
_ptrNativeOverlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred);
}
private void InnerStartOperationSend()
{
// WSASend uses a WSABuffer array describing buffers of data to send.
//
// Single and multiple buffers are handled differently so as to optimize
// performance for the more common single buffer case.
//
// For a single buffer:
// The Overlapped.UnsafePack method is used that takes a single object to pin.
// A single WSABuffer that pre-exists in SocketAsyncEventArgs is used.
//
// For multiple buffers:
// The Overlapped.UnsafePack method is used that takes an array of objects to pin.
// An array to reference the multiple buffer is allocated.
// An array of WSABuffer descriptors is allocated.
}
internal unsafe SocketError DoOperationSend(SafeCloseSocket handle)
{
PrepareIOCPOperation();
SocketError socketError;
int bytesTransferred;
if (_buffer != null)
{
// Single buffer case.
socketError = Interop.Winsock.WSASend(
handle,
ref _wsaBuffer,
1,
out bytesTransferred,
_socketFlags,
_ptrNativeOverlapped,
IntPtr.Zero);
}
else
{
// Multi buffer case.
socketError = Interop.Winsock.WSASend(
handle,
_wsaBufferArray,
_wsaBufferArray.Length,
out bytesTransferred,
_socketFlags,
_ptrNativeOverlapped,
IntPtr.Zero);
}
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred);
}
private void InnerStartOperationSendPackets()
{
// Prevent mutithreaded manipulation of the list.
if (_sendPacketsElements != null)
{
_sendPacketsElementsInternal = (SendPacketsElement[])_sendPacketsElements.Clone();
}
// TransmitPackets uses an array of TRANSMIT_PACKET_ELEMENT structs as
// descriptors for buffers and files to be sent. It also takes a send size
// and some flags. The TRANSMIT_PACKET_ELEMENT for a file contains a native file handle.
// This function basically opens the files to get the file handles, pins down any buffers
// specified and builds the native TRANSMIT_PACKET_ELEMENT array that will be passed
// to TransmitPackets.
// Scan the elements to count files and buffers.
_sendPacketsElementsFileCount = 0;
_sendPacketsElementsBufferCount = 0;
Debug.Assert(_sendPacketsElementsInternal != null);
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null)
{
if (spe._filePath != null)
{
_sendPacketsElementsFileCount++;
}
if (spe._buffer != null && spe._count > 0)
{
_sendPacketsElementsBufferCount++;
}
}
}
// Attempt to open the files if any were given.
if (_sendPacketsElementsFileCount > 0)
{
// Create arrays for streams and handles.
_sendPacketsFileStreams = new FileStream[_sendPacketsElementsFileCount];
_sendPacketsFileHandles = new SafeHandle[_sendPacketsElementsFileCount];
// Loop through the elements attempting to open each files and get its handle.
int index = 0;
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null && spe._filePath != null)
{
Exception fileStreamException = null;
try
{
// Create a FileStream to open the file.
_sendPacketsFileStreams[index] =
new FileStream(spe._filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (Exception ex)
{
// Save the exception to throw after closing any previous successful file opens.
fileStreamException = ex;
}
if (fileStreamException != null)
{
// Got an exception opening a file - do some cleanup then throw.
for (int i = 0; i < _sendPacketsElementsFileCount; i++)
{
// Drop handles.
_sendPacketsFileHandles[i] = null;
// Close any open streams.
if (_sendPacketsFileStreams[i] != null)
{
_sendPacketsFileStreams[i].Dispose();
_sendPacketsFileStreams[i] = null;
}
}
throw fileStreamException;
}
// Get the file handle from the stream.
_sendPacketsFileHandles[index] = _sendPacketsFileStreams[index].SafeFileHandle;
index++;
}
}
}
CheckPinSendPackets();
}
internal SocketError DoOperationSendPackets(Socket socket, SafeCloseSocket handle)
{
PrepareIOCPOperation();
bool result = socket.TransmitPackets(
handle,
_ptrSendPacketsDescriptor,
_sendPacketsDescriptor.Length,
_sendPacketsSendSize,
_ptrNativeOverlapped,
_sendPacketsFlags);
return ProcessIOCPResult(result, 0);
}
private void InnerStartOperationSendTo()
{
// WSASendTo uses a WSABuffer array describing buffers in which to
// receive data and from which to send data respectively. Single and multiple buffers
// are handled differently so as to optimize performance for the more common single buffer case.
//
// For a single buffer:
// The Overlapped.UnsafePack method is used that takes a single object to pin.
// A single WSABuffer that pre-exists in SocketAsyncEventArgs is used.
//
// For multiple buffers:
// The Overlapped.UnsafePack method is used that takes an array of objects to pin.
// An array to reference the multiple buffer is allocated.
// An array of WSABuffer descriptors is allocated.
//
// WSARecvFrom and WSASendTo also uses a sockaddr buffer in which to store the address from which the data was received.
// The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack.
PinSocketAddressBuffer();
}
internal SocketError DoOperationSendTo(SafeCloseSocket handle)
{
PrepareIOCPOperation();
int bytesTransferred;
SocketError socketError;
if (_buffer != null)
{
// Single buffer case.
socketError = Interop.Winsock.WSASendTo(
handle,
ref _wsaBuffer,
1,
out bytesTransferred,
_socketFlags,
_ptrSocketAddressBuffer,
_socketAddress.Size,
_ptrNativeOverlapped,
IntPtr.Zero);
}
else
{
socketError = Interop.Winsock.WSASendTo(
handle,
_wsaBufferArray,
_wsaBufferArray.Length,
out bytesTransferred,
_socketFlags,
_ptrSocketAddressBuffer,
_socketAddress.Size,
_ptrNativeOverlapped,
IntPtr.Zero);
}
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred);
}
// Ensures Overlapped object exists for operations that need no data buffer.
private void CheckPinNoBuffer()
{
// PreAllocatedOverlapped will be reused.
if (_pinState == PinState.None)
{
SetupOverlappedSingle(true);
}
}
// Maintains pinned state of single buffer.
private void CheckPinSingleBuffer(bool pinUsersBuffer)
{
if (pinUsersBuffer)
{
// Using app supplied buffer.
if (_buffer == null)
{
// No user buffer is set so unpin any existing single buffer pinning.
if (_pinState == PinState.SingleBuffer)
{
FreeOverlapped(false);
}
}
else
{
if (_pinState == PinState.SingleBuffer && _pinnedSingleBuffer == _buffer)
{
// This buffer is already pinned - update if offset or count has changed.
if (_offset != _pinnedSingleBufferOffset)
{
_pinnedSingleBufferOffset = _offset;
_ptrSingleBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, _offset);
_wsaBuffer.Pointer = _ptrSingleBuffer;
}
if (_count != _pinnedSingleBufferCount)
{
_pinnedSingleBufferCount = _count;
_wsaBuffer.Length = _count;
}
}
else
{
FreeOverlapped(false);
SetupOverlappedSingle(true);
}
}
}
else
{
// Using internal accept buffer.
if (!(_pinState == PinState.SingleAcceptBuffer) || !(_pinnedSingleBuffer == _acceptBuffer))
{
// Not already pinned - so pin it.
FreeOverlapped(false);
SetupOverlappedSingle(false);
}
}
}
// Ensures Overlapped object exists with appropriate multiple buffers pinned.
private void CheckPinMultipleBuffers()
{
if (_bufferListInternal == null || _bufferListInternal.Count == 0)
{
// No buffer list is set so unpin any existing multiple buffer pinning.
if (_pinState == PinState.MultipleBuffer)
{
FreeOverlapped(false);
}
}
else
{
// Need to setup a new Overlapped.
FreeOverlapped(false);
try
{
SetupOverlappedMultiple();
}
catch (Exception)
{
FreeOverlapped(false);
throw;
}
}
}
// Ensures Overlapped object exists with appropriate buffers pinned.
private void CheckPinSendPackets()
{
if (_pinState != PinState.None)
{
FreeOverlapped(false);
}
SetupOverlappedSendPackets();
}
// Ensures appropriate SocketAddress buffer is pinned.
private void PinSocketAddressBuffer()
{
// Check if already pinned.
if (_pinnedSocketAddress == _socketAddress)
{
return;
}
// Unpin any existing.
if (_socketAddressGCHandle.IsAllocated)
{
_socketAddressGCHandle.Free();
}
// Pin down the new one.
_socketAddressGCHandle = GCHandle.Alloc(_socketAddress.Buffer, GCHandleType.Pinned);
_socketAddress.CopyAddressSizeIntoBuffer();
_ptrSocketAddressBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, 0);
_ptrSocketAddressBufferSize = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, _socketAddress.GetAddressSizeOffset());
_pinnedSocketAddress = _socketAddress;
}
// Cleans up any existing Overlapped object and related state variables.
private void FreeOverlapped(bool checkForShutdown)
{
if (!checkForShutdown || !Environment.HasShutdownStarted)
{
// Free the overlapped object.
if (_ptrNativeOverlapped != null && !_ptrNativeOverlapped.IsInvalid)
{
_ptrNativeOverlapped.Dispose();
_ptrNativeOverlapped = null;
}
// Free the preallocated overlapped object. This in turn will unpin
// any pinned buffers.
if (_preAllocatedOverlapped != null)
{
_preAllocatedOverlapped.Dispose();
_preAllocatedOverlapped = null;
_pinState = PinState.None;
_pinnedAcceptBuffer = null;
_pinnedSingleBuffer = null;
_pinnedSingleBufferOffset = 0;
_pinnedSingleBufferCount = 0;
}
// Free any allocated GCHandles.
if (_socketAddressGCHandle.IsAllocated)
{
_socketAddressGCHandle.Free();
_pinnedSocketAddress = null;
}
if (_wsaMessageBufferGCHandle.IsAllocated)
{
_wsaMessageBufferGCHandle.Free();
_ptrWSAMessageBuffer = IntPtr.Zero;
}
if (_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated)
{
_wsaRecvMsgWSABufferArrayGCHandle.Free();
_ptrWSARecvMsgWSABufferArray = IntPtr.Zero;
}
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
_ptrControlBuffer = IntPtr.Zero;
}
}
}
// Sets up an Overlapped object with either _buffer or _acceptBuffer pinned.
private unsafe void SetupOverlappedSingle(bool pinSingleBuffer)
{
// Pin buffer, get native pointers, and fill in WSABuffer descriptor.
if (pinSingleBuffer)
{
if (_buffer != null)
{
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _buffer);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"new PreAllocatedOverlapped pinSingleBuffer=true, non-null buffer:{_preAllocatedOverlapped}");
_pinnedSingleBuffer = _buffer;
_pinnedSingleBufferOffset = _offset;
_pinnedSingleBufferCount = _count;
_ptrSingleBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, _offset);
_ptrAcceptBuffer = IntPtr.Zero;
_wsaBuffer.Pointer = _ptrSingleBuffer;
_wsaBuffer.Length = _count;
_pinState = PinState.SingleBuffer;
}
else
{
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, null);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"new PreAllocatedOverlapped pinSingleBuffer=true, null buffer: {_preAllocatedOverlapped}");
_pinnedSingleBuffer = null;
_pinnedSingleBufferOffset = 0;
_pinnedSingleBufferCount = 0;
_ptrSingleBuffer = IntPtr.Zero;
_ptrAcceptBuffer = IntPtr.Zero;
_wsaBuffer.Pointer = _ptrSingleBuffer;
_wsaBuffer.Length = _count;
_pinState = PinState.NoBuffer;
}
}
else
{
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _acceptBuffer);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"new PreAllocatedOverlapped pinSingleBuffer=false:{_preAllocatedOverlapped}");
_pinnedAcceptBuffer = _acceptBuffer;
_ptrAcceptBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_acceptBuffer, 0);
_ptrSingleBuffer = IntPtr.Zero;
_pinState = PinState.SingleAcceptBuffer;
}
}
// Sets up an Overlapped object with multiple buffers pinned.
private unsafe void SetupOverlappedMultiple()
{
int bufferCount = _bufferListInternal.Count;
// Number of things to pin is number of buffers.
// Ensure we have properly sized object array.
if (_objectsToPin == null || (_objectsToPin.Length != bufferCount))
{
_objectsToPin = new object[bufferCount];
}
// Fill in object array.
for (int i = 0; i < bufferCount; i++)
{
_objectsToPin[i] = _bufferListInternal[i].Array;
}
if (_wsaBufferArray == null || _wsaBufferArray.Length != bufferCount)
{
_wsaBufferArray = new WSABuffer[bufferCount];
}
// Pin buffers and fill in WSABuffer descriptor pointers and lengths.
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"new PreAllocatedOverlapped.{_preAllocatedOverlapped}");
for (int i = 0; i < bufferCount; i++)
{
ArraySegment<byte> localCopy = _bufferListInternal[i];
RangeValidationHelpers.ValidateSegment(localCopy);
_wsaBufferArray[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(localCopy.Array, localCopy.Offset);
_wsaBufferArray[i].Length = localCopy.Count;
}
_pinState = PinState.MultipleBuffer;
}
// Sets up an Overlapped object for SendPacketsAsync.
private unsafe void SetupOverlappedSendPackets()
{
int index;
// Alloc native descriptor.
_sendPacketsDescriptor =
new Interop.Winsock.TransmitPacketsElement[_sendPacketsElementsFileCount + _sendPacketsElementsBufferCount];
// Number of things to pin is number of buffers + 1 (native descriptor).
// Ensure we have properly sized object array.
if (_objectsToPin == null || (_objectsToPin.Length != _sendPacketsElementsBufferCount + 1))
{
_objectsToPin = new object[_sendPacketsElementsBufferCount + 1];
}
// Fill in objects to pin array. Native descriptor buffer first and then user specified buffers.
_objectsToPin[0] = _sendPacketsDescriptor;
index = 1;
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null && spe._buffer != null && spe._count > 0)
{
_objectsToPin[index] = spe._buffer;
index++;
}
}
// Pin buffers.
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"new PreAllocatedOverlapped:{_preAllocatedOverlapped}");
// Get pointer to native descriptor.
_ptrSendPacketsDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(_sendPacketsDescriptor, 0);
// Fill in native descriptor.
int descriptorIndex = 0;
int fileIndex = 0;
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null)
{
if (spe._buffer != null && spe._count > 0)
{
// This element is a buffer.
_sendPacketsDescriptor[descriptorIndex].buffer = Marshal.UnsafeAddrOfPinnedArrayElement(spe._buffer, spe._offset);
_sendPacketsDescriptor[descriptorIndex].length = (uint)spe._count;
_sendPacketsDescriptor[descriptorIndex].flags = (Interop.Winsock.TransmitPacketsElementFlags)spe._flags;
descriptorIndex++;
}
else if (spe._filePath != null)
{
// This element is a file.
_sendPacketsDescriptor[descriptorIndex].fileHandle = _sendPacketsFileHandles[fileIndex].DangerousGetHandle();
_sendPacketsDescriptor[descriptorIndex].fileOffset = spe._offset;
_sendPacketsDescriptor[descriptorIndex].length = (uint)spe._count;
_sendPacketsDescriptor[descriptorIndex].flags = (Interop.Winsock.TransmitPacketsElementFlags)spe._flags;
fileIndex++;
descriptorIndex++;
}
}
}
_pinState = PinState.SendPackets;
}
internal void LogBuffer(int size)
{
if (!NetEventSource.IsEnabled) return;
switch (_pinState)
{
case PinState.SingleAcceptBuffer:
NetEventSource.DumpBuffer(this, _acceptBuffer, 0, size);
break;
case PinState.SingleBuffer:
NetEventSource.DumpBuffer(this, _buffer, _offset, size);
break;
case PinState.MultipleBuffer:
foreach (WSABuffer wsaBuffer in _wsaBufferArray)
{
NetEventSource.DumpBuffer(this, wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size));
if ((size -= wsaBuffer.Length) <= 0)
{
break;
}
}
break;
default:
break;
}
}
internal void LogSendPacketsBuffers(int size)
{
if (!NetEventSource.IsEnabled) return;
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null)
{
if (spe._buffer != null && spe._count > 0)
{
// This element is a buffer.
NetEventSource.DumpBuffer(this, spe._buffer, spe._offset, Math.Min(spe._count, size));
}
else if (spe._filePath != null)
{
// This element is a file.
NetEventSource.NotLoggedFile(spe._filePath, _currentSocket, _completedOperation);
}
}
}
}
private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress)
{
SocketError socketError;
IntPtr localAddr;
int localAddrLength;
IntPtr remoteAddr;
try
{
_currentSocket.GetAcceptExSockaddrs(
_ptrSingleBuffer != IntPtr.Zero ? _ptrSingleBuffer : _ptrAcceptBuffer,
_count != 0 ? _count - _acceptAddressBufferCount : 0,
_acceptAddressBufferCount / 2,
_acceptAddressBufferCount / 2,
out localAddr,
out localAddrLength,
out remoteAddr,
out remoteSocketAddress.InternalSize
);
Marshal.Copy(remoteAddr, remoteSocketAddress.Buffer, 0, remoteSocketAddress.Size);
// Set the socket context.
IntPtr handle = _currentSocket.SafeHandle.DangerousGetHandle();
socketError = Interop.Winsock.setsockopt(
_acceptSocket.SafeHandle,
SocketOptionLevel.Socket,
SocketOptionName.UpdateAcceptContext,
ref handle,
IntPtr.Size);
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
}
catch (ObjectDisposedException)
{
socketError = SocketError.OperationAborted;
}
return socketError;
}
private SocketError FinishOperationConnect()
{
SocketError socketError;
// Update the socket context.
try
{
socketError = Interop.Winsock.setsockopt(
_currentSocket.SafeHandle,
SocketOptionLevel.Socket,
SocketOptionName.UpdateConnectContext,
null,
0);
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
}
catch (ObjectDisposedException)
{
socketError = SocketError.OperationAborted;
}
return socketError;
}
private unsafe int GetSocketAddressSize()
{
return *(int*)_ptrSocketAddressBufferSize;
}
private unsafe void FinishOperationReceiveMessageFrom()
{
Interop.Winsock.WSAMsg* PtrMessage = (Interop.Winsock.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0);
if (_controlBuffer.Length == sizeof(Interop.Winsock.ControlData))
{
// IPv4.
_receiveMessageFromPacketInfo = SocketPal.GetIPPacketInformation((Interop.Winsock.ControlData*)PtrMessage->controlBuffer.Pointer);
}
else if (_controlBuffer.Length == sizeof(Interop.Winsock.ControlDataIPv6))
{
// IPv6.
_receiveMessageFromPacketInfo = SocketPal.GetIPPacketInformation((Interop.Winsock.ControlDataIPv6*)PtrMessage->controlBuffer.Pointer);
}
else
{
// Other.
_receiveMessageFromPacketInfo = new IPPacketInformation();
}
}
private void FinishOperationSendPackets()
{
// Close the files if open.
if (_sendPacketsFileStreams != null)
{
for (int i = 0; i < _sendPacketsElementsFileCount; i++)
{
// Drop handles.
_sendPacketsFileHandles[i] = null;
// Close any open streams.
if (_sendPacketsFileStreams[i] != null)
{
_sendPacketsFileStreams[i].Dispose();
_sendPacketsFileStreams[i] = null;
}
}
}
_sendPacketsFileStreams = null;
_sendPacketsFileHandles = null;
}
private unsafe void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
{
#if DEBUG
DebugThreadTracking.SetThreadSource(ThreadKinds.CompletionPort);
using (DebugThreadTracking.SetThreadKind(ThreadKinds.System))
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"errorCode:{errorCode}, numBytes:{numBytes}, overlapped:{(IntPtr)nativeOverlapped}");
#endif
SocketFlags socketFlags = SocketFlags.None;
SocketError socketError = (SocketError)errorCode;
// This is the same NativeOverlapped* as we already have a SafeHandle for, re-use the original.
Debug.Assert((IntPtr)nativeOverlapped == _ptrNativeOverlapped.DangerousGetHandle(), "Handle mismatch");
if (socketError == SocketError.Success)
{
FinishOperationAsyncSuccess((int)numBytes, SocketFlags.None);
}
else
{
if (socketError != SocketError.OperationAborted)
{
if (_currentSocket.CleanedUp)
{
socketError = SocketError.OperationAborted;
}
else
{
try
{
// The Async IO completed with a failure.
// here we need to call WSAGetOverlappedResult() just so GetLastSocketError() will return the correct error.
bool success = Interop.Winsock.WSAGetOverlappedResult(
_currentSocket.SafeHandle,
_ptrNativeOverlapped,
out numBytes,
false,
out socketFlags);
socketError = SocketPal.GetLastSocketError();
}
catch
{
// _currentSocket.CleanedUp check above does not always work since this code is subject to race conditions.
socketError = SocketError.OperationAborted;
}
}
}
FinishOperationAsyncFailure(socketError, (int)numBytes, socketFlags);
}
#if DEBUG
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
#endif
}
}
}
| |
//
// TreeView.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Drawing;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Xwt.Backends;
namespace Xwt
{
[BackendType (typeof(ITreeViewBackend))]
public class TreeView: Widget, IColumnContainer, IScrollableWidget
{
ListViewColumnCollection columns;
ITreeDataSource dataSource;
SelectionMode mode;
protected new class WidgetBackendHost: Widget.WidgetBackendHost<TreeView,ITreeViewBackend>, ITreeViewEventSink
{
protected override void OnBackendCreated ()
{
base.OnBackendCreated ();
Backend.Initialize (this);
Parent.columns.Attach (Backend);
}
public void OnSelectionChanged ()
{
((TreeView)Parent).OnSelectionChanged (EventArgs.Empty);
}
public void OnRowActivated (TreePosition position)
{
((TreeView)Parent).OnRowActivated (new TreeViewRowEventArgs (position));
}
public void OnRowExpanded (TreePosition position)
{
((TreeView)Parent).OnRowExpanded (new TreeViewRowEventArgs (position));
}
public void OnRowExpanding (TreePosition position)
{
((TreeView)Parent).OnRowExpanding (new TreeViewRowEventArgs (position));
}
public void OnRowCollapsed (TreePosition position)
{
((TreeView)Parent).OnRowCollapsed (new TreeViewRowEventArgs (position));
}
public void OnRowCollapsing (TreePosition position)
{
((TreeView)Parent).OnRowCollapsing (new TreeViewRowEventArgs (position));
}
public override Size GetDefaultNaturalSize ()
{
return Xwt.Backends.DefaultNaturalSizes.TreeView;
}
public void ColumnHeaderClicked(object handle)
{
return; // treeview sorting todo
}
}
static TreeView ()
{
MapEvent (TableViewEvent.SelectionChanged, typeof(TreeView), "OnSelectionChanged");
MapEvent (TreeViewEvent.RowActivated, typeof(TreeView), "OnRowActivated");
MapEvent (TreeViewEvent.RowExpanded, typeof(TreeView), "OnRowExpanded");
MapEvent (TreeViewEvent.RowExpanding, typeof(TreeView), "OnRowExpanding");
MapEvent (TreeViewEvent.RowCollapsed, typeof(TreeView), "OnRowCollapsed");
MapEvent (TreeViewEvent.RowCollapsing, typeof(TreeView), "OnRowCollapsing");
}
/// <summary>
/// Initializes a new instance of the <see cref="Xwt.TreeView"/> class.
/// </summary>
public TreeView ()
{
columns = new ListViewColumnCollection (this);
VerticalScrollPolicy = HorizontalScrollPolicy = ScrollPolicy.Automatic;
}
/// <summary>
/// Initializes a new instance of the <see cref="Xwt.TreeView"/> class.
/// </summary>
/// <param name='source'>
/// Data source
/// </param>
public TreeView (ITreeDataSource source): this ()
{
VerifyConstructorCall (this);
DataSource = source;
}
protected override BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
ITreeViewBackend Backend {
get { return (ITreeViewBackend) BackendHost.Backend; }
}
public ScrollPolicy VerticalScrollPolicy {
get { return Backend.VerticalScrollPolicy; }
set { Backend.VerticalScrollPolicy = value; }
}
public ScrollPolicy HorizontalScrollPolicy {
get { return Backend.HorizontalScrollPolicy; }
set { Backend.HorizontalScrollPolicy = value; }
}
ScrollControl verticalScrollAdjustment;
public ScrollControl VerticalScrollControl {
get {
if (verticalScrollAdjustment == null)
verticalScrollAdjustment = new ScrollControl (Backend.CreateVerticalScrollControl ());
return verticalScrollAdjustment;
}
}
ScrollControl horizontalScrollAdjustment;
public ScrollControl HorizontalScrollControl {
get {
if (horizontalScrollAdjustment == null)
horizontalScrollAdjustment = new ScrollControl (Backend.CreateHorizontalScrollControl ());
return horizontalScrollAdjustment;
}
}
/// <summary>
/// Gets the tree columns.
/// </summary>
/// <value>
/// The columns.
/// </value>
public ListViewColumnCollection Columns {
get {
return columns;
}
}
/// <summary>
/// Gets or sets the data source.
/// </summary>
/// <value>
/// The data source.
/// </value>
public ITreeDataSource DataSource {
get {
return dataSource;
}
set {
if (dataSource != value) {
Backend.SetSource (value, value is IFrontend ? (IBackend)BackendHost.ToolkitEngine.GetSafeBackend (value) : null);
dataSource = value;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether headers are visible or not.
/// </summary>
/// <value>
/// <c>true</c> if headers are visible; otherwise, <c>false</c>.
/// </value>
public bool HeadersVisible {
get {
return Backend.HeadersVisible;
}
set {
Backend.HeadersVisible = value;
}
}
public GridLines GridLinesVisible
{
get { return Backend.GridLinesVisible; }
set { Backend.GridLinesVisible = value; }
}
/// <summary>
/// Gets or sets the selection mode.
/// </summary>
/// <value>
/// The selection mode.
/// </value>
public SelectionMode SelectionMode {
get {
return mode;
}
set {
mode = value;
Backend.SetSelectionMode (mode);
}
}
/// <summary>
/// Gets or sets the row the current event applies to.
/// The behavior of this property is undefined when used outside an
/// event that supports it.
/// </summary>
/// <value>
/// The current event row.
/// </value>
public TreePosition CurrentEventRow {
get {
return Backend.CurrentEventRow;
}
}
/// <summary>
/// Gets the selected row.
/// </summary>
/// <value>
/// The selected row.
/// </value>
public TreePosition SelectedRow {
get {
var items = SelectedRows;
if (items.Length == 0)
return null;
else
return items [0];
}
}
/// <summary>
/// Gets the selected rows.
/// </summary>
/// <value>
/// The selected rows.
/// </value>
public TreePosition[] SelectedRows {
get {
return Backend.SelectedRows;
}
}
/// <summary>
/// Gets or sets the focused row.
/// </summary>
/// <value>The row with the keyboard focus.</value>
public TreePosition FocusedRow {
get {
return Backend.FocusedRow;
}
set {
Backend.FocusedRow = value;
}
}
/// <summary>
/// Selects a row.
/// </summary>
/// <param name='pos'>
/// Position of the row
/// </param>
public void SelectRow (TreePosition pos)
{
Backend.SelectRow (pos);
}
/// <summary>
/// Unselects a row.
/// </summary>
/// <param name='pos'>
/// Position of the row
/// </param>
public void UnselectRow (TreePosition pos)
{
Backend.UnselectRow (pos);
}
/// <summary>
/// Selects all rows
/// </summary>
public void SelectAll ()
{
Backend.SelectAll ();
}
/// <summary>
/// Unselects all rows
/// </summary>
public void UnselectAll ()
{
Backend.UnselectAll ();
}
/// <summary>
/// Determines whether the row at the specified position is selected
/// </summary>
/// <returns>
/// <c>true</c> if the row is selected, <c>false</c> otherwise.
/// </returns>
/// <param name='pos'>
/// Row position
/// </param>
public bool IsRowSelected (TreePosition pos)
{
return Backend.IsRowSelected (pos);
}
/// <summary>
/// Determines whether the row at the specified position is expanded
/// </summary>
/// <returns>
/// <c>true</c> if the row is expanded, <c>false</c> otherwise.
/// </returns>
/// <param name='pos'>
/// Row position
/// </param>
public bool IsRowExpanded (TreePosition pos)
{
return Backend.IsRowExpanded (pos);
}
/// <summary>
/// Expands a row.
/// </summary>
/// <param name='pos'>
/// Position of the row
/// </param>
/// <param name='expandChildren'>
/// If True, all children are recursively expanded
/// </param>
public void ExpandRow (TreePosition pos, bool expandChildren)
{
Backend.ExpandRow (pos, expandChildren);
}
/// <summary>
/// Collapses a row.
/// </summary>
/// <param name='pos'>
/// Position of the row
/// </param>
public void CollapseRow (TreePosition pos)
{
Backend.CollapseRow (pos);
}
/// <summary>
/// Recursively expands all nodes of the tree
/// </summary>
public void ExpandAll ()
{
if (DataSource != null) {
var nc = DataSource.GetChildrenCount (null);
for (int n=0; n<nc; n++) {
var p = DataSource.GetChild (null, n);
Backend.ExpandRow (p, true);
}
}
}
/// <summary>
/// Saves the status of the tree
/// </summary>
/// <returns>
/// A status object
/// </returns>
/// <param name='idField'>
/// Field to be used to identify each row
/// </param>
/// <remarks>
/// The status information includes node expansion and selection status. The returned object
/// can be used to restore the status by calling RestoreStatus.
/// The provided field is used to generate an identifier for each row. When restoring the
/// status, those ids are used to find matching rows.
/// </remarks>
public TreeViewStatus SaveStatus (IDataField idField)
{
return new TreeViewStatus (this, idField.Index);
}
/// <summary>
/// Restores the status of the tree
/// </summary>
/// <param name='status'>
/// Status object
/// </param>
/// <remarks>
/// The status information includes node expansion and selection status. The provided object
/// must have been generated with a SaveStatus call on this same tree.
/// </remarks>
public void RestoreStatus (TreeViewStatus status)
{
status.Load (this);
}
public void ScrollToRow (TreePosition pos)
{
Backend.ScrollToRow (pos);
}
public void ExpandToRow (TreePosition pos)
{
Backend.ExpandToRow (pos);
}
/// <summary>
/// Returns the row at the given widget coordinates
/// </summary>
/// <returns>The row index</returns>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
public TreePosition GetRowAtPosition (double x, double y)
{
return GetRowAtPosition (new Point (x, y));
}
/// <summary>
/// Returns the row at the given widget coordinates
/// </summary>
/// <returns>The row index</returns>
/// <param name="p">A position, in widget coordinates</param>
public TreePosition GetRowAtPosition (Point p)
{
return Backend.GetRowAtPosition (p);
}
/// <summary>
/// Gets the bounds of a cell inside the row at the given position.
/// </summary>
/// <returns>The cell bounds inside the widget, relative to the widget bounds.</returns>
/// <param name="pos">The node position.</param>
/// <param name="cell">The cell view.</param>
/// <param name="includeMargin">If set to <c>true</c> include margin (the background of the row).</param>
public Rectangle GetCellBounds (TreePosition pos, CellView cell, bool includeMargin)
{
return Backend.GetCellBounds (pos, cell, includeMargin);
}
/// <summary>
/// Gets the bounds of the row at the given position.
/// </summary>
/// <returns>The row bounds inside the widget, relative to the widget bounds.</returns>
/// <param name="pos">The node position.</param>
/// <param name="includeMargin">If set to <c>true</c> include margin (the background of the row).</param>
public Rectangle GetRowBounds (TreePosition pos, bool includeMargin)
{
return Backend.GetRowBounds (pos, includeMargin);
}
public bool GetDropTargetRow (double x, double y, out RowDropPosition pos, out TreePosition nodePosition)
{
return Backend.GetDropTargetRow (x, y, out pos, out nodePosition);
}
internal protected sealed override bool SupportsCustomScrolling {
get {
return false;
}
}
void IColumnContainer.NotifyColumnsChanged ()
{
}
/// <summary>
/// Raises the selection changed event.
/// </summary>
/// <param name='a'>
/// Event arguments
/// </param>
protected virtual void OnSelectionChanged (EventArgs a)
{
if (selectionChanged != null)
selectionChanged (this, a);
}
EventHandler selectionChanged;
/// <summary>
/// Occurs when the selection changes
/// </summary>
public event EventHandler SelectionChanged {
add {
BackendHost.OnBeforeEventAdd (TableViewEvent.SelectionChanged, selectionChanged);
selectionChanged += value;
}
remove {
selectionChanged -= value;
BackendHost.OnAfterEventRemove (TableViewEvent.SelectionChanged, selectionChanged);
}
}
/// <summary>
/// Raises the row activated event.
/// </summary>
/// <param name="a">The alpha component.</param>
protected virtual void OnRowActivated (TreeViewRowEventArgs a)
{
if (rowActivated != null)
rowActivated (this, a);
}
EventHandler<TreeViewRowEventArgs> rowActivated;
/// <summary>
/// Occurs when the user double-clicks on a row
/// </summary>
public event EventHandler<TreeViewRowEventArgs> RowActivated {
add {
BackendHost.OnBeforeEventAdd (TreeViewEvent.RowActivated, rowActivated);
rowActivated += value;
}
remove {
rowActivated -= value;
BackendHost.OnAfterEventRemove (TreeViewEvent.RowActivated, rowActivated);
}
}
/// <summary>
/// Raises the row expanding event.
/// </summary>
/// <param name="a">The alpha component.</param>
protected virtual void OnRowExpanding (TreeViewRowEventArgs a)
{
if (rowExpanding != null)
rowExpanding (this, a);
}
EventHandler<TreeViewRowEventArgs> rowExpanding;
/// <summary>
/// Occurs just before a row is expanded
/// </summary>
public event EventHandler<TreeViewRowEventArgs> RowExpanding {
add {
BackendHost.OnBeforeEventAdd (TreeViewEvent.RowExpanding, rowExpanding);
rowExpanding += value;
}
remove {
rowExpanding -= value;
BackendHost.OnAfterEventRemove (TreeViewEvent.RowExpanding, rowExpanding);
}
}
/// <summary>
/// Raises the row expanding event.
/// </summary>
/// <param name="a">The alpha component.</param>
protected virtual void OnRowExpanded (TreeViewRowEventArgs a)
{
if (rowExpanded != null)
rowExpanded (this, a);
}
EventHandler<TreeViewRowEventArgs> rowExpanded;
/// <summary>
/// Occurs just before a row is expanded
/// </summary>
public event EventHandler<TreeViewRowEventArgs> RowExpanded {
add {
BackendHost.OnBeforeEventAdd (TreeViewEvent.RowExpanded, rowExpanded);
rowExpanded += value;
}
remove {
rowExpanded -= value;
BackendHost.OnAfterEventRemove (TreeViewEvent.RowExpanded, rowExpanded);
}
}
/// <summary>
/// Raises the row collapsing event.
/// </summary>
/// <param name="a">The alpha component.</param>
protected virtual void OnRowCollapsing (TreeViewRowEventArgs a)
{
if (rowCollapsing != null)
rowCollapsing (this, a);
}
EventHandler<TreeViewRowEventArgs> rowCollapsing;
/// <summary>
/// Occurs just before a row is collapsed.
/// </summary>
public event EventHandler<TreeViewRowEventArgs> RowCollapsing {
add {
BackendHost.OnBeforeEventAdd (TreeViewEvent.RowCollapsing, rowCollapsing);
rowCollapsing += value;
}
remove {
rowCollapsing -= value;
BackendHost.OnAfterEventRemove (TreeViewEvent.RowCollapsing, rowCollapsing);
}
}
/// <summary>
/// Raises the row collapsing event.
/// </summary>
/// <param name="a">The alpha component.</param>
protected virtual void OnRowCollapsed (TreeViewRowEventArgs a)
{
if (rowCollapsed != null)
rowCollapsed (this, a);
}
EventHandler<TreeViewRowEventArgs> rowCollapsed;
/// <summary>
/// Occurs just before a row is collapsed
/// </summary>
public event EventHandler<TreeViewRowEventArgs> RowCollapsed {
add {
BackendHost.OnBeforeEventAdd (TreeViewEvent.RowCollapsed, rowCollapsed);
rowCollapsed += value;
}
remove {
rowCollapsed -= value;
BackendHost.OnAfterEventRemove (TreeViewEvent.RowCollapsed, rowCollapsed);
}
}
}
interface IColumnContainer
{
void NotifyColumnsChanged ();
}
interface ICellContainer
{
void NotifyCellChanged ();
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Cdn
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for EndpointsOperations.
/// </summary>
public static partial class EndpointsOperationsExtensions
{
/// <summary>
/// Lists existing CDN endpoints.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
public static IPage<Endpoint> ListByProfile(this IEndpointsOperations operations, string resourceGroupName, string profileName)
{
return operations.ListByProfileAsync(resourceGroupName, profileName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists existing CDN endpoints.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Endpoint>> ListByProfileAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByProfileWithHttpMessagesAsync(resourceGroupName, profileName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets an existing CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
public static Endpoint Get(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName)
{
return operations.GetAsync(resourceGroupName, profileName, endpointName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets an existing CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> GetAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='endpoint'>
/// Endpoint properties
/// </param>
public static Endpoint Create(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, Endpoint endpoint)
{
return operations.CreateAsync(resourceGroupName, profileName, endpointName, endpoint).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='endpoint'>
/// Endpoint properties
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> CreateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, Endpoint endpoint, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, endpoint, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile. Only tags and Origin
/// HostHeader can be updated after creating an endpoint. To update origins,
/// use the Update Origin operation. To update custom domains, use the Update
/// Custom Domain operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='endpointUpdateProperties'>
/// Endpoint update properties
/// </param>
public static Endpoint Update(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, EndpointUpdateParameters endpointUpdateProperties)
{
return operations.UpdateAsync(resourceGroupName, profileName, endpointName, endpointUpdateProperties).GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile. Only tags and Origin
/// HostHeader can be updated after creating an endpoint. To update origins,
/// use the Update Origin operation. To update custom domains, use the Update
/// Custom Domain operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='endpointUpdateProperties'>
/// Endpoint update properties
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> UpdateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, EndpointUpdateParameters endpointUpdateProperties, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, endpointUpdateProperties, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an existing CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
public static void Delete(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName)
{
operations.DeleteAsync(resourceGroupName, profileName, endpointName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Starts an existing CDN endpoint that is on a stopped state.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
public static Endpoint Start(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName)
{
return operations.StartAsync(resourceGroupName, profileName, endpointName).GetAwaiter().GetResult();
}
/// <summary>
/// Starts an existing CDN endpoint that is on a stopped state.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> StartAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.StartWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Stops an existing running CDN endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
public static Endpoint Stop(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName)
{
return operations.StopAsync(resourceGroupName, profileName, endpointName).GetAwaiter().GetResult();
}
/// <summary>
/// Stops an existing running CDN endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> StopAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.StopWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Removes a content from CDN.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be purged. Can describe a file path or a wild
/// card directory.
/// </param>
public static void PurgeContent(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, IList<string> contentPaths)
{
operations.PurgeContentAsync(resourceGroupName, profileName, endpointName, contentPaths).GetAwaiter().GetResult();
}
/// <summary>
/// Removes a content from CDN.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be purged. Can describe a file path or a wild
/// card directory.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PurgeContentAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, IList<string> contentPaths, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PurgeContentWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, contentPaths, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Pre-loads a content to CDN. Available for Verizon Profiles.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be loaded. Path should be a relative file URL of
/// the origin.
/// </param>
public static void LoadContent(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, IList<string> contentPaths)
{
operations.LoadContentAsync(resourceGroupName, profileName, endpointName, contentPaths).GetAwaiter().GetResult();
}
/// <summary>
/// Pre-loads a content to CDN. Available for Verizon Profiles.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be loaded. Path should be a relative file URL of
/// the origin.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task LoadContentAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, IList<string> contentPaths, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.LoadContentWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, contentPaths, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Validates the custom domain mapping to ensure it maps to the correct CDN
/// endpoint in DNS.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='hostName'>
/// The host name of the custom domain. Must be a domain name.
/// </param>
public static ValidateCustomDomainOutput ValidateCustomDomain(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, string hostName)
{
return operations.ValidateCustomDomainAsync(resourceGroupName, profileName, endpointName, hostName).GetAwaiter().GetResult();
}
/// <summary>
/// Validates the custom domain mapping to ensure it maps to the correct CDN
/// endpoint in DNS.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='hostName'>
/// The host name of the custom domain. Must be a domain name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ValidateCustomDomainOutput> ValidateCustomDomainAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, string hostName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ValidateCustomDomainWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, hostName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Checks the quota and usage of geo filters and custom domains under the
/// given endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
public static IPage<ResourceUsage> ListResourceUsage(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName)
{
return operations.ListResourceUsageAsync(resourceGroupName, profileName, endpointName).GetAwaiter().GetResult();
}
/// <summary>
/// Checks the quota and usage of geo filters and custom domains under the
/// given endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ResourceUsage>> ListResourceUsageAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListResourceUsageWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='endpoint'>
/// Endpoint properties
/// </param>
public static Endpoint BeginCreate(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, Endpoint endpoint)
{
return operations.BeginCreateAsync(resourceGroupName, profileName, endpointName, endpoint).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='endpoint'>
/// Endpoint properties
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> BeginCreateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, Endpoint endpoint, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, endpoint, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile. Only tags and Origin
/// HostHeader can be updated after creating an endpoint. To update origins,
/// use the Update Origin operation. To update custom domains, use the Update
/// Custom Domain operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='endpointUpdateProperties'>
/// Endpoint update properties
/// </param>
public static Endpoint BeginUpdate(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, EndpointUpdateParameters endpointUpdateProperties)
{
return operations.BeginUpdateAsync(resourceGroupName, profileName, endpointName, endpointUpdateProperties).GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile. Only tags and Origin
/// HostHeader can be updated after creating an endpoint. To update origins,
/// use the Update Origin operation. To update custom domains, use the Update
/// Custom Domain operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='endpointUpdateProperties'>
/// Endpoint update properties
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> BeginUpdateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, EndpointUpdateParameters endpointUpdateProperties, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, endpointUpdateProperties, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an existing CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
public static void BeginDelete(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName)
{
operations.BeginDeleteAsync(resourceGroupName, profileName, endpointName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing CDN endpoint with the specified endpoint name under the
/// specified subscription, resource group and profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Starts an existing CDN endpoint that is on a stopped state.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
public static Endpoint BeginStart(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName)
{
return operations.BeginStartAsync(resourceGroupName, profileName, endpointName).GetAwaiter().GetResult();
}
/// <summary>
/// Starts an existing CDN endpoint that is on a stopped state.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> BeginStartAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginStartWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Stops an existing running CDN endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
public static Endpoint BeginStop(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName)
{
return operations.BeginStopAsync(resourceGroupName, profileName, endpointName).GetAwaiter().GetResult();
}
/// <summary>
/// Stops an existing running CDN endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> BeginStopAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginStopWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Removes a content from CDN.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be purged. Can describe a file path or a wild
/// card directory.
/// </param>
public static void BeginPurgeContent(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, IList<string> contentPaths)
{
operations.BeginPurgeContentAsync(resourceGroupName, profileName, endpointName, contentPaths).GetAwaiter().GetResult();
}
/// <summary>
/// Removes a content from CDN.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be purged. Can describe a file path or a wild
/// card directory.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginPurgeContentAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, IList<string> contentPaths, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginPurgeContentWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, contentPaths, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Pre-loads a content to CDN. Available for Verizon Profiles.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be loaded. Path should be a relative file URL of
/// the origin.
/// </param>
public static void BeginLoadContent(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, IList<string> contentPaths)
{
operations.BeginLoadContentAsync(resourceGroupName, profileName, endpointName, contentPaths).GetAwaiter().GetResult();
}
/// <summary>
/// Pre-loads a content to CDN. Available for Verizon Profiles.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='contentPaths'>
/// The path to the content to be loaded. Path should be a relative file URL of
/// the origin.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginLoadContentAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, IList<string> contentPaths, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginLoadContentWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, contentPaths, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Lists existing CDN endpoints.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Endpoint> ListByProfileNext(this IEndpointsOperations operations, string nextPageLink)
{
return operations.ListByProfileNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists existing CDN endpoints.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Endpoint>> ListByProfileNextAsync(this IEndpointsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByProfileNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Checks the quota and usage of geo filters and custom domains under the
/// given endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ResourceUsage> ListResourceUsageNext(this IEndpointsOperations operations, string nextPageLink)
{
return operations.ListResourceUsageNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Checks the quota and usage of geo filters and custom domains under the
/// given endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ResourceUsage>> ListResourceUsageNextAsync(this IEndpointsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListResourceUsageNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2007 - 2020 Microting A/S
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microting.eForm.Infrastructure.Constants;
using Microting.eForm.Infrastructure.Data.Entities;
using NUnit.Framework;
namespace eFormSDK.Base.Tests
{
[TestFixture]
public class UnitsUTest : DbTestFixture
{
[Test]
public async Task Units_Create_DoesCreate()
{
//Arrange
Random rnd = new Random();
Site site = new Site
{
Name = Guid.NewGuid().ToString(),
MicrotingUid = rnd.Next(1, 255)
};
await site.Create(DbContext).ConfigureAwait(false);
Unit unit = new Unit
{
CustomerNo = rnd.Next(1, 255),
MicrotingUid = rnd.Next(1, 255),
OtpCode = rnd.Next(1, 255),
Site = site,
SiteId = site.Id,
Manufacturer = Guid.NewGuid().ToString(),
Model = Guid.NewGuid().ToString(),
Note = Guid.NewGuid().ToString(),
eFormVersion = Guid.NewGuid().ToString(),
InSightVersion = Guid.NewGuid().ToString()
};
//Act
await unit.Create(DbContext).ConfigureAwait(false);
List<Unit> units = DbContext.Units.AsNoTracking().ToList();
List<UnitVersion> unitsVersions = DbContext.UnitVersions.AsNoTracking().ToList();
//Assert
Assert.NotNull(units);
Assert.NotNull(unitsVersions);
Assert.AreEqual(1, units.Count());
Assert.AreEqual(1, unitsVersions.Count());
Assert.AreEqual(unit.CustomerNo, units[0].CustomerNo);
Assert.AreEqual(unit.MicrotingUid, units[0].MicrotingUid);
Assert.AreEqual(unit.OtpCode, units[0].OtpCode);
Assert.AreEqual(unit.SiteId, site.Id);
Assert.AreEqual(units[0].WorkflowState, Constants.WorkflowStates.Created);
Assert.AreEqual(unit.CreatedAt.ToString(), units[0].CreatedAt.ToString());
Assert.AreEqual(unit.Version, units[0].Version);
Assert.AreEqual(unit.Id, units[0].Id);
// Assert.AreEqual(unit.UpdatedAt.ToString(), units[0].UpdatedAt.ToString());
Assert.AreEqual(unit.Model , units[0].Model);
Assert.AreEqual(unit.Manufacturer , units[0].Manufacturer);
Assert.AreEqual(unit.eFormVersion , units[0].eFormVersion);
Assert.AreEqual(unit.InSightVersion , units[0].InSightVersion);
Assert.AreEqual(unit.Note , units[0].Note);
//Versions
Assert.AreEqual(unit.CustomerNo, unitsVersions[0].CustomerNo);
Assert.AreEqual(unit.MicrotingUid, unitsVersions[0].MicrotingUid);
Assert.AreEqual(unit.OtpCode, unitsVersions[0].OtpCode);
Assert.AreEqual(site.Id, unitsVersions[0].SiteId);
Assert.AreEqual(unitsVersions[0].WorkflowState, Constants.WorkflowStates.Created);
Assert.AreEqual(unit.CreatedAt.ToString(), unitsVersions[0].CreatedAt.ToString());
Assert.AreEqual(1, unitsVersions[0].Version);
Assert.AreEqual(unit.Id, unitsVersions[0].Id);
// Assert.AreEqual(unit.UpdatedAt.ToString(), unitsVersions[0].UpdatedAt.ToString());
Assert.AreEqual(unit.Model , unitsVersions[0].Model);
Assert.AreEqual(unit.Manufacturer , unitsVersions[0].Manufacturer);
Assert.AreEqual(unit.eFormVersion , unitsVersions[0].eFormVersion);
Assert.AreEqual(unit.InSightVersion , unitsVersions[0].InSightVersion);
Assert.AreEqual(unit.Note , unitsVersions[0].Note);
}
[Test]
public async Task Units_Update_DoesUpdate()
{
//Arrange
Random rnd = new Random();
Site site = new Site
{
Name = Guid.NewGuid().ToString(),
MicrotingUid = rnd.Next(1, 255)
};
await site.Create(DbContext).ConfigureAwait(false);
Unit unit = new Unit
{
CustomerNo = rnd.Next(1, 255),
MicrotingUid = rnd.Next(1, 255),
OtpCode = rnd.Next(1, 255),
Site = site,
SiteId = site.Id,
Manufacturer = Guid.NewGuid().ToString(),
Model = Guid.NewGuid().ToString(),
Note = Guid.NewGuid().ToString(),
eFormVersion = Guid.NewGuid().ToString(),
InSightVersion = Guid.NewGuid().ToString()
};
await unit.Create(DbContext).ConfigureAwait(false);
//Act
int? oldCustomerNo = unit.CustomerNo;
int? oldMicrotingUid = unit.MicrotingUid;
int? oldOtpCode = unit.OtpCode;
int? oldSiteId = unit.SiteId;
DateTime? oldUpdatedAt = unit.UpdatedAt;
int? oldId = unit.Id;
string oldManufacturer = unit.Manufacturer;
string oldModel = unit.Model;
string oldNote = unit.Note;
string unitEFormVersion = unit.eFormVersion;
string unitInSightVersion = unit.InSightVersion;
unit.CustomerNo = rnd.Next(1, 255);
unit.MicrotingUid = rnd.Next(1, 255);
unit.OtpCode = rnd.Next(1, 255);
await unit.Update(DbContext).ConfigureAwait(false);
List<Unit> units = DbContext.Units.AsNoTracking().ToList();
List<UnitVersion> unitsVersions = DbContext.UnitVersions.AsNoTracking().ToList();
//Assert
Assert.NotNull(units);
Assert.NotNull(unitsVersions);
Assert.AreEqual(1, units.Count());
Assert.AreEqual(2, unitsVersions.Count());
Assert.AreEqual(unit.CustomerNo, units[0].CustomerNo);
Assert.AreEqual(unit.MicrotingUid, units[0].MicrotingUid);
Assert.AreEqual(unit.OtpCode, units[0].OtpCode);
Assert.AreEqual(unit.SiteId, site.Id);
Assert.AreEqual(unit.CreatedAt.ToString(), units[0].CreatedAt.ToString());
Assert.AreEqual(unit.Version, units[0].Version);
// Assert.AreEqual(unit.UpdatedAt.ToString(), units[0].UpdatedAt.ToString());
Assert.AreEqual(unit.Id, units[0].Id);
Assert.AreEqual(unit.Model , units[0].Model);
Assert.AreEqual(unit.Manufacturer , units[0].Manufacturer);
Assert.AreEqual(unit.eFormVersion , units[0].eFormVersion);
Assert.AreEqual(unit.InSightVersion , units[0].InSightVersion);
Assert.AreEqual(unit.Note , units[0].Note);
//Version 1 Old Version
Assert.AreEqual(oldCustomerNo, unitsVersions[0].CustomerNo);
Assert.AreEqual(oldMicrotingUid, unitsVersions[0].MicrotingUid);
Assert.AreEqual(oldOtpCode, unitsVersions[0].OtpCode);
Assert.AreEqual(site.Id, unitsVersions[0].SiteId);
Assert.AreEqual(unit.CreatedAt.ToString(), unitsVersions[0].CreatedAt.ToString());
Assert.AreEqual(1, unitsVersions[0].Version);
// Assert.AreEqual(oldUpdatedAt.ToString(), unitsVersions[0].UpdatedAt.ToString());
Assert.AreEqual(oldId, unitsVersions[0].UnitId);
Assert.AreEqual(oldModel , unitsVersions[0].Model);
Assert.AreEqual(oldManufacturer , unitsVersions[0].Manufacturer);
Assert.AreEqual(unitEFormVersion , unitsVersions[0].eFormVersion);
Assert.AreEqual(unitInSightVersion , unitsVersions[0].InSightVersion);
Assert.AreEqual(oldNote , unitsVersions[0].Note);
//Version 2 Updated Version
Assert.AreEqual(unit.CustomerNo, unitsVersions[1].CustomerNo);
Assert.AreEqual(unit.MicrotingUid, unitsVersions[1].MicrotingUid);
Assert.AreEqual(unit.OtpCode, unitsVersions[1].OtpCode);
Assert.AreEqual(site.Id, unitsVersions[1].SiteId);
Assert.AreEqual(unit.CreatedAt.ToString(), unitsVersions[1].CreatedAt.ToString());
Assert.AreEqual(2, unitsVersions[1].Version);
// Assert.AreEqual(unit.UpdatedAt.ToString(), unitsVersions[1].UpdatedAt.ToString());
Assert.AreEqual(unit.Id, unitsVersions[1].UnitId);
Assert.AreEqual(unit.Model , unitsVersions[1].Model);
Assert.AreEqual(unit.Manufacturer , unitsVersions[1].Manufacturer);
Assert.AreEqual(unit.eFormVersion , unitsVersions[1].eFormVersion);
Assert.AreEqual(unit.InSightVersion , unitsVersions[1].InSightVersion);
Assert.AreEqual(unit.Note , unitsVersions[1].Note);
}
[Test]
public async Task Units_Delete_DoesSetWorkflowStateToRemoved()
{
//Arrange
Random rnd = new Random();
Site site = new Site
{
Name = Guid.NewGuid().ToString(),
MicrotingUid = rnd.Next(1, 255)
};
await site.Create(DbContext).ConfigureAwait(false);
Unit unit = new Unit
{
CustomerNo = rnd.Next(1, 255),
MicrotingUid = rnd.Next(1, 255),
OtpCode = rnd.Next(1, 255),
Site = site,
SiteId = site.Id,
Manufacturer = Guid.NewGuid().ToString(),
Model = Guid.NewGuid().ToString(),
Note = Guid.NewGuid().ToString(),
eFormVersion = Guid.NewGuid().ToString(),
InSightVersion = Guid.NewGuid().ToString()
};
await unit.Create(DbContext).ConfigureAwait(false);
//Act
DateTime? oldUpdatedAt = unit.UpdatedAt;
await unit.Delete(DbContext);
List<Unit> units = DbContext.Units.AsNoTracking().ToList();
List<UnitVersion> unitsVersions = DbContext.UnitVersions.AsNoTracking().ToList();
//Assert
Assert.NotNull(units);
Assert.NotNull(unitsVersions);
Assert.AreEqual(1, units.Count());
Assert.AreEqual(2, unitsVersions.Count());
Assert.AreEqual(unit.CustomerNo, units[0].CustomerNo);
Assert.AreEqual(unit.MicrotingUid, units[0].MicrotingUid);
Assert.AreEqual(unit.OtpCode, units[0].OtpCode);
Assert.AreEqual(unit.SiteId, site.Id);
Assert.AreEqual(unit.CreatedAt.ToString(), units[0].CreatedAt.ToString());
Assert.AreEqual(unit.Version, units[0].Version);
// Assert.AreEqual(unit.UpdatedAt.ToString(), units[0].UpdatedAt.ToString());
Assert.AreEqual(unit.Id, units[0].Id);
Assert.AreEqual(units[0].WorkflowState, Constants.WorkflowStates.Removed);
Assert.AreEqual(unit.Model , units[0].Model);
Assert.AreEqual(unit.Manufacturer , units[0].Manufacturer);
Assert.AreEqual(unit.eFormVersion , units[0].eFormVersion);
Assert.AreEqual(unit.InSightVersion , units[0].InSightVersion);
Assert.AreEqual(unit.Note , units[0].Note);
//Version 1
Assert.AreEqual(unit.CustomerNo, unitsVersions[0].CustomerNo);
Assert.AreEqual(unit.MicrotingUid, unitsVersions[0].MicrotingUid);
Assert.AreEqual(unit.OtpCode, unitsVersions[0].OtpCode);
Assert.AreEqual(site.Id, unitsVersions[0].SiteId);
Assert.AreEqual(unit.CreatedAt.ToString(), unitsVersions[0].CreatedAt.ToString());
Assert.AreEqual(1, unitsVersions[0].Version);
// Assert.AreEqual(oldUpdatedAt.ToString(), unitsVersions[0].UpdatedAt.ToString());
Assert.AreEqual(unit.Id, unitsVersions[0].UnitId);
Assert.AreEqual(unit.Model , unitsVersions[0].Model);
Assert.AreEqual(unit.Manufacturer , unitsVersions[0].Manufacturer);
Assert.AreEqual(unit.eFormVersion , unitsVersions[0].eFormVersion);
Assert.AreEqual(unit.InSightVersion , unitsVersions[0].InSightVersion);
Assert.AreEqual(unit.Note , unitsVersions[0].Note);
Assert.AreEqual(unitsVersions[0].WorkflowState, Constants.WorkflowStates.Created);
//Version 2 Deleted Version
Assert.AreEqual(unit.CustomerNo, unitsVersions[1].CustomerNo);
Assert.AreEqual(unit.MicrotingUid, unitsVersions[1].MicrotingUid);
Assert.AreEqual(unit.OtpCode, unitsVersions[1].OtpCode);
Assert.AreEqual(site.Id, unitsVersions[1].SiteId);
Assert.AreEqual(unit.CreatedAt.ToString(), unitsVersions[1].CreatedAt.ToString());
Assert.AreEqual(2, unitsVersions[1].Version);
// Assert.AreEqual(unit.UpdatedAt.ToString(), unitsVersions[1].UpdatedAt.ToString());
Assert.AreEqual(unit.Id, unitsVersions[1].UnitId);
Assert.AreEqual(unit.Model , unitsVersions[1].Model);
Assert.AreEqual(unit.Manufacturer , unitsVersions[1].Manufacturer);
Assert.AreEqual(unit.eFormVersion , unitsVersions[1].eFormVersion);
Assert.AreEqual(unit.InSightVersion , unitsVersions[1].InSightVersion);
Assert.AreEqual(unit.Note , unitsVersions[1].Note);
Assert.AreEqual(unitsVersions[1].WorkflowState, Constants.WorkflowStates.Removed);
}
}
}
| |
/*
* 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.Generic;
using System.Linq;
using Moq;
using NUnit.Framework;
using Python.Runtime;
using QuantConnect.Algorithm;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Tests.Common.Data.UniverseSelection;
using QuantConnect.Tests.Engine.DataFeeds;
namespace QuantConnect.Tests.Algorithm.Framework.Execution
{
[TestFixture]
public class SpreadExecutionModelTests
{
[TestCase(Language.CSharp)]
[TestCase(Language.Python)]
public void OrdersAreNotSubmittedWhenNoTargetsToExecute(Language language)
{
var actualOrdersSubmitted = new List<SubmitOrderRequest>();
var orderProcessor = new Mock<IOrderProcessor>();
orderProcessor.Setup(m => m.Process(It.IsAny<SubmitOrderRequest>()))
.Returns((OrderTicket)null)
.Callback((OrderRequest request) => actualOrdersSubmitted.Add((SubmitOrderRequest)request));
var algorithm = new QCAlgorithm();
algorithm.SetPandasConverter();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
algorithm.Transactions.SetOrderProcessor(orderProcessor.Object);
var model = GetExecutionModel(language);
algorithm.SetExecution(model);
var changes = SecurityChangesTests.CreateNonInternal(Enumerable.Empty<Security>(), Enumerable.Empty<Security>());
model.OnSecuritiesChanged(algorithm, changes);
model.Execute(algorithm, new IPortfolioTarget[0]);
Assert.AreEqual(0, actualOrdersSubmitted.Count);
}
[TestCase(Language.CSharp, 240, 1, 10)]
[TestCase(Language.CSharp, 250, 0, 0)]
[TestCase(Language.Python, 240, 1, 10)]
[TestCase(Language.Python, 250, 0, 0)]
public void OrdersAreSubmittedWhenRequiredForTargetsToExecute(
Language language,
decimal currentPrice,
int expectedOrdersSubmitted,
decimal expectedTotalQuantity)
{
var actualOrdersSubmitted = new List<SubmitOrderRequest>();
var time = new DateTime(2018, 8, 2, 14, 0, 0);
var algorithm = new QCAlgorithm();
algorithm.SetPandasConverter();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
algorithm.SetDateTime(time.AddMinutes(5));
var security = algorithm.AddEquity(Symbols.AAPL.Value);
security.SetMarketPrice(new TradeBar { Value = 250 });
// pushing the ask higher will cause the spread the widen and no trade to happen
var ask = expectedOrdersSubmitted == 0 ? currentPrice * 1.1m : currentPrice;
security.SetMarketPrice(new QuoteBar
{
Time = time,
Symbol = Symbols.AAPL,
Ask = new Bar(ask, ask, ask, ask),
Bid = new Bar(currentPrice, currentPrice, currentPrice, currentPrice)
});
algorithm.SetFinishedWarmingUp();
var orderProcessor = new Mock<IOrderProcessor>();
orderProcessor.Setup(m => m.Process(It.IsAny<SubmitOrderRequest>()))
.Returns((SubmitOrderRequest request) => new OrderTicket(algorithm.Transactions, request))
.Callback((OrderRequest request) => actualOrdersSubmitted.Add((SubmitOrderRequest)request));
orderProcessor.Setup(m => m.GetOpenOrders(It.IsAny<Func<Order, bool>>()))
.Returns(new List<Order>());
algorithm.Transactions.SetOrderProcessor(orderProcessor.Object);
var model = GetExecutionModel(language);
algorithm.SetExecution(model);
var changes = SecurityChangesTests.CreateNonInternal(new[] { security }, Enumerable.Empty<Security>());
model.OnSecuritiesChanged(algorithm, changes);
var targets = new IPortfolioTarget[] { new PortfolioTarget(Symbols.AAPL, 10) };
model.Execute(algorithm, targets);
Assert.AreEqual(expectedOrdersSubmitted, actualOrdersSubmitted.Count);
Assert.AreEqual(expectedTotalQuantity, actualOrdersSubmitted.Sum(x => x.Quantity));
if (actualOrdersSubmitted.Count == 1)
{
var request = actualOrdersSubmitted[0];
Assert.AreEqual(expectedTotalQuantity, request.Quantity);
Assert.AreEqual(algorithm.UtcTime, request.Time);
}
}
[TestCase(Language.CSharp, 1, 10, true)]
[TestCase(Language.Python, 1, 10, true)]
[TestCase(Language.CSharp, 0, 0, false)]
[TestCase(Language.Python, 0, 0, false)]
public void FillsOnTradesOnlyRespectingExchangeOpen(Language language, int expectedOrdersSubmitted, decimal expectedTotalQuantity, bool exchangeOpen)
{
var actualOrdersSubmitted = new List<SubmitOrderRequest>();
var time = new DateTime(2018, 8, 2, 0, 0, 0);
if (exchangeOpen)
{
time = time.AddHours(14);
}
var algorithm = new QCAlgorithm();
algorithm.SetPandasConverter();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
algorithm.SetDateTime(time.AddMinutes(5));
var security = algorithm.AddEquity(Symbols.AAPL.Value);
security.SetMarketPrice(new TradeBar { Value = 250 });
algorithm.SetFinishedWarmingUp();
var orderProcessor = new Mock<IOrderProcessor>();
orderProcessor.Setup(m => m.Process(It.IsAny<SubmitOrderRequest>()))
.Returns((SubmitOrderRequest request) => new OrderTicket(algorithm.Transactions, request))
.Callback((OrderRequest request) => actualOrdersSubmitted.Add((SubmitOrderRequest)request));
orderProcessor.Setup(m => m.GetOpenOrders(It.IsAny<Func<Order, bool>>()))
.Returns(new List<Order>());
algorithm.Transactions.SetOrderProcessor(orderProcessor.Object);
var model = GetExecutionModel(language);
algorithm.SetExecution(model);
var changes = SecurityChangesTests.CreateNonInternal(new[] { security }, Enumerable.Empty<Security>());
model.OnSecuritiesChanged(algorithm, changes);
var targets = new IPortfolioTarget[] { new PortfolioTarget(Symbols.AAPL, 10) };
model.Execute(algorithm, targets);
Assert.AreEqual(expectedOrdersSubmitted, actualOrdersSubmitted.Count);
Assert.AreEqual(expectedTotalQuantity, actualOrdersSubmitted.Sum(x => x.Quantity));
if (actualOrdersSubmitted.Count == 1)
{
var request = actualOrdersSubmitted[0];
Assert.AreEqual(expectedTotalQuantity, request.Quantity);
Assert.AreEqual(algorithm.UtcTime, request.Time);
}
}
[TestCase(Language.CSharp, MarketDataType.TradeBar)]
[TestCase(Language.Python, MarketDataType.TradeBar)]
[TestCase(Language.CSharp, MarketDataType.QuoteBar)]
[TestCase(Language.Python, MarketDataType.QuoteBar)]
public void OnSecuritiesChangeDoesNotThrow(
Language language,
MarketDataType marketDataType)
{
var time = new DateTime(2018, 8, 2, 16, 0, 0);
Func<double, int, BaseData> func = (x, i) =>
{
var price = Convert.ToDecimal(x);
switch (marketDataType)
{
case MarketDataType.TradeBar:
return new TradeBar(time.AddMinutes(i), Symbols.AAPL, price, price, price, price, 100m);
case MarketDataType.QuoteBar:
var bar = new Bar(price, price, price, price);
return new QuoteBar(time.AddMinutes(i), Symbols.AAPL, bar, 10m, bar, 10m);
default:
throw new ArgumentException($"Invalid MarketDataType: {marketDataType}");
}
};
var algorithm = new QCAlgorithm();
algorithm.SetPandasConverter();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
algorithm.SetDateTime(time.AddMinutes(5));
var security = algorithm.AddEquity(Symbols.AAPL.Value);
security.SetMarketPrice(new TradeBar { Value = 250 });
algorithm.SetFinishedWarmingUp();
var model = GetExecutionModel(language);
algorithm.SetExecution(model);
var changes = SecurityChangesTests.CreateNonInternal(new[] { security }, Enumerable.Empty<Security>());
Assert.DoesNotThrow(() => model.OnSecuritiesChanged(algorithm, changes));
}
private static IExecutionModel GetExecutionModel(Language language)
{
const decimal acceptingSpreadPercent = 0.005m;
if (language == Language.Python)
{
using (Py.GIL())
{
const string name = nameof(SpreadExecutionModel);
var instance = Py.Import(name).GetAttr(name).Invoke(acceptingSpreadPercent.ToPython());
return new ExecutionModelPythonWrapper(instance);
}
}
return new SpreadExecutionModel(acceptingSpreadPercent);
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// ProductTypeColl (editable root list).<br/>
/// This is a generated <see cref="ProductTypeColl"/> business object.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="ProductTypeItem"/> objects.
/// </remarks>
[Serializable]
#if WINFORMS
public partial class ProductTypeColl : BusinessBindingListBase<ProductTypeColl, ProductTypeItem>
#else
public partial class ProductTypeColl : BusinessListBase<ProductTypeColl, ProductTypeItem>
#endif
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="ProductTypeItem"/> item from the collection.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the item to be removed.</param>
public void Remove(int productTypeId)
{
foreach (var productTypeItem in this)
{
if (productTypeItem.ProductTypeId == productTypeId)
{
Remove(productTypeItem);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="ProductTypeItem"/> item is in the collection.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the item to search for.</param>
/// <returns><c>true</c> if the ProductTypeItem is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int productTypeId)
{
foreach (var productTypeItem in this)
{
if (productTypeItem.ProductTypeId == productTypeId)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="ProductTypeItem"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the item to search for.</param>
/// <returns><c>true</c> if the ProductTypeItem is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int productTypeId)
{
foreach (var productTypeItem in DeletedList)
{
if (productTypeItem.ProductTypeId == productTypeId)
{
return true;
}
}
return false;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="ProductTypeColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="ProductTypeColl"/> collection.</returns>
public static ProductTypeColl NewProductTypeColl()
{
return DataPortal.Create<ProductTypeColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="ProductTypeColl"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="ProductTypeColl"/> collection.</returns>
public static ProductTypeColl GetProductTypeColl()
{
return DataPortal.Fetch<ProductTypeColl>();
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="ProductTypeColl"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewProductTypeColl(EventHandler<DataPortalResult<ProductTypeColl>> callback)
{
DataPortal.BeginCreate<ProductTypeColl>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="ProductTypeColl"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetProductTypeColl(EventHandler<DataPortalResult<ProductTypeColl>> callback)
{
DataPortal.BeginFetch<ProductTypeColl>(callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductTypeColl()
{
// Use factory methods and do not use direct creation.
Saved += OnProductTypeCollSaved;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Cache Invalidation
// TODO: edit "ProductTypeColl.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: Saved += OnProductTypeCollSaved;
private void OnProductTypeCollSaved(object sender, Csla.Core.SavedEventArgs e)
{
// this runs on the client
ProductTypeCachedList.InvalidateCache();
ProductTypeCachedNVL.InvalidateCache();
}
/// <summary>
/// Called by the server-side DataPortal after calling the requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
protected override void DataPortal_OnDataPortalInvokeComplete(Csla.DataPortalEventArgs e)
{
if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Server &&
e.Operation == DataPortalOperations.Update)
{
// this runs on the server
ProductTypeCachedNVL.InvalidateCache();
}
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="ProductTypeColl"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
var args = new DataPortalHookArgs();
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<IProductTypeCollDal>();
var data = dal.Fetch();
LoadCollection(data);
}
OnFetchPost(args);
}
private void LoadCollection(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="ProductTypeColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(DataPortal.FetchChild<ProductTypeItem>(dr));
}
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Updates in the database all changes made to the <see cref="ProductTypeColl"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
base.Child_Update();
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Http.Features
{
/// <summary>
/// Default implementation for <see cref="IFormFeature"/>.
/// </summary>
public class FormFeature : IFormFeature
{
private readonly HttpRequest _request;
private readonly FormOptions _options;
private Task<IFormCollection>? _parsedFormTask;
private IFormCollection? _form;
/// <summary>
/// Initializes a new instance of <see cref="FormFeature"/>.
/// </summary>
/// <param name="form">The <see cref="IFormCollection"/> to use as the backing store.</param>
public FormFeature(IFormCollection form)
{
if (form == null)
{
throw new ArgumentNullException(nameof(form));
}
Form = form;
_request = default!;
_options = FormOptions.Default;
}
/// <summary>
/// Initializes a new instance of <see cref="FormFeature"/>.
/// </summary>
/// <param name="request">The <see cref="HttpRequest"/>.</param>
public FormFeature(HttpRequest request)
: this(request, FormOptions.Default)
{
}
/// <summary>
/// Initializes a new instance of <see cref="FormFeature"/>.
/// </summary>
/// <param name="request">The <see cref="HttpRequest"/>.</param>
/// <param name="options">The <see cref="FormOptions"/>.</param>
public FormFeature(HttpRequest request, FormOptions options)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_request = request;
_options = options;
}
private MediaTypeHeaderValue? ContentType
{
get
{
MediaTypeHeaderValue.TryParse(_request.ContentType, out var mt);
return mt;
}
}
/// <inheritdoc />
public bool HasFormContentType
{
get
{
// Set directly
if (Form != null)
{
return true;
}
var contentType = ContentType;
return HasApplicationFormContentType(contentType) || HasMultipartFormContentType(contentType);
}
}
/// <inheritdoc />
public IFormCollection? Form
{
get { return _form; }
set
{
_parsedFormTask = null;
_form = value;
}
}
/// <inheritdoc />
public IFormCollection ReadForm()
{
if (Form != null)
{
return Form;
}
if (!HasFormContentType)
{
throw new InvalidOperationException("Incorrect Content-Type: " + _request.ContentType);
}
// TODO: Issue #456 Avoid Sync-over-Async http://blogs.msdn.com/b/pfxteam/archive/2012/04/13/10293638.aspx
// TODO: How do we prevent thread exhaustion?
return ReadFormAsync().GetAwaiter().GetResult();
}
/// <inheritdoc />
public Task<IFormCollection> ReadFormAsync() => ReadFormAsync(CancellationToken.None);
/// <inheritdoc />
public Task<IFormCollection> ReadFormAsync(CancellationToken cancellationToken)
{
// Avoid state machine and task allocation for repeated reads
if (_parsedFormTask == null)
{
if (Form != null)
{
_parsedFormTask = Task.FromResult(Form);
}
else
{
_parsedFormTask = InnerReadFormAsync(cancellationToken);
}
}
return _parsedFormTask;
}
private async Task<IFormCollection> InnerReadFormAsync(CancellationToken cancellationToken)
{
if (!HasFormContentType)
{
throw new InvalidOperationException("Incorrect Content-Type: " + _request.ContentType);
}
cancellationToken.ThrowIfCancellationRequested();
if (_request.ContentLength == 0)
{
return FormCollection.Empty;
}
if (_options.BufferBody)
{
_request.EnableRewind(_options.MemoryBufferThreshold, _options.BufferBodyLengthLimit);
}
FormCollection? formFields = null;
FormFileCollection? files = null;
// Some of these code paths use StreamReader which does not support cancellation tokens.
using (cancellationToken.Register((state) => ((HttpContext)state!).Abort(), _request.HttpContext))
{
var contentType = ContentType;
// Check the content-type
if (HasApplicationFormContentType(contentType))
{
var encoding = FilterEncoding(contentType.Encoding);
var formReader = new FormPipeReader(_request.BodyReader, encoding)
{
ValueCountLimit = _options.ValueCountLimit,
KeyLengthLimit = _options.KeyLengthLimit,
ValueLengthLimit = _options.ValueLengthLimit,
};
formFields = new FormCollection(await formReader.ReadFormAsync(cancellationToken));
}
else if (HasMultipartFormContentType(contentType))
{
var formAccumulator = new KeyValueAccumulator();
var boundary = GetBoundary(contentType, _options.MultipartBoundaryLengthLimit);
var multipartReader = new MultipartReader(boundary, _request.Body)
{
HeadersCountLimit = _options.MultipartHeadersCountLimit,
HeadersLengthLimit = _options.MultipartHeadersLengthLimit,
BodyLengthLimit = _options.MultipartBodyLengthLimit,
};
var section = await multipartReader.ReadNextSectionAsync(cancellationToken);
while (section != null)
{
// Parse the content disposition here and pass it further to avoid reparsings
if (!ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition))
{
throw new InvalidDataException("Form section has invalid Content-Disposition value: " + section.ContentDisposition);
}
if (contentDisposition.IsFileDisposition())
{
var fileSection = new FileMultipartSection(section, contentDisposition);
// Enable buffering for the file if not already done for the full body
section.EnableRewind(
_request.HttpContext.Response.RegisterForDispose,
_options.MemoryBufferThreshold, _options.MultipartBodyLengthLimit);
// Find the end
await section.Body.DrainAsync(cancellationToken);
var name = fileSection.Name;
var fileName = fileSection.FileName;
FormFile file;
if (section.BaseStreamOffset.HasValue)
{
// Relative reference to buffered request body
file = new FormFile(_request.Body, section.BaseStreamOffset.GetValueOrDefault(), section.Body.Length, name, fileName);
}
else
{
// Individually buffered file body
file = new FormFile(section.Body, 0, section.Body.Length, name, fileName);
}
file.Headers = new HeaderDictionary(section.Headers);
if (files == null)
{
files = new FormFileCollection();
}
if (files.Count >= _options.ValueCountLimit)
{
throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded.");
}
files.Add(file);
}
else if (contentDisposition.IsFormDisposition())
{
var formDataSection = new FormMultipartSection(section, contentDisposition);
// Content-Disposition: form-data; name="key"
//
// value
// Do not limit the key name length here because the multipart headers length limit is already in effect.
var key = formDataSection.Name;
var value = await formDataSection.GetValueAsync();
formAccumulator.Append(key, value);
if (formAccumulator.ValueCount > _options.ValueCountLimit)
{
throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded.");
}
}
else
{
System.Diagnostics.Debug.Assert(false, "Unrecognized content-disposition for this section: " + section.ContentDisposition);
}
section = await multipartReader.ReadNextSectionAsync(cancellationToken);
}
if (formAccumulator.HasValues)
{
formFields = new FormCollection(formAccumulator.GetResults(), files);
}
}
}
// Rewind so later readers don't have to.
if (_request.Body.CanSeek)
{
_request.Body.Seek(0, SeekOrigin.Begin);
}
if (formFields != null)
{
Form = formFields;
}
else if (files != null)
{
Form = new FormCollection(null, files);
}
else
{
Form = FormCollection.Empty;
}
return Form;
}
private static Encoding FilterEncoding(Encoding? encoding)
{
// UTF-7 is insecure and should not be honored. UTF-8 will succeed for most cases.
// https://docs.microsoft.com/en-us/dotnet/core/compatibility/syslib-warnings/syslib0001
if (encoding == null || encoding.CodePage == 65000)
{
return Encoding.UTF8;
}
return encoding;
}
private static bool HasApplicationFormContentType([NotNullWhen(true)] MediaTypeHeaderValue? contentType)
{
// Content-Type: application/x-www-form-urlencoded; charset=utf-8
return contentType != null && contentType.MediaType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase);
}
private static bool HasMultipartFormContentType([NotNullWhen(true)] MediaTypeHeaderValue? contentType)
{
// Content-Type: multipart/form-data; boundary=----WebKitFormBoundarymx2fSWqWSd0OxQqq
return contentType != null && contentType.MediaType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase);
}
// Content-Type: multipart/form-data; boundary="----WebKitFormBoundarymx2fSWqWSd0OxQqq"
// The spec says 70 characters is a reasonable limit.
private static string GetBoundary(MediaTypeHeaderValue contentType, int lengthLimit)
{
var boundary = HeaderUtilities.RemoveQuotes(contentType.Boundary);
if (StringSegment.IsNullOrEmpty(boundary))
{
throw new InvalidDataException("Missing content-type boundary.");
}
if (boundary.Length > lengthLimit)
{
throw new InvalidDataException($"Multipart boundary length limit {lengthLimit} exceeded.");
}
return boundary.ToString();
}
}
}
| |
#if SQLCLR
using System.IO;
using System.Reflection;
using System.Data.SqlTypes;
using System.Xml;
namespace System.Data.SqlClient
{
/// <summary>
/// SqlParseEx
/// </summary>
public static class SqlParseEx
{
internal static readonly Type SqlInt32Type = typeof(SqlInt32);
internal static readonly Type SqlDateTimeType = typeof(SqlDateTime);
internal static readonly Type SqlStringType = typeof(SqlString);
internal static readonly Type SqlBooleanType = typeof(SqlBoolean);
internal static readonly Type SqlXmlType = typeof(SqlXml);
private static readonly Type BinaryReaderType = typeof(BinaryReader);
private static readonly Type BinaryWriterType = typeof(BinaryWriter);
#region SqlTypeT
/// <summary>
/// SqlTypeT class
/// </summary>
/// <typeparam name="T"></typeparam>
public static class SqlTypeT<T>
{
private static readonly Type s_type = typeof(T);
public static readonly Func<BinaryReader, T> BinaryRead = SqlTypeT<T>.CreateBinaryRead(s_type);
public static readonly Action<BinaryWriter, T> BinaryWrite = SqlTypeT<T>.CreateBinaryWrite(s_type);
public static readonly Func<XmlReader, string, T> XmlRead = SqlTypeT<T>.CreateXmlRead(s_type);
public static readonly Action<XmlWriter, string, T> XmlWrite = SqlTypeT<T>.CreateXmlWrite(s_type);
/// <summary>
/// Initializes the <see cref="SqlTypeT<T>"/> class.
/// </summary>
static SqlTypeT() { }
#region BinaryRead Implementation
/// <summary>
/// Creates the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private static Func<BinaryReader, T> CreateBinaryRead(Type type)
{
if (type == SqlInt32Type)
return (Func<BinaryReader, T>)Delegate.CreateDelegate(typeof(Func<BinaryReader, T>), typeof(SqlTypeT<T>).GetMethod("BinaryRead_SqlInt32", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryReaderType }, null));
else if (type == SqlDateTimeType)
return (Func<BinaryReader, T>)Delegate.CreateDelegate(typeof(Func<BinaryReader, T>), typeof(SqlTypeT<T>).GetMethod("BinaryRead_SqlDateTime", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryReaderType }, null));
else if (type == SqlStringType)
return (Func<BinaryReader, T>)Delegate.CreateDelegate(typeof(Func<BinaryReader, T>), typeof(SqlTypeT<T>).GetMethod("BinaryRead_SqlString", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryReaderType }, null));
else if (type == SqlBooleanType)
return (Func<BinaryReader, T>)Delegate.CreateDelegate(typeof(Func<BinaryReader, T>), typeof(SqlTypeT<T>).GetMethod("BinaryRead_SqlBoolean", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryReaderType }, null));
else if (type == SqlXmlType)
return (Func<BinaryReader, T>)Delegate.CreateDelegate(typeof(Func<BinaryReader, T>), typeof(SqlTypeT<T>).GetMethod("BinaryRead_SqlXml", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryReaderType }, null));
throw new InvalidOperationException(string.Format("\nUndefined Type [{0}]", type.ToString()));
}
/// <summary>
/// Read_s the SQL int32.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlInt32 BinaryRead_SqlInt32(BinaryReader r)
{
return (!r.ReadBoolean() ? new SqlInt32(r.ReadInt32()) : SqlInt32.Null);
}
/// <summary>
/// Read_s the SQL int32.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlDateTime BinaryRead_SqlDateTime(BinaryReader r)
{
return (!r.ReadBoolean() ? new SqlDateTime(r.ReadInt32(), r.ReadInt32()) : SqlDateTime.Null);
}
/// <summary>
/// Read_s the SQL string.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlString BinaryRead_SqlString(BinaryReader r)
{
return (!r.ReadBoolean() ? new SqlString(r.ReadString()) : SqlString.Null);
}
/// <summary>
/// Read_s the SQL boolean.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlBoolean BinaryRead_SqlBoolean(BinaryReader r)
{
return (!r.ReadBoolean() ? new SqlBoolean(r.ReadBoolean()) : SqlBoolean.Null);
}
/// <summary>
/// Read_s the SQL XML.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlXml BinaryRead_SqlXml(BinaryReader r)
{
if (!r.ReadBoolean())
{
var s = new MemoryStream();
var w = new StreamWriter(s);
w.Write(r.ReadString());
w.Flush();
return new SqlXml(s);
}
return SqlXml.Null;
}
#endregion
#region BinaryWrite Implementation
/// <summary>
/// Creates the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private static Action<BinaryWriter, T> CreateBinaryWrite(Type type)
{
if (type == SqlInt32Type)
return (Action<BinaryWriter, T>)Delegate.CreateDelegate(typeof(Action<BinaryWriter, T>), typeof(SqlTypeT<T>).GetMethod("BinaryWrite_SqlInt32", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryWriterType, SqlInt32Type }, null));
else if (type == SqlDateTimeType)
return (Action<BinaryWriter, T>)Delegate.CreateDelegate(typeof(Action<BinaryWriter, T>), typeof(SqlTypeT<T>).GetMethod("BinaryWrite_SqlDateTime", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryWriterType, SqlDateTimeType }, null));
else if (type == SqlStringType)
return (Action<BinaryWriter, T>)Delegate.CreateDelegate(typeof(Action<BinaryWriter, T>), typeof(SqlTypeT<T>).GetMethod("BinaryWrite_SqlString", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryWriterType, SqlStringType }, null));
else if (type == SqlBooleanType)
return (Action<BinaryWriter, T>)Delegate.CreateDelegate(typeof(Action<BinaryWriter, T>), typeof(SqlTypeT<T>).GetMethod("BinaryWrite_SqlBoolean", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryWriterType, SqlBooleanType }, null));
else if (type == SqlXmlType)
return (Action<BinaryWriter, T>)Delegate.CreateDelegate(typeof(Action<BinaryWriter, T>), typeof(SqlTypeT<T>).GetMethod("BinaryWrite_SqlXml", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { BinaryWriterType, SqlXmlType }, null));
throw new InvalidOperationException();
}
/// <summary>
/// Write_s the SQL int32.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void BinaryWrite_SqlInt32(BinaryWriter w, SqlInt32 value)
{
bool isNull = value.IsNull;
w.Write(isNull);
if (!isNull)
w.Write(value.Value);
}
/// <summary>
/// Write_s the SQL int32.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void BinaryWrite_SqlDateTime(BinaryWriter w, SqlDateTime value)
{
bool isNull = value.IsNull;
w.Write(isNull);
if (!isNull)
{
w.Write(value.DayTicks);
w.Write(value.TimeTicks);
}
}
/// <summary>
/// Write_s the SQL string.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void BinaryWrite_SqlString(BinaryWriter w, SqlString value)
{
bool isNull = value.IsNull;
w.Write(isNull);
if (!isNull)
w.Write(value.Value);
}
/// <summary>
/// Write_s the SQL boolean.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void BinaryWrite_SqlBoolean(BinaryWriter w, SqlBoolean value)
{
bool isNull = value.IsNull;
w.Write(isNull);
if (!isNull)
w.Write(value.Value);
}
/// <summary>
/// Write_s the SQL XML.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void BinaryWrite_SqlXml(BinaryWriter w, SqlXml value)
{
if (value == null)
throw new ArgumentNullException("value");
bool isNull = value.IsNull;
w.Write(isNull);
if (!isNull)
w.Write(value.Value);
}
#endregion
#region XmlRead Implementation
/// <summary>
/// Creates the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private static Func<XmlReader, string, T> CreateXmlRead(Type type)
{
if (type == SqlInt32Type)
return (Func<XmlReader, string, T>)Delegate.CreateDelegate(typeof(Func<XmlReader, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlRead_SqlInt32", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlReaderType, CoreExInternal.StringType }, null));
else if (type == SqlDateTimeType)
return (Func<XmlReader, string, T>)Delegate.CreateDelegate(typeof(Func<XmlReader, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlRead_SqlDateTime", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlReaderType, CoreExInternal.StringType }, null));
else if (type == SqlStringType)
return (Func<XmlReader, string, T>)Delegate.CreateDelegate(typeof(Func<XmlReader, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlRead_SqlString", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlReaderType, CoreExInternal.StringType }, null));
else if (type == SqlBooleanType)
return (Func<XmlReader, string, T>)Delegate.CreateDelegate(typeof(Func<XmlReader, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlRead_SqlBoolean", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlReaderType, CoreExInternal.StringType }, null));
else if (type == SqlXmlType)
return (Func<XmlReader, string, T>)Delegate.CreateDelegate(typeof(Func<XmlReader, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlRead_SqlXml", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlReaderType, CoreExInternal.StringType }, null));
throw new InvalidOperationException(string.Format("\nUndefined Type [{0}]", type.ToString()));
}
/// <summary>
/// Read_s the SQL int32.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlInt32 XmlRead_SqlInt32(XmlReader r, string id)
{
string value = r.GetAttribute(id);
return (value != null ? new SqlInt32(value.Parse<int>()) : SqlInt32.Null);
}
/// <summary>
/// Read_s the SQL int32.
/// </summary>
/// <param name="r">The r.</param>
/// <param name="id">The id.</param>
/// <returns></returns>
private static SqlDateTime XmlRead_SqlDateTime(XmlReader r, string id)
{
string value = r.GetAttribute(id);
return (value != null ? new SqlDateTime(value.Parse<DateTime>()) : SqlDateTime.Null);
}
/// <summary>
/// Read_s the SQL string.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlString XmlRead_SqlString(XmlReader r, string id)
{
string value = r.GetAttribute(id);
return (value != null ? new SqlString(value) : SqlString.Null);
}
/// <summary>
/// Read_s the SQL boolean.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlBoolean XmlRead_SqlBoolean(XmlReader r, string id)
{
string value = r.GetAttribute(id);
return (value != null ? new SqlBoolean(value.Parse<bool>()) : SqlBoolean.Null);
}
/// <summary>
/// Read_s the SQL XML.
/// </summary>
/// <param name="r">The r.</param>
/// <returns></returns>
private static SqlXml XmlRead_SqlXml(XmlReader r, string id)
{
string value;
switch (id)
{
case "":
return (!r.IsEmptyElement ? new SqlXml(r.ReadSubtree()) : SqlXml.Null);
case "#":
value = r.ReadString();
break;
default:
value = r.GetAttribute(id);
break;
}
if (!string.IsNullOrEmpty(value))
{
var s = new MemoryStream();
var w = new StreamWriter(s);
w.Write(value);
w.Flush();
return new SqlXml(s);
}
return SqlXml.Null;
}
#endregion
#region XmlWrite Implementation
/// <summary>
/// Creates the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
private static Action<XmlWriter, string, T> CreateXmlWrite(Type type)
{
if (type == SqlInt32Type)
return (Action<XmlWriter, string, T>)Delegate.CreateDelegate(typeof(Action<XmlWriter, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlWrite_SqlInt32", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlWriterType, CoreExInternal.StringType, SqlInt32Type }, null));
else if (type == SqlDateTimeType)
return (Action<XmlWriter, string, T>)Delegate.CreateDelegate(typeof(Action<XmlWriter, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlWrite_SqlDateTime", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlWriterType, CoreExInternal.StringType, SqlDateTimeType }, null));
else if (type == SqlStringType)
return (Action<XmlWriter, string, T>)Delegate.CreateDelegate(typeof(Action<XmlWriter, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlWrite_SqlString", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlWriterType, CoreExInternal.StringType, SqlStringType }, null));
else if (type == SqlBooleanType)
return (Action<XmlWriter, string, T>)Delegate.CreateDelegate(typeof(Action<XmlWriter, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlWrite_SqlBoolean", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlWriterType, CoreExInternal.StringType, SqlBooleanType }, null));
else if (type == SqlXmlType)
return (Action<XmlWriter, string, T>)Delegate.CreateDelegate(typeof(Action<XmlWriter, string, T>), typeof(SqlTypeT<T>).GetMethod("XmlWrite_SqlXml", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { CoreExInternal.XmlWriterType, CoreExInternal.StringType, SqlXmlType }, null));
throw new InvalidOperationException();
}
/// <summary>
/// Write_s the SQL int32.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void XmlWrite_SqlInt32(XmlWriter w, string id, SqlInt32 value)
{
bool isNull = value.IsNull;
if (!isNull)
w.WriteAttributeString(id, value.Value.ToString());
}
/// <summary>
/// Write_s the SQL int32.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void XmlWrite_SqlDateTime(XmlWriter w, string id, SqlDateTime value)
{
bool isNull = value.IsNull;
if (!isNull)
w.WriteAttributeString(id, value.Value.ToString());
}
/// <summary>
/// Write_s the SQL string.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void XmlWrite_SqlString(XmlWriter w, string id, SqlString value)
{
bool isNull = value.IsNull;
if (!isNull)
w.WriteAttributeString(id, value.Value.ToString());
}
/// <summary>
/// Write_s the SQL boolean.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void XmlWrite_SqlBoolean(XmlWriter w, string id, SqlBoolean value)
{
bool isNull = value.IsNull;
if (!isNull)
w.WriteAttributeString(id, value.Value.ToString());
}
/// <summary>
/// Write_s the SQL XML.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="value">The value.</param>
private static void XmlWrite_SqlXml(XmlWriter w, string id, SqlXml value)
{
if (value == null)
throw new ArgumentNullException("value");
bool isNull = value.IsNull;
if (!isNull)
{
string valueAsText;
switch (id)
{
case "":
w.WriteNode(value.CreateReader(), false);
return;
case "#":
valueAsText = value.Value;
if (!string.IsNullOrEmpty(valueAsText))
w.WriteString(valueAsText);
break;
default:
valueAsText = value.Value;
if (!string.IsNullOrEmpty(valueAsText))
w.WriteAttributeString(id, valueAsText);
break;
}
}
}
#endregion
}
#endregion
}
}
#endif
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
/// <summary>
/// CA1724: Type names should not match namespaces
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class TypeNamesShouldNotMatchNamespacesAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1724";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.TypeNamesShouldNotMatchNamespacesTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDefault = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.TypeNamesShouldNotMatchNamespacesMessageDefault), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageSystem = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.TypeNamesShouldNotMatchNamespacesMessageSystem), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.TypeNamesShouldNotMatchNamespacesDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
internal static DiagnosticDescriptor DefaultRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageDefault,
DiagnosticCategory.Naming,
RuleLevel.Disabled,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor SystemRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageSystem,
DiagnosticCategory.Naming,
RuleLevel.Disabled,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DefaultRule, SystemRule);
private static readonly object s_lock = new object();
private static ImmutableDictionary<string, string>? s_wellKnownSystemNamespaceTable;
private static ImmutableDictionary<string, string> WellKnownSystemNamespaceTable
{
get
{
InitializeWellKnownSystemNamespaceTable();
RoslynDebug.Assert(s_wellKnownSystemNamespaceTable != null);
return s_wellKnownSystemNamespaceTable;
}
}
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.EnableConcurrentExecution();
analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze);
analysisContext.RegisterCompilationStartAction(
compilationStartAnalysisContext =>
{
var externallyVisibleNamedTypes = new ConcurrentBag<INamedTypeSymbol>();
compilationStartAnalysisContext.RegisterSymbolAction(
symbolAnalysisContext =>
{
var namedType = (INamedTypeSymbol)symbolAnalysisContext.Symbol;
if (namedType.IsExternallyVisible())
{
externallyVisibleNamedTypes.Add(namedType);
}
}, SymbolKind.NamedType);
compilationStartAnalysisContext.RegisterCompilationEndAction(
compilationAnalysisContext =>
{
var namespaceNamesInCompilation = new ConcurrentBag<string>();
Compilation compilation = compilationAnalysisContext.Compilation;
AddNamespacesFromCompilation(namespaceNamesInCompilation, compilation.GlobalNamespace);
/* We construct a dictionary whose keys are all the components of all the namespace names in the compilation,
* and whose values are the namespace names of which the components are a part. For example, if the compilation
* includes namespaces A.B and C.D, the dictionary will map "A" to "A", "B" to "A.B", "C" to "C", and "D" to "C.D".
* When the analyzer encounters a type name that appears in a dictionary, it will emit a diagnostic, for instance,
* "Type name "D" conflicts with namespace name "C.D"".
* A component can occur in more than one namespace (for example, you might have namespaces "A" and "A.B".).
* In that case, we have to choose one namespace to report the diagnostic on. We want to make sure that this is
* deterministic (we don't want to complain about "A" in one compilation, and about "A.B" in the next).
* By calling ToImmutableSortedSet on the list of namespace names in the compilation, we ensure that
* we'll always construct the dictionary with the same set of keys.
*/
var namespaceComponentToNamespaceNameDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
UpdateNamespaceTable(namespaceComponentToNamespaceNameDictionary, namespaceNamesInCompilation.ToImmutableSortedSet());
foreach (INamedTypeSymbol symbol in externallyVisibleNamedTypes)
{
string symbolName = symbol.Name;
if (WellKnownSystemNamespaceTable.ContainsKey(symbolName))
{
compilationAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(SystemRule, symbolName, WellKnownSystemNamespaceTable[symbolName]));
}
else if (namespaceComponentToNamespaceNameDictionary.ContainsKey(symbolName))
{
compilationAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(DefaultRule, symbolName, namespaceComponentToNamespaceNameDictionary[symbolName]));
}
}
});
});
}
private static bool AddNamespacesFromCompilation(ConcurrentBag<string> namespaceNamesInCompilation, INamespaceSymbol @namespace)
{
bool hasExternallyVisibleType = false;
foreach (INamespaceSymbol namespaceMember in @namespace.GetNamespaceMembers())
{
if (AddNamespacesFromCompilation(namespaceNamesInCompilation, namespaceMember))
{
hasExternallyVisibleType = true;
}
}
if (!hasExternallyVisibleType)
{
foreach (var type in @namespace.GetTypeMembers())
{
if (type.IsExternallyVisible())
{
hasExternallyVisibleType = true;
break;
}
}
}
if (hasExternallyVisibleType)
{
namespaceNamesInCompilation.Add(@namespace.ToDisplayString());
return true;
}
return false;
}
private static void InitializeWellKnownSystemNamespaceTable()
{
if (s_wellKnownSystemNamespaceTable == null)
{
lock (s_lock)
{
if (s_wellKnownSystemNamespaceTable == null)
{
#region List of Well known System Namespaces
var wellKnownSystemNamespaces = new List<string>
{
"Microsoft.CSharp",
"Microsoft.SqlServer.Server",
"Microsoft.VisualBasic",
"Microsoft.Win32",
"Microsoft.Win32.SafeHandles",
"System",
"System.CodeDom",
"System.CodeDom.Compiler",
"System.Collections",
"System.Collections.Generic",
"System.Collections.ObjectModel",
"System.Collections.Specialized",
"System.ComponentModel",
"System.ComponentModel.Design",
"System.ComponentModel.Design.Serialization",
"System.Configuration",
"System.Configuration.Assemblies",
"System.Data",
"System.Data.Common",
"System.Data.Odbc",
"System.Data.OleDb",
"System.Data.Sql",
"System.Data.SqlClient",
"System.Data.SqlTypes",
"System.Deployment.Internal",
"System.Diagnostics",
"System.Diagnostics.CodeAnalysis",
"System.Diagnostics.SymbolStore",
"System.Drawing",
"System.Drawing.Design",
"System.Drawing.Drawing2D",
"System.Drawing.Imaging",
"System.Drawing.Printing",
"System.Drawing.Text",
"System.Globalization",
"System.IO",
"System.IO.Compression",
"System.IO.IsolatedStorage",
"System.IO.Ports",
"System.Media",
"System.Net",
"System.Net.Cache",
"System.Net.Configuration",
"System.Net.Mail",
"System.Net.Mime",
"System.Net.NetworkInformation",
"System.Net.Security",
"System.Net.Sockets",
"System.Reflection",
"System.Reflection.Emit",
"System.Resources",
"System.Runtime",
"System.Runtime.CompilerServices",
"System.Runtime.ConstrainedExecution",
"System.Runtime.Hosting",
"System.Runtime.InteropServices",
"System.Runtime.InteropServices.ComTypes",
"System.Runtime.InteropServices.Expando",
"System.Runtime.Remoting",
"System.Runtime.Remoting.Activation",
"System.Runtime.Remoting.Channels",
"System.Runtime.Remoting.Contexts",
"System.Runtime.Remoting.Lifetime",
"System.Runtime.Remoting.Messaging",
"System.Runtime.Remoting.Metadata",
"System.Runtime.Remoting.Metadata.W3cXsd2001",
"System.Runtime.Remoting.Proxies",
"System.Runtime.Remoting.Services",
"System.Runtime.Serialization",
"System.Runtime.Serialization.Formatters",
"System.Runtime.Serialization.Formatters.Binary",
"System.Runtime.Versioning",
"System.Security",
"System.Security.AccessControl",
"System.Security.Authentication",
"System.Security.Cryptography",
"System.Security.Cryptography.X509Certificates",
"System.Security.Permissions",
"System.Security.Policy",
"System.Security.Principal",
"System.Text",
"System.Text.RegularExpressions",
"System.Threading",
"System.Timers",
"System.Web",
"System.Web.Caching",
"System.Web.Compilation",
"System.Web.Configuration",
"System.Web.Configuration.Internal",
"System.Web.Handlers",
"System.Web.Hosting",
"System.Web.Mail",
"System.Web.Management",
"System.Web.Profile",
"System.Web.Security",
"System.Web.SessionState",
"System.Web.UI",
"System.Web.UI.Adapters",
"System.Web.UI.HtmlControls",
"System.Web.UI.WebControls",
"System.Web.UI.WebControls.Adapters",
"System.Web.UI.WebControls.WebParts",
"System.Web.Util",
"System.Windows.Forms",
"System.Windows.Forms.ComponentModel.Com2Interop",
"System.Windows.Forms.Design",
"System.Windows.Forms.Layout",
"System.Windows.Forms.PropertyGridInternal",
"System.Windows.Forms.VisualStyles",
"System.Xml",
"System.Xml.Schema",
"System.Xml.Serialization",
"System.Xml.Serialization.Advanced",
"System.Xml.Serialization.Configuration",
"System.Xml.XPath",
"System.Xml.Xsl"
};
#endregion
var wellKnownSystemNamespaceTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
UpdateNamespaceTable(wellKnownSystemNamespaceTable, wellKnownSystemNamespaces);
s_wellKnownSystemNamespaceTable = wellKnownSystemNamespaceTable.ToImmutableDictionary();
}
}
}
}
private static void UpdateNamespaceTable(Dictionary<string, string> namespaceTable, IList<string> namespaces)
{
if (namespaces == null)
{
return;
}
foreach (string namespaceName in namespaces)
{
UpdateNamespaceTable(namespaceTable, namespaceName);
}
}
private static void UpdateNamespaceTable(Dictionary<string, string> namespaceTable, string namespaceName)
{
foreach (string word in namespaceName.Split('.'))
{
if (!namespaceTable.ContainsKey(word))
namespaceTable.Add(word, namespaceName);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Claims;
using System.Security.Principal;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using AspNetBootstrapLess;
using AspNetBootstrapLess.Models;
namespace AspNetBootstrapLess.Controllers
{
[Authorize]
public class ManageController : Controller
{
public ManageController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
UserManager = userManager;
SignInManager = signInManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
public SignInManager<ApplicationUser> SignInManager { get; private set; }
//
// GET: /Account/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
var model = new IndexViewModel
{
HasPassword = await UserManager.HasPasswordAsync(user),
PhoneNumber = await UserManager.GetPhoneNumberAsync(user),
TwoFactor = await UserManager.GetTwoFactorEnabledAsync(user),
Logins = await UserManager.GetLoginsAsync(user),
BrowserRemembered = await SignInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// GET: /Account/RemoveLogin
[HttpGet]
public async Task<IActionResult> RemoveLogin()
{
var user = await GetCurrentUserAsync();
var linkedAccounts = await UserManager.GetLoginsAsync(user);
ViewBag.ShowRemoveButton = await UserManager.HasPasswordAsync(user) || linkedAccounts.Count > 1;
return View(linkedAccounts);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(string loginProvider, string providerKey)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await UserManager.RemoveLoginAsync(user, loginProvider, providerKey);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction("ManageLogins", new { Message = message });
}
//
// GET: /Account/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Account/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(user, model.Number);
await MessageServices.SendSmsAsync(model.Number, "Your security code is: " + code);
return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await UserManager.SetTwoFactorEnabledAsync(user, true);
await SignInManager.SignInAsync(user, isPersistent: false);
}
return RedirectToAction("Index", "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await UserManager.SetTwoFactorEnabledAsync(user, false);
await SignInManager.SignInAsync(user, isPersistent: false);
}
return RedirectToAction("Index", "Manage");
}
//
// GET: /Account/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Account/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await UserManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// GET: /Account/RemovePhoneNumber
[HttpGet]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await UserManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Account/Manage
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await UserManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await UserManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
//GET: /Account/Manage
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewBag.StatusMessage =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await UserManager.GetLoginsAsync(user);
var otherLogins = SignInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = SignInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, User.GetUserId());
return new ChallengeResult(provider, properties);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await SignInManager.GetExternalLoginInfoAsync(User.GetUserId());
if (info == null)
{
return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
var result = await UserManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction("ManageLogins", new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private async Task<bool> HasPhoneNumber()
{
var user = await UserManager.FindByIdAsync(User.GetUserId());
if (user != null)
{
return user.PhoneNumber != null;
}
return false;
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await UserManager.FindByIdAsync(Context.User.GetUserId());
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
#endregion
}
}
| |
// Copyright (C) Pash Contributors. License GPL/BSD. See https://github.com/Pash-Project/Pash/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.PowerShell.Commands;
using System.Management.Automation.Runspaces;
using System.Collections;
using System.Collections.ObjectModel;
namespace System.Management.Automation.Runspaces
{
public class InitialSessionState
{
PSLanguageMode langmode;
InitialSessionStateEntryCollection<SessionStateCommandEntry> _commandEntries;
InitialSessionStateEntryCollection<SessionStateProviderEntry> sessionstatprovider;
InitialSessionStateEntryCollection<SessionStateVariableEntry> variables;
List<ModuleSpecification> modules = new List<ModuleSpecification>();
protected InitialSessionState()
{
_commandEntries = new InitialSessionStateEntryCollection<SessionStateCommandEntry>();
sessionstatprovider = new InitialSessionStateEntryCollection<SessionStateProviderEntry>();
variables = new InitialSessionStateEntryCollection<SessionStateVariableEntry>();
}
#region Properties
public ApartmentState ApartmentState
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public virtual InitialSessionStateEntryCollection<SessionStateAssemblyEntry> Assemblies
{
get
{
throw new NotImplementedException();
}
}
public virtual AuthorizationManager AuthorizationManager
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public virtual InitialSessionStateEntryCollection<SessionStateCommandEntry> Commands
{
get
{
return _commandEntries;
}
}
public bool DisableFormatUpdates
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public virtual InitialSessionStateEntryCollection<SessionStateFormatEntry> Formats
{
get
{
throw new NotImplementedException();
}
}
public PSLanguageMode LanguageMode
{
get
{
return langmode;
}
set
{
langmode = value;
}
}
public ReadOnlyCollection<ModuleSpecification> Modules
{
get
{
return modules.AsReadOnly();
}
}
public virtual InitialSessionStateEntryCollection<SessionStateProviderEntry> Providers
{
get
{
return sessionstatprovider;
}
}
public PSThreadOptions ThreadOptions
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool ThrowOnRunspaceOpenError
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public virtual InitialSessionStateEntryCollection<SessionStateTypeEntry> Types
{
get
{
throw new NotImplementedException();
}
}
public bool UseFullLanguageModeInDebugger
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public virtual InitialSessionStateEntryCollection<SessionStateVariableEntry> Variables
{
get
{
return variables;
}
}
#endregion
public InitialSessionState Clone()
{
throw new NotImplementedException();
}
public static InitialSessionState Create()
{
return new InitialSessionState();
}
public static InitialSessionState Create(string snapInName)
{
return new InitialSessionState();
}
public static InitialSessionState Create(string[] snapInNameCollection, out PSConsoleLoadException warning)
{
warning = null;
return new InitialSessionState();
}
public static InitialSessionState CreateDefault()
{
InitialSessionState initialSessionState = new InitialSessionState();
// TODO: I think this is also the correct location for importing the default snapins, not in SessionStateGlobal
AddDefaultVariables(initialSessionState);
AddDefaultCommands(initialSessionState);
return initialSessionState;
}
public static InitialSessionState CreateDefault2()
{
return CreateDefault();
}
static private void AddDefaultVariables(InitialSessionState initialSessionState)
{
initialSessionState.Variables.Add(new SessionStateVariableEntry("true", true, "", ScopedItemOptions.Constant | ScopedItemOptions.AllScope));
initialSessionState.Variables.Add(new SessionStateVariableEntry("false", false, "", ScopedItemOptions.Constant | ScopedItemOptions.AllScope));
initialSessionState.Variables.Add(new SessionStateVariableEntry("Error", new ArrayList(), "Last errors", ScopedItemOptions.Constant));
initialSessionState.Variables.Add(new SessionStateVariableEntry("?", true, "Last command success", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
}
static private void AddDefaultCommands(InitialSessionState initialSessionState)
{
// Add Default Commands
initialSessionState.Commands.Add(new SessionStateApplicationEntry("*"));
initialSessionState.Commands.Add(new SessionStateScriptEntry("*"));
// Default Functions
initialSessionState.Commands.Add(new SessionStateFunctionEntry("A:", "Set-Location A:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("B:", "Set-Location B:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("C:", "Set-Location C:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("D:", "Set-Location D:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("E:", "Set-Location E:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("F:", "Set-Location F:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("G:", "Set-Location G:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("H:", "Set-Location H:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("I:", "Set-Location I:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("J:", "Set-Location J:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("K:", "Set-Location K:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("L:", "Set-Location L:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("M:", "Set-Location M:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("N:", "Set-Location N:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("O:", "Set-Location O:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("P:", "Set-Location P:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("Q:", "Set-Location Q:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("R:", "Set-Location R:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("S:", "Set-Location S:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("T:", "Set-Location T:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("U:", "Set-Location U:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("V:", "Set-Location V:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("W:", "Set-Location W:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("X:", "Set-Location X:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("Y:", "Set-Location Y:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("Z:", "Set-Location Z:"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("cd..", "Set-Location .."));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("cd\\", "Set-Location \\"));
/* not yet working
initialSessionState.Commands.Add(new SessionStateFunctionEntry("prompt", "$(if (test-path variable:/PSDebugContext) { '[DBG]: ' } else { '' }) + 'PS ' + $(Get-Location) + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> '"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("ImportSystemModules", "\r\n $SnapIns = @(Get-PSSnapin -Registered -ErrorAction SilentlyContinue)"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("more", "param([string[]]$paths)\n\n$OutputEncoding = [System.Console]::OutputEncoding\n\nif($paths)\n{\n foreach ($file in $paths)\n {\n Get-Content $file | more.com\n }\n}\nelse\n{\n $input | more.com\n}\n"));
initialSessionState.Commands.Add(new SessionStateFunctionEntry("Get-Verb", "\r\nparam(\r\n [Parameter(ValueFromPipeline=$true)]\r\n [string[]]\r\n $verb = '*'\r\n)\r\nbegin {\r\n $allVerbs = [PSObject].Assembly.GetTypes() |\r\n Where-Object {$_.Name -match '^Verbs.'} |\r\n Get-Member -type Properties -static |\r\n Select-Object @{\r\n Name='Verb'\r\n Expression = {$_.Name}\r\n }, @{\r\n Name='Group'\r\n Expression = {\r\n $str = \"$($_.TypeName)\"\r\n $str.Substring($str.LastIndexOf('Verbs') + 5)\r\n } \r\n } \r\n}\r\nprocess {\r\n foreach ($v in $verb) {\r\n $allVerbs | Where-Object { $_.Verb -like $v }\r\n } \r\n}\r\n"));
*/
initialSessionState.Commands.Add(new SessionStateFunctionEntry("Prompt", "'PASH ' + (Get-Location) + '> '"));
/* TODO: as soon as we have #HostSupport for other hosts than our console, we need to enable the following
/ function and implement the proper functions/structs
initialSessionState.Commands.Add(new SessionStateFunctionEntry("Clear-Host",
"$space = New-Object System.Management.Automation.Host.BufferCell\n" +
"$space.Character = ' '\n" +
"$space.ForegroundColor = $host.ui.rawui.ForegroundColor\n" +
"$space.BackgroundColor = $host.ui.rawui.BackgroundColor\n" +
"$rect = New-Object System.Management.Automation.Host.Rectangle\n" +
"$rect.Top = $rect.Bottom = $rect.Right = $rect.Left = -1\n" +
"$origin = New-Object System.Management.Automation.Host.Coordinates\n" +
"$Host.UI.RawUI.CursorPosition = $origin\n" +
"$Host.UI.RawUI.SetBufferContents($rect, $space)\n")
);
*/
initialSessionState.Commands.Add(new SessionStateFunctionEntry("Clear-Host", "[Console]::Clear()"));
// TODO:
// "TabExpansion"
// "help"
// "mkdir"
// "Disable-PSRemoting"
// Default Aliases
initialSessionState.Commands.Add(new SessionStateAliasEntry("ac", "Add-Content", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("asnp", "Add-PSSnapIn", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("cat", "Get-Content", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("cd", "Set-Location", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("chdir", "Set-Location", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("cp", "Copy-Item", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("clc", "Clear-Content", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("clear", "Clear-Host", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("clhy", "Clear-History", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("cli", "Clear-Item", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("clp", "Clear-ItemProperty", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("cls", "Clear-Host", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("clv", "Clear-Variable", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("compare", "Compare-Object", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("copy", "Copy-Item", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("cpi", "Copy-Item", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("cpp", "Copy-ItemProperty", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("cvpa", "Convert-Path", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("dbp", "Disable-PSBreakpoint", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("del", "Remove-Item", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("dir", "Get-ChildItem", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("diff", "Compare-Object", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ebp", "Enable-PSBreakpoint", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("echo", "Write-Output", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("epal", "Export-Alias", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("epcsv", "Export-Csv", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("erase", "Remove-Item", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("epsn", "Export-PSSession", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("etsn", "Enter-PSSession", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("exsn", "Exit-PSSession", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("fc", "Format-Custom", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("fl", "Format-List", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("foreach", "ForEach-Object", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("%", "ForEach-Object", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ft", "Format-Table", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("fw", "Format-Wide", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gal", "Get-Alias", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gbp", "Get-PSBreakpoint", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gc", "Get-Content", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gci", "Get-ChildItem", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gcm", "Get-Command", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gdr", "Get-PSDrive", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gcs", "Get-PSCallStack", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ghy", "Get-History", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gi", "Get-Item", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gjb", "Get-Job", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gl", "Get-Location", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gm", "Get-Member", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gmo", "Get-Module", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gp", "Get-ItemProperty", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gps", "Get-Process", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("group", "Group-Object", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gsn", "Get-PSSession", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gsv", "Get-Service", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gsnp", "Get-PSSnapIn", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gu", "Get-Unique", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gv", "Get-Variable", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("gwmi", "Get-WmiObject", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("h", "Get-History", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("history", "Get-History", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("icm", "Invoke-Command", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("iex", "Invoke-Expression", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ihy", "Invoke-History", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ii", "Invoke-Item", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ipmo", "Import-Module", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ipsn", "Import-PSSession", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ise", "powershell_ise.exe", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("iwmi", "Invoke-WMIMethod", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ipal", "Import-Alias", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ipcsv", "Import-Csv", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("kill", "Stop-Process", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("lp", "Out-Printer", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ls", "Get-ChildItem", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("man", "help", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("md", "mkdir", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("measure", "Measure-Object", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("mi", "Move-Item", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("mount", "New-PSDrive", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("move", "Move-Item", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("mp", "Move-ItemProperty", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("mv", "Move-Item", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("nal", "New-Alias", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ndr", "New-PSDrive", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ni", "New-Item", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("nv", "New-Variable", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("nmo", "New-Module", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("nsn", "New-PSSession", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("oh", "Out-Host", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ogv", "Out-GridView", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("popd", "Pop-Location", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ps", "Get-Process", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("pushd", "Push-Location", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("pwd", "Get-Location", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("r", "Invoke-History", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rbp", "Remove-PSBreakpoint", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rcjb", "Receive-Job", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rd", "Remove-Item", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rdr", "Remove-PSDrive", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ren", "Rename-Item", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("ri", "Remove-Item", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rjb", "Remove-Job", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rm", "Remove-Item", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rmdir", "Remove-Item", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rni", "Rename-Item", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rnp", "Rename-ItemProperty", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rp", "Remove-ItemProperty", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rmo", "Remove-Module", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rsn", "Remove-PSSession", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rsnp", "Remove-PSSnapin", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rv", "Remove-Variable", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rwmi", "Remove-WMIObject", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("rvpa", "Resolve-Path", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("sajb", "Start-Job", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("sal", "Set-Alias", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("sasv", "Start-Service", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("sbp", "Set-PSBreakpoint", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("sc", "Set-Content", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("select", "Select-Object", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("set", "Set-Variable", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("si", "Set-Item", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("sl", "Set-Location", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("sls", "Select-String", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("swmi", "Set-WMIInstance", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("sleep", "Start-Sleep", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("sort", "Sort-Object", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("sp", "Set-ItemProperty", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("spjb", "Stop-Job", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("saps", "Start-Process", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("start", "Start-Process", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("spps", "Stop-Process", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("spsv", "Stop-Service", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("sv", "Set-Variable", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("tee", "Tee-Object", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("type", "Get-Content", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("where", "Where-Object", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("wjb", "Wait-Job", "", ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("write", "Write-Output", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
initialSessionState.Commands.Add(new SessionStateAliasEntry("?", "Where-Object", "", ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope));
}
public static InitialSessionState CreateFrom(string snapInPath, out PSConsoleLoadException warnings)
{
warnings = null;
return new InitialSessionState();
}
public static InitialSessionState CreateFrom(string[] snapInPathCollection, out PSConsoleLoadException warnings)
{
warnings = null;
return new InitialSessionState();
}
public static InitialSessionState CreateRestricted(SessionCapabilities sessionCapabilities)
{
InitialSessionState initialSessionState = new InitialSessionState();
return initialSessionState;
}
public void ImportPSModule(string[] name)
{
var specifications = from string moduleName in name
select new ModuleSpecification(moduleName);
modules.AddRange(specifications);
}
public void ImportPSModulesFromPath(string path)
{
throw new NotImplementedException();
}
public PSSnapInInfo ImportPSSnapIn(string name, out PSSnapInException warning)
{
throw new NotImplementedException();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using AutoRest.Core;
using AutoRest.Core.Model;
using AutoRest.Core.Utilities;
using AutoRest.CSharp.Azure.Model;
using AutoRest.CSharp.Model;
using AutoRest.Extensions;
using AutoRest.Extensions.Azure;
using Newtonsoft.Json.Linq;
using static AutoRest.Core.Utilities.DependencyInjection;
namespace AutoRest.CSharp.Azure
{
public class TransformerCsa : TransformerCs, ITransformer<CodeModelCsa>
{
/// <summary>
/// A type-specific method for code model tranformation.
/// Note: This is the method you want to override.
/// </summary>
/// <param name="codeModel"></param>
/// <returns></returns>
public override CodeModelCs TransformCodeModel(CodeModel codeModel)
{
return ((ITransformer<CodeModelCsa>)this).TransformCodeModel(codeModel);
}
CodeModelCsa ITransformer<CodeModelCsa>.TransformCodeModel(CodeModel cs)
{
var codeModel = cs as CodeModelCsa;
// we're guaranteed to be in our language-specific context here.
Settings.Instance.AddCredentials = true;
// add the Credentials
// PopulateAdditionalProperties(codeModel);
// Do parameter transformations
TransformParameters(codeModel);
// todo: these should be turned into individual transformers
AzureExtensions.NormalizeAzureClientModel(codeModel);
NormalizePaginatedMethods(codeModel);
NormalizeODataMethods(codeModel);
foreach (var model in codeModel.ModelTypes)
{
if (model.Extensions.ContainsKey(AzureExtensions.AzureResourceExtension) &&
(bool)model.Extensions[AzureExtensions.AzureResourceExtension])
{
model.BaseModelType = New<ILiteralType>("Microsoft.Rest.Azure.IResource",
new { SerializedName = "Microsoft.Rest.Azure.IResource" }) as CompositeType;
}
}
return codeModel;
}
public virtual void NormalizeODataMethods(CodeModel client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
foreach (var method in client.Methods)
{
if (method.Extensions.ContainsKey(AzureExtensions.ODataExtension))
{
var odataFilter = method.Parameters.FirstOrDefault(p =>
p.SerializedName.EqualsIgnoreCase("$filter") &&
(p.Location == ParameterLocation.Query) &&
p.ModelType is CompositeType);
if (odataFilter == null)
{
continue;
}
// Remove all odata parameters
method.Remove(source =>
(source.SerializedName.EqualsIgnoreCase("$filter") ||
source.SerializedName.EqualsIgnoreCase("$top") ||
source.SerializedName.EqualsIgnoreCase("$orderby") ||
source.SerializedName.EqualsIgnoreCase("$skip") ||
source.SerializedName.EqualsIgnoreCase("$expand"))
&& (source.Location == ParameterLocation.Query));
var odataQuery = New<Parameter>(new
{
SerializedName = "$filter",
Name = "odataQuery",
// ModelType = New<CompositeType>($"Microsoft.Rest.Azure.OData.ODataQuery<{odataFilter.ModelType.Name}>"),
// ModelType = New<CompositeType>(new { Name = new Fixable<string>(){FixedValue = $"Microsoft.Rest.Azure.OData.ODataQuery<{odataFilter.ModelType.Name}>"} } ),
ModelType =
New<ILiteralType>($"Microsoft.Rest.Azure.OData.ODataQuery<{odataFilter.ModelType.Name}>"),
Documentation = "OData parameters to apply to the operation.",
Location = ParameterLocation.Query,
odataFilter.IsRequired
});
odataQuery.Extensions[AzureExtensions.ODataExtension] =
method.Extensions[AzureExtensions.ODataExtension];
method.Insert(odataQuery);
}
}
}
/// <summary>
/// Changes paginated method signatures to return Page type.
/// </summary>
/// <param name="codeModel"></param>
/// <param name="pageClasses"></param>
public virtual void NormalizePaginatedMethods(CodeModelCsa codeModel)
{
if (codeModel == null)
{
throw new ArgumentNullException($"serviceClient");
}
var convertedTypes = new Dictionary<IModelType, CompositeType>();
foreach (
var method in
codeModel.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension)))
{
string nextLinkString;
var pageClassName = GetPagingSetting(method.Extensions, codeModel.pageClasses, out nextLinkString);
if (string.IsNullOrEmpty(pageClassName))
{
continue;
}
var pageTypeFormat = "{0}<{1}>";
var ipageTypeFormat = "Microsoft.Rest.Azure.IPage<{0}>";
if (string.IsNullOrWhiteSpace(nextLinkString))
{
ipageTypeFormat = "System.Collections.Generic.IEnumerable<{0}>";
}
foreach (var responseStatus in method.Responses
.Where(r => r.Value.Body is CompositeType).Select(s => s.Key).ToArray())
{
var compositType = (CompositeType)method.Responses[responseStatus].Body;
var sequenceType =
compositType.Properties.Select(p => p.ModelType).FirstOrDefault(t => t is SequenceType) as
SequenceTypeCs;
// if the type is a wrapper over page-able response
if (sequenceType != null)
{
var pagableTypeName = string.Format(CultureInfo.InvariantCulture, pageTypeFormat, pageClassName,
sequenceType.ElementType.AsNullableType(!sequenceType.ElementType.IsValueType() || (sequenceType.IsXNullable ?? true)));
var ipagableTypeName = string.Format(CultureInfo.InvariantCulture, ipageTypeFormat,
sequenceType.ElementType.AsNullableType(!sequenceType.ElementType.IsValueType() || (sequenceType.IsXNullable ?? true)));
var pagedResult = New<ILiteralType>(pagableTypeName) as CompositeType;
pagedResult.Extensions[AzureExtensions.ExternalExtension] = true;
pagedResult.Extensions[AzureExtensions.PageableExtension] = ipagableTypeName;
convertedTypes[method.Responses[responseStatus].Body] = pagedResult;
method.Responses[responseStatus] = new Response(pagedResult,
method.Responses[responseStatus].Headers);
}
}
if (convertedTypes.ContainsKey(method.ReturnType.Body))
{
method.ReturnType = new Response(convertedTypes[method.ReturnType.Body],
method.ReturnType.Headers);
}
}
SwaggerExtensions.RemoveUnreferencedTypes(codeModel,
new HashSet<string>(convertedTypes.Keys.Cast<CompositeType>().Select(t => t.Name.Value)));
}
private static string GetPagingSetting(Dictionary<string, object> extensions,
IDictionary<KeyValuePair<string, string>, string> pageClasses, out string nextLinkName)
{
// default value
nextLinkName = null;
var ext = extensions[AzureExtensions.PageableExtension] as JContainer;
if (ext == null)
{
return null;
}
nextLinkName = (string)ext["nextLinkName"];
var itemName = (string)ext["itemName"] ?? "value";
var keypair = new KeyValuePair<string, string>(nextLinkName, itemName);
if (!pageClasses.ContainsKey(keypair))
{
var className = (string)ext["className"];
if (string.IsNullOrEmpty(className))
{
if (pageClasses.Count > 0)
{
className = string.Format(CultureInfo.InvariantCulture, "Page{0}", pageClasses.Count);
}
else
{
className = "Page";
}
}
pageClasses.Add(keypair, className);
}
return pageClasses[keypair];
}
}
}
| |
#if !(UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2)
#define SupportCustomYieldInstruction
#endif
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Callbacks;
#endif
using System;
using System.Collections;
using System.Reflection;
using UnityEngine;
using UtyRx;
using UtyRx.InternalUtil;
namespace Assets.Scripts.Environment.Reactive
{
public sealed class MainThreadDispatcher : MonoBehaviour
{
public enum CullingMode
{
/// <summary>
/// Won't remove any MainThreadDispatchers.
/// </summary>
Disabled,
/// <summary>
/// Checks if there is an existing MainThreadDispatcher on Awake(). If so, the new dispatcher removes itself.
/// </summary>
Self,
/// <summary>
/// Search for excess MainThreadDispatchers and removes them all on Awake().
/// </summary>
All
}
public static CullingMode cullingMode = CullingMode.Self;
#if UNITY_EDITOR
[InitializeOnLoad]
public class ScenePlaybackDetector
{
private static bool _isPlaying = false;
private static bool AboutToStartScene
{
get
{
return EditorPrefs.GetBool("AboutToStartScene");
}
set
{
EditorPrefs.SetBool("AboutToStartScene", value);
}
}
public static bool IsPlaying
{
get
{
return _isPlaying;
}
set
{
if (_isPlaying != value)
{
_isPlaying = value;
}
}
}
// This callback is notified after scripts have been reloaded.
[DidReloadScripts]
public static void OnDidReloadScripts()
{
// Filter DidReloadScripts callbacks to the moment where playmodeState transitions into isPlaying.
if (AboutToStartScene)
{
IsPlaying = true;
}
}
// InitializeOnLoad ensures that this constructor is called when the Unity Editor is started.
static ScenePlaybackDetector()
{
EditorApplication.playmodeStateChanged += () =>
{
// Before scene start: isPlayingOrWillChangePlaymode = false; isPlaying = false
// Pressed Playback button: isPlayingOrWillChangePlaymode = true; isPlaying = false
// Playing: isPlayingOrWillChangePlaymode = false; isPlaying = true
// Pressed stop button: isPlayingOrWillChangePlaymode = true; isPlaying = true
if (EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying)
{
AboutToStartScene = true;
}
else
{
AboutToStartScene = false;
}
// Detect when playback is stopped.
if (!EditorApplication.isPlaying)
{
IsPlaying = false;
}
};
}
}
// In UnityEditor's EditorMode can't instantiate and work MonoBehaviour.Update.
// EditorThreadDispatcher use EditorApplication.update instead of MonoBehaviour.Update.
class EditorThreadDispatcher
{
static object gate = new object();
static EditorThreadDispatcher instance;
public static EditorThreadDispatcher Instance
{
get
{
// Activate EditorThreadDispatcher is dangerous, completely Lazy.
lock (gate)
{
if (instance == null)
{
instance = new EditorThreadDispatcher();
}
return instance;
}
}
}
ThreadSafeQueueWorker editorQueueWorker = new ThreadSafeQueueWorker();
EditorThreadDispatcher()
{
UnityEditor.EditorApplication.update += Update;
}
public void Enqueue(Action<object> action, object state)
{
editorQueueWorker.Enqueue(action, state);
}
public void UnsafeInvoke(Action action)
{
try
{
action();
}
catch (Exception ex)
{
UnityEngine.Debug.LogException(ex);
}
}
public void UnsafeInvoke<T>(Action<T> action, T state)
{
try
{
action(state);
}
catch (Exception ex)
{
UnityEngine.Debug.LogException(ex);
}
}
public void PseudoStartCoroutine(IEnumerator routine)
{
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(routine), null);
}
void Update()
{
editorQueueWorker.ExecuteAll(x => UnityEngine.Debug.LogException(x));
}
void ConsumeEnumerator(IEnumerator routine)
{
if (routine.MoveNext())
{
var current = routine.Current;
if (current == null)
{
goto ENQUEUE;
}
var type = current.GetType();
if (type == typeof(WWW))
{
var www = (WWW)current;
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitWWW(www, routine)), null);
return;
}
else if (type == typeof(AsyncOperation))
{
var asyncOperation = (AsyncOperation)current;
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitAsyncOperation(asyncOperation, routine)), null);
return;
}
else if (type == typeof(WaitForSeconds))
{
var waitForSeconds = (WaitForSeconds)current;
var accessor = typeof(WaitForSeconds).GetField("m_Seconds", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic);
var second = (float)accessor.GetValue(waitForSeconds);
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitForSeconds(second, routine)), null);
return;
}
else if (type == typeof(Coroutine))
{
UnityEngine.Debug.Log("Can't wait coroutine on UnityEditor");
goto ENQUEUE;
}
#if SupportCustomYieldInstruction
else if (current is IEnumerator)
{
var enumerator = (IEnumerator)current;
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapEnumerator(enumerator, routine)), null);
return;
}
#endif
ENQUEUE:
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(routine), null); // next update
}
}
IEnumerator UnwrapWaitWWW(WWW www, IEnumerator continuation)
{
while (!www.isDone)
{
yield return null;
}
ConsumeEnumerator(continuation);
}
IEnumerator UnwrapWaitAsyncOperation(AsyncOperation asyncOperation, IEnumerator continuation)
{
while (!asyncOperation.isDone)
{
yield return null;
}
ConsumeEnumerator(continuation);
}
IEnumerator UnwrapWaitForSeconds(float second, IEnumerator continuation)
{
var startTime = DateTimeOffset.UtcNow;
while (true)
{
yield return null;
var elapsed = (DateTimeOffset.UtcNow - startTime).TotalSeconds;
if (elapsed >= second)
{
break;
}
};
ConsumeEnumerator(continuation);
}
IEnumerator UnwrapEnumerator(IEnumerator enumerator, IEnumerator continuation)
{
while (enumerator.MoveNext())
{
yield return null;
}
ConsumeEnumerator(continuation);
}
}
#endif
/// <summary>Dispatch Asyncrhonous action.</summary>
public static void Post(Action<object> action, object state)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action, state); return; }
#endif
var dispatcher = Instance;
if (!isQuitting && !object.ReferenceEquals(dispatcher, null))
{
dispatcher.queueWorker.Enqueue(action, state);
}
}
/// <summary>Dispatch Synchronous action if possible.</summary>
public static void Send(Action<object> action, object state)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action, state); return; }
#endif
if (mainThreadToken != null)
{
try
{
action(state);
}
catch (Exception ex)
{
var dispatcher = MainThreadDispatcher.Instance;
if (dispatcher != null)
{
dispatcher.unhandledExceptionCallback(ex);
}
}
}
else
{
Post(action, state);
}
}
/// <summary>Run Synchronous action.</summary>
public static void UnsafeSend(Action action)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action); return; }
#endif
try
{
action();
}
catch (Exception ex)
{
var dispatcher = MainThreadDispatcher.Instance;
if (dispatcher != null)
{
dispatcher.unhandledExceptionCallback(ex);
}
}
}
/// <summary>Run Synchronous action.</summary>
public static void UnsafeSend<T>(Action<T> action, T state)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action, state); return; }
#endif
try
{
action(state);
}
catch (Exception ex)
{
var dispatcher = MainThreadDispatcher.Instance;
if (dispatcher != null)
{
dispatcher.unhandledExceptionCallback(ex);
}
}
}
/// <summary>ThreadSafe StartCoroutine.</summary>
public static void SendStartCoroutine(IEnumerator routine)
{
if (mainThreadToken != null)
{
StartCoroutine(routine);
}
else
{
#if UNITY_EDITOR
// call from other thread
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; }
#endif
var dispatcher = Instance;
if (!isQuitting && !object.ReferenceEquals(dispatcher, null))
{
dispatcher.queueWorker.Enqueue(_ =>
{
var dispatcher2 = Instance;
if (dispatcher2 != null)
{
(dispatcher2 as MonoBehaviour).StartCoroutine(routine);
}
}, null);
}
}
}
public static void StartUpdateMicroCoroutine(IEnumerator routine)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; }
#endif
var dispatcher = Instance;
if (dispatcher != null)
{
dispatcher.updateMicroCoroutine.AddCoroutine(routine);
}
}
public static void StartFixedUpdateMicroCoroutine(IEnumerator routine)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; }
#endif
var dispatcher = Instance;
if (dispatcher != null)
{
dispatcher.fixedUpdateMicroCoroutine.AddCoroutine(routine);
}
}
public static void StartEndOfFrameMicroCoroutine(IEnumerator routine)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; }
#endif
var dispatcher = Instance;
if (dispatcher != null)
{
dispatcher.endOfFrameMicroCoroutine.AddCoroutine(routine);
}
}
new public static Coroutine StartCoroutine(IEnumerator routine)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return null; }
#endif
var dispatcher = Instance;
if (dispatcher != null)
{
return (dispatcher as MonoBehaviour).StartCoroutine(routine);
}
else
{
return null;
}
}
public static void RegisterUnhandledExceptionCallback(Action<Exception> exceptionCallback)
{
if (exceptionCallback == null)
{
// do nothing
Instance.unhandledExceptionCallback = Stubs<Exception>.Ignore;
}
else
{
Instance.unhandledExceptionCallback = exceptionCallback;
}
}
ThreadSafeQueueWorker queueWorker = new ThreadSafeQueueWorker();
Action<Exception> unhandledExceptionCallback = ex => UnityEngine.Debug.LogException(ex); // default
MicroCoroutine updateMicroCoroutine = null;
MicroCoroutine fixedUpdateMicroCoroutine = null;
MicroCoroutine endOfFrameMicroCoroutine = null;
static MainThreadDispatcher instance;
static bool initialized;
static bool isQuitting = false;
public static string InstanceName
{
get
{
if (instance == null)
{
throw new NullReferenceException("MainThreadDispatcher is not initialized.");
}
return instance.name;
}
}
public static bool IsInitialized
{
get { return initialized && instance != null; }
}
[ThreadStatic]
static object mainThreadToken;
static MainThreadDispatcher Instance
{
get
{
Initialize();
return instance;
}
}
public static void Initialize()
{
if (!initialized)
{
#if UNITY_EDITOR
// Don't try to add a GameObject when the scene is not playing. Only valid in the Editor, EditorView.
if (!ScenePlaybackDetector.IsPlaying) return;
#endif
MainThreadDispatcher dispatcher = null;
try
{
dispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>();
}
catch
{
// Throw exception when calling from a worker thread.
var ex = new Exception("UniRx requires a MainThreadDispatcher component created on the main thread. Make sure it is added to the scene before calling UniRx from a worker thread.");
UnityEngine.Debug.LogException(ex);
throw ex;
}
if (isQuitting)
{
// don't create new instance after quitting
// avoid "Some objects were not cleaned up when closing the scene find target" error.
return;
}
if (dispatcher == null)
{
instance = new GameObject("MainThreadDispatcher").AddComponent<MainThreadDispatcher>();
}
else
{
instance = dispatcher;
}
DontDestroyOnLoad(instance);
mainThreadToken = new object();
initialized = true;
}
}
void Awake()
{
if (instance == null)
{
instance = this;
mainThreadToken = new object();
initialized = true;
StartCoroutine(RunUpdateMicroCoroutine());
StartCoroutine(RunFixedUpdateMicroCoroutine());
StartCoroutine(RunEndOfFrameMicroCoroutine());
// Added for consistency with Initialize()
DontDestroyOnLoad(gameObject);
}
else
{
if (cullingMode == CullingMode.Self)
{
UnityEngine.Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Removing myself...");
// Destroy this dispatcher if there's already one in the scene.
DestroyDispatcher(this);
}
else if (cullingMode == CullingMode.All)
{
UnityEngine.Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Cleaning up all excess dispatchers...");
CullAllExcessDispatchers();
}
else
{
UnityEngine.Debug.LogWarning("There is already a MainThreadDispatcher in the scene.");
}
}
}
IEnumerator RunUpdateMicroCoroutine()
{
this.updateMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex));
while (true)
{
yield return null;
updateMicroCoroutine.Run();
}
}
IEnumerator RunFixedUpdateMicroCoroutine()
{
this.fixedUpdateMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex));
while (true)
{
yield return YieldInstructionCache.WaitForFixedUpdate;
fixedUpdateMicroCoroutine.Run();
}
}
IEnumerator RunEndOfFrameMicroCoroutine()
{
this.endOfFrameMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex));
while (true)
{
yield return YieldInstructionCache.WaitForEndOfFrame;
endOfFrameMicroCoroutine.Run();
}
}
static void DestroyDispatcher(MainThreadDispatcher aDispatcher)
{
if (aDispatcher != instance)
{
// Try to remove game object if it's empty
var components = aDispatcher.gameObject.GetComponents<Component>();
if (aDispatcher.gameObject.transform.childCount == 0 && components.Length == 2)
{
if (components[0] is Transform && components[1] is MainThreadDispatcher)
{
Destroy(aDispatcher.gameObject);
}
}
else
{
// Remove component
MonoBehaviour.Destroy(aDispatcher);
}
}
}
public static void CullAllExcessDispatchers()
{
var dispatchers = GameObject.FindObjectsOfType<MainThreadDispatcher>();
for (int i = 0; i < dispatchers.Length; i++)
{
DestroyDispatcher(dispatchers[i]);
}
}
void OnDestroy()
{
if (instance == this)
{
instance = GameObject.FindObjectOfType<MainThreadDispatcher>();
initialized = instance != null;
/*
// Although `this` still refers to a gameObject, it won't be found.
var foundDispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>();
if (foundDispatcher != null)
{
// select another game object
Debug.Log("new instance: " + foundDispatcher.name);
instance = foundDispatcher;
initialized = true;
}
*/
}
}
void Update()
{
if (update != null)
{
try
{
update.OnNext(Unit.Default);
}
catch (Exception ex)
{
unhandledExceptionCallback(ex);
}
}
queueWorker.ExecuteAll(unhandledExceptionCallback);
}
// for Lifecycle Management
Subject<Unit> update;
public static UtyRx.IObservable<Unit> UpdateAsObservable()
{
return Instance.update ?? (Instance.update = new Subject<Unit>());
}
Subject<Unit> lateUpdate;
void LateUpdate()
{
if (lateUpdate != null) lateUpdate.OnNext(Unit.Default);
}
public static UtyRx.IObservable<Unit> LateUpdateAsObservable()
{
return Instance.lateUpdate ?? (Instance.lateUpdate = new Subject<Unit>());
}
Subject<bool> onApplicationFocus;
void OnApplicationFocus(bool focus)
{
if (onApplicationFocus != null) onApplicationFocus.OnNext(focus);
}
public static UtyRx.IObservable<bool> OnApplicationFocusAsObservable()
{
return Instance.onApplicationFocus ?? (Instance.onApplicationFocus = new Subject<bool>());
}
Subject<bool> onApplicationPause;
void OnApplicationPause(bool pause)
{
if (onApplicationPause != null) onApplicationPause.OnNext(pause);
}
public static UtyRx.IObservable<bool> OnApplicationPauseAsObservable()
{
return Instance.onApplicationPause ?? (Instance.onApplicationPause = new Subject<bool>());
}
Subject<Unit> onApplicationQuit;
void OnApplicationQuit()
{
isQuitting = true;
if (onApplicationQuit != null) onApplicationQuit.OnNext(Unit.Default);
}
public static UtyRx.IObservable<Unit> OnApplicationQuitAsObservable()
{
return Instance.onApplicationQuit ?? (Instance.onApplicationQuit = new Subject<Unit>());
}
}
internal static class YieldInstructionCache
{
public static readonly WaitForEndOfFrame WaitForEndOfFrame = new WaitForEndOfFrame();
public static readonly WaitForFixedUpdate WaitForFixedUpdate = new WaitForFixedUpdate();
}
}
| |
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* RDP
*
* Copyright 2011-2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace FreeRDP
{
public unsafe class RDP
{
[DllImport("libfreerdp-core")]
public static extern void freerdp_context_new(freerdp* instance);
[DllImport("libfreerdp-core")]
public static extern void freerdp_context_free(freerdp* instance);
[DllImport("libfreerdp-core")]
public static extern int freerdp_connect(freerdp* instance);
[DllImport("libfreerdp-core")]
public static extern int freerdp_disconnect(freerdp* instance);
[DllImport("libfreerdp-core")]
public static extern int freerdp_check_fds(freerdp* instance);
[DllImport("libfreerdp-core")]
public static extern freerdp* freerdp_new();
[DllImport("libfreerdp-core")]
public static extern void freerdp_free(freerdp* instance);
[DllImport("libfreerdp-core")]
public static extern void freerdp_input_send_synchronize_event(IntPtr input, UInt32 flags);
[DllImport("libfreerdp-core")]
public static extern void freerdp_input_send_keyboard_event(IntPtr input, UInt16 flags, UInt16 code);
[DllImport("libfreerdp-core")]
public static extern void freerdp_input_send_unicode_keyboard_event(IntPtr input, UInt16 flags, UInt16 code);
[DllImport("libfreerdp-core")]
public static extern void freerdp_input_send_mouse_event(IntPtr input, UInt16 flags, UInt16 x, UInt16 y);
[DllImport("libfreerdp-core")]
public static extern void freerdp_input_send_extended_mouse_event(IntPtr input, UInt16 flags, UInt16 x, UInt16 y);
public int Port { get { return (int) settings->port; } set { settings->port = (UInt32) value; } }
public int Width { get { return (int) settings->width; } set { settings->width = (UInt32) value; } }
public int Height { get { return (int) settings->height; } set { settings->height = (UInt32) value; } }
private freerdp* handle;
private IntPtr input;
private rdpContext* context;
private rdpSettings* settings;
private IUpdate iUpdate;
private IPrimaryUpdate iPrimaryUpdate;
private ISecondaryUpdate iSecondaryUpdate;
private IAltSecUpdate iAltSecUpdate;
private pContextNew hContextNew;
private pContextFree hContextFree;
private pPreConnect hPreConnect;
private pPostConnect hPostConnect;
private pAuthenticate hAuthenticate;
private pVerifyCertificate hVerifyCertificate;
private Update update;
private PrimaryUpdate primary;
public RDP()
{
handle = freerdp_new();
iUpdate = null;
iPrimaryUpdate = null;
iSecondaryUpdate = null;
iAltSecUpdate = null;
hContextNew = new pContextNew(ContextNew);
hContextFree = new pContextFree(ContextFree);
handle->ContextNew = Marshal.GetFunctionPointerForDelegate(hContextNew);
handle->ContextFree = Marshal.GetFunctionPointerForDelegate(hContextFree);
hAuthenticate = new pAuthenticate(Authenticate);
hVerifyCertificate = new pVerifyCertificate(VerifyCertificate);
handle->Authenticate = Marshal.GetFunctionPointerForDelegate(hAuthenticate);
handle->VerifyCertificate = Marshal.GetFunctionPointerForDelegate(hVerifyCertificate);
freerdp_context_new(handle);
}
~RDP()
{
}
public void SetUpdateInterface(IUpdate iUpdate)
{
this.iUpdate = iUpdate;
}
public void SetPrimaryUpdateInterface(IPrimaryUpdate iPrimaryUpdate)
{
this.iPrimaryUpdate = iPrimaryUpdate;
}
private IntPtr GetNativeAnsiString(string str)
{
ASCIIEncoding strEncoder = new ASCIIEncoding();
int size = strEncoder.GetByteCount(str);
IntPtr pStr = Memory.Zalloc(size);
byte[] buffer = strEncoder.GetBytes(str);
Marshal.Copy(buffer, 0, pStr, size);
return pStr;
}
void ContextNew(freerdp* instance, rdpContext* context)
{
Console.WriteLine("ContextNew");
hPreConnect = new pPreConnect(this.PreConnect);
hPostConnect = new pPostConnect(this.PostConnect);
instance->PreConnect = Marshal.GetFunctionPointerForDelegate(hPreConnect);
instance->PostConnect = Marshal.GetFunctionPointerForDelegate(hPostConnect);
this.context = context;
input = instance->input;
settings = instance->settings;
}
void ContextFree(freerdp* instance, rdpContext* context)
{
Console.WriteLine("ContextFree");
}
bool PreConnect(freerdp* instance)
{
Console.WriteLine("PreConnect");
if (iUpdate != null)
{
update = new Update(instance->context);
update.RegisterInterface(iUpdate);
}
if (iPrimaryUpdate != null)
{
primary = new PrimaryUpdate(instance->context);
primary.RegisterInterface(iPrimaryUpdate);
}
settings->rfxCodec = 1;
settings->fastpathOutput = 1;
settings->colorDepth = 32;
settings->frameAcknowledge = 0;
settings->performanceFlags = 0;
settings->largePointer = 1;
settings->glyphCache = 0;
settings->bitmapCache = 0;
settings->offscreenBitmapCache = 0;
return true;
}
bool PostConnect(freerdp* instance)
{
Console.WriteLine("PostConnect");
return true;
}
public bool Connect(string hostname, int port, string username, string domain, string password)
{
settings->port = (uint) port;
Console.WriteLine("hostname:{0} username:{1} width:{2} height:{3} port:{4}",
hostname, username, settings->width, settings->height, settings->port);
settings->ignoreCertificate = 1;
settings->hostname = GetNativeAnsiString(hostname);
settings->username = GetNativeAnsiString(username);
if (domain.Length > 1)
settings->domain = GetNativeAnsiString(domain);
if (password.Length > 1)
settings->password = GetNativeAnsiString(password);
else
settings->authentication = 0;
return ((freerdp_connect(handle) == 0) ? false : true);
}
public bool Disconnect()
{
return ((freerdp_disconnect(handle) == 0) ? false : true);
}
private bool Authenticate(freerdp* instance, IntPtr username, IntPtr password, IntPtr domain)
{
return true;
}
private bool VerifyCertificate(freerdp* instance, IntPtr subject, IntPtr issuer, IntPtr fingerprint)
{
return true;
}
public bool CheckFileDescriptor()
{
return ((freerdp_check_fds(handle) == 0) ? false : true);
}
public void SendInputSynchronizeEvent(UInt32 flags)
{
freerdp_input_send_synchronize_event(input, flags);
}
public void SendInputKeyboardEvent(UInt16 flags, UInt16 code)
{
freerdp_input_send_keyboard_event(input, flags, code);
}
public void SendInputUnicodeKeyboardEvent(UInt16 flags, UInt16 code)
{
freerdp_input_send_unicode_keyboard_event(input, flags, code);
}
public void SendInputMouseEvent(UInt16 flags, UInt16 x, UInt16 y)
{
freerdp_input_send_mouse_event(input, flags, x, y);
}
public void SendInputExtendedMouseEvent(UInt16 flags, UInt16 x, UInt16 y)
{
freerdp_input_send_extended_mouse_event(input, flags, x, y);
}
}
}
| |
using System;
using System.Collections.Specialized;
using Skybrud.Social.Google.Analytics.Endpoints.Raw;
using Skybrud.Social.Google.Analytics.Objects;
using Skybrud.Social.Google.OAuth;
namespace Skybrud.Social.Google.Analytics {
/// <summary>
/// Raw implementation of the Analytics endpoint.
/// </summary>
public class AnalyticsRawEndpoint {
// TODO: Move class to the "Skybrud.Social.Google.Analytics.Endpoints.Raw" namespace for v1.0
protected const string ManagementUrl = "https://www.googleapis.com/analytics/v3/management/";
#region Properties
/// <summary>
/// Gets a reference to the Google OAuth client.
/// </summary>
public GoogleOAuthClient Client { get; private set; }
/// <summary>
/// Gets a reference to the raw management endpoint.
/// </summary>
public AnalyticsManagementRawEndpoint Management { get; private set; }
/// <summary>
/// Gets a reference to the raw data endpoint.
/// </summary>
public AnalyticsDataRawEndpoint Data { get; private set; }
#endregion
#region Constructors
internal AnalyticsRawEndpoint(GoogleOAuthClient client) {
Client = client;
Management = new AnalyticsManagementRawEndpoint(client);
Data = new AnalyticsDataRawEndpoint(client);
}
#endregion
#region Accounts
/// <summary>
/// Gets a list of Analytics accounts of the authenticated user.
/// </summary>
/// <returns>Returns an instance of <code>SocialHttpResponse</code> representing the response.</returns>
[Obsolete("Use the GetAccounts method in the new Management endpoint. See release notes for v0.9.4 for further information.")]
public string GetAccounts() {
return SocialUtils.DoHttpGetRequestAndGetBodyAsString("https://www.googleapis.com/analytics/v3/management/accounts", new NameValueCollection {
{"access_token", Client.AccessToken}
});
}
#endregion
#region Web properties
[Obsolete("Use the GetWebProperties method in the new Management endpoint. See release notes for v0.9.4 for further information.")]
public string GetWebProperties(int maxResults = 0, int startIndex = 0) {
return GetWebProperties("~all", maxResults, startIndex);
}
[Obsolete("Use the GetWebProperties method in the new Management endpoint. See release notes for v0.9.4 for further information.")]
public string GetWebProperties(AnalyticsAccount account, int maxResults = 0, int startIndex = 0) {
return GetWebProperties(account.Id, maxResults, startIndex);
}
[Obsolete("Use the GetWebProperties method in the new Management endpoint. See release notes for v0.9.4 for further information.")]
public string GetWebProperties(string accountId, int maxResults = 0, int startIndex = 0) {
NameValueCollection query = new NameValueCollection();
if (maxResults > 0) query.Add("max-results", maxResults + "");
if (startIndex > 0) query.Add("start-index", startIndex + "");
query.Add("access_token", Client.AccessToken);
return SocialUtils.DoHttpGetRequestAndGetBodyAsString("https://www.googleapis.com/analytics/v3/management/accounts/" + accountId + "/webproperties", query);
}
#endregion
#region Profiles
/// <summary>
/// Gets a view (profile) to which the user has access.
/// </summary>
/// <param name="accountId">Account ID to retrieve the goal for.</param>
/// <param name="webPropertyId">Web property ID to retrieve the goal for.</param>
/// <param name="profileId">View (Profile) ID to retrieve the goal for.</param>
public string GetProfile(string accountId, string webPropertyId, string profileId) {
// Construct the URL
string url = String.Format(
"{0}accounts/{1}/webproperties/{2}/profiles/{3}",
ManagementUrl,
accountId,
webPropertyId,
profileId
);
// Make the call to the API
return Client.DoAuthenticatedGetRequest(url);
}
/// <summary>
/// Gets a list of all profiles the user has access to.
/// </summary>
/// <param name="maxResults">The maximum number of views (profiles) to include in this response.</param>
/// <param name="startIndex">An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.</param>
public string GetProfiles(int maxResults = 0, int startIndex = 0) {
return GetProfiles("~all", "~all", maxResults, startIndex);
}
/// <summary>
/// Gets a list of all profiles for the specified account. The result will profiles of all web properties of the account.
/// </summary>
/// <param name="account">The parent account.</param>
/// <param name="maxResults">The maximum number of views (profiles) to include in this response.</param>
/// <param name="startIndex">An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.</param>
public string GetProfiles(AnalyticsAccount account, int maxResults = 0, int startIndex = 0) {
return GetProfiles(account.Id, "~all", maxResults, startIndex);
}
/// <summary>
/// Gets a list of profiles for the specified web property.
/// </summary>
/// <param name="property">The parent web propaerty.</param>
/// <param name="maxResults">The maximum number of views (profiles) to include in this response.</param>
/// <param name="startIndex">An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.</param>
public string GetProfiles(AnalyticsWebProperty property, int maxResults = 0, int startIndex = 0) {
return GetProfiles(property.AccountId, property.Id, maxResults, startIndex);
}
/// <summary>
/// Gets a list of profiles for the specified account.
/// </summary>
/// <param name="accountId">Account ID for the view (profiles) to retrieve. Can either be a specific account ID or '~all', which refers to all the accounts to which the user has access.</param>
/// <param name="maxResults">The maximum number of views (profiles) to include in this response.</param>
/// <param name="startIndex">An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.</param>
public string GetProfiles(string accountId, int maxResults = 0, int startIndex = 0) {
return GetProfiles(accountId, "~all", maxResults, startIndex);
}
/// <summary>
/// Gets a list of profiles for the specified account and web property.
/// </summary>
/// <param name="accountId">Account ID for the view (profiles) to retrieve. Can either be a specific account ID or '~all', which refers to all the accounts to which the user has access.</param>
/// <param name="webPropertyId">Web property ID for the views (profiles) to retrieve. Can either be a specific web property ID or '~all', which refers to all the web properties to which the user has access.</param>
/// <param name="maxResults">The maximum number of views (profiles) to include in this response.</param>
/// <param name="startIndex">An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.</param>
public string GetProfiles(string accountId, string webPropertyId, int maxResults = 0, int startIndex = 0) {
// Construct the query string
NameValueCollection query = new NameValueCollection();
if (maxResults > 0) query.Add("max-results", maxResults + "");
if (startIndex > 0) query.Add("start-index", startIndex + "");
// Construct the URL
string url = String.Format(
"{0}accounts/" + accountId + "/webproperties/" + webPropertyId + "/profiles",
ManagementUrl,
accountId,
webPropertyId
);
// Make the call to the API
return Client.DoAuthenticatedGetRequest(url, query);
}
#endregion
#region Data
[Obsolete("Use the GetData method in the new Data endpoint. See release notes for v0.9.4 for further information.")]
public string GetData(AnalyticsProfile profile, DateTime startDate, DateTime endDate, string[] metrics, string[] dimensions) {
return GetData(profile.Id, startDate, endDate, metrics, dimensions);
}
[Obsolete("Use the GetData method in the new Data endpoint. See release notes for v0.9.4 for further information.")]
public string GetData(string profileId, DateTime startDate, DateTime endDate, string[] metrics, string[] dimensions) {
return GetData(profileId, new AnalyticsDataOptions {
StartDate = startDate,
EndDate = endDate,
Metrics = metrics,
Dimensions = dimensions
});
}
[Obsolete("Use the GetData method in the new Data endpoint. See release notes for v0.9.4 for further information.")]
public string GetData(AnalyticsProfile profile, DateTime startDate, DateTime endDate, AnalyticsMetricCollection metrics, AnalyticsDimensionCollection dimensions) {
return GetData(profile.Id, startDate, endDate, metrics, dimensions);
}
[Obsolete("Use the GetData method in the new Data endpoint. See release notes for v0.9.4 for further information.")]
public string GetData(string profileId, DateTime startDate, DateTime endDate, AnalyticsMetricCollection metrics, AnalyticsDimensionCollection dimensions) {
return GetData(profileId, new AnalyticsDataOptions {
StartDate = startDate,
EndDate = endDate,
Metrics = metrics,
Dimensions = dimensions
});
}
[Obsolete("Use the GetData method in the new Data endpoint. See release notes for v0.9.4 for further information.")]
public string GetData(AnalyticsProfile profile, AnalyticsDataOptions options) {
return GetData(profile.Id, options);
}
[Obsolete("Use the GetData method in the new Data endpoint. See release notes for v0.9.4 for further information.")]
public string GetData(string profileId, AnalyticsDataOptions options) {
// Validate arguments
if (options == null) throw new ArgumentNullException("options");
// Generate the name value collection
NameValueCollection query = options.ToNameValueCollection(profileId, Client.AccessToken);
// Make the call to the API
return SocialUtils.DoHttpGetRequestAndGetBodyAsString("https://www.googleapis.com/analytics/v3/data/ga", query);
}
#endregion
#region Realtime data
/// <summary>
/// Gets the realtime data from the specified profile and metrics.
/// </summary>
/// <param name="profile">The Analytics profile to gather realtime data from.</param>
/// <param name="metrics">The metrics collection of what data to return.</param>
[Obsolete("Use the GetRealtimeData method in the new Data endpoint. See release notes for v0.9.4 for further information.")]
public string GetRealtimeData(AnalyticsProfile profile, AnalyticsMetricCollection metrics) {
return GetRealtimeData(profile.Id, metrics);
}
/// <summary>
/// Gets the realtime data from the specified profile, metrics and dimensions.
/// </summary>
/// <param name="profile">The Analytics profile to gather realtime data from.</param>
/// <param name="metrics">The metrics collection of what data to return.</param>
/// <param name="dimensions">The dimensions collection of what data to return.</param>
[Obsolete("Use the GetRealtimeData method in the new Data endpoint. See release notes for v0.9.4 for further information.")]
public string GetRealtimeData(AnalyticsProfile profile, AnalyticsMetricCollection metrics, AnalyticsDimensionCollection dimensions) {
return GetRealtimeData(profile.Id, metrics, dimensions);
}
/// <summary>
/// Gets the realtime data from the specified profile and options.
/// </summary>
/// <param name="profile">The Analytics profile to gather realtime data from.</param>
/// <param name="options">The options specifying the query.</param>
[Obsolete("Use the GetRealtimeData method in the new Data endpoint. See release notes for v0.9.4 for further information.")]
public string GetRealtimeData(AnalyticsProfile profile, AnalyticsRealtimeDataOptions options) {
return GetRealtimeData(profile.Id, options);
}
/// <summary>
/// Gets the realtime data from the specified profile and metrics.
/// </summary>
/// <param name="profileId">The ID of the Analytics profile.</param>
/// <param name="metrics">The metrics collection of what data to return.</param>
[Obsolete("Use the GetRealtimeData method in the new Data endpoint. See release notes for v0.9.4 for further information.")]
public string GetRealtimeData(string profileId, AnalyticsMetricCollection metrics) {
return GetRealtimeData(profileId, new AnalyticsRealtimeDataOptions {
Metrics = metrics
});
}
/// <summary>
/// Gets the realtime data from the specified profile and metrics.
/// </summary>
/// <param name="profileId">The ID of the Analytics profile.</param>
/// <param name="metrics">The metrics collection of what data to return.</param>
/// <param name="dimensions">The dimensions collection of what data to return.</param>
[Obsolete("Use the GetRealtimeData method in the new Data endpoint. See release notes for v0.9.4 for further information.")]
public string GetRealtimeData(string profileId, AnalyticsMetricCollection metrics, AnalyticsDimensionCollection dimensions) {
return GetRealtimeData(profileId, new AnalyticsRealtimeDataOptions {
Metrics = metrics,
Dimensions = dimensions
});
}
/// <summary>
/// Gets the realtime data from the specified profile and options.
/// </summary>
/// <param name="profileId">The ID of the Analytics profile.</param>
/// <param name="options">The options specifying the query.</param>
[Obsolete("Use the GetRealtimeData method in the new Data endpoint. See release notes for v0.9.4 for further information.")]
public string GetRealtimeData(string profileId, AnalyticsRealtimeDataOptions options) {
// Validate arguments
if (options == null) throw new ArgumentNullException("options");
// Generate the name value collection
NameValueCollection query = options.ToNameValueCollection(profileId, Client.AccessToken);
// Make the call to the API
return SocialUtils.DoHttpGetRequestAndGetBodyAsString("https://www.googleapis.com/analytics/v3/data/realtime", query);
}
#endregion
}
}
| |
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.TestFramework.Fixtures
{
using System;
using System.Collections.Generic;
using System.Linq;
using BusConfigurators;
using Configurators;
using EndpointConfigurators;
using Exceptions;
using Magnum.Extensions;
using MassTransit.Transports;
using NUnit.Framework;
using Saga;
using Services.Subscriptions;
/// <summary>
/// Test fixture that tests a single endpoint, given
/// a transport factory. The transport factory needs to
/// have a default public c'tor. The endpoint is one-to-one
/// with the bus in this test fixture.
/// </summary>
/// <typeparam name="TTransportFactory">Type of transport factory to create the endpoint with</typeparam>
[TestFixture]
public abstract class EndpointTestFixture<TTransportFactory> :
AbstractTestFixture
where TTransportFactory : class, ITransportFactory, new()
{
/// <summary>
/// Sets up the endpoint factory by calling the configurator (see <see cref="ConfigureEndpointFactory"/>)
/// and sets a few defaults on the service bus factory.
/// </summary>
[TestFixtureSetUp]
public void Setup()
{
if (EndpointFactoryConfigurator != null)
{
ConfigurationResult result = ConfigurationResultImpl.CompileResults(EndpointFactoryConfigurator.Validate());
try
{
EndpointFactory = EndpointFactoryConfigurator.CreateEndpointFactory();
EndpointFactoryConfigurator = null;
_endpointCache = new EndpointCache(EndpointFactory);
EndpointCache = new EndpointCacheProxy(_endpointCache);
}
catch (Exception ex)
{
throw new ConfigurationException(result, "An exception was thrown during endpoint cache creation", ex);
}
}
ServiceBusFactory.ConfigureDefaultSettings(x =>
{
x.SetEndpointCache(EndpointCache);
x.SetConcurrentConsumerLimit(4);
x.SetReceiveTimeout(150.Milliseconds());
x.EnableAutoStart();
});
}
/// <summary>
/// Tears down the buses,
/// tears down the endpoint caches.
/// </summary>
[TestFixtureTearDown]
public void FixtureTeardown()
{
TeardownBuses();
if (EndpointCache != null)
{
_endpointCache.Dispose();
_endpointCache = null;
EndpointCache = null;
}
ServiceBusFactory.ConfigureDefaultSettings(x => { x.SetEndpointCache(null); });
}
/// <summary>
/// c'tor that sets up the endpoint configurator, its default settings,
/// and uses the class type parameter <see cref="TTransportFactory"/>
/// as the transport for that endpoint.
/// </summary>
protected EndpointTestFixture()
{
Buses = new List<IServiceBus>();
var defaultSettings = new EndpointFactoryDefaultSettings();
EndpointFactoryConfigurator = new EndpointFactoryConfiguratorImpl(defaultSettings);
EndpointFactoryConfigurator.AddTransportFactory<TTransportFactory>();
EndpointFactoryConfigurator.SetPurgeOnStartup(true);
}
/// <summary>
/// Add further transport factories to the endpoint configured as a
/// result of this test fixture set up logic.
/// </summary>
/// <typeparam name="T">type of transport factory to add.</typeparam>
protected void AddTransport<T>()
where T : class, ITransportFactory, new()
{
EndpointFactoryConfigurator.AddTransportFactory<T>();
}
protected IEndpointFactory EndpointFactory { get; private set; }
/// <summary>
/// Call this method from anytime before the test fixture set up
/// starts running (i.e. in the c'tor) to configure the endpoint factory.
/// </summary>
/// <param name="configure">The action that configures the endpoint factory configurator.</param>
protected void ConfigureEndpointFactory(Action<EndpointFactoryConfigurator> configure)
{
if (EndpointFactoryConfigurator == null)
throw new ConfigurationException("The endpoint factory configurator has already been executed.");
configure(EndpointFactoryConfigurator);
}
protected void ConnectSubscriptionService(ServiceBusConfigurator configurator,
ISubscriptionService subscriptionService)
{
configurator.AddService(BusServiceLayer.Session, () => new SubscriptionPublisher(subscriptionService));
configurator.AddService(BusServiceLayer.Session, () => new SubscriptionConsumer(subscriptionService));
}
/// <summary>
/// Sets up a new in memory saga repository for the passed type of saga.
/// </summary>
/// <typeparam name="TSaga">The saga to test.</typeparam>
/// <returns>An instance of the saga repository.</returns>
protected static InMemorySagaRepository<TSaga> SetupSagaRepository<TSaga>()
where TSaga : class, ISaga
{
var sagaRepository = new InMemorySagaRepository<TSaga>();
return sagaRepository;
}
/// <summary>
/// Set this property to have custom [<see cref="TestFixtureSetUpAttribute"/>] logic.
/// </summary>
protected EndpointFactoryConfigurator EndpointFactoryConfigurator;
EndpointCache _endpointCache;
void TeardownBuses()
{
Buses.Reverse().Each(bus => { bus.Dispose(); });
Buses.Clear();
}
/// <summary>
/// Gets the list of buses that are created in this test fixture. Call
/// <see cref="SetupServiceBus(System.Uri,System.Action{MassTransit.BusConfigurators.ServiceBusConfigurator})"/>
/// to create more of them
/// </summary>
protected IList<IServiceBus> Buses { get; private set; }
/// <summary>
/// Gets the endpoint cache implementation used in this test. Is set up
/// during the [TestFixtureSetUp] phase aka. [Given] phase.
/// </summary>
protected IEndpointCache EndpointCache { get; private set; }
/// <summary>
/// Call this method to set up a new service bus and add it to the <see cref="Buses"/> list.
/// </summary>
/// <param name="uri">The bus endpoint uri (its consumption point)</param>
/// <param name="configure">The configuration action, that allows you to configure the new
/// bus as you please.</param>
/// <returns>The new service bus that was configured.</returns>
protected virtual IServiceBus SetupServiceBus(Uri uri, Action<ServiceBusConfigurator> configure)
{
IServiceBus bus = ServiceBusFactory.New(x =>
{
x.ReceiveFrom(uri);
configure(x);
});
Buses.Add(bus);
return bus;
}
/// <summary>
/// See <see cref="SetupServiceBus(System.Uri,System.Action{MassTransit.BusConfigurators.ServiceBusConfigurator})"/>.
/// </summary>
/// <param name="uri">The uri to set the service bus up at.</param>
/// <returns>The service bus instance.</returns>
protected virtual IServiceBus SetupServiceBus(Uri uri)
{
return SetupServiceBus(uri, x =>
{
ConfigureServiceBus(uri, x);
});
}
/// <summary>
/// This method does nothing at all. Override (you don't need to call into the base)
/// to provide the default action to configure the buses newly created, with.
/// </summary>
/// <param name="uri">The uri that is passed from the configuration lambda of the bus.</param>
/// <param name="configurator">The service bus configurator.</param>
protected virtual void ConfigureServiceBus(Uri uri, ServiceBusConfigurator configurator)
{
}
}
}
| |
//
// Created by Ian Copland on 2015-11-10
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tag Games Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using SdkCore.MiniJSON;
namespace SdkCore
{
/// <summary>
/// <para>Provides a means to make both GET and POST requests to the given
/// web-server. Requests can be both HTTP and HTTPS.</para>
///
/// <para>This is thread-safe.</para>
/// </summary>
public sealed class HttpSystem
{
private TaskScheduler m_taskScheduler;
/// <summary>
/// Initializes a new instance of the HTTP system with the given task
/// scheduler.
/// </summary>
///
/// <param name="taskScheduler">The task scheduler.</param>
public HttpSystem(TaskScheduler taskScheduler)
{
ReleaseAssert.IsTrue(taskScheduler != null, "The task scheduler in a HTTP request system must not be null.");
m_taskScheduler = taskScheduler;
}
/// <summary>
/// Makes a HTTP GET request with the given request object. This is
/// performed asynchronously, with the callback block run on a background
/// thread.
/// </summary>
///
/// <param name="request">The GET HTTP request.</param>
/// <param name="callback">The callback which will provide the response from the server.
/// The callback will be made on a background thread.</param>
public void SendRequest(HttpGetRequest request, Action<HttpGetRequest, HttpResponse> callback)
{
ReleaseAssert.IsTrue(request != null, "The HTTP GET request must not be null when sending a request.");
ReleaseAssert.IsTrue(callback != null, "The callback must not be null when sending a request.");
SendRequest(request.Url, request.Headers, null, (HttpResponse response) =>
{
callback(request, response);
});
}
/// <summary>
/// Makes a HTTP POST request with the given request object. This is
/// performed asynchronously, with the callback block run on a background
/// thread.
/// </summary>
///
/// <param name="request">The POST HTTP request.</param>
/// <param name="callback">The callback which will provide the response from the server.
/// The callback will be made on a background thread.</param>
public void SendRequest(HttpPostRequest request, Action<HttpPostRequest, HttpResponse> callback)
{
ReleaseAssert.IsTrue(request != null, "The HTTP POST request must not be null when sending a request.");
ReleaseAssert.IsTrue(callback != null, "The callback must not be null when sending a request.");
var headers = new Dictionary<string, string>(request.Headers);
if (request.ContentType != null)
{
headers.Add("Content-Type", request.ContentType);
}
SendRequest(request.Url, headers, request.Body, (HttpResponse response) =>
{
callback(request, response);
});
}
/// <summary>
/// Provides the means to send both GET and POST requests depending on the
/// input data.
/// </summary>
///
/// <param name="url">The URL that the request is targetting.</param>
/// <param name="headers">The headers for the HTTP request.</param>
/// <param name="body">The body of the request. If null, a GET request will be sent.</param>
/// <param name="callback">The callback providing the response from the server.</param>
private void SendRequest(String url, IDictionary<string, string> headers, byte[] body, Action<HttpResponse> callback)
{
ReleaseAssert.IsTrue(url != null, "The URL must not be null when sending a request.");
ReleaseAssert.IsTrue(headers != null, "The headers must not be null when sending a request.");
ReleaseAssert.IsTrue(callback != null, "The callback must not be null when sending a request.");
// Unity's WWW class works with the Dictionary concrete class rather than the abstract
// IDictionary. Rather than cast a copy is made so we can be sure other dictionary types
// will work.
Dictionary<string, string> headersConcreteDict = new Dictionary<string, string>(headers);
m_taskScheduler.ScheduleMainThreadTask(() =>
{
var www = new WWW(url, body, headersConcreteDict);
m_taskScheduler.StartCoroutine(ProcessRequest(www, callback));
});
}
/// <summary>
/// <para>The coroutine for processing the HTTP request. This will yield until the
/// request has completed then parse the information required by a HTTP response
/// from the WWW object.</para>
/// </summary>
///
/// <returns>The coroutine enumerator.</returns>
///
/// <param name="www">The WWW object.</param>
/// <param name="callback">The callback providing the response from the server.</param>
private IEnumerator ProcessRequest(WWW www, Action<HttpResponse> callback)
{
ReleaseAssert.IsTrue(www != null, "The WWW must not be null when sending a request.");
ReleaseAssert.IsTrue(callback != null, "The callback must not be null when sending a request.");
yield return www;
HttpResponseDesc desc = null;
if (string.IsNullOrEmpty(www.error))
{
ReleaseAssert.IsTrue(www.responseHeaders != null, "A successful HTTP response must have a headers object.");
desc = new HttpResponseDesc(HttpResult.Success);
desc.Headers = new Dictionary<string, string>(www.responseHeaders);
if (www.bytes != null)
{
desc.Body = www.bytes;
}
var httpStatus = www.responseHeaders ["STATUS"];
ReleaseAssert.IsTrue(!string.IsNullOrEmpty(httpStatus), "A successful HTTP response must have a HTTP status value in the header.");
desc.HttpResponseCode = ParseHttpStatus(httpStatus);
}
else
{
var bytes = www.bytes;
int httpResponseCode = 0;
#if UNITY_IPHONE && !UNITY_EDITOR
var text = www.text;
if ( !string.IsNullOrEmpty(text) )
{
var bodyDictionary = Json.Deserialize(text) as Dictionary<string, object>;
if (bodyDictionary != null && bodyDictionary.ContainsKey ("HttpCode"))
{
httpResponseCode = Convert.ToInt32(bodyDictionary ["HttpCode"]);
bytes = Encoding.UTF8.GetBytes(text);
}
}
#else
httpResponseCode = ParseHttpError(www.error);
#endif
if (httpResponseCode != 0)
{
desc = new HttpResponseDesc(HttpResult.Success);
desc.Headers = new Dictionary<string, string>(www.responseHeaders);
if (www.bytes != null)
{
desc.Body = www.bytes;
}
desc.HttpResponseCode = httpResponseCode;
}
else
{
desc = new HttpResponseDesc(HttpResult.CouldNotConnect);
}
}
HttpResponse response = new HttpResponse(desc);
m_taskScheduler.ScheduleBackgroundTask(() =>
{
callback(response);
});
}
/// <summary>
/// Parses the HTTP response code from the given HTTP STATUS string. The string should
/// be in the format 'HTTP/X YYY...' or 'HTTP/X.X YYY...' where YYY is the response
/// code.
/// </summary>
///
/// <returns>The response code.</returns>
///
/// <param name="httpStatus">The HTTP status string in the format 'HTTP/X YYY...'
/// or 'HTTP/X.X YYY...'.</param>
private int ParseHttpStatus(string httpStatus)
{
ReleaseAssert.IsTrue(httpStatus != null, "The HTTP status string must not be null when parsing a response code.");
var regex = new Regex("[a-zA-Z]*\\/\\d+(\\.\\d)?\\s(?<httpResponseCode>\\d+)\\s");
var match = regex.Match(httpStatus);
ReleaseAssert.IsTrue(match.Groups.Count == 3, "There must be exactly 3 match groups when using a regex on a HTTP status.");
var responseCodeString = match.Groups ["httpResponseCode"].Value;
ReleaseAssert.IsTrue(responseCodeString != null, "The response code string cannot be null when using a regex on a HTTP status.");
return Int32.Parse(responseCodeString);
}
/// <summary>
/// Parses the HTTP response code from the given HTTP error string. The string should
/// be in the format 'XXX ...' where XXX is the HTTP response code.
/// </summary>
///
/// <returns>The response code parsed from the error, or 0 if there wasn't one.</returns>
///
/// <param name="httpError">The HTTP error string.</param>
private int ParseHttpError(string httpError)
{
ReleaseAssert.IsTrue(httpError != null, "The HTTP error string must not be null when parsing a response code.");
var regex = new Regex("(?<httpResponseCode>[0-9][0-9][0-9])\\s");
if (regex.IsMatch(httpError))
{
var match = regex.Match(httpError);
ReleaseAssert.IsTrue(match.Groups.Count == 2, "There must be exactly 2 match groups when using a regex on a HTTP error.");
var responseCodeString = match.Groups ["httpResponseCode"].Value;
ReleaseAssert.IsTrue(responseCodeString != null, "The response code string cannot be null when using a regex on a HTTP error.");
return Int32.Parse(responseCodeString);
}
return 0;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
/*
================================================================================
The DOFPostEffect API
================================================================================
DOFPostEffect::setFocalDist( %dist )
@summary
This method is for manually controlling the focus distance. It will have no
effect if auto focus is currently enabled. Makes use of the parameters set by
setFocusParams.
@param dist
float distance in meters
--------------------------------------------------------------------------------
DOFPostEffect::setAutoFocus( %enabled )
@summary
This method sets auto focus enabled or disabled. Makes use of the parameters set
by setFocusParams. When auto focus is enabled it determines the focal depth
by performing a raycast at the screen-center.
@param enabled
bool
--------------------------------------------------------------------------------
DOFPostEffect::setFocusParams( %nearBlurMax, %farBlurMax, %minRange, %maxRange, %nearSlope, %farSlope )
Set the parameters that control how the near and far equations are calculated
from the focal distance. If you are not using auto focus you will need to call
setFocusParams PRIOR to calling setFocalDist.
@param nearBlurMax
float between 0.0 and 1.0
The max allowed value of near blur.
@param farBlurMax
float between 0.0 and 1.0
The max allowed value of far blur.
@param minRange/maxRange
float in meters
The distance range around the focal distance that remains in focus is a lerp
between the min/maxRange using the normalized focal distance as the parameter.
The point is to allow the focal range to expand as you focus farther away since this is
visually appealing.
Note: since min/maxRange are lerped by the "normalized" focal distance it is
dependant on the visible distance set in your level.
@param nearSlope
float less than zero
The slope of the near equation. A small number causes bluriness to increase gradually
at distances closer than the focal distance. A large number causes bluriness to
increase quickly.
@param farSlope
float greater than zero
The slope of the far equation. A small number causes bluriness to increase gradually
at distances farther than the focal distance. A large number causes bluriness to
increase quickly.
Note: To rephrase, the min/maxRange parameters control how much area around the
focal distance is completely in focus where the near/farSlope parameters control
how quickly or slowly bluriness increases at distances outside of that range.
================================================================================
Examples
================================================================================
Example1: Turn on DOF while zoomed in with a weapon.
NOTE: These are not real callbacks! Hook these up to your code where appropriate!
function onSniperZoom()
{
// Parameterize how you want DOF to look.
DOFPostEffect.setFocusParams( 0.3, 0.3, 50, 500, -5, 5 );
// Turn on auto focus
DOFPostEffect.setAutoFocus( true );
// Turn on the PostEffect
DOFPostEffect.enable();
}
function onSniperUnzoom()
{
// Turn off the PostEffect
DOFPostEffect.disable();
}
Example2: Manually control DOF with the mouse wheel.
// Somewhere on startup...
// Parameterize how you want DOF to look.
DOFPostEffect.setFocusParams( 0.3, 0.3, 50, 500, -5, 5 );
// Turn off auto focus
DOFPostEffect.setAutoFocus( false );
// Turn on the PostEffect
DOFPostEffect.enable();
NOTE: These are not real callbacks! Hook these up to your code where appropriate!
function onMouseWheelUp()
{
// Since setFocalDist is really just a wrapper to assign to the focalDist
// dynamic field we can shortcut and increment it directly.
DOFPostEffect.focalDist += 8;
}
function onMouseWheelDown()
{
DOFPostEffect.focalDist -= 8;
}
*/
/// This method is for manually controlling the focal distance. It will have no
/// effect if auto focus is currently enabled. Makes use of the parameters set by
/// setFocusParams.
function DOFPostEffect::setFocalDist( %this, %dist )
{
%this.focalDist = %dist;
}
/// This method sets auto focus enabled or disabled. Makes use of the parameters set
/// by setFocusParams. When auto focus is enabled it determine the focal depth
/// by performing a raycast at the screen-center.
function DOFPostEffect::setAutoFocus( %this, %enabled )
{
%this.autoFocusEnabled = %enabled;
}
/// Set the parameters that control how the near and far equations are calculated
/// from the focal distance. If you are not using auto focus you will need to call
/// setFocusParams PRIOR to calling setFocalDist.
function DOFPostEffect::setFocusParams( %this, %nearBlurMax, %farBlurMax, %minRange, %maxRange, %nearSlope, %farSlope )
{
%this.nearBlurMax = %nearBlurMax;
%this.farBlurMax = %farBlurMax;
%this.minRange = %minRange;
%this.maxRange = %maxRange;
%this.nearSlope = %nearSlope;
%this.farSlope = %farSlope;
}
/*
More information...
This DOF technique is based on this paper:
http://http.developer.nvidia.com/GPUGems3/gpugems3_ch28.html
================================================================================
1. Overview of how we represent "Depth of Field"
================================================================================
DOF is expressed as an amount of bluriness per pixel according to its depth.
We represented this by a piecewise linear curve depicted below.
Note: we also refer to "bluriness" as CoC ( circle of confusion ) which is the term
used in the basis paper and in photography.
X-axis (depth)
x = 0.0----------------------------------------------x = 1.0
Y-axis (bluriness)
y = 1.0
|
| ____(x1,y1) (x4,y4)____
| (ns,nb)\ <--Line1 line2---> /(fe,fb)
| \ /
| \(x2,y2) (x3,y3)/
| (ne,0)------(fs,0)
y = 0.0
I have labeled the "corners" of this graph with (Xn,Yn) to illustrate that
this is in fact a collection of line segments where the x/y of each point
corresponds to the key below.
key:
ns - (n)ear blur (s)tart distance
nb - (n)ear (b)lur amount (max value)
ne - (n)ear blur (e)nd distance
fs - (f)ar blur (s)tart distance
fe - (f)ar blur (e)nd distance
fb - (f)ar (b)lur amount (max value)
Of greatest importance in this graph is Line1 and Line2. Where...
L1 { (x1,y1), (x2,y2) }
L2 { (x3,y3), (x4,y4) }
Line one represents the amount of "near" blur given a pixels depth and line two
represents the amount of "far" blur at that depth.
Both these equations are evaluated for each pixel and then the larger of the two
is kept. Also the output blur (for each equation) is clamped between 0 and its
maximum allowable value.
Therefore, to specify a DOF "qualify" you need to specify the near-blur-line,
far-blur-line, and maximum near and far blur value.
================================================================================
2. Abstracting a "focal depth"
================================================================================
Although the shader(s) work in terms of a near and far equation it is more
useful to express DOF as an adjustable focal depth and derive the other parameters
"under the hood".
Given a maximum near/far blur amount and a near/far slope we can calculate the
near/far equations for any focal depth. We extend this to also support a range
of depth around the focal depth that is also in focus and for that range to
shrink or grow as the focal depth moves closer or farther.
Keep in mind this is only one implementation and depending on the effect you
desire you may which to express the relationship between focal depth and
the shader paramaters different.
*/
//-----------------------------------------------------------------------------
// GFXStateBlockData / ShaderData
//-----------------------------------------------------------------------------
singleton GFXStateBlockData( PFX_DefaultDOFStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerClampPoint;
};
singleton GFXStateBlockData( PFX_DOFCalcCoCStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
};
singleton GFXStateBlockData( PFX_DOFDownSampleStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampPoint;
};
singleton GFXStateBlockData( PFX_DOFBlurStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
};
singleton GFXStateBlockData( PFX_DOFFinalStateBlock )
{
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
samplerStates[2] = SamplerClampLinear;
samplerStates[3] = SamplerClampPoint;
blendDefined = true;
blendEnable = true;
blendDest = GFXBlendInvSrcAlpha;
blendSrc = GFXBlendOne;
};
singleton ShaderData( PFX_DOFDownSampleShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_DownSample_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_DownSample_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_DownSample_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_DownSample_P.glsl";
samplerNames[0] = "$colorSampler";
samplerNames[1] = "$depthSampler";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFBlurYShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_Gausian_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_Gausian_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_Gausian_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_Gausian_P.glsl";
samplerNames[0] = "$diffuseMap";
pixVersion = 2.0;
defines = "BLUR_DIR=float2(0.0,1.0)";
};
singleton ShaderData( PFX_DOFBlurXShader : PFX_DOFBlurYShader )
{
defines = "BLUR_DIR=float2(1.0,0.0)";
};
singleton ShaderData( PFX_DOFCalcCoCShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_CalcCoC_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_CalcCoC_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_CalcCoC_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_CalcCoC_P.glsl";
samplerNames[0] = "$shrunkSampler";
samplerNames[1] = "$blurredSampler";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFSmallBlurShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_SmallBlur_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_SmallBlur_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_SmallBlur_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_SmallBlur_P.glsl";
samplerNames[0] = "$colorSampler";
pixVersion = 3.0;
};
singleton ShaderData( PFX_DOFFinalShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_Final_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/DOF_Final_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_Final_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/dof/gl/DOF_Final_P.glsl";
samplerNames[0] = "$colorSampler";
samplerNames[1] = "$smallBlurSampler";
samplerNames[2] = "$largeBlurSampler";
samplerNames[3] = "$depthSampler";
pixVersion = 3.0;
};
//-----------------------------------------------------------------------------
// PostEffects
//-----------------------------------------------------------------------------
function DOFPostEffect::onAdd( %this )
{
// The weighted distribution of CoC value to the three blur textures
// in the order small, medium, large. Most likely you will not need to
// change this value.
%this.setLerpDist( 0.2, 0.3, 0.5 );
// Fill out some default values but DOF really should not be turned on
// without actually specifying your own parameters!
%this.autoFocusEnabled = false;
%this.focalDist = 0.0;
%this.nearBlurMax = 0.5;
%this.farBlurMax = 0.5;
%this.minRange = 50;
%this.maxRange = 500;
%this.nearSlope = -5.0;
%this.farSlope = 5.0;
}
function DOFPostEffect::setLerpDist( %this, %d0, %d1, %d2 )
{
%this.lerpScale = -1.0 / %d0 SPC -1.0 / %d1 SPC -1.0 / %d2 SPC 1.0 / %d2;
%this.lerpBias = 1.0 SPC ( 1.0 - %d2 ) / %d1 SPC 1.0 / %d2 SPC ( %d2 - 1.0 ) / %d2;
}
singleton PostEffect( DOFPostEffect )
{
renderTime = "PFXAfterBin";
renderBin = "GlowBin";
renderPriority = 0.1;
shader = PFX_DOFDownSampleShader;
stateBlock = PFX_DOFDownSampleStateBlock;
texture[0] = "$backBuffer";
texture[1] = "#deferred";
target = "#shrunk";
targetScale = "0.25 0.25";
isEnabled = false;
};
singleton PostEffect( DOFBlurY )
{
shader = PFX_DOFBlurYShader;
stateBlock = PFX_DOFBlurStateBlock;
texture[0] = "#shrunk";
target = "$outTex";
};
DOFPostEffect.add( DOFBlurY );
singleton PostEffect( DOFBlurX )
{
shader = PFX_DOFBlurXShader;
stateBlock = PFX_DOFBlurStateBlock;
texture[0] = "$inTex";
target = "#largeBlur";
};
DOFPostEffect.add( DOFBlurX );
singleton PostEffect( DOFCalcCoC )
{
shader = PFX_DOFCalcCoCShader;
stateBlock = PFX_DOFCalcCoCStateBlock;
texture[0] = "#shrunk";
texture[1] = "#largeBlur";
target = "$outTex";
};
DOFPostEffect.add( DOFCalcCoc );
singleton PostEffect( DOFSmallBlur )
{
shader = PFX_DOFSmallBlurShader;
stateBlock = PFX_DefaultDOFStateBlock;
texture[0] = "$inTex";
target = "$outTex";
};
DOFPostEffect.add( DOFSmallBlur );
singleton PostEffect( DOFFinalPFX )
{
shader = PFX_DOFFinalShader;
stateBlock = PFX_DOFFinalStateBlock;
texture[0] = "$backBuffer";
texture[1] = "$inTex";
texture[2] = "#largeBlur";
texture[3] = "#deferred";
target = "$backBuffer";
};
DOFPostEffect.add( DOFFinalPFX );
//-----------------------------------------------------------------------------
// Scripts
//-----------------------------------------------------------------------------
function DOFPostEffect::setShaderConsts( %this )
{
if ( %this.autoFocusEnabled )
%this.autoFocus();
%fd = %this.focalDist / $Param::FarDist;
%range = mLerp( %this.minRange, %this.maxRange, %fd ) / $Param::FarDist * 0.5;
// We work in "depth" space rather than real-world units for the
// rest of this method...
// Given the focal distance and the range around it we want in focus
// we can determine the near-end-distance and far-start-distance
%ned = getMax( %fd - %range, 0.0 );
%fsd = getMin( %fd + %range, 1.0 );
// near slope
%nsl = %this.nearSlope;
// Given slope of near blur equation and the near end dist and amount (x2,y2)
// solve for the y-intercept
// y = mx + b
// so...
// y - mx = b
%b = 0.0 - %nsl * %ned;
%eqNear = %nsl SPC %b SPC 0.0;
// Do the same for the far blur equation...
%fsl = %this.farSlope;
%b = 0.0 - %fsl * %fsd;
%eqFar = %fsl SPC %b SPC 1.0;
%this.setShaderConst( "$dofEqWorld", %eqNear );
DOFFinalPFX.setShaderConst( "$dofEqFar", %eqFar );
%this.setShaderConst( "$maxWorldCoC", %this.nearBlurMax );
DOFFinalPFX.setShaderConst( "$maxFarCoC", %this.farBlurMax );
DOFFinalPFX.setShaderConst( "$dofLerpScale", %this.lerpScale );
DOFFinalPFX.setShaderConst( "$dofLerpBias", %this.lerpBias );
}
function DOFPostEffect::autoFocus( %this )
{
if ( !isObject( ServerConnection ) ||
!isObject( ServerConnection.getCameraObject() ) )
{
return;
}
%mask = $TypeMasks::StaticObjectType | $TypeMasks::TerrainObjectType;
%control = ServerConnection.getCameraObject();
%fvec = %control.getEyeVector();
%start = %control.getEyePoint();
%end = VectorAdd( %start, VectorScale( %fvec, $Param::FarDist ) );
// Use the client container for this ray cast.
%result = containerRayCast( %start, %end, %mask, %control, true );
%hitPos = getWords( %result, 1, 3 );
if ( %hitPos $= "" )
%focDist = $Param::FarDist;
else
%focDist = VectorDist( %hitPos, %start );
// For debuging
//$DOF::debug_dist = %focDist;
//$DOF::debug_depth = %focDist / $Param::FarDist;
//echo( "F: " @ %focDist SPC "D: " @ %delta );
%this.focalDist = %focDist;
}
// For debugging
/*
function reloadDOF()
{
exec( "./dof.cs" );
DOFPostEffect.reload();
DOFPostEffect.disable();
DOFPostEffect.enable();
}
function dofMetricsCallback()
{
return " | DOF |" @
" Dist: " @ $DOF::debug_dist @
" Depth: " @ $DOF::debug_depth;
}
*/
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.Diagnostics;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.Transactions;
using System.Runtime.Diagnostics;
public abstract class ReceiveContext
{
public readonly static string Name = "ReceiveContext";
ThreadNeutralSemaphore stateLock; // protects state that may be reverted
bool contextFaulted;
object thisLock;
EventTraceActivity eventTraceActivity;
protected ReceiveContext()
{
this.thisLock = new object();
this.State = ReceiveContextState.Received;
this.stateLock = new ThreadNeutralSemaphore(1);
}
public ReceiveContextState State
{
get;
protected set;
}
protected object ThisLock
{
get { return thisLock; }
}
public event EventHandler Faulted;
public static bool TryGet(Message message, out ReceiveContext property)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
}
bool result = TryGet(message.Properties, out property);
if (result && FxTrace.Trace.IsEnd2EndActivityTracingEnabled && property.eventTraceActivity == null)
{
property.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
}
return result;
}
public static bool TryGet(MessageProperties properties, out ReceiveContext property)
{
if (properties == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("properties");
}
property = null;
object foundProperty;
if (properties.TryGetValue(Name, out foundProperty))
{
property = (ReceiveContext)foundProperty;
return true;
}
return false;
}
public virtual void Abandon(TimeSpan timeout)
{
Abandon(null, timeout);
}
public virtual void Abandon(Exception exception, TimeSpan timeout)
{
EnsureValidTimeout(timeout);
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
this.WaitForStateLock(timeoutHelper.RemainingTime());
try
{
if (PreAbandon())
{
return;
}
}
finally
{
// Abandon can never be reverted, release the state lock.
this.ReleaseStateLock();
}
bool success = false;
try
{
if (exception == null)
{
OnAbandon(timeoutHelper.RemainingTime());
}
else
{
if (TD.ReceiveContextAbandonWithExceptionIsEnabled())
{
TD.ReceiveContextAbandonWithException(this.eventTraceActivity, this.GetType().ToString(), exception.GetType().ToString());
}
OnAbandon(exception, timeoutHelper.RemainingTime());
}
lock (ThisLock)
{
ThrowIfFaulted();
ThrowIfNotAbandoning();
this.State = ReceiveContextState.Abandoned;
}
success = true;
}
finally
{
if (!success)
{
if (TD.ReceiveContextAbandonFailedIsEnabled())
{
TD.ReceiveContextAbandonFailed(this.eventTraceActivity, this.GetType().ToString());
}
Fault();
}
}
}
public virtual IAsyncResult BeginAbandon(TimeSpan timeout, AsyncCallback callback, object state)
{
return BeginAbandon(null, timeout, callback, state);
}
public virtual IAsyncResult BeginAbandon(Exception exception, TimeSpan timeout, AsyncCallback callback, object state)
{
EnsureValidTimeout(timeout);
return new AbandonAsyncResult(this, exception, timeout, callback, state);
}
public virtual IAsyncResult BeginComplete(TimeSpan timeout, AsyncCallback callback, object state)
{
EnsureValidTimeout(timeout);
return new CompleteAsyncResult(this, timeout, callback, state);
}
public virtual void Complete(TimeSpan timeout)
{
EnsureValidTimeout(timeout);
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
this.WaitForStateLock(timeoutHelper.RemainingTime());
bool success = false;
try
{
PreComplete();
success = true;
}
finally
{
// Case 1: State validation fails, release the lock.
// Case 2: No trasaction, the state can never be reverted, release the lock.
// Case 3: Transaction, keep the lock until we know the transaction outcome (OnTransactionStatusNotification).
if (!success || Transaction.Current == null)
{
this.ReleaseStateLock();
}
}
success = false;
try
{
OnComplete(timeoutHelper.RemainingTime());
lock (ThisLock)
{
ThrowIfFaulted();
ThrowIfNotCompleting();
this.State = ReceiveContextState.Completed;
}
success = true;
}
finally
{
if (!success)
{
if (TD.ReceiveContextCompleteFailedIsEnabled())
{
TD.ReceiveContextCompleteFailed(this.eventTraceActivity, this.GetType().ToString());
}
Fault();
}
}
}
public virtual void EndAbandon(IAsyncResult result)
{
AbandonAsyncResult.End(result);
}
public virtual void EndComplete(IAsyncResult result)
{
CompleteAsyncResult.End(result);
}
void EnsureValidTimeout(TimeSpan timeout)
{
if (timeout < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("timeout", SR.GetString(SR.SFxTimeoutOutOfRange0)));
}
if (TimeoutHelper.IsTooLarge(timeout))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("timeout", timeout, SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
}
protected internal virtual void Fault()
{
lock (ThisLock)
{
if (this.State == ReceiveContextState.Completed || this.State == ReceiveContextState.Abandoned || this.State == ReceiveContextState.Faulted)
{
return;
}
this.State = ReceiveContextState.Faulted;
}
OnFaulted();
}
protected abstract void OnAbandon(TimeSpan timeout);
protected virtual void OnAbandon(Exception exception, TimeSpan timeout)
{
// default implementation: delegate to non-exception overload, ignoring reason
OnAbandon(timeout);
}
protected abstract IAsyncResult OnBeginAbandon(TimeSpan timeout, AsyncCallback callback, object state);
protected virtual IAsyncResult OnBeginAbandon(Exception exception, TimeSpan timeout, AsyncCallback callback, object state)
{
// default implementation: delegate to non-exception overload, ignoring reason
return OnBeginAbandon(timeout, callback, state);
}
protected abstract IAsyncResult OnBeginComplete(TimeSpan timeout, AsyncCallback callback, object state);
protected abstract void OnComplete(TimeSpan timeout);
protected abstract void OnEndAbandon(IAsyncResult result);
protected abstract void OnEndComplete(IAsyncResult result);
protected virtual void OnFaulted()
{
lock (ThisLock)
{
if (this.contextFaulted)
{
return;
}
this.contextFaulted = true;
}
if (TD.ReceiveContextFaultedIsEnabled())
{
TD.ReceiveContextFaulted(this.eventTraceActivity, this);
}
EventHandler handler = this.Faulted;
if (handler != null)
{
try
{
handler(this, EventArgs.Empty);
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception);
}
}
}
void OnTransactionStatusNotification(TransactionStatus status)
{
lock (ThisLock)
{
if (status == TransactionStatus.Aborted)
{
if (this.State == ReceiveContextState.Completing || this.State == ReceiveContextState.Completed)
{
this.State = ReceiveContextState.Received;
}
}
}
if (status != TransactionStatus.Active)
{
this.ReleaseStateLock();
}
}
bool PreAbandon()
{
bool alreadyAbandoned = false;
lock (ThisLock)
{
if (this.State == ReceiveContextState.Abandoning || this.State == ReceiveContextState.Abandoned)
{
alreadyAbandoned = true;
}
else
{
ThrowIfFaulted();
ThrowIfNotReceived();
this.State = ReceiveContextState.Abandoning;
}
}
return alreadyAbandoned;
}
void PreComplete()
{
lock (ThisLock)
{
ThrowIfFaulted();
ThrowIfNotReceived();
if (Transaction.Current != null)
{
Transaction.Current.EnlistVolatile(new EnlistmentNotifications(this), EnlistmentOptions.None);
}
this.State = ReceiveContextState.Completing;
}
}
void ReleaseStateLock()
{
this.stateLock.Exit();
}
void ThrowIfFaulted()
{
if (State == ReceiveContextState.Faulted)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new CommunicationException(SR.GetString(SR.ReceiveContextFaulted, this.GetType().ToString())));
}
}
void ThrowIfNotAbandoning()
{
if (State != ReceiveContextState.Abandoning)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.ReceiveContextInInvalidState, this.GetType().ToString(), this.State.ToString())));
}
}
void ThrowIfNotCompleting()
{
if (State != ReceiveContextState.Completing)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.ReceiveContextInInvalidState, this.GetType().ToString(), this.State.ToString())));
}
}
void ThrowIfNotReceived()
{
if (State != ReceiveContextState.Received)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.ReceiveContextCannotBeUsed, this.GetType().ToString(), this.State.ToString())));
}
}
void WaitForStateLock(TimeSpan timeout)
{
try
{
this.stateLock.Enter(timeout);
}
catch (TimeoutException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(WrapStateException(exception));
}
}
bool WaitForStateLockAsync(TimeSpan timeout, FastAsyncCallback callback, object state)
{
return this.stateLock.EnterAsync(timeout, callback, state);
}
Exception WrapStateException(Exception exception)
{
return new InvalidOperationException(SR.GetString(SR.ReceiveContextInInvalidState, this.GetType().ToString(), this.State.ToString()), exception);
}
sealed class AbandonAsyncResult : WaitAndContinueOperationAsyncResult
{
Exception exception;
static AsyncCompletion handleOperationComplete = new AsyncCompletion(HandleOperationComplete);
public AbandonAsyncResult(ReceiveContext receiveContext, Exception exception, TimeSpan timeout, AsyncCallback callback, object state)
: base(receiveContext, timeout, callback, state)
{
this.exception = exception;
base.Begin();
}
// The main Abandon logic.
protected override bool ContinueOperation()
{
try
{
if (this.ReceiveContext.PreAbandon())
{
return true;
}
}
finally
{
// Abandon can never be reverted, release the state lock.
this.ReceiveContext.ReleaseStateLock();
}
bool success = false;
IAsyncResult result;
try
{
if (exception == null)
{
result = this.ReceiveContext.OnBeginAbandon(this.TimeoutHelper.RemainingTime(), PrepareAsyncCompletion(handleOperationComplete), this);
}
else
{
if (TD.ReceiveContextAbandonWithExceptionIsEnabled())
{
TD.ReceiveContextAbandonWithException(this.ReceiveContext.eventTraceActivity, this.GetType().ToString(), exception.GetType().ToString());
}
result = this.ReceiveContext.OnBeginAbandon(exception, this.TimeoutHelper.RemainingTime(), PrepareAsyncCompletion(handleOperationComplete), this);
}
success = true;
}
finally
{
if (!success)
{
if (TD.ReceiveContextAbandonFailedIsEnabled())
{
TD.ReceiveContextAbandonFailed((this.ReceiveContext != null) ? this.ReceiveContext.eventTraceActivity : null,
this.GetType().ToString());
}
this.ReceiveContext.Fault();
}
}
return SyncContinue(result);
}
public static void End(IAsyncResult result)
{
AsyncResult.End<AbandonAsyncResult>(result);
}
void EndAbandon(IAsyncResult result)
{
this.ReceiveContext.OnEndAbandon(result);
lock (this.ReceiveContext.ThisLock)
{
this.ReceiveContext.ThrowIfFaulted();
this.ReceiveContext.ThrowIfNotAbandoning();
this.ReceiveContext.State = ReceiveContextState.Abandoned;
}
}
static bool HandleOperationComplete(IAsyncResult result)
{
bool success = false;
AbandonAsyncResult thisPtr = (AbandonAsyncResult)result.AsyncState;
try
{
thisPtr.EndAbandon(result);
success = true;
return true;
}
finally
{
if (!success)
{
if (TD.ReceiveContextAbandonFailedIsEnabled())
{
TD.ReceiveContextAbandonFailed(thisPtr.ReceiveContext.eventTraceActivity, thisPtr.GetType().ToString());
}
thisPtr.ReceiveContext.Fault();
}
}
}
}
sealed class CompleteAsyncResult : WaitAndContinueOperationAsyncResult
{
Transaction transaction;
static AsyncCompletion handleOperationComplete = new AsyncCompletion(HandleOperationComplete);
public CompleteAsyncResult(ReceiveContext receiveContext, TimeSpan timeout, AsyncCallback callback, object state)
: base(receiveContext, timeout, callback, state)
{
this.transaction = Transaction.Current;
this.Begin();
}
protected override bool ContinueOperation()
{
IAsyncResult result;
using (PrepareTransactionalCall(this.transaction))
{
bool success = false;
try
{
this.ReceiveContext.PreComplete();
success = true;
}
finally
{
// Case 1: State validation fails, release the lock.
// Case 2: No trasaction, the state can never be reverted, release the lock.
// Case 3: Transaction, keep the lock until we know the transaction outcome (OnTransactionStatusNotification).
if (!success || this.transaction == null)
{
this.ReceiveContext.ReleaseStateLock();
}
}
success = false;
try
{
result = this.ReceiveContext.OnBeginComplete(this.TimeoutHelper.RemainingTime(), PrepareAsyncCompletion(handleOperationComplete), this);
success = true;
}
finally
{
if (!success)
{
if (TD.ReceiveContextCompleteFailedIsEnabled())
{
TD.ReceiveContextCompleteFailed(this.ReceiveContext.eventTraceActivity, this.GetType().ToString());
}
this.ReceiveContext.Fault();
}
}
}
return SyncContinue(result);
}
public static void End(IAsyncResult result)
{
AsyncResult.End<CompleteAsyncResult>(result);
}
void EndComplete(IAsyncResult result)
{
this.ReceiveContext.OnEndComplete(result);
lock (this.ReceiveContext.ThisLock)
{
this.ReceiveContext.ThrowIfFaulted();
this.ReceiveContext.ThrowIfNotCompleting();
this.ReceiveContext.State = ReceiveContextState.Completed;
}
}
static bool HandleOperationComplete(IAsyncResult result)
{
CompleteAsyncResult thisPtr = (CompleteAsyncResult)result.AsyncState;
bool success = false;
try
{
thisPtr.EndComplete(result);
success = true;
return true;
}
finally
{
if (!success)
{
if (TD.ReceiveContextCompleteFailedIsEnabled())
{
TD.ReceiveContextCompleteFailed(thisPtr.ReceiveContext.eventTraceActivity, thisPtr.GetType().ToString());
}
thisPtr.ReceiveContext.Fault();
}
}
}
}
class EnlistmentNotifications : IEnlistmentNotification
{
ReceiveContext context;
public EnlistmentNotifications(ReceiveContext context)
{
this.context = context;
}
public void Commit(Enlistment enlistment)
{
this.context.OnTransactionStatusNotification(TransactionStatus.Committed);
enlistment.Done();
}
public void InDoubt(Enlistment enlistment)
{
this.context.OnTransactionStatusNotification(TransactionStatus.InDoubt);
enlistment.Done();
}
public void Prepare(PreparingEnlistment preparingEnlistment)
{
this.context.OnTransactionStatusNotification(TransactionStatus.Active);
preparingEnlistment.Prepared();
}
public void Rollback(Enlistment enlistment)
{
this.context.OnTransactionStatusNotification(TransactionStatus.Aborted);
enlistment.Done();
}
}
abstract class WaitAndContinueOperationAsyncResult : TransactedAsyncResult
{
static FastAsyncCallback onWaitForStateLockComplete = new FastAsyncCallback(OnWaitForStateLockComplete);
public WaitAndContinueOperationAsyncResult(ReceiveContext receiveContext, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.ReceiveContext = receiveContext;
this.TimeoutHelper = new TimeoutHelper(timeout);
}
protected ReceiveContext ReceiveContext
{
get;
private set;
}
protected TimeoutHelper TimeoutHelper
{
get;
private set;
}
protected void Begin()
{
if (!this.ReceiveContext.WaitForStateLockAsync(this.TimeoutHelper.RemainingTime(), onWaitForStateLockComplete, this))
{
return;
}
if (this.ContinueOperation())
{
this.Complete(true);
}
}
protected abstract bool ContinueOperation();
static void OnWaitForStateLockComplete(object state, Exception asyncException)
{
WaitAndContinueOperationAsyncResult thisPtr = (WaitAndContinueOperationAsyncResult)state;
bool completeAsyncResult = true;
Exception completeException = null;
if (asyncException != null)
{
if (asyncException is TimeoutException)
{
asyncException = thisPtr.ReceiveContext.WrapStateException(asyncException);
}
completeException = asyncException;
}
else
{
try
{
completeAsyncResult = thisPtr.ContinueOperation();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeException = e;
}
}
if (completeAsyncResult)
{
thisPtr.Complete(false, completeException);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Achartengine.Renderer {
// Metadata.xml XPath class reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='BasicStroke']"
[global::Android.Runtime.Register ("org/achartengine/renderer/BasicStroke", DoNotGenerateAcw=true)]
public partial class BasicStroke : global::Java.Lang.Object, global::Java.IO.ISerializable {
static IntPtr DASHED_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='BasicStroke']/field[@name='DASHED']"
[Register ("DASHED")]
public static global::Org.Achartengine.Renderer.BasicStroke Dashed {
get {
if (DASHED_jfieldId == IntPtr.Zero)
DASHED_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "DASHED", "Lorg/achartengine/renderer/BasicStroke;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, DASHED_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.BasicStroke> (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (DASHED_jfieldId == IntPtr.Zero)
DASHED_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "DASHED", "Lorg/achartengine/renderer/BasicStroke;");
IntPtr native_value = JNIEnv.ToLocalJniHandle (value);
JNIEnv.SetStaticField (class_ref, DASHED_jfieldId, native_value);
JNIEnv.DeleteLocalRef (native_value);
}
}
static IntPtr DOTTED_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='BasicStroke']/field[@name='DOTTED']"
[Register ("DOTTED")]
public static global::Org.Achartengine.Renderer.BasicStroke Dotted {
get {
if (DOTTED_jfieldId == IntPtr.Zero)
DOTTED_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "DOTTED", "Lorg/achartengine/renderer/BasicStroke;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, DOTTED_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.BasicStroke> (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (DOTTED_jfieldId == IntPtr.Zero)
DOTTED_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "DOTTED", "Lorg/achartengine/renderer/BasicStroke;");
IntPtr native_value = JNIEnv.ToLocalJniHandle (value);
JNIEnv.SetStaticField (class_ref, DOTTED_jfieldId, native_value);
JNIEnv.DeleteLocalRef (native_value);
}
}
static IntPtr SOLID_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='BasicStroke']/field[@name='SOLID']"
[Register ("SOLID")]
public static global::Org.Achartengine.Renderer.BasicStroke Solid {
get {
if (SOLID_jfieldId == IntPtr.Zero)
SOLID_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "SOLID", "Lorg/achartengine/renderer/BasicStroke;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, SOLID_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.BasicStroke> (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (SOLID_jfieldId == IntPtr.Zero)
SOLID_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "SOLID", "Lorg/achartengine/renderer/BasicStroke;");
IntPtr native_value = JNIEnv.ToLocalJniHandle (value);
JNIEnv.SetStaticField (class_ref, SOLID_jfieldId, native_value);
JNIEnv.DeleteLocalRef (native_value);
}
}
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/achartengine/renderer/BasicStroke", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (BasicStroke); }
}
protected BasicStroke (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Landroid_graphics_Paint_Cap_Landroid_graphics_Paint_Join_FarrayFF;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='BasicStroke']/constructor[@name='BasicStroke' and count(parameter)=5 and parameter[1][@type='android.graphics.Paint.Cap'] and parameter[2][@type='android.graphics.Paint.Join'] and parameter[3][@type='float'] and parameter[4][@type='float[]'] and parameter[5][@type='float']]"
[Register (".ctor", "(Landroid/graphics/Paint$Cap;Landroid/graphics/Paint$Join;F[FF)V", "")]
public BasicStroke (global::Android.Graphics.Paint.Cap p0, global::Android.Graphics.Paint.Join p1, float p2, float[] p3, float p4) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
IntPtr native_p3 = JNIEnv.NewArray (p3);;
if (GetType () != typeof (BasicStroke)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Landroid/graphics/Paint$Cap;Landroid/graphics/Paint$Join;F[FF)V", new JValue (p0), new JValue (p1), new JValue (p2), new JValue (native_p3), new JValue (p4)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Landroid/graphics/Paint$Cap;Landroid/graphics/Paint$Join;F[FF)V", new JValue (p0), new JValue (p1), new JValue (p2), new JValue (native_p3), new JValue (p4));
if (p3 != null) {
JNIEnv.CopyArray (native_p3, p3);
JNIEnv.DeleteLocalRef (native_p3);
}
return;
}
if (id_ctor_Landroid_graphics_Paint_Cap_Landroid_graphics_Paint_Join_FarrayFF == IntPtr.Zero)
id_ctor_Landroid_graphics_Paint_Cap_Landroid_graphics_Paint_Join_FarrayFF = JNIEnv.GetMethodID (class_ref, "<init>", "(Landroid/graphics/Paint$Cap;Landroid/graphics/Paint$Join;F[FF)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Landroid_graphics_Paint_Cap_Landroid_graphics_Paint_Join_FarrayFF, new JValue (p0), new JValue (p1), new JValue (p2), new JValue (native_p3), new JValue (p4)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Landroid_graphics_Paint_Cap_Landroid_graphics_Paint_Join_FarrayFF, new JValue (p0), new JValue (p1), new JValue (p2), new JValue (native_p3), new JValue (p4));
if (p3 != null) {
JNIEnv.CopyArray (native_p3, p3);
JNIEnv.DeleteLocalRef (native_p3);
}
}
static Delegate cb_getCap;
#pragma warning disable 0169
static Delegate GetGetCapHandler ()
{
if (cb_getCap == null)
cb_getCap = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetCap);
return cb_getCap;
}
static IntPtr n_GetCap (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.BasicStroke __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.BasicStroke> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.Cap);
}
#pragma warning restore 0169
static IntPtr id_getCap;
public virtual global::Android.Graphics.Paint.Cap Cap {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='BasicStroke']/method[@name='getCap' and count(parameter)=0]"
[Register ("getCap", "()Landroid/graphics/Paint$Cap;", "GetGetCapHandler")]
get {
if (id_getCap == IntPtr.Zero)
id_getCap = JNIEnv.GetMethodID (class_ref, "getCap", "()Landroid/graphics/Paint$Cap;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Android.Graphics.Paint.Cap> (JNIEnv.CallObjectMethod (Handle, id_getCap), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Android.Graphics.Paint.Cap> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_getCap), JniHandleOwnership.TransferLocalRef);
}
}
static Delegate cb_getJoin;
#pragma warning disable 0169
static Delegate GetGetJoinHandler ()
{
if (cb_getJoin == null)
cb_getJoin = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetJoin);
return cb_getJoin;
}
static IntPtr n_GetJoin (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.BasicStroke __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.BasicStroke> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.Join);
}
#pragma warning restore 0169
static IntPtr id_getJoin;
public virtual global::Android.Graphics.Paint.Join Join {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='BasicStroke']/method[@name='getJoin' and count(parameter)=0]"
[Register ("getJoin", "()Landroid/graphics/Paint$Join;", "GetGetJoinHandler")]
get {
if (id_getJoin == IntPtr.Zero)
id_getJoin = JNIEnv.GetMethodID (class_ref, "getJoin", "()Landroid/graphics/Paint$Join;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Android.Graphics.Paint.Join> (JNIEnv.CallObjectMethod (Handle, id_getJoin), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Android.Graphics.Paint.Join> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_getJoin), JniHandleOwnership.TransferLocalRef);
}
}
static Delegate cb_getMiter;
#pragma warning disable 0169
static Delegate GetGetMiterHandler ()
{
if (cb_getMiter == null)
cb_getMiter = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, float>) n_GetMiter);
return cb_getMiter;
}
static float n_GetMiter (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.BasicStroke __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.BasicStroke> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.Miter;
}
#pragma warning restore 0169
static IntPtr id_getMiter;
public virtual float Miter {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='BasicStroke']/method[@name='getMiter' and count(parameter)=0]"
[Register ("getMiter", "()F", "GetGetMiterHandler")]
get {
if (id_getMiter == IntPtr.Zero)
id_getMiter = JNIEnv.GetMethodID (class_ref, "getMiter", "()F");
if (GetType () == ThresholdType)
return JNIEnv.CallFloatMethod (Handle, id_getMiter);
else
return JNIEnv.CallNonvirtualFloatMethod (Handle, ThresholdClass, id_getMiter);
}
}
static Delegate cb_getPhase;
#pragma warning disable 0169
static Delegate GetGetPhaseHandler ()
{
if (cb_getPhase == null)
cb_getPhase = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, float>) n_GetPhase);
return cb_getPhase;
}
static float n_GetPhase (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.BasicStroke __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.BasicStroke> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.Phase;
}
#pragma warning restore 0169
static IntPtr id_getPhase;
public virtual float Phase {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='BasicStroke']/method[@name='getPhase' and count(parameter)=0]"
[Register ("getPhase", "()F", "GetGetPhaseHandler")]
get {
if (id_getPhase == IntPtr.Zero)
id_getPhase = JNIEnv.GetMethodID (class_ref, "getPhase", "()F");
if (GetType () == ThresholdType)
return JNIEnv.CallFloatMethod (Handle, id_getPhase);
else
return JNIEnv.CallNonvirtualFloatMethod (Handle, ThresholdClass, id_getPhase);
}
}
static Delegate cb_getIntervals;
#pragma warning disable 0169
static Delegate GetGetIntervalsHandler ()
{
if (cb_getIntervals == null)
cb_getIntervals = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetIntervals);
return cb_getIntervals;
}
static IntPtr n_GetIntervals (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.BasicStroke __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.BasicStroke> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewArray (__this.GetIntervals ());
}
#pragma warning restore 0169
static IntPtr id_getIntervals;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='BasicStroke']/method[@name='getIntervals' and count(parameter)=0]"
[Register ("getIntervals", "()[F", "GetGetIntervalsHandler")]
public virtual float[] GetIntervals ()
{
if (id_getIntervals == IntPtr.Zero)
id_getIntervals = JNIEnv.GetMethodID (class_ref, "getIntervals", "()[F");
if (GetType () == ThresholdType)
return (float[]) JNIEnv.GetArray (JNIEnv.CallObjectMethod (Handle, id_getIntervals), JniHandleOwnership.TransferLocalRef, typeof (float));
else
return (float[]) JNIEnv.GetArray (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_getIntervals), JniHandleOwnership.TransferLocalRef, typeof (float));
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Cake.Scripting.Abstractions;
using Cake.Scripting.Abstractions.Models;
using Cake.Scripting.Transport.Tcp.Client;
using Microsoft.Extensions.Logging;
using Xunit;
namespace Integration
{
class MonoScriptGenerationProcess : IScriptGenerationProcess
{
private readonly ILogger _logger;
private Process _process;
public MonoScriptGenerationProcess(string serverExecutablePath, ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger(typeof(MonoScriptGenerationProcess));
ServerExecutablePath = serverExecutablePath;
}
public void Dispose()
{
_process?.Kill();
_process?.WaitForExit();
_process?.Dispose();
}
public void Start(int port, string workingDirectory)
{
var tuple = GetMonoRuntime();
var fileName = tuple.Item1;
var arguments = tuple.Item2;
if (fileName == null)
{
// Something went wrong figuring out mono runtime,
// try executing exe and let mono handle it.
fileName = ServerExecutablePath;
}
else
{
// Else set exe as argument
arguments += $"\"{ServerExecutablePath}\"";
}
arguments += $" --port={port}";
if (_logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
{
arguments += " --verbose";
}
var startInfo = new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
WorkingDirectory = workingDirectory,
};
_logger.LogDebug("Starting \"{fileName}\" with arguments \"{arguments}\"", startInfo.FileName, startInfo.Arguments);
_process = Process.Start(startInfo);
_process.ErrorDataReceived += (s, e) =>
{
if (e.Data != null)
{
_logger.LogError(e.Data);
}
};
_process.BeginErrorReadLine();
_process.OutputDataReceived += (s, e) =>
{
if (e.Data != null)
{
_logger.LogDebug(e.Data);
}
};
_process.BeginOutputReadLine();
}
private Tuple<string, string> GetMonoRuntime()
{
// If OmniSharp bundled Mono runtime, use bootstrap script.
var script = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Program.MonoRuntime), "../run");
if (System.IO.File.Exists(script))
{
return Tuple.Create(script, "--no-omnisharp ");
}
// Else use mono directly.
return Tuple.Create(Program.MonoRuntime, string.Empty);
}
public string ServerExecutablePath { get; set; }
}
public class Program
{
internal static string MonoRuntime = System.Environment.GetEnvironmentVariable("CakeBakeryTestsIntegrationMono");
static void Should_Generate_From_File()
{
// Given
var fileChange = new FileChange
{
FileName = CakeHelloWorldFile,
FromDisk = true
};
// When
var response = service.Generate(fileChange);
// Then
var cakeCorePath = $"{workingDirectory}/tools/Cake.Bakery/tools/Cake.Core.dll";
var lineDirective = $"#line 1 \"{workingDirectory}/{CakeHelloWorldFile}\"";
var sourceLines = response.Source.Split('\n').ToList();
var expectedLines = CakeHelloWorldSrc.Split('\n').ToList();
Assert.Equal(response.Host.AssemblyPath, cakeCorePath);
Assert.Contains("Cake.Core", response.Usings);
Assert.Contains(cakeCorePath, response.References, StringComparer.OrdinalIgnoreCase);
Assert.Contains(lineDirective, sourceLines, StringComparer.OrdinalIgnoreCase);
var startIndex = sourceLines.FindIndex(x => x.Equals(lineDirective, StringComparison.OrdinalIgnoreCase)) + 1;
for(var i = 0; i < expectedLines.Count; i++)
{
Assert.Equal(sourceLines[startIndex + i], expectedLines[i].TrimEnd(new [] { '\r', '\n' }));
}
}
static void Should_Generate_From_Buffer()
{
// Given
var buffer = CakeHelloWorldSrc;
var fileName = $"{Guid.NewGuid()}.cake";
var fileChange = new FileChange
{
Buffer = buffer,
FileName = fileName,
FromDisk = false
};
// When
var response = service.Generate(fileChange);
// Then
var cakeCorePath = $"{workingDirectory}/tools/Cake.Bakery/tools/Cake.Core.dll";
var lineDirective = $"#line 1 \"{workingDirectory}/{fileName}\"";
var sourceLines = response.Source.Split('\n').ToList();
var expectedLines = CakeHelloWorldSrc.Split('\n').ToList();
Assert.Equal(response.Host.AssemblyPath, cakeCorePath);
Assert.Contains("Cake.Core", response.Usings);
Assert.Contains(cakeCorePath, response.References, StringComparer.OrdinalIgnoreCase);
Assert.Contains(lineDirective, sourceLines, StringComparer.OrdinalIgnoreCase);
var startIndex = sourceLines.FindIndex(x => x.Equals(lineDirective, StringComparison.OrdinalIgnoreCase)) + 1;
for(var i = 0; i < expectedLines.Count; i++)
{
Assert.Equal(sourceLines[startIndex + i], expectedLines[i].TrimEnd(new [] { '\r', '\n' }));
}
}
static void Should_Generate_With_Line_Changes()
{
// Given
var buffer = CakeHelloWorldSrc;
var fileName = $"{Guid.NewGuid()}.cake";
var fileChange = new FileChange
{
Buffer = buffer,
FileName = fileName,
FromDisk = false
};
service.Generate(fileChange);
fileChange = new FileChange
{
LineChanges =
{
new LineChange
{
StartLine = 0,
StartColumn = 33,
EndLine = 0,
EndColumn = 40,
NewText = "Foobar"
},
new LineChange
{
StartLine = 2,
StartColumn = 6,
EndLine = 2,
EndColumn = 13,
NewText = "Foobar"
},
new LineChange
{
StartLine = 5,
StartColumn = 2,
EndLine = 5,
EndColumn = 13,
NewText = "Verbose"
}
},
FileName = fileName,
FromDisk = false
};
// When
var response = service.Generate(fileChange);
// Then
var cakeCorePath = $"{workingDirectory}/tools/Cake.Bakery/tools/Cake.Core.dll";
var lineDirective = $"#line 1 \"{workingDirectory}/{fileName}\"";
var sourceLines = response.Source.Split('\n').ToList();
var expectedLines = CakeHelloWorldModified.Split('\n').ToList();
Assert.Equal(response.Host.AssemblyPath, cakeCorePath);
Assert.Contains("Cake.Core", response.Usings);
Assert.Contains(cakeCorePath, response.References, StringComparer.OrdinalIgnoreCase);
Assert.Contains(lineDirective, sourceLines, StringComparer.OrdinalIgnoreCase);
var startIndex = sourceLines.FindIndex(x => x.Equals(lineDirective, StringComparison.OrdinalIgnoreCase)) + 1;
for(var i = 0; i < expectedLines.Count; i++)
{
Assert.Equal(sourceLines[startIndex + i], expectedLines[i].TrimEnd(new [] { '\r', '\n' }));
}
}
static void Should_Install_Addins()
{
// Given
var fileChange = new FileChange
{
FileName = CakeAddinDirectiveFile,
FromDisk = true
};
// When
var response = service.Generate(fileChange);
// Then
var addin = Path.GetFullPath("./tools/Addins/Cake.Wyam2.3.0.0-rc2/lib/netstandard2.0/Cake.Wyam.dll")
.Replace('\\', '/');
Assert.Contains(addin, response.References);
}
static IScriptGenerationService service;
static string workingDirectory;
const string CakeHelloWorldFile = "helloworld.cake";
const string CakeHelloWorldSrc =
@"var target = Argument(""target"", ""Default"");
Task(""Default"")
.Does(ctx =>
{
Information(""Hello World!"");
});
RunTarget(target);";
const string CakeHelloWorldModified =
@"var target = Argument(""target"", ""Foobar"");
Task(""Foobar"")
.Does(ctx =>
{
Verbose(""Hello World!"");
});
RunTarget(target);";
const string CakeAddinDirectiveFile = "addin.cake";
static int Main(string[] args)
{
var isRunningOnMono = !string.IsNullOrWhiteSpace(MonoRuntime);
using var loggerFactory = LoggerFactory.Create(
builder => builder
.AddConsole()
.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug));
var bakeryPath = args[0];
workingDirectory = Environment.CurrentDirectory.Replace('\\', '/');;
service = isRunningOnMono ?
new ScriptGenerationClient(new MonoScriptGenerationProcess(bakeryPath, loggerFactory), workingDirectory, loggerFactory) :
new ScriptGenerationClient(bakeryPath, workingDirectory, loggerFactory);
Should_Generate_From_File();
Should_Generate_From_Buffer();
Should_Generate_With_Line_Changes();
Should_Install_Addins();
return 0;
}
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. 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.
#endregion
namespace MoreLinq
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static partial class MoreEnumerable
{
/// <summary>
/// Returns a sequence of <see cref="IList{T}"/> representing all of the subsets
/// of any size that are part of the original sequence.
/// </summary>
/// <remarks>
/// This operator produces all of the subsets of a given sequence. Subsets are returned
/// in increasing cardinality, starting with the empty set and terminating with the
/// entire original sequence.<br/>
/// Subsets are produced in a deferred, streaming manner; however, each subset is returned
/// as a materialized list.<br/>
/// There are 2^N subsets of a given sequence, where N => sequence.Count().
/// </remarks>
/// <param name="sequence">Sequence for which to produce subsets</param>
/// <typeparam name="T">The type of the elements in the sequence</typeparam>
/// <returns>A sequence of lists that represent the all subsets of the original sequence</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="sequence"/> is <see langword="null"/></exception>
public static IEnumerable<IList<T>> Subsets<T>(this IEnumerable<T> sequence)
{
if (sequence == null)
throw new ArgumentNullException("sequence");
return SubsetsImpl(sequence);
}
/// <summary>
/// Returns a sequence of <see cref="IList{T}"/> representing all subsets of the
/// specified size that are part of the original sequence.
/// </summary>
/// <param name="sequence">Sequence for which to produce subsets</param>
/// <param name="subsetSize">The size of the subsets to produce</param>
/// <typeparam name="T">The type of the elements in the sequence</typeparam>
/// <returns>A sequence of lists that represents of K-sized subsets of the original sequence</returns>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="sequence"/> is <see langword="null"/>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="subsetSize"/> is less than zero.
/// </exception>
public static IEnumerable<IList<T>> Subsets<T>(this IEnumerable<T> sequence, int subsetSize)
{
if (sequence == null)
throw new ArgumentNullException("sequence");
if (subsetSize < 0)
throw new ArgumentOutOfRangeException("subsetSize", "Subset size must be >= 0");
// NOTE: Theres an interesting trade-off that we have to make in this operator.
// Ideally, we would throw an exception here if the {subsetSize} parameter is
// greater than the sequence length. Unforunately, determining the length of a
// sequence is not always possible without enumerating it. Herein lies the rub.
// We want Subsets() to be a deferred operation that only iterates the sequence
// when the caller is ready to consume the results. However, this forces us to
// defer the precondition check on the {subsetSize} upper bound. This can result
// in an exception that is far removed from the point of failure - an unfortunate
// and undesirable outcome.
// At the moment, this operator prioritizes deferred execution over fail-fast
// preconditions. This however, needs to be carefully considered - and perhaps
// may change after further thought and review.
return new SubsetGenerator<T>(sequence, subsetSize);
}
/// <summary>
/// Underlying implementation for Subsets() overload.
/// </summary>
/// <typeparam name="T">The type of the elements in the sequence</typeparam>
/// <param name="sequence">Sequence for which to produce subsets</param>
/// <returns>Sequence of lists representing all subsets of a sequence</returns>
private static IEnumerable<IList<T>> SubsetsImpl<T>(IEnumerable<T> sequence)
{
var sequenceAsList = sequence.ToList();
var sequenceLength = sequenceAsList.Count;
// the first subset is the empty set
yield return new List<T>();
// all other subsets are computed using the subset generator
// this check also resolves the case of permuting empty sets
if (sequenceLength > 0)
{
for (var i = 1; i < sequenceLength; i++)
{
// each intermediate subset is a lexographically ordered K-subset
var subsetGenerator = new SubsetGenerator<T>(sequenceAsList, i);
foreach (var subset in subsetGenerator)
yield return subset;
}
yield return sequenceAsList; // the last subet is the original set itself
}
}
/// <summary>
/// This class is responsible for producing the lexographically ordered k-subsets
/// </summary>
private sealed class SubsetGenerator<T> : IEnumerable<IList<T>>
{
/// <summary>
/// SubsetEnumerator uses a snapshot of the original sequence, and an
/// iterative, reductive swap algorithm to produce all subsets of a
/// predetermined size less than or equal to the original set size.
/// </summary>
private class SubsetEnumerator : IEnumerator<IList<T>>
{
private readonly IList<T> _set; // the original set of elements
private readonly T[] _subset; // the current subset to return
private readonly int[] _indices; // indices into the original set
// TODO: It would be desirable to give these index members clearer names
private bool _continue; // termination indicator, set when all subsets have been produced
private int _m; // previous swap index (upper index)
private int _m2; // current swap index (lower index)
private int _k; // size of the subset being produced
private int _n; // size of the original set (sequence)
private int _z; // count of items excluded from the subet
public SubsetEnumerator(IList<T> set, int subsetSize)
{
// precondition: subsetSize <= set.Count
if (subsetSize > set.Count)
throw new ArgumentOutOfRangeException("subsetSize", "Subset size must be <= sequence.Count()");
// initialize set arrays...
_set = set;
_subset = new T[subsetSize];
_indices = new int[subsetSize];
// initialize index counters...
Reset();
}
public void Reset()
{
_m = _subset.Length;
_m2 = -1;
_k = _subset.Length;
_n = _set.Count;
_z = _n - _k + 1;
_continue = _subset.Length > 0;
}
public IList<T> Current
{
get { return (IList<T>)_subset.Clone(); }
}
object IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
if (!_continue)
return false;
if (_m2 == -1)
{
_m2 = 0;
_m = _k;
}
else
{
if (_m2 < _n - _m)
{
_m = 0;
}
_m++;
_m2 = _indices[_k - _m];
}
for (var j = 1; j <= _m; j++)
_indices[_k + j - _m - 1] = _m2 + j;
ExtractSubset();
_continue = (_indices[0] != _z);
return true;
}
void IDisposable.Dispose() { }
private void ExtractSubset()
{
for (var i = 0; i < _k; i++)
_subset[i] = _set[_indices[i] - 1];
}
}
private readonly IEnumerable<T> _sequence;
private readonly int _subsetSize;
public SubsetGenerator(IEnumerable<T> sequence, int subsetSize)
{
if (sequence == null)
throw new ArgumentNullException("sequence");
if (subsetSize < 0)
throw new ArgumentOutOfRangeException("subsetSize", "{subsetSize} must be between 0 and set.Count()");
_subsetSize = subsetSize;
_sequence = sequence;
}
/// <summary>
/// Returns an enumerator that produces all of the k-sized
/// subsets of the initial value set. The enumerator returns
/// and <see cref="IList{T}"/> for each subset.
/// </summary>
/// <returns>an <see cref="IEnumerator"/> that enumerates all k-sized subsets</returns>
public IEnumerator<IList<T>> GetEnumerator()
{
return new SubsetEnumerator(_sequence.ToList(), _subsetSize);
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.OpsWorks.Model
{
/// <summary>
/// <para>A description of the app.</para>
/// </summary>
public class App
{
private string appId;
private string stackId;
private string shortname;
private string name;
private string description;
private string type;
private Source appSource;
private List<string> domains = new List<string>();
private bool? enableSsl;
private SslConfiguration sslConfiguration;
private Dictionary<string,string> attributes = new Dictionary<string,string>();
private string createdAt;
/// <summary>
/// The app ID.
///
/// </summary>
public string AppId
{
get { return this.appId; }
set { this.appId = value; }
}
/// <summary>
/// Sets the AppId property
/// </summary>
/// <param name="appId">The value to set for the AppId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public App WithAppId(string appId)
{
this.appId = appId;
return this;
}
// Check to see if AppId property is set
internal bool IsSetAppId()
{
return this.appId != null;
}
/// <summary>
/// The app stack ID.
///
/// </summary>
public string StackId
{
get { return this.stackId; }
set { this.stackId = value; }
}
/// <summary>
/// Sets the StackId property
/// </summary>
/// <param name="stackId">The value to set for the StackId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public App WithStackId(string stackId)
{
this.stackId = stackId;
return this;
}
// Check to see if StackId property is set
internal bool IsSetStackId()
{
return this.stackId != null;
}
/// <summary>
/// The app's short name.
///
/// </summary>
public string Shortname
{
get { return this.shortname; }
set { this.shortname = value; }
}
/// <summary>
/// Sets the Shortname property
/// </summary>
/// <param name="shortname">The value to set for the Shortname property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public App WithShortname(string shortname)
{
this.shortname = shortname;
return this;
}
// Check to see if Shortname property is set
internal bool IsSetShortname()
{
return this.shortname != null;
}
/// <summary>
/// The app name.
///
/// </summary>
public string Name
{
get { return this.name; }
set { this.name = value; }
}
/// <summary>
/// Sets the Name property
/// </summary>
/// <param name="name">The value to set for the Name property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public App WithName(string name)
{
this.name = name;
return this;
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this.name != null;
}
/// <summary>
/// A description of the app.
///
/// </summary>
public string Description
{
get { return this.description; }
set { this.description = value; }
}
/// <summary>
/// Sets the Description property
/// </summary>
/// <param name="description">The value to set for the Description property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public App WithDescription(string description)
{
this.description = description;
return this;
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this.description != null;
}
/// <summary>
/// The app type.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>rails, php, nodejs, static, other</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Type
{
get { return this.type; }
set { this.type = value; }
}
/// <summary>
/// Sets the Type property
/// </summary>
/// <param name="type">The value to set for the Type property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public App WithType(string type)
{
this.type = type;
return this;
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this.type != null;
}
/// <summary>
/// A <c>Source</c> object that describes the app repository.
///
/// </summary>
public Source AppSource
{
get { return this.appSource; }
set { this.appSource = value; }
}
/// <summary>
/// Sets the AppSource property
/// </summary>
/// <param name="appSource">The value to set for the AppSource property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public App WithAppSource(Source appSource)
{
this.appSource = appSource;
return this;
}
// Check to see if AppSource property is set
internal bool IsSetAppSource()
{
return this.appSource != null;
}
/// <summary>
/// The app vhost settings, with multiple domains separated by commas. For example: <c>'www.example.com, example.com'</c>
///
/// </summary>
public List<string> Domains
{
get { return this.domains; }
set { this.domains = value; }
}
/// <summary>
/// Adds elements to the Domains collection
/// </summary>
/// <param name="domains">The values to add to the Domains collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public App WithDomains(params string[] domains)
{
foreach (string element in domains)
{
this.domains.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Domains collection
/// </summary>
/// <param name="domains">The values to add to the Domains collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public App WithDomains(IEnumerable<string> domains)
{
foreach (string element in domains)
{
this.domains.Add(element);
}
return this;
}
// Check to see if Domains property is set
internal bool IsSetDomains()
{
return this.domains.Count > 0;
}
/// <summary>
/// Whether to enable SSL for the app.
///
/// </summary>
public bool EnableSsl
{
get { return this.enableSsl ?? default(bool); }
set { this.enableSsl = value; }
}
/// <summary>
/// Sets the EnableSsl property
/// </summary>
/// <param name="enableSsl">The value to set for the EnableSsl property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public App WithEnableSsl(bool enableSsl)
{
this.enableSsl = enableSsl;
return this;
}
// Check to see if EnableSsl property is set
internal bool IsSetEnableSsl()
{
return this.enableSsl.HasValue;
}
/// <summary>
/// An <c>SslConfiguration</c> object with the SSL configuration.
///
/// </summary>
public SslConfiguration SslConfiguration
{
get { return this.sslConfiguration; }
set { this.sslConfiguration = value; }
}
/// <summary>
/// Sets the SslConfiguration property
/// </summary>
/// <param name="sslConfiguration">The value to set for the SslConfiguration property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public App WithSslConfiguration(SslConfiguration sslConfiguration)
{
this.sslConfiguration = sslConfiguration;
return this;
}
// Check to see if SslConfiguration property is set
internal bool IsSetSslConfiguration()
{
return this.sslConfiguration != null;
}
/// <summary>
/// The contents of the stack attributes bag.
///
/// </summary>
public Dictionary<string,string> Attributes
{
get { return this.attributes; }
set { this.attributes = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the Attributes dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the Attributes dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public App WithAttributes(params KeyValuePair<string, string>[] pairs)
{
foreach (KeyValuePair<string, string> pair in pairs)
{
this.Attributes[pair.Key] = pair.Value;
}
return this;
}
// Check to see if Attributes property is set
internal bool IsSetAttributes()
{
return this.attributes != null;
}
/// <summary>
/// When the app was created.
///
/// </summary>
public string CreatedAt
{
get { return this.createdAt; }
set { this.createdAt = value; }
}
/// <summary>
/// Sets the CreatedAt property
/// </summary>
/// <param name="createdAt">The value to set for the CreatedAt property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public App WithCreatedAt(string createdAt)
{
this.createdAt = createdAt;
return this;
}
// Check to see if CreatedAt property is set
internal bool IsSetCreatedAt()
{
return this.createdAt != 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.LambdaSimplifier;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.LambdaSimplifier
{
public class LambdaSimplifierTests : AbstractCSharpCodeActionTest
{
protected override object CreateCodeRefactoringProvider(Workspace workspace)
{
return new LambdaSimplifierCodeRefactoringProvider();
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixAll1()
{
await TestAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); } void Bar(Func<int,string> f); string Quux(int i); }",
@"using System; class C { void Foo() { Bar(Quux); } void Bar(Func<int,string> f); string Quux(int i); }",
index: 1);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixCoContravariance1()
{
await TestAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); } void Bar(Func<object,string> f); string Quux(object o); }",
@"using System; class C { void Foo() { Bar(Quux); } void Bar(Func<object,string> f); string Quux(object o); }",
index: 1);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixCoContravariance2()
{
await TestAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); } void Bar(Func<string, object> f); string Quux(object o); }",
@"using System; class C { void Foo() { Bar(Quux); } void Bar(Func<string, object> f); string Quux(object o); }",
index: 1);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixCoContravariance3()
{
await TestMissingAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); } void Bar(Func<string, string> f); object Quux(object o); }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixCoContravariance4()
{
await TestMissingAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); } void Bar(Func<object, object> f); string Quux(string o); }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixCoContravariance5()
{
await TestMissingAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); } void Bar(Func<object, string> f); object Quux(string o); }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixAll2()
{
await TestAsync(
@"using System; class C { void Foo() { Bar((s1, s2) [||]=> Quux(s1, s2)); } void Bar(Func<int,bool,string> f); string Quux(int i, bool b); }",
@"using System; class C { void Foo() { Bar(Quux); } void Bar(Func<int,bool,string> f); string Quux(int i, bool b); }",
index: 1);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixAll3()
{
await TestAsync(
@"using System; class C { void Foo() { Bar((s1, s2) [||]=> { return Quux(s1, s2); }); } void Bar(Func<int,bool,string> f); string Quux(int i, bool b); }",
@"using System; class C { void Foo() { Bar(Quux); } void Bar(Func<int,bool,string> f); string Quux(int i, bool b); }",
index: 1);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixAll4()
{
await TestAsync(
@"using System; class C { void Foo() { Bar((s1, s2) [||]=> { return this.Quux(s1, s2); }); } void Bar(Func<int,bool,string> f); string Quux(int i, bool b); }",
@"using System; class C { void Foo() { Bar(this.Quux); } void Bar(Func<int,bool,string> f); string Quux(int i, bool b); }",
index: 1);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixOneOrAll()
{
await TestAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); Bar(s => Quux(s)); } void Bar(Func<int,string> f); string Quux(int i); }",
@"using System; class C { void Foo() { Bar(Quux); Bar(s => Quux(s)); } void Bar(Func<int,string> f); string Quux(int i); }",
index: 0);
await TestAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); Bar(s => Quux(s)); } void Bar(Func<int,string> f); string Quux(int i); }",
@"using System; class C { void Foo() { Bar(Quux); Bar(Quux); } void Bar(Func<int,string> f); string Quux(int i); }",
index: 1);
}
[WorkItem(542562)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestMissingOnAmbiguity1()
{
await TestMissingAsync(
@"
using System;
class A
{
static void Foo<T>(T x) where T : class { }
static void Bar(Action<int> x) { }
static void Bar(Action<string> x) { }
static void Main()
{
Bar(x => [||]Foo(x));
}
}");
}
[WorkItem(627092)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestMissingOnLambdaWithDynamic_1()
{
await TestMissingAsync(
@"using System;
class Program
{
static void Main()
{
C<string>.InvokeFoo();
}
}
class C<T>
{
public static void InvokeFoo()
{
Action<dynamic, string> foo = (x, y) => [||]C<T>.Foo(x, y); // Simplify lambda expression
foo(1, "");
}
static void Foo(object x, object y)
{
Console.WriteLine(""Foo(object x, object y)"");
}
static void Foo(object x, T y)
{
Console.WriteLine(""Foo(object x, T y)"");
}
}");
}
[WorkItem(627092)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestMissingOnLambdaWithDynamic_2()
{
await TestMissingAsync(
@"using System;
class Program
{
static void Main()
{
C<string>.InvokeFoo();
}
}
class Casd<T>
{
public static void InvokeFoo()
{
Action<dynamic> foo = x => [||]Casd<T>.Foo(x); // Simplify lambda expression
foo(1, "");
}
private static void Foo(dynamic x)
{
throw new NotImplementedException();
}
static void Foo(object x, object y)
{
Console.WriteLine(""Foo(object x, object y)"");
}
static void Foo(object x, T y)
{
Console.WriteLine(""Foo(object x, T y)"");
}
}");
}
[WorkItem(544625)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task ParenthesizeIfParseChanges()
{
var code = @"
using System;
class C
{
static void M()
{
C x = new C();
int y = 1;
Bar(() [||]=> { return Console.ReadLine(); } < x, y > (1 + 2));
}
static void Bar(object a, object b) { }
public static bool operator <(Func<string> y, C x) { return true; }
public static bool operator >(Func<string> y, C x) { return true; }
}";
var expected = @"
using System;
class C
{
static void M()
{
C x = new C();
int y = 1;
Bar((Console.ReadLine) < x, y > (1 + 2));
}
static void Bar(object a, object b) { }
public static bool operator <(Func<string> y, C x) { return true; }
public static bool operator >(Func<string> y, C x) { return true; }
}";
await TestAsync(code, expected, compareTokens: false);
}
[WorkItem(545856)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestWarningOnSideEffects()
{
await TestAsync(
@"using System ; class C { void Main ( ) { Func < string > a = ( ) [||]=> new C ( ) . ToString ( ) ; } } ",
@"using System ; class C { void Main ( ) { Func < string > a = {|Warning:new C ()|} . ToString ; } } ");
}
[WorkItem(545994)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestNonReturnBlockSyntax()
{
await TestAsync(
@"using System ; class Program { static void Main ( ) { Action a = [||]( ) => { Console . WriteLine ( ) ; } ; } } ",
@"using System ; class Program { static void Main ( ) { Action a = Console . WriteLine ; } } ");
}
}
}
| |
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Xml;
using System.Data.SqlClient;
namespace Microsoft.Samples.SsbTransportChannel
{
public class SsbOutputSessionChannel : ChannelBase, IOutputSessionChannel
{
SsbConversationSender sender;
Uri via;
//Uri sourceAddress;
//EndpointAddress replyTo;
EndpointAddress to;
SsbSession session;
BufferManager bufferManager;
MessageEncoder encoder;
string connectionString;
string contract;
bool useEncryption;
bool useActionForSsbMessageType;
SsbChannelFactory factory;
public SsbOutputSessionChannel(SsbChannelFactory factory, string connectionString, Uri via,EndpointAddress remoteAddress, BufferManager buffermanager, MessageEncoder encoder, bool endConversationOnClose, string contract, bool useEncryption, bool useActionForSsbMessageType)
: base(factory)
{
if (via == null)
{
throw new ArgumentNullException("via");
}
if (factory == null)
{
throw new ArgumentNullException("factory");
}
if (encoder == null)
{
throw new ArgumentNullException("encoder");
}
if (buffermanager == null)
{
throw new ArgumentNullException("bufferManager");
}
if (String.IsNullOrEmpty(connectionString))
{
throw new ArgumentNullException("connectionString");
}
this.factory = factory;
this.via = via;
this.to = remoteAddress;
this.session = new SsbSession();
this.encoder = encoder;
this.bufferManager = buffermanager;
this.connectionString = connectionString;
this.contract = contract;
this.useEncryption = useEncryption;
this.useActionForSsbMessageType = useActionForSsbMessageType;
this.sender = new SsbConversationSender(connectionString, via, factory, endConversationOnClose,contract,useEncryption );
}
#region IOutputChannel Members
public EndpointAddress RemoteAddress
{
get { return this.to; }
}
public void Send(Message message, TimeSpan timeout)
{
ThrowIfDisposedOrNotOpen(); //now must be Opened
string messageType = "DEFAULT";
if (this.useActionForSsbMessageType )
{
messageType = message.Headers.Action;
}
if (this.to != null)
{
this.to.ApplyTo(message);
}
ArraySegment<byte> messagebuffer = this.encoder.WriteMessage(message, Int32.MaxValue, bufferManager);
message.Close();
byte[] buffer = new byte[messagebuffer.Count];
Buffer.BlockCopy(messagebuffer.Array, messagebuffer.Offset, buffer, 0, messagebuffer.Count);
this.sender.Send(buffer, timeout, messageType);
bufferManager.ReturnBuffer(messagebuffer.Array);
}
public void Send(Message message)
{
this.Send(message, TimeSpan.MaxValue);
}
public Uri Via
{
get { return this.via; }
}
#endregion
public IOutputSession Session
{
get { return this.session; }
}
protected override void OnAbort()
{
sender.Abort();
}
protected override void OnClose(TimeSpan timeout)
{
sender.Close();
}
protected override void OnOpen(TimeSpan timeout)
{
sender.Open();
}
#region AsyncAWrappers
public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
throw new Exception("The method or operation is not implemented.");
}
public IAsyncResult BeginSend(Message message, AsyncCallback callback, object state)
{
throw new Exception("The method or operation is not implemented.");
}
public void EndSend(IAsyncResult result)
{
throw new Exception("The method or operation is not implemented.");
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
CloseDelegate d = new CloseDelegate(this.Close);
return d.BeginInvoke(timeout, callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CloseDelegate d = new CloseDelegate(this.Close);
d.EndInvoke(result);
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
OpenDelegate d = new OpenDelegate(this.Open);
return d.BeginInvoke(timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
OpenDelegate d = new OpenDelegate(this.Open);
d.EndInvoke(result);
}
#endregion
public override T GetProperty<T>()
{
if (typeof(T)==typeof(SsbConversationSender))
{
return ((T)(object)this.sender);
}
return base.GetProperty<T>();
}
//private void SetConversation(Message message)
//{
// XmlReader reader = message.GetReaderAtBodyContents();
// while (reader.Read())
// {
// if (reader.NodeType == XmlNodeType.Element &&
// reader.Name == SsbConstants.ConversationHandleElementName &&
// reader.NamespaceURI == SsbConstants.SsbContractNs)
// {
// string t = reader.ReadElementString();
// if (!String.IsNullOrEmpty(t))
// {
// this.cid = new Guid(t);
// }
// }
// else if (reader.NodeType == XmlNodeType.Element &&
// reader.Name == SsbConstants.ConversationGroupHandleElementName &&
// reader.NamespaceURI == SsbConstants.SsbContractNs)
// {
// string t = reader.ReadElementString();
// if (!String.IsNullOrEmpty(t))
// {
// this.cgid = new Guid(t);
// }
// }
// }
// reader.Close();
//}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System {
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Security;
using System.Security.Permissions;
[Serializable]
[AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple=false)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Attribute))]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Attribute : _Attribute
{
#region Private Statics
#region PropertyInfo
private static Attribute[] InternalGetCustomAttributes(PropertyInfo element, Type type, bool inherit)
{
Contract.Requires(element != null);
Contract.Requires(type != null);
Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute));
// walk up the hierarchy chain
Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
if (!inherit)
return attributes;
// create the hashtable that keeps track of inherited types
Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11);
// create an array list to collect all the requested attibutes
List<Attribute> attributeList = new List<Attribute>();
CopyToArrayList(attributeList, attributes, types);
PropertyInfo baseProp = GetParentDefinition(element);
while (baseProp != null)
{
attributes = GetCustomAttributes(baseProp, type, false);
AddAttributesToList(attributeList, attributes, types);
baseProp = GetParentDefinition(baseProp);
}
Array array = CreateAttributeArrayHelper(type, attributeList.Count);
Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count);
return (Attribute[])array;
}
private static bool InternalIsDefined(PropertyInfo element, Type attributeType, bool inherit)
{
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
if (inherit)
{
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
if (!usage.Inherited)
return false;
PropertyInfo baseProp = GetParentDefinition(element);
while (baseProp != null)
{
if (baseProp.IsDefined(attributeType, false))
return true;
baseProp = GetParentDefinition(baseProp);
}
}
return false;
}
private static PropertyInfo GetParentDefinition(PropertyInfo property)
{
Contract.Requires(property != null);
// for the current property get the base class of the getter and the setter, they might be different
// note that this only works for RuntimeMethodInfo
MethodInfo propAccessor = property.GetGetMethod(true);
if (propAccessor == null)
propAccessor = property.GetSetMethod(true);
RuntimeMethodInfo rtPropAccessor = propAccessor as RuntimeMethodInfo;
if (rtPropAccessor != null)
{
rtPropAccessor = rtPropAccessor.GetParentDefinition();
if (rtPropAccessor != null)
{
#if FEATURE_LEGACYNETCF
// Mimicing NetCF which only looks for public properties.
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
return rtPropAccessor.DeclaringType.GetProperty(property.Name, property.PropertyType);
#endif //FEATURE_LEGACYNETCF
// There is a public overload of Type.GetProperty that takes both a BingingFlags enum and a return type.
// However, we cannot use that because it doesn't accept null for "types".
return rtPropAccessor.DeclaringType.GetProperty(
property.Name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
property.PropertyType);
}
}
return null;
}
#endregion
#region EventInfo
private static Attribute[] InternalGetCustomAttributes(EventInfo element, Type type, bool inherit)
{
Contract.Requires(element != null);
Contract.Requires(type != null);
Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute));
// walk up the hierarchy chain
Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
if (inherit)
{
// create the hashtable that keeps track of inherited types
Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11);
// create an array list to collect all the requested attibutes
List<Attribute> attributeList = new List<Attribute>();
CopyToArrayList(attributeList, attributes, types);
EventInfo baseEvent = GetParentDefinition(element);
while (baseEvent != null)
{
attributes = GetCustomAttributes(baseEvent, type, false);
AddAttributesToList(attributeList, attributes, types);
baseEvent = GetParentDefinition(baseEvent);
}
Array array = CreateAttributeArrayHelper(type, attributeList.Count);
Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count);
return (Attribute[])array;
}
else
return attributes;
}
private static EventInfo GetParentDefinition(EventInfo ev)
{
Contract.Requires(ev != null);
// note that this only works for RuntimeMethodInfo
MethodInfo add = ev.GetAddMethod(true);
RuntimeMethodInfo rtAdd = add as RuntimeMethodInfo;
if (rtAdd != null)
{
rtAdd = rtAdd.GetParentDefinition();
if (rtAdd != null)
return rtAdd.DeclaringType.GetEvent(ev.Name);
}
return null;
}
private static bool InternalIsDefined (EventInfo element, Type attributeType, bool inherit)
{
Contract.Requires(element != null);
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
if (inherit)
{
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
if (!usage.Inherited)
return false;
EventInfo baseEvent = GetParentDefinition(element);
while (baseEvent != null)
{
if (baseEvent.IsDefined(attributeType, false))
return true;
baseEvent = GetParentDefinition(baseEvent);
}
}
return false;
}
#endregion
#region ParameterInfo
private static ParameterInfo GetParentDefinition(ParameterInfo param)
{
Contract.Requires(param != null);
// note that this only works for RuntimeMethodInfo
RuntimeMethodInfo rtMethod = param.Member as RuntimeMethodInfo;
if (rtMethod != null)
{
rtMethod = rtMethod.GetParentDefinition();
if (rtMethod != null)
{
// Find the ParameterInfo on this method
ParameterInfo[] parameters = rtMethod.GetParameters();
return parameters[param.Position]; // Point to the correct ParameterInfo of the method
}
}
return null;
}
private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type type, bool inherit)
{
Contract.Requires(param != null);
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that
// have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
// that are marked inherited from the remainder of the MethodInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk so the default ParameterInfo attributes are returned.
// For MethodInfo's on a class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the
// class inherits from and return the respective ParameterInfo attributes
List<Type> disAllowMultiple = new List<Type>();
Object [] objAttr;
if (type == null)
type = typeof(Attribute);
objAttr = param.GetCustomAttributes(type, false);
for (int i =0;i < objAttr.Length;i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if (attribUsage.AllowMultiple == false)
disAllowMultiple.Add(objType);
}
// Get all the attributes that have Attribute as the base class
Attribute [] ret = null;
if (objAttr.Length == 0)
ret = CreateAttributeArrayHelper(type,0);
else
ret = (Attribute[])objAttr;
if (param.Member.DeclaringType == null) // This is an interface so we are done.
return ret;
if (!inherit)
return ret;
ParameterInfo baseParam = GetParentDefinition(param);
while (baseParam != null)
{
objAttr = baseParam.GetCustomAttributes(type, false);
int count = 0;
for (int i =0;i < objAttr.Length;i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if ((attribUsage.Inherited) && (disAllowMultiple.Contains(objType) == false))
{
if (attribUsage.AllowMultiple == false)
disAllowMultiple.Add(objType);
count++;
}
else
objAttr[i] = null;
}
// Get all the attributes that have Attribute as the base class
Attribute [] attributes = CreateAttributeArrayHelper(type,count);
count = 0;
for (int i =0;i < objAttr.Length;i++)
{
if (objAttr[i] != null)
{
attributes[count] = (Attribute)objAttr[i];
count++;
}
}
Attribute [] temp = ret;
ret = CreateAttributeArrayHelper(type,temp.Length + count);
Array.Copy(temp,ret,temp.Length);
int offset = temp.Length;
for (int i =0;i < attributes.Length;i++)
ret[offset + i] = attributes[i];
baseParam = GetParentDefinition(baseParam);
}
return ret;
}
private static bool InternalParamIsDefined(ParameterInfo param, Type type, bool inherit)
{
Contract.Requires(param != null);
Contract.Requires(type != null);
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain.
// We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
// that are marked inherited from the remainder of the ParameterInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk. For ParameterInfo's on a
// Class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the class inherits from.
if (param.IsDefined(type, false))
return true;
if (param.Member.DeclaringType == null || !inherit) // This is an interface so we are done.
return false;
ParameterInfo baseParam = GetParentDefinition(param);
while (baseParam != null)
{
Object[] objAttr = baseParam.GetCustomAttributes(type, false);
for (int i =0; i < objAttr.Length; i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if ((objAttr[i] is Attribute) && (attribUsage.Inherited))
return true;
}
baseParam = GetParentDefinition(baseParam);
}
return false;
}
#endregion
#region Utility
private static void CopyToArrayList(List<Attribute> attributeList,Attribute[] attributes,Dictionary<Type, AttributeUsageAttribute> types)
{
for (int i = 0; i < attributes.Length; i++)
{
attributeList.Add(attributes[i]);
Type attrType = attributes[i].GetType();
if (!types.ContainsKey(attrType))
types[attrType] = InternalGetAttributeUsage(attrType);
}
}
private static void AddAttributesToList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types)
{
for (int i = 0; i < attributes.Length; i++)
{
Type attrType = attributes[i].GetType();
AttributeUsageAttribute usage = null;
types.TryGetValue(attrType, out usage);
if (usage == null)
{
// the type has never been seen before if it's inheritable add it to the list
usage = InternalGetAttributeUsage(attrType);
types[attrType] = usage;
if (usage.Inherited)
attributeList.Add(attributes[i]);
}
else if (usage.Inherited && usage.AllowMultiple)
{
// we saw this type already add it only if it is inheritable and it does allow multiple
attributeList.Add(attributes[i]);
}
}
}
private static AttributeUsageAttribute InternalGetAttributeUsage(Type type)
{
// Check if the custom attributes is Inheritable
Object [] obj = type.GetCustomAttributes(typeof(AttributeUsageAttribute), false);
if (obj.Length == 1)
return (AttributeUsageAttribute)obj[0];
if (obj.Length == 0)
return AttributeUsageAttribute.Default;
throw new FormatException(
Environment.GetResourceString("Format_AttributeUsage", type));
}
[System.Security.SecuritySafeCritical]
private static Attribute[] CreateAttributeArrayHelper(Type elementType, int elementCount)
{
return (Attribute[])Array.UnsafeCreateInstance(elementType, elementCount);
}
#endregion
#endregion
#region Public Statics
#region MemberInfo
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type)
{
return GetCustomAttributes(element, type, true);
}
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (type == null)
throw new ArgumentNullException("type");
if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
switch (element.MemberType)
{
case MemberTypes.Property:
return InternalGetCustomAttributes((PropertyInfo)element, type, inherit);
case MemberTypes.Event:
return InternalGetCustomAttributes((EventInfo)element, type, inherit);
default:
return element.GetCustomAttributes(type, inherit) as Attribute[];
}
}
public static Attribute[] GetCustomAttributes(MemberInfo element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
Contract.EndContractBlock();
switch (element.MemberType)
{
case MemberTypes.Property:
return InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit);
case MemberTypes.Event:
return InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit);
default:
return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
}
}
public static bool IsDefined(MemberInfo element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(MemberInfo element, Type attributeType, bool inherit)
{
// Returns true if a custom attribute subclass of attributeType class/interface with inheritance walk
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
switch(element.MemberType)
{
case MemberTypes.Property:
return InternalIsDefined((PropertyInfo)element, attributeType, inherit);
case MemberTypes.Event:
return InternalIsDefined((EventInfo)element, attributeType, inherit);
default:
return element.IsDefined(attributeType, inherit);
}
}
public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit)
{
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
#endregion
#region ParameterInfo
public static Attribute[] GetCustomAttributes(ParameterInfo element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType)
{
return (Attribute[])GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
if (element.Member == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), "element");
Contract.EndContractBlock();
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes(element, attributeType, inherit) as Attribute[];
return element.GetCustomAttributes(attributeType, inherit) as Attribute[];
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (element.Member == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), "element");
Contract.EndContractBlock();
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes(element, null, inherit) as Attribute[];
return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
}
public static bool IsDefined(ParameterInfo element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
MemberInfo member = element.Member;
switch(member.MemberType)
{
case MemberTypes.Method: // We need to climb up the member hierarchy
return InternalParamIsDefined(element, attributeType, inherit);
case MemberTypes.Constructor:
return element.IsDefined(attributeType, false);
case MemberTypes.Property:
return element.IsDefined(attributeType, false);
default:
Contract.Assert(false, "Invalid type for ParameterInfo member in Attribute class");
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo"));
}
}
public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the ParameterInfo or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
#endregion
#region Module
public static Attribute[] GetCustomAttributes(Module element, Type attributeType)
{
return GetCustomAttributes (element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(Module element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(Module element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
public static Attribute[] GetCustomAttributes(Module element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
public static bool IsDefined(Module element, Type attributeType)
{
return IsDefined(element, attributeType, false);
}
public static bool IsDefined(Module element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
return element.IsDefined(attributeType,false);
}
public static Attribute GetCustomAttribute(Module element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(Module element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the Module or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
#endregion
#region Assembly
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType)
{
return GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
public static Attribute[] GetCustomAttributes(Assembly element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(Assembly element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
public static bool IsDefined (Assembly element, Type attributeType)
{
return IsDefined (element, attributeType, true);
}
public static bool IsDefined (Assembly element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
return element.IsDefined(attributeType, false);
}
public static Attribute GetCustomAttribute(Assembly element, Type attributeType)
{
return GetCustomAttribute (element, attributeType, true);
}
public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
#endregion
#endregion
#region Constructor
protected Attribute() { }
#endregion
#region Object Overrides
[SecuritySafeCritical]
public override bool Equals(Object obj)
{
if (obj == null)
return false;
RuntimeType thisType = (RuntimeType)this.GetType();
RuntimeType thatType = (RuntimeType)obj.GetType();
if (thatType != thisType)
return false;
Object thisObj = this;
Object thisResult, thatResult;
FieldInfo[] thisFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
for (int i = 0; i < thisFields.Length; i++)
{
// Visibility check and consistency check are not necessary.
thisResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(thisObj);
thatResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(obj);
if (!AreFieldValuesEqual(thisResult, thatResult))
{
return false;
}
}
return true;
}
// Compares values of custom-attribute fields.
private static bool AreFieldValuesEqual(Object thisValue, Object thatValue)
{
if (thisValue == null && thatValue == null)
return true;
if (thisValue == null || thatValue == null)
return false;
if (thisValue.GetType().IsArray)
{
// Ensure both are arrays of the same type.
if (!thisValue.GetType().Equals(thatValue.GetType()))
{
return false;
}
Array thisValueArray = thisValue as Array;
Array thatValueArray = thatValue as Array;
if (thisValueArray.Length != thatValueArray.Length)
{
return false;
}
// Attributes can only contain single-dimension arrays, so we don't need to worry about
// multidimensional arrays.
Contract.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1);
for (int j = 0; j < thisValueArray.Length; j++)
{
if (!AreFieldValuesEqual(thisValueArray.GetValue(j), thatValueArray.GetValue(j)))
{
return false;
}
}
}
else
{
// An object of type Attribute will cause a stack overflow.
// However, this should never happen because custom attributes cannot contain values other than
// constants, single-dimensional arrays and typeof expressions.
Contract.Assert(!(thisValue is Attribute));
if (!thisValue.Equals(thatValue))
return false;
}
return true;
}
[SecuritySafeCritical]
public override int GetHashCode()
{
Type type = GetType();
FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
Object vThis = null;
for (int i = 0; i < fields.Length; i++)
{
// Visibility check and consistency check are not necessary.
Object fieldValue = ((RtFieldInfo)fields[i]).UnsafeGetValue(this);
// The hashcode of an array ignores the contents of the array, so it can produce
// different hashcodes for arrays with the same contents.
// Since we do deep comparisons of arrays in Equals(), this means Equals and GetHashCode will
// be inconsistent for arrays. Therefore, we ignore hashes of arrays.
if (fieldValue != null && !fieldValue.GetType().IsArray)
vThis = fieldValue;
if (vThis != null)
break;
}
if (vThis != null)
return vThis.GetHashCode();
return type.GetHashCode();
}
#endregion
#region Public Virtual Members
public virtual Object TypeId { get { return GetType(); } }
public virtual bool Match(Object obj) { return Equals(obj); }
#endregion
#region Public Members
public virtual bool IsDefaultAttribute() { return false; }
#endregion
void _Attribute.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _Attribute.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _Attribute.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _Attribute.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Globalization
{
public static class __GregorianCalendar
{
public static IObservable<System.DateTime> AddMonths(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.DateTime> time, IObservable<System.Int32> months)
{
return Observable.Zip(GregorianCalendarValue, time, months,
(GregorianCalendarValueLambda, timeLambda, monthsLambda) =>
GregorianCalendarValueLambda.AddMonths(timeLambda, monthsLambda));
}
public static IObservable<System.DateTime> AddYears(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.DateTime> time, IObservable<System.Int32> years)
{
return Observable.Zip(GregorianCalendarValue, time, years,
(GregorianCalendarValueLambda, timeLambda, yearsLambda) =>
GregorianCalendarValueLambda.AddYears(timeLambda, yearsLambda));
}
public static IObservable<System.Int32> GetDayOfMonth(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.DateTime> time)
{
return Observable.Zip(GregorianCalendarValue, time,
(GregorianCalendarValueLambda, timeLambda) => GregorianCalendarValueLambda.GetDayOfMonth(timeLambda));
}
public static IObservable<System.DayOfWeek> GetDayOfWeek(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.DateTime> time)
{
return Observable.Zip(GregorianCalendarValue, time,
(GregorianCalendarValueLambda, timeLambda) => GregorianCalendarValueLambda.GetDayOfWeek(timeLambda));
}
public static IObservable<System.Int32> GetDayOfYear(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.DateTime> time)
{
return Observable.Zip(GregorianCalendarValue, time,
(GregorianCalendarValueLambda, timeLambda) => GregorianCalendarValueLambda.GetDayOfYear(timeLambda));
}
public static IObservable<System.Int32> GetDaysInMonth(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> era)
{
return Observable.Zip(GregorianCalendarValue, year, month, era,
(GregorianCalendarValueLambda, yearLambda, monthLambda, eraLambda) =>
GregorianCalendarValueLambda.GetDaysInMonth(yearLambda, monthLambda, eraLambda));
}
public static IObservable<System.Int32> GetDaysInYear(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> era)
{
return Observable.Zip(GregorianCalendarValue, year, era,
(GregorianCalendarValueLambda, yearLambda, eraLambda) =>
GregorianCalendarValueLambda.GetDaysInYear(yearLambda, eraLambda));
}
public static IObservable<System.Int32> GetEra(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.DateTime> time)
{
return Observable.Zip(GregorianCalendarValue, time,
(GregorianCalendarValueLambda, timeLambda) => GregorianCalendarValueLambda.GetEra(timeLambda));
}
public static IObservable<System.Int32> GetMonth(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.DateTime> time)
{
return Observable.Zip(GregorianCalendarValue, time,
(GregorianCalendarValueLambda, timeLambda) => GregorianCalendarValueLambda.GetMonth(timeLambda));
}
public static IObservable<System.Int32> GetMonthsInYear(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> era)
{
return Observable.Zip(GregorianCalendarValue, year, era,
(GregorianCalendarValueLambda, yearLambda, eraLambda) =>
GregorianCalendarValueLambda.GetMonthsInYear(yearLambda, eraLambda));
}
public static IObservable<System.Int32> GetYear(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.DateTime> time)
{
return Observable.Zip(GregorianCalendarValue, time,
(GregorianCalendarValueLambda, timeLambda) => GregorianCalendarValueLambda.GetYear(timeLambda));
}
public static IObservable<System.Boolean> IsLeapDay(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> day,
IObservable<System.Int32> era)
{
return Observable.Zip(GregorianCalendarValue, year, month, day, era,
(GregorianCalendarValueLambda, yearLambda, monthLambda, dayLambda, eraLambda) =>
GregorianCalendarValueLambda.IsLeapDay(yearLambda, monthLambda, dayLambda, eraLambda));
}
public static IObservable<System.Int32> GetLeapMonth(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> era)
{
return Observable.Zip(GregorianCalendarValue, year, era,
(GregorianCalendarValueLambda, yearLambda, eraLambda) =>
GregorianCalendarValueLambda.GetLeapMonth(yearLambda, eraLambda));
}
public static IObservable<System.Boolean> IsLeapMonth(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> era)
{
return Observable.Zip(GregorianCalendarValue, year, month, era,
(GregorianCalendarValueLambda, yearLambda, monthLambda, eraLambda) =>
GregorianCalendarValueLambda.IsLeapMonth(yearLambda, monthLambda, eraLambda));
}
public static IObservable<System.Boolean> IsLeapYear(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> era)
{
return Observable.Zip(GregorianCalendarValue, year, era,
(GregorianCalendarValueLambda, yearLambda, eraLambda) =>
GregorianCalendarValueLambda.IsLeapYear(yearLambda, eraLambda));
}
public static IObservable<System.DateTime> ToDateTime(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> day,
IObservable<System.Int32> hour, IObservable<System.Int32> minute, IObservable<System.Int32> second,
IObservable<System.Int32> millisecond, IObservable<System.Int32> era)
{
return Observable.Zip(GregorianCalendarValue, year, month, day, hour, minute, second, millisecond, era,
(GregorianCalendarValueLambda, yearLambda, monthLambda, dayLambda, hourLambda, minuteLambda,
secondLambda, millisecondLambda, eraLambda) =>
GregorianCalendarValueLambda.ToDateTime(yearLambda, monthLambda, dayLambda, hourLambda, minuteLambda,
secondLambda, millisecondLambda, eraLambda));
}
public static IObservable<System.Int32> ToFourDigitYear(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.Int32> year)
{
return Observable.Zip(GregorianCalendarValue, year,
(GregorianCalendarValueLambda, yearLambda) => GregorianCalendarValueLambda.ToFourDigitYear(yearLambda));
}
public static IObservable<System.DateTime> get_MinSupportedDateTime(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue)
{
return Observable.Select(GregorianCalendarValue,
(GregorianCalendarValueLambda) => GregorianCalendarValueLambda.MinSupportedDateTime);
}
public static IObservable<System.DateTime> get_MaxSupportedDateTime(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue)
{
return Observable.Select(GregorianCalendarValue,
(GregorianCalendarValueLambda) => GregorianCalendarValueLambda.MaxSupportedDateTime);
}
public static IObservable<System.Globalization.CalendarAlgorithmType> get_AlgorithmType(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue)
{
return Observable.Select(GregorianCalendarValue,
(GregorianCalendarValueLambda) => GregorianCalendarValueLambda.AlgorithmType);
}
public static IObservable<System.Globalization.GregorianCalendarTypes> get_CalendarType(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue)
{
return Observable.Select(GregorianCalendarValue,
(GregorianCalendarValueLambda) => GregorianCalendarValueLambda.CalendarType);
}
public static IObservable<System.Int32[]> get_Eras(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue)
{
return Observable.Select(GregorianCalendarValue,
(GregorianCalendarValueLambda) => GregorianCalendarValueLambda.Eras);
}
public static IObservable<System.Int32> get_TwoDigitYearMax(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue)
{
return Observable.Select(GregorianCalendarValue,
(GregorianCalendarValueLambda) => GregorianCalendarValueLambda.TwoDigitYearMax);
}
public static IObservable<System.Reactive.Unit> set_CalendarType(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.Globalization.GregorianCalendarTypes> value)
{
return ObservableExt.ZipExecute(GregorianCalendarValue, value,
(GregorianCalendarValueLambda, valueLambda) => GregorianCalendarValueLambda.CalendarType = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_TwoDigitYearMax(
this IObservable<System.Globalization.GregorianCalendar> GregorianCalendarValue,
IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(GregorianCalendarValue, value,
(GregorianCalendarValueLambda, valueLambda) =>
GregorianCalendarValueLambda.TwoDigitYearMax = valueLambda);
}
}
}
| |
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Activation;
using System.Runtime.Serialization;
using System.Text;
namespace Arebis.Mocking {
/// <summary>
/// Represents the mockable call to a method. A MockableCall can stand for a regular
/// method call, a constructor call, or a get or set of a property.
/// </summary>
/// <remarks>MockableCall is a serializable class.</remarks>
[Serializable]
//[DebuggerDisplayAttribute("MockableCall: {MethodSignature}")]
public class MockableCall : ISerializable {
[NonSerialized] private IMethodCallMessage originalCall;
private MockingProxy callee;
private MethodBase method;
private object[] inArgs;
private object[] outArgs;
private object returnValue;
private Exception exception;
[NonSerialized] private int callCreationTime;
private int callDuration = -1;
private bool isConstructorCall;
private bool isCompleted;
#region Constructors
/// <summary>
/// Instantiates a new MockableCall object based on a IMethodCallMessage.
/// </summary>
public MockableCall(MockingProxy callee, IMethodCallMessage callmsg) {
if (callee == null) throw new ArgumentNullException("callee");
if (callmsg == null) throw new ArgumentNullException("callmsg");
this.originalCall = callmsg;
this.callCreationTime = Environment.TickCount;
this.callee = callee;
this.method = callmsg.MethodBase;
this.inArgs = callmsg.InArgs;
this.isConstructorCall = (callmsg is IConstructionCallMessage);
this.isCompleted = false;
}
/// <summary>
/// Instantiates a new MockableCall object based on a MethodBase.
/// </summary>
/// <param name="callee">The proxy of the called object.</param>
/// <param name="method">The method of this call.</param>
/// <param name="arguments">The arguments passed to the methodcall (output arguments must be provided but they can have any value).</param>
public MockableCall(MockingProxy callee, System.Reflection.MethodBase method, object[] arguments){
if (callee == null) throw new ArgumentNullException("callee");
if (method == null) throw new ArgumentNullException("method");
this.originalCall = null;
this.callCreationTime = Environment.TickCount;
this.callee = callee;
this.method = method;
this.inArgs = new object[this.GetInParameters().Length];
if (arguments != null) {
int i = 0;
foreach(ParameterInfo param in this.GetInParameters()) {
this.inArgs[i++] = arguments[param.Position];
}
}
this.isConstructorCall = (method.IsConstructor);
this.isCompleted = false;
}
#endregion
#region Accessors
/// <summary>
/// The original call object from the .NET Framework.
/// </summary>
public System.Runtime.Remoting.Messaging.IMethodCallMessage OriginalCall {
get {
return this.originalCall;
}
}
/// <summary>
/// The instance that receives the call.
/// </summary>
public virtual MockingProxy Callee {
get {
return this.callee;
}
}
/// <summary>
/// The method that is called.
/// </summary>
public virtual System.Reflection.MethodBase Method {
get {
return this.method;
}
}
/// <summary>
/// Returns the method signature string.
/// </summary>
public string MethodSignature {
get {
System.Text.StringBuilder sig = new System.Text.StringBuilder();
string argseparator = "";
if (this.isConstructorCall) {
ConstructorInfo ci = (ConstructorInfo)this.method;
sig.Append(ci.DeclaringType.Name);
} else {
MethodInfo mi = (MethodInfo)this.method;
sig.Append(mi.ReturnType.Name);
sig.Append(' ');
sig.Append(mi.Name);
}
sig.Append("(");
foreach(ParameterInfo param in this.method.GetParameters()) {
sig.Append(argseparator);
if (param.IsIn) sig.Append("in ");
if (param.IsOut) sig.Append("out ");
sig.Append(param.ParameterType.Name);
sig.Append(' ');
sig.Append(param.Name);
argseparator = ", ";
}
sig.Append(")");
return sig.ToString();
}
}
/// <summary>
/// Whether the called method is a constructor.
/// </summary>
public virtual bool IsConstructorCall {
get {
return this.isConstructorCall;
}
}
/// <summary>
/// The input arguments of the call.
/// </summary>
public virtual object[] InArgs {
get {
return this.inArgs;
}
}
/// <summary>
/// The output arguments of the call.
/// </summary>
public virtual object[] OutArgs {
get {
return this.outArgs;
}
}
/// <summary>
/// The arguments of the call (input and output arguments combined).
/// </summary>
public virtual object[] Args {
get {
int i;
// Prepare array:
object[] args = new object[this.GetParameters().Length];
// Copy input arguments:
i = 0;
foreach(ParameterInfo param in GetInParameters()) {
args[param.Position] = this.inArgs[i++];
}
// Overwrite with output arguments if yet available:
if (this.outArgs != null) {
i = 0;
foreach(ParameterInfo param in GetOutParameters()) {
args[param.Position] = this.outArgs[i++];
}
}
// Return result:
return args;
}
}
/// <summary>
/// The returnvalue of the call.
/// </summary>
public virtual object ReturnValue {
get {
return this.returnValue;
}
}
/// <summary>
/// The exception the call raises.
/// </summary>
public virtual System.Exception Exception {
get {
return this.exception;
}
}
/// <summary>
/// The duration of the recorded call in milliseconds.
/// </summary>
public virtual int CallDuration {
get {
return this.callDuration;
}
}
/// <summary>
/// Returns whether the call has completed.
/// </summary>
/// <remarks>Asynchonous calls and playback calls are initially not
/// completed and will be completed by setting their result.</remarks>
public virtual bool IsCompleted {
get {
return this.isCompleted;
}
}
/// <summary>
/// Returns information about all parameters (input and output).
/// </summary>
public virtual ParameterInfo[] GetParameters() {
return this.Method.GetParameters();
}
/// <summary>
/// Returns information about the input parameters.
/// </summary>
public virtual ParameterInfo[] GetInParameters() {
ArrayList paraminfos = new ArrayList();
foreach(ParameterInfo paraminfo in this.Method.GetParameters()) {
if (!paraminfo.IsOut) paraminfos.Add(paraminfo);
}
return (ParameterInfo[])paraminfos.ToArray(typeof(ParameterInfo));
}
/// <summary>
/// Returns information about the output parameters.
/// </summary>
public virtual ParameterInfo[] GetOutParameters() {
ArrayList paraminfos = new ArrayList();
foreach(ParameterInfo paraminfo in this.Method.GetParameters()) {
if ((paraminfo.ParameterType.IsByRef)) paraminfos.Add(paraminfo);
}
return (ParameterInfo[])paraminfos.ToArray(typeof(ParameterInfo));
}
/// <summary>
/// Whether the given parameter is an input or input-output parameter.
/// </summary>
/// <param name="parameterIndex">The index of the parameter.</param>
public virtual bool IsParameterIn(int parameterIndex) {
return !this.Method.GetParameters()[parameterIndex].IsOut;
}
/// <summary>
/// Whether the given parameter is an output or input-output parameter.
/// </summary>
/// <param name="parameterIndex">The index of the parameter.</param>
public virtual bool IsParameterOut(int parameterIndex) {
return this.Method.GetParameters()[parameterIndex].ParameterType.IsByRef;
}
/// <summary>
/// Returns the type the method of this call returns.
/// </summary>
public virtual Type GetReturnType() {
if (this.IsConstructorCall) {
return this.Callee.ServerType;
} else {
MethodInfo meth = this.Method as System.Reflection.MethodInfo;
if (meth != null) {
return meth.ReturnType;
} else {
return null;
}
}
}
#endregion
#region Setting results
/// <summary>
/// Set the result of the call by it's return message.
/// </summary>
public virtual void SetResult(IMethodReturnMessage returnmsg) {
if (returnmsg.Exception != null) {
this.SetExceptionResult(returnmsg.Exception);
} else if (this.IsConstructorCall) {
this.SetConstructionResult(callee.InstanceName, returnmsg.OutArgs);
} else {
this.SetCallResult(returnmsg.ReturnValue, returnmsg.OutArgs);
}
}
/// <summary>
/// Set the result of the call by copying the result of another call.
/// </summary>
public virtual void SetResult(MockableCall call) {
if (call.Exception != null) {
this.SetExceptionResult(call.Exception);
} else if (this.IsConstructorCall) {
this.SetConstructionResult(call.callee.InstanceName, call.OutArgs);
} else {
this.SetCallResult(call.ReturnValue, call.OutArgs);
}
}
/// <summary>
/// Set the result of construction call.
/// </summary>
/// <param name="instanceName">Name to be assigned to the created instance.</param>
// Not to be virtual, as merely forwaring to virtual method.
public void SetConstructionResult(string instanceName) {
SetConstructionResult(instanceName, new object[] {});
}
/// <summary>
/// Set the result of construction call.
/// </summary>
/// <param name="instanceName">Name to be assigned to the created instance.</param>
/// <param name="outArgs">The values of output arguments returned by the call.</param>
public virtual void SetConstructionResult(string instanceName, object[] outArgs) {
// Set return values:
this.callee.InstanceName = instanceName;
this.returnValue = callee.GetTransparentProxy();
this.outArgs = outArgs;
this.callDuration = Environment.TickCount - callCreationTime;
this.isCompleted = true;
}
/// <summary>
/// Set the call completed without return value.
/// </summary>
/// <remarks>Use this method to mark a void() call complete.</remarks>
// Not to be virtual, as merely forwaring to virtual method.
public void SetCallResult() {
this.SetCallResult(null);
}
/// <summary>
/// Set the call completed, returning the given output arguments.
/// </summary>
/// <param name="outArgs">The values of output arguments returned by the call.</param>
public virtual void SetCallResult(object[] outArgs) {
this.SetCallResult(null, outArgs);
}
/// <summary>
/// Set the call return value.
/// </summary>
/// <param name="returnValue">The value returned by the call.</param>
// Not to be virtual, as merely forwaring to virtual method.
public void SetCallResult(object returnValue) {
this.SetCallResult(returnValue, new object[] {});
}
/// <summary>
/// Set the call return value.
/// </summary>
/// <param name="returnValue">The value returned by the call.</param>
/// <param name="outArgs">The values of output arguments returned by the call.</param>
public virtual void SetCallResult(object returnValue, object[] outArgs) {
this.returnValue = returnValue;
this.outArgs = outArgs;
this.callDuration = Environment.TickCount - callCreationTime;
this.isCompleted = true;
}
/// <summary>
/// Set the exception thrown by the call.
/// </summary>
/// <param name="ex">The exception thrown by the call.</param>
public virtual void SetExceptionResult(Exception ex) {
this.returnValue = null;
this.outArgs = new object[] {};
this.exception = ex;
this.callDuration = Environment.TickCount - callCreationTime;
this.isCompleted = true;
}
#endregion
#region Serialization
private MockableCall(SerializationInfo info, StreamingContext context) {
// Retrieve serialization version:
string assemblyVersion = info.GetString("assemblyVersion");
decimal serializationVersion = info.GetDecimal("serializationVersion");
// Retrieve callee:
this.callee = new MockingProxy(Type.GetType(info.GetString("calleeType")), new PlayBackMocker(), info.GetString("calleeInstanceName"));
// Retrieve isConstructorCall:
this.isConstructorCall = info.GetBoolean("isConstructorCall");
// Retrieve method:
Type methodType = Type.GetType(info.GetString("methodType"));
string[] methodSignatureStr = (string[])info.GetValue("methodSignature", typeof(string[]));
Type[] methodSignature = new Type[methodSignatureStr.Length];
for(int i=0; i<methodSignatureStr.Length; i++) methodSignature[i] = Type.GetType(methodSignatureStr[i]);
if (this.isConstructorCall) {
this.method = methodType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, methodSignature, null);
} else {
this.method = methodType.GetMethod(info.GetString("methodName"), BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, methodSignature, null);
}
// Retrieve inArgs:
this.inArgs = (object[])info.GetValue("inArgs", typeof(object[]));
object[] inArgsSubstitutions = (object[])info.GetValue("inArgsMockers", typeof(object[]));
foreach(object[] subst in inArgsSubstitutions) {
MockingProxy proxy = new MockingProxy(Type.GetType((string)subst[1]), new PlayBackMocker(), (string)subst[2]);
this.inArgs[(int)subst[0]] = proxy.GetTransparentProxy();
}
// Retrieve outArgs:
this.outArgs = (object[])info.GetValue("outArgs", typeof(object[]));
object[] outArgsSubstitutions = (object[])info.GetValue("outArgsMockers", typeof(object[]));
if (outArgs != null) {
foreach(object[] subst in outArgsSubstitutions) {
MockingProxy proxy = new MockingProxy(Type.GetType((string)subst[1]), new PlayBackMocker(), (string)subst[2]);
this.outArgs[(int)subst[0]] = proxy.GetTransparentProxy();
}
}
// Retrieve returnValue:
bool returnValueMocked = info.GetBoolean("returnValueMocked");
Type returnValueType = Type.GetType(info.GetString("returnValueType"));
if (returnValueMocked) {
MockingProxy proxy = new MockingProxy(Type.GetType(info.GetString("returnValueType")), new PlayBackMocker(), info.GetString("returnValueName"));
this.returnValue = proxy.GetTransparentProxy();
} else {
this.returnValue = info.GetValue("returnValue", returnValueType);
}
// Retrieve exception:
this.exception = (Exception)info.GetValue("exception", typeof(Exception));
if (exception == null) {
string exceptionType = info.GetString("exceptionType");
if (exceptionType != null) {
this.exception = (Exception)Type.GetType(exceptionType).GetConstructor(new Type[] {}).Invoke(new object[] {});
}
}
// Retrieve iscompleted & duration:
this.isCompleted = info.GetBoolean("isCompleted");
this.callDuration = info.GetInt32("callDuration");
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
// Serialize serialization version:
info.AddValue("assemblyVersion", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
info.AddValue("serializationVersion", 2.0m);
// Serialize callee:
info.AddValue("calleeType", TypeRef(callee.GetProxiedType()));
info.AddValue("calleeInstanceName", callee.InstanceName);
// Serialize method:
info.AddValue("methodType", TypeRef(this.method.DeclaringType));
info.AddValue("methodName", this.method.Name);
ParameterInfo[] parameters = this.method.GetParameters();
string[] methodSignatureStr = new string[parameters.Length];
for(int i=0; i<parameters.Length; i++) methodSignatureStr[i] = TypeRef(parameters[i].ParameterType);
info.AddValue("methodSignature", methodSignatureStr);
// Serialize isConstructorCall:
info.AddValue("isConstructorCall", this.isConstructorCall);
// Serialize inArgs:
object[] inArgsSubstituted;
object[] inArgsSubstitutions;
SubstituteMockers(this.inArgs, out inArgsSubstituted, out inArgsSubstitutions);
info.AddValue("inArgs", inArgsSubstituted);
info.AddValue("inArgsMockers", inArgsSubstitutions);
// Serialize outArgs:
object[] outArgsSubstituted;
object[] outArgsSubstitutions;
if (outArgs == null) {
outArgsSubstituted = null;
outArgsSubstitutions = null;
} else {
SubstituteMockers(this.outArgs, out outArgsSubstituted, out outArgsSubstitutions);
}
info.AddValue("outArgs", outArgsSubstituted);
info.AddValue("outArgsMockers", outArgsSubstitutions);
// Serialize returnValue:
if (this.returnValue == null) {
info.AddValue("returnValueMocked", false);
info.AddValue("returnValueType", TypeRef(this.GetReturnType()));
info.AddValue("returnValue", null);
} else if (RemotingServices.IsTransparentProxy(this.returnValue)) {
MockingProxy rp = RemotingServices.GetRealProxy(this.returnValue) as MockingProxy;
info.AddValue("returnValueMocked", true);
info.AddValue("returnValueType", TypeRef(rp.ServerType));
info.AddValue("returnValueName", rp.InstanceName);
} else {
info.AddValue("returnValueMocked", false);
info.AddValue("returnValueType", TypeRef(this.GetReturnType()));
info.AddValue("returnValue", this.returnValue);
}
// Serialize exception:
if (this.exception == null) {
info.AddValue("exception", null);
info.AddValue("exceptionType", null);
} else if (this.exception.GetType().IsSerializable) {
info.AddValue("exception", this.exception);
info.AddValue("exceptionType", null);
} else {
info.AddValue("exception", null);
info.AddValue("exceptionType", TypeRef(this.exception.GetType()));
}
// Serialize icompleted & duration:
info.AddValue("isCompleted", this.isCompleted);
info.AddValue("callDuration", this.callDuration);
}
/// <summary>
/// Returns a string refering to the given type such that passing this string to
/// Type.GetType() should return the current version of the passed type.
/// </summary>
private static string TypeRef(Type t) {
StringBuilder sb = new StringBuilder();
TypeRefInternal(t, sb);
return sb.ToString();
}
/// <summary>
/// Internal implementation of TypeRef, supports recursive calls for generic types.
/// </summary>
private static void TypeRefInternal(Type t, StringBuilder sb)
{
Type t2 = (t.IsArray) ? t.GetElementType() : t;
if (t2.IsGenericType)
{
sb.Append(t2.GetGenericTypeDefinition().FullName);
string sep = "";
sb.Append("[[");
foreach (Type gt in t2.GetGenericArguments())
{
sb.Append(sep);
TypeRefInternal(gt, sb);
sep = "],[";
}
sb.Append("]]");
}
else
{
sb.Append(t2.FullName);
}
if (t.IsArray)
{
sb.Append("[]");
}
sb.Append(", ");
sb.Append(t2.Assembly.GetName().Name);
}
/// <summary>
/// Receiving an array of values, it returns an array of the same values where
/// mockers are replaced by null (substitutedValues), and an array of substitutions
/// indicating the positions, typenames and instancenames of the mockers (substitutions).
/// </summary>
/// <param name="values">The original values.</param>
/// <param name="substitutedValues">The substituted values (original values or null for mockers).</param>
/// <param name="substitutions">Position, type and name information of mockers.</param>
private static void SubstituteMockers(object[] values, out object[] substitutedValues, out object[] substitutions) {
ArrayList substitutionsTemp = new ArrayList();
substitutedValues = new object[values.Length];
for(int i=0; i<values.Length; i++) {
if (values[i] == null) {
substitutedValues[i] = null;
} else if (RemotingServices.IsTransparentProxy(values[i])) {
substitutedValues[i] = null;
MockingProxy rp = RemotingServices.GetRealProxy(values[i]) as MockingProxy;
substitutionsTemp.Add(new object[]{i, TypeRef(rp.ServerType), rp.InstanceName});
} else if (values[i].GetType().IsSerializable) {
substitutedValues[i] = values[i];
} else {
substitutedValues[i] = null;
}
}
substitutions = substitutionsTemp.ToArray();
}
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using Foundation;
using UIKit;
using Xamarin.Forms.Internals;
namespace Xamarin.Forms.Platform.iOS
{
public class WebViewRenderer : UIWebView, IVisualElementRenderer, IWebViewDelegate, IEffectControlProvider
{
EventTracker _events;
bool _ignoreSourceChanges;
WebNavigationEvent _lastBackForwardEvent;
VisualElementPackager _packager;
#pragma warning disable 0414
VisualElementTracker _tracker;
#pragma warning restore 0414
public WebViewRenderer() : base(RectangleF.Empty)
{
}
public VisualElement Element { get; private set; }
public event EventHandler<VisualElementChangedEventArgs> ElementChanged;
public SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
{
return NativeView.GetSizeRequest(widthConstraint, heightConstraint, 44, 44);
}
public void SetElement(VisualElement element)
{
var oldElement = Element;
Element = element;
Element.PropertyChanged += HandlePropertyChanged;
((WebView)Element).EvalRequested += OnEvalRequested;
((WebView)Element).GoBackRequested += OnGoBackRequested;
((WebView)Element).GoForwardRequested += OnGoForwardRequested;
Delegate = new CustomWebViewDelegate(this);
BackgroundColor = UIColor.Clear;
AutosizesSubviews = true;
_tracker = new VisualElementTracker(this);
_packager = new VisualElementPackager(this);
_packager.Load();
_events = new EventTracker(this);
_events.LoadEvents(this);
Load();
OnElementChanged(new VisualElementChangedEventArgs(oldElement, element));
EffectUtilities.RegisterEffectControlProvider(this, oldElement, element);
if (Element != null && !string.IsNullOrEmpty(Element.AutomationId))
AccessibilityIdentifier = Element.AutomationId;
if (element != null)
element.SendViewInitialized(this);
}
public void SetElementSize(Size size)
{
Layout.LayoutChildIntoBoundingRegion(Element, new Rectangle(Element.X, Element.Y, size.Width, size.Height));
}
public void LoadHtml(string html, string baseUrl)
{
if (html != null)
LoadHtmlString(html, baseUrl == null ? new NSUrl(NSBundle.MainBundle.BundlePath, true) : new NSUrl(baseUrl, true));
}
public void LoadUrl(string url)
{
LoadRequest(new NSUrlRequest(new NSUrl(url)));
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
// ensure that inner scrollview properly resizes when frame of webview updated
ScrollView.Frame = Bounds;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (IsLoading)
StopLoading();
Element.PropertyChanged -= HandlePropertyChanged;
((WebView)Element).EvalRequested -= OnEvalRequested;
((WebView)Element).GoBackRequested -= OnGoBackRequested;
((WebView)Element).GoForwardRequested -= OnGoForwardRequested;
_tracker?.Dispose();
_packager?.Dispose();
}
base.Dispose(disposing);
}
protected virtual void OnElementChanged(VisualElementChangedEventArgs e)
{
var changed = ElementChanged;
if (changed != null)
changed(this, e);
}
void HandlePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == WebView.SourceProperty.PropertyName)
Load();
}
void Load()
{
if (_ignoreSourceChanges)
return;
if (((WebView)Element).Source != null)
((WebView)Element).Source.Load(this);
UpdateCanGoBackForward();
}
void OnEvalRequested(object sender, EvalRequested eventArg)
{
EvaluateJavascript(eventArg.Script);
}
void OnGoBackRequested(object sender, EventArgs eventArgs)
{
if (CanGoBack)
{
_lastBackForwardEvent = WebNavigationEvent.Back;
GoBack();
}
UpdateCanGoBackForward();
}
void OnGoForwardRequested(object sender, EventArgs eventArgs)
{
if (CanGoForward)
{
_lastBackForwardEvent = WebNavigationEvent.Forward;
GoForward();
}
UpdateCanGoBackForward();
}
void UpdateCanGoBackForward()
{
((WebView)Element).CanGoBack = CanGoBack;
((WebView)Element).CanGoForward = CanGoForward;
}
class CustomWebViewDelegate : UIWebViewDelegate
{
readonly WebViewRenderer _renderer;
WebNavigationEvent _lastEvent;
public CustomWebViewDelegate(WebViewRenderer renderer)
{
if (renderer == null)
throw new ArgumentNullException("renderer");
_renderer = renderer;
}
WebView WebView
{
get { return (WebView)_renderer.Element; }
}
public override void LoadFailed(UIWebView webView, NSError error)
{
var url = GetCurrentUrl();
WebView.SendNavigated(new WebNavigatedEventArgs(_lastEvent, new UrlWebViewSource { Url = url }, url, WebNavigationResult.Failure));
_renderer.UpdateCanGoBackForward();
}
public override void LoadingFinished(UIWebView webView)
{
if (webView.IsLoading)
return;
_renderer._ignoreSourceChanges = true;
var url = GetCurrentUrl();
((IElementController)WebView).SetValueFromRenderer(WebView.SourceProperty, new UrlWebViewSource { Url = url });
_renderer._ignoreSourceChanges = false;
var args = new WebNavigatedEventArgs(_lastEvent, WebView.Source, url, WebNavigationResult.Success);
WebView.SendNavigated(args);
_renderer.UpdateCanGoBackForward();
}
public override void LoadStarted(UIWebView webView)
{
}
public override bool ShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
{
var navEvent = WebNavigationEvent.NewPage;
switch (navigationType)
{
case UIWebViewNavigationType.LinkClicked:
navEvent = WebNavigationEvent.NewPage;
break;
case UIWebViewNavigationType.FormSubmitted:
navEvent = WebNavigationEvent.NewPage;
break;
case UIWebViewNavigationType.BackForward:
navEvent = _renderer._lastBackForwardEvent;
break;
case UIWebViewNavigationType.Reload:
navEvent = WebNavigationEvent.Refresh;
break;
case UIWebViewNavigationType.FormResubmitted:
navEvent = WebNavigationEvent.NewPage;
break;
case UIWebViewNavigationType.Other:
navEvent = WebNavigationEvent.NewPage;
break;
}
_lastEvent = navEvent;
var lastUrl = request.Url.ToString();
var args = new WebNavigatingEventArgs(navEvent, new UrlWebViewSource { Url = lastUrl }, lastUrl);
WebView.SendNavigating(args);
_renderer.UpdateCanGoBackForward();
return !args.Cancel;
}
string GetCurrentUrl()
{
return _renderer?.Request?.Url?.AbsoluteUrl?.ToString();
}
}
#region IPlatformRenderer implementation
public UIView NativeView
{
get { return this; }
}
public UIViewController ViewController
{
get { return null; }
}
#endregion
void IEffectControlProvider.RegisterEffect(Effect effect)
{
VisualElementRenderer<VisualElement>.RegisterEffect(effect, this, NativeView);
}
}
}
| |
using GitHub.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
[Serializable]
class SettingsView : Subview
{
private const string GitRepositoryTitle = "Repository Configuration";
private const string GitRepositoryRemoteLabel = "Remote";
private const string GitRepositorySave = "Save Repository";
private const string GeneralSettingsTitle = "General";
private const string DebugSettingsTitle = "Debug";
private const string PrivacyTitle = "Privacy";
private const string WebTimeoutLabel = "Timeout of web requests";
private const string GitTimeoutLabel = "Timeout of git commands";
private const string EnableTraceLoggingLabel = "Enable Trace Logging";
private const string MetricsOptInLabel = "Help us improve by sending anonymous usage data";
private const string DefaultRepositoryRemoteName = "origin";
[NonSerialized] private bool currentRemoteHasUpdate;
[NonSerialized] private bool isBusy;
[NonSerialized] private bool metricsHasChanged;
[SerializeField] private GitPathView gitPathView = new GitPathView();
[SerializeField] private bool hasRemote;
[SerializeField] private CacheUpdateEvent lastCurrentRemoteChangedEvent;
[SerializeField] private bool metricsEnabled;
[SerializeField] private string newRepositoryRemoteUrl;
[SerializeField] private string repositoryRemoteName;
[SerializeField] private string repositoryRemoteUrl;
[SerializeField] private Vector2 scroll;
[SerializeField] private UserSettingsView userSettingsView = new UserSettingsView();
[SerializeField] private int webTimeout;
[SerializeField] private int gitTimeout;
public override void InitializeView(IView parent)
{
base.InitializeView(parent);
gitPathView.InitializeView(this);
userSettingsView.InitializeView(this);
}
public override void OnEnable()
{
base.OnEnable();
gitPathView.OnEnable();
userSettingsView.OnEnable();
AttachHandlers(Repository);
if (Repository != null)
{
ValidateCachedData(Repository);
}
metricsHasChanged = true;
}
public override void OnDisable()
{
base.OnDisable();
gitPathView.OnDisable();
userSettingsView.OnDisable();
DetachHandlers(Repository);
}
public override void OnDataUpdate()
{
base.OnDataUpdate();
userSettingsView.OnDataUpdate();
gitPathView.OnDataUpdate();
MaybeUpdateData();
}
public override void Refresh()
{
base.Refresh();
gitPathView.Refresh();
userSettingsView.Refresh();
Refresh(CacheType.RepositoryInfo);
}
public override void OnGUI()
{
scroll = GUILayout.BeginScrollView(scroll);
{
userSettingsView.OnGUI();
GUILayout.Space(EditorGUIUtility.standardVerticalSpacing);
if (Repository != null)
{
OnRepositorySettingsGUI();
GUILayout.Space(EditorGUIUtility.standardVerticalSpacing);
}
gitPathView.OnGUI();
OnPrivacyGui();
OnGeneralSettingsGui();
OnLoggingSettingsGui();
}
GUILayout.EndScrollView();
DoProgressGUI();
}
private void AttachHandlers(IRepository repository)
{
if (repository == null)
{
return;
}
repository.CurrentRemoteChanged += RepositoryOnCurrentRemoteChanged;
}
private void RepositoryOnCurrentRemoteChanged(CacheUpdateEvent cacheUpdateEvent)
{
if (!lastCurrentRemoteChangedEvent.Equals(cacheUpdateEvent))
{
lastCurrentRemoteChangedEvent = cacheUpdateEvent;
currentRemoteHasUpdate = true;
Redraw();
}
}
private void DetachHandlers(IRepository repository)
{
if (repository == null)
{
return;
}
repository.CurrentRemoteChanged -= RepositoryOnCurrentRemoteChanged;
}
private void ValidateCachedData(IRepository repository)
{
repository.CheckAndRaiseEventsIfCacheNewer(CacheType.RepositoryInfo, lastCurrentRemoteChangedEvent);
}
private void MaybeUpdateData()
{
if (metricsHasChanged)
{
metricsEnabled = Manager.UsageTracker != null ? Manager.UsageTracker.Enabled : false;
metricsHasChanged = false;
}
if (Repository == null)
return;
if (currentRemoteHasUpdate)
{
currentRemoteHasUpdate = false;
var currentRemote = Repository.CurrentRemote;
hasRemote = currentRemote.HasValue && !String.IsNullOrEmpty(currentRemote.Value.Url);
if (!hasRemote)
{
repositoryRemoteName = DefaultRepositoryRemoteName;
newRepositoryRemoteUrl = repositoryRemoteUrl = string.Empty;
}
else
{
repositoryRemoteName = currentRemote.Value.Name;
newRepositoryRemoteUrl = repositoryRemoteUrl = currentRemote.Value.Url;
}
}
}
private void OnRepositorySettingsGUI()
{
GUILayout.Label(GitRepositoryTitle, EditorStyles.boldLabel);
EditorGUI.BeginDisabledGroup(IsBusy);
{
newRepositoryRemoteUrl = EditorGUILayout.TextField(GitRepositoryRemoteLabel + ": " + repositoryRemoteName, newRepositoryRemoteUrl);
var needsSaving = newRepositoryRemoteUrl != repositoryRemoteUrl && !String.IsNullOrEmpty(newRepositoryRemoteUrl);
EditorGUI.BeginDisabledGroup(!needsSaving);
{
if (GUILayout.Button(GitRepositorySave, GUILayout.ExpandWidth(false)))
{
try
{
isBusy = true;
Repository.SetupRemote(repositoryRemoteName, newRepositoryRemoteUrl)
.FinallyInUI((_, __) =>
{
isBusy = false;
Redraw();
})
.Start();
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
}
EditorGUI.EndDisabledGroup();
}
EditorGUI.EndDisabledGroup();
}
private void OnPrivacyGui()
{
GUILayout.Label(PrivacyTitle, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
{
metricsEnabled = GUILayout.Toggle(metricsEnabled, MetricsOptInLabel);
}
if (EditorGUI.EndChangeCheck())
{
if (Manager.UsageTracker != null)
Manager.UsageTracker.Enabled = metricsEnabled;
}
EditorGUI.EndDisabledGroup();
}
private void OnLoggingSettingsGui()
{
GUILayout.Label(DebugSettingsTitle, EditorStyles.boldLabel);
var traceLogging = LogHelper.TracingEnabled;
EditorGUI.BeginChangeCheck();
{
traceLogging = GUILayout.Toggle(traceLogging, EnableTraceLoggingLabel);
}
if (EditorGUI.EndChangeCheck())
{
LogHelper.TracingEnabled = traceLogging;
Manager.UserSettings.Set(Constants.TraceLoggingKey, traceLogging);
}
}
private void OnGeneralSettingsGui()
{
GUILayout.Label(GeneralSettingsTitle, EditorStyles.boldLabel);
webTimeout = ApplicationConfiguration.WebTimeout;
EditorGUI.BeginChangeCheck();
{
webTimeout = EditorGUILayout.IntField(WebTimeoutLabel, webTimeout);
}
if (EditorGUI.EndChangeCheck())
{
ApplicationConfiguration.WebTimeout = webTimeout;
Manager.UserSettings.Set(Constants.WebTimeoutKey, webTimeout);
}
gitTimeout = ApplicationConfiguration.GitTimeout;
EditorGUI.BeginChangeCheck();
{
gitTimeout = EditorGUILayout.IntField(GitTimeoutLabel, gitTimeout);
}
if (EditorGUI.EndChangeCheck())
{
ApplicationConfiguration.GitTimeout = gitTimeout;
Manager.UserSettings.Set(Constants.GitTimeoutKey, gitTimeout);
}
}
public override bool IsBusy
{
get { return isBusy || userSettingsView.IsBusy || gitPathView.IsBusy; }
}
}
}
| |
// 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 Internal.Text;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.DependencyAnalysis
{
// These classes defined below are Windows-specific. The VC CRT library has equivalent definition
// for ThreadStaticsIndexNode and ThreadStaticsDirectoryNode, but it does not support cross-module
// TLS references where the name of _tls_index_ will need to be module-sensitive. Therefore, we
// define them here.
// The TLS slot index allocated for this module by the OS loader. We keep a pointer to this
// value in the module header.
public class ThreadStaticsIndexNode : ObjectNode, ISymbolNode
{
string _prefix;
public ThreadStaticsIndexNode(string prefix)
{
_prefix = prefix;
}
public string MangledName
{
get
{
return GetMangledName(_prefix);
}
}
public static string GetMangledName(string prefix)
{
return "_tls_index_" + prefix;
}
public int Offset => 0;
protected override string GetName() => this.GetMangledName();
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append(GetMangledName(_prefix));
}
public override ObjectNodeSection Section
{
get
{
return ObjectNodeSection.DataSection;
}
}
public override bool IsShareable => false;
public override bool StaticDependenciesAreComputed => true;
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
{
// TODO: define _tls_index as "comdat select any" when multiple object files present.
ObjectDataBuilder objData = new ObjectDataBuilder(factory);
objData.RequireInitialPointerAlignment();
objData.AddSymbol(this);
// Emit an aliased symbol named _tls_index for native P/Invoke code that uses TLS. This is required
// because we do not link against libcmt.lib.
ObjectAndOffsetSymbolNode aliasedSymbol = new ObjectAndOffsetSymbolNode(this, objData.CountBytes, "_tls_index", false);
objData.AddSymbol(aliasedSymbol);
// This is the TLS index field which is a 4-byte integer.
objData.EmitInt(0);
return objData.ToObjectData();
}
}
// The data structure used by the OS loader to load TLS chunks.
public class ThreadStaticsDirectoryNode : ObjectNode, ISymbolNode
{
string _prefix;
public ThreadStaticsDirectoryNode(string prefix)
{
_prefix = prefix;
}
public string MangledName
{
get
{
return GetMangledName(_prefix);
}
}
public static string GetMangledName(string prefix)
{
return prefix + "_tls_used";
}
public int Offset => 0;
protected override string GetName() => GetMangledName("");
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append(GetMangledName(_prefix));
}
public override ObjectNodeSection Section
{
get
{
return ObjectNodeSection.ReadOnlyDataSection;
}
}
public override bool IsShareable => false;
public override bool StaticDependenciesAreComputed => true;
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
{
// TODO: define _tls_used as comdat select any when multiple object files present.
UtcNodeFactory hostedFactory = factory as UtcNodeFactory;
ObjectDataBuilder objData = new ObjectDataBuilder(factory);
objData.RequireInitialPointerAlignment();
objData.AddSymbol(this);
// Allocate and initialize the IMAGE_TLS_DIRECTORY PE data structure used by the OS loader to determine
// TLS allocations. The structure is defined by the OS as following:
/*
struct _IMAGE_TLS_DIRECTORY32
{
DWORD StartAddressOfRawData;
DWORD EndAddressOfRawData;
DWORD AddressOfIndex;
DWORD AddressOfCallBacks;
DWORD SizeOfZeroFill;
DWORD Characteristics;
}
struct _IMAGE_TLS_DIRECTORY64
{
ULONGLONG StartAddressOfRawData;
ULONGLONG EndAddressOfRawData;
ULONGLONG AddressOfIndex;
ULONGLONG AddressOfCallBacks;
DWORD SizeOfZeroFill;
DWORD Characteristics;
}
*/
// In order to utilize linker support, the struct variable needs to be named _tls_used
objData.EmitPointerReloc(hostedFactory.TlsStart); // start of tls data
objData.EmitPointerReloc(hostedFactory.TlsEnd); // end of tls data
objData.EmitPointerReloc(hostedFactory.ThreadStaticsIndex); // address of tls_index
objData.EmitZeroPointer(); // pointer to call back array
objData.EmitInt(0); // size of tls zero fill
objData.EmitInt(0); // characteristics
return objData.ToObjectData();
}
}
// The offset into the TLS block at which managed data begins.
public class ThreadStaticsStartNode : ObjectNode, ISymbolNode
{
public ThreadStaticsStartNode()
{
}
public string MangledName
{
get
{
return GetMangledName();
}
}
public static string GetMangledName()
{
return "_tls_offset";
}
public int Offset => 0;
protected override string GetName() => GetMangledName();
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append(GetMangledName());
}
public override ObjectNodeSection Section
{
get
{
return ObjectNodeSection.ReadOnlyDataSection;
}
}
public override bool IsShareable => false;
public override bool ShouldSkipEmittingObjectNode(NodeFactory factory)
{
return factory.ThreadStaticsRegion.ShouldSkipEmittingObjectNode(factory);
}
public override bool StaticDependenciesAreComputed => true;
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
{
ObjectDataBuilder objData = new ObjectDataBuilder(factory);
objData.RequireInitialPointerAlignment();
objData.AddSymbol(this);
objData.EmitReloc(factory.ThreadStaticsRegion.StartSymbol, RelocType.IMAGE_REL_SECREL);
return objData.ToObjectData();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using System;
using System.Reflection;
namespace OpenSim.Region.ClientStack.LindenUDP
{
/// <summary>
/// Stores information about a current texture download and a reference to the texture asset
/// </summary>
public class J2KImage
{
public UUID AgentID;
public IAssetService AssetService;
public sbyte DiscardLevel;
public IInventoryAccessModule InventoryAccessModule;
public IJ2KDecoder J2KDecoder;
public uint LastSequence;
public float Priority;
public C5.IPriorityQueueHandle<J2KImage> PriorityQueueHandle;
public uint StartPacket;
public UUID TextureID;
/// <summary>
/// If we've requested an asset but not received it in this ticks timeframe, then allow a duplicate
/// request from the client to trigger a fresh asset request.
/// </summary>
/// <remarks>
/// There are 10,000 ticks in a millisecond
/// </remarks>
private const int ASSET_REQUEST_TIMEOUT = 100000000;
private const int FIRST_PACKET_SIZE = 600;
private const int IMAGE_PACKET_SIZE = 1000;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private byte[] m_asset;
private bool m_assetRequested;
private uint m_currentPacket;
private bool m_decodeRequested;
private LLImageManager m_imageManager;
private OpenJPEG.J2KLayerInfo[] m_layers;
private bool m_sentInfo;
private uint m_stopPacket;
public J2KImage(LLImageManager imageManager)
{
m_imageManager = imageManager;
}
/// <summary>
/// Time in milliseconds at which the asset was requested.
/// </summary>
public long AssetRequestTime { get; private set; }
/// <summary>
/// Has this request received the required asset data?
/// </summary>
public bool HasAsset { get; private set; }
/// <summary>
/// Has this request decoded the asset data?
/// </summary>
public bool IsDecoded { get; private set; }
/// <summary>
/// This is where we decide what we need to update
/// and assign the real discardLevel and packetNumber
/// assuming of course that the connected client might be bonkers
/// </summary>
public void RunUpdate()
{
if (!HasAsset)
{
if (!m_assetRequested || DateTime.UtcNow.Ticks > AssetRequestTime + ASSET_REQUEST_TIMEOUT)
{
// m_log.DebugFormat(
// "[J2KIMAGE]: Requesting asset {0} from request in packet {1}, already requested? {2}, due to timeout? {3}",
// TextureID, LastSequence, m_assetRequested, DateTime.UtcNow.Ticks > AssetRequestTime + ASSET_REQUEST_TIMEOUT);
m_assetRequested = true;
AssetRequestTime = DateTime.UtcNow.Ticks;
AssetService.Get(TextureID.ToString(), this, AssetReceived);
}
}
else
{
if (!IsDecoded)
{
//We need to decode the requested image first
if (!m_decodeRequested)
{
//Request decode
m_decodeRequested = true;
// m_log.DebugFormat("[J2KIMAGE]: Requesting decode of asset {0}", TextureID);
// Do we have a jpeg decoder?
if (J2KDecoder != null)
{
if (m_asset == null)
{
J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]);
}
else
{
// Send it off to the jpeg decoder
J2KDecoder.BeginDecode(TextureID, m_asset, J2KDecodedCallback);
}
}
else
{
J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]);
}
}
}
else
{
// Check for missing image asset data
if (m_asset == null)
{
m_log.Warn("[J2KIMAGE]: RunUpdate() called with missing asset data (no missing image texture?). Canceling texture transfer");
m_currentPacket = m_stopPacket;
return;
}
if (DiscardLevel >= 0 || m_stopPacket == 0)
{
// This shouldn't happen, but if it does, we really can't proceed
if (m_layers == null)
{
m_log.Warn("[J2KIMAGE]: RunUpdate() called with missing Layers. Canceling texture transfer");
m_currentPacket = m_stopPacket;
return;
}
int maxDiscardLevel = Math.Max(0, m_layers.Length - 1);
// Treat initial texture downloads with a DiscardLevel of -1 a request for the highest DiscardLevel
if (DiscardLevel < 0 && m_stopPacket == 0)
DiscardLevel = (sbyte)maxDiscardLevel;
// Clamp at the highest discard level
DiscardLevel = (sbyte)Math.Min(DiscardLevel, maxDiscardLevel);
//Calculate the m_stopPacket
if (m_layers.Length > 0)
{
m_stopPacket = (uint)GetPacketForBytePosition(m_layers[(m_layers.Length - 1) - DiscardLevel].End);
//I don't know why, but the viewer seems to expect the final packet if the file
//is just one packet bigger.
if (TexturePacketCount() == m_stopPacket + 1)
{
m_stopPacket = TexturePacketCount();
}
}
else
{
m_stopPacket = TexturePacketCount();
}
m_currentPacket = StartPacket;
}
}
}
}
/// <summary>
/// Sends packets for this texture to a client until packetsToSend is
/// hit or the transfer completes
/// </summary>
/// <param name="client">Reference to the client that the packets are destined for</param>
/// <param name="packetsToSend">Maximum number of packets to send during this call</param>
/// <param name="packetsSent">Number of packets sent during this call</param>
/// <returns>True if the transfer completes at the current discard level, otherwise false</returns>
public bool SendPackets(IClientAPI client, int packetsToSend, out int packetsSent)
{
packetsSent = 0;
if (m_currentPacket <= m_stopPacket)
{
bool sendMore = true;
if (!m_sentInfo || (m_currentPacket == 0))
{
sendMore = !SendFirstPacket(client);
m_sentInfo = true;
++m_currentPacket;
++packetsSent;
}
if (m_currentPacket < 2)
{
m_currentPacket = 2;
}
while (sendMore && packetsSent < packetsToSend && m_currentPacket <= m_stopPacket)
{
sendMore = SendPacket(client);
++m_currentPacket;
++packetsSent;
}
}
return (m_currentPacket > m_stopPacket);
}
private void AssetDataCallback(UUID AssetID, AssetBase asset)
{
HasAsset = true;
if (asset == null || asset.Data == null)
{
if (m_imageManager.MissingImage != null)
{
m_asset = m_imageManager.MissingImage.Data;
}
else
{
m_asset = null;
IsDecoded = true;
}
}
else
{
m_asset = asset.Data;
}
RunUpdate();
}
private void AssetReceived(string id, Object sender, AssetBase asset)
{
// m_log.DebugFormat(
// "[J2KIMAGE]: Received asset {0} ({1} bytes)", id, asset != null ? asset.Data.Length.ToString() : "n/a");
UUID assetID = UUID.Zero;
if (asset != null)
{
assetID = asset.FullID;
}
else if ((InventoryAccessModule != null) && (sender != InventoryAccessModule))
{
// Unfortunately we need this here, there's no other way.
// This is due to the fact that textures opened directly from the agent's inventory
// don't have any distinguishing feature. As such, in order to serve those when the
// foreign user is visiting, we need to try again after the first fail to the local
// asset service.
string assetServerURL = string.Empty;
if (InventoryAccessModule.IsForeignUser(AgentID, out assetServerURL) && !string.IsNullOrEmpty(assetServerURL))
{
if (!assetServerURL.EndsWith("/") && !assetServerURL.EndsWith("="))
assetServerURL = assetServerURL + "/";
// m_log.DebugFormat("[J2KIMAGE]: texture {0} not found in local asset storage. Trying user's storage.", assetServerURL + id);
AssetService.Get(assetServerURL + id, InventoryAccessModule, AssetReceived);
return;
}
}
AssetDataCallback(assetID, asset);
}
private int CurrentBytePosition()
{
if (m_currentPacket == 0)
return 0;
if (m_currentPacket == 1)
return FIRST_PACKET_SIZE;
int result = FIRST_PACKET_SIZE + ((int)m_currentPacket - 2) * IMAGE_PACKET_SIZE;
if (result < 0)
result = FIRST_PACKET_SIZE;
return result;
}
private int GetPacketForBytePosition(int bytePosition)
{
return ((bytePosition - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1;
}
private void J2KDecodedCallback(UUID AssetId, OpenJPEG.J2KLayerInfo[] layers)
{
m_layers = layers;
IsDecoded = true;
RunUpdate();
}
private int LastPacketSize()
{
if (m_currentPacket == 1)
return m_asset.Length;
int lastsize = (m_asset.Length - FIRST_PACKET_SIZE) % IMAGE_PACKET_SIZE;
//If the last packet size is zero, it's really cImagePacketSize, it sits on the boundary
if (lastsize == 0)
{
lastsize = IMAGE_PACKET_SIZE;
}
return lastsize;
}
private bool SendFirstPacket(IClientAPI client)
{
if (client == null)
return false;
if (m_asset == null)
{
m_log.Warn("[J2KIMAGE]: Sending ImageNotInDatabase for texture " + TextureID);
client.SendImageNotFound(TextureID);
return true;
}
else if (m_asset.Length <= FIRST_PACKET_SIZE)
{
// We have less then one packet's worth of data
client.SendImageFirstPart(1, TextureID, (uint)m_asset.Length, m_asset, 2);
m_stopPacket = 0;
return true;
}
else
{
// This is going to be a multi-packet texture download
byte[] firstImageData = new byte[FIRST_PACKET_SIZE];
try { Buffer.BlockCopy(m_asset, 0, firstImageData, 0, FIRST_PACKET_SIZE); }
catch (Exception)
{
m_log.ErrorFormat("[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}", TextureID, m_asset.Length);
return true;
}
client.SendImageFirstPart(TexturePacketCount(), TextureID, (uint)m_asset.Length, firstImageData, (byte)ImageCodec.J2C);
}
return false;
}
private bool SendPacket(IClientAPI client)
{
if (client == null)
return false;
bool complete = false;
int imagePacketSize = ((int)m_currentPacket == (TexturePacketCount())) ? LastPacketSize() : IMAGE_PACKET_SIZE;
try
{
if ((CurrentBytePosition() + IMAGE_PACKET_SIZE) > m_asset.Length)
{
imagePacketSize = LastPacketSize();
complete = true;
if ((CurrentBytePosition() + imagePacketSize) > m_asset.Length)
{
imagePacketSize = m_asset.Length - CurrentBytePosition();
complete = true;
}
}
// It's concievable that the client might request packet one
// from a one packet image, which is really packet 0,
// which would leave us with a negative imagePacketSize..
if (imagePacketSize > 0)
{
byte[] imageData = new byte[imagePacketSize];
int currentPosition = CurrentBytePosition();
try { Buffer.BlockCopy(m_asset, currentPosition, imageData, 0, imagePacketSize); }
catch (Exception e)
{
m_log.ErrorFormat("[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}, currentposition={2}, imagepacketsize={3}, exception={4}",
TextureID, m_asset.Length, currentPosition, imagePacketSize, e.Message);
return false;
}
//Send the packet
client.SendImageNextPart((ushort)(m_currentPacket - 1), TextureID, imageData);
}
return !complete;
}
catch (Exception)
{
return false;
}
}
private ushort TexturePacketCount()
{
if (!IsDecoded)
return 0;
if (m_asset == null)
return 0;
if (m_asset.Length <= FIRST_PACKET_SIZE)
return 1;
return (ushort)(((m_asset.Length - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1);
}
}
}
| |
#region Using directives
using System;
using System.Configuration;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml.Xsl;
using System.Xml.Schema;
using System.Xml;
using System.Xml.Serialization;
using log4net;
using Commanigy.Iquomi.Data;
using Commanigy.Iquomi.Api;
using Commanigy.Utils;
using IqContactsRef;
#endregion
namespace Commanigy.Iquomi.Web {
/// <summary>
///
/// </summary>
public partial class ServicesIqContactsPage : Commanigy.Iquomi.Web.WebPage {
protected static readonly ILog log = LogManager.GetLogger("WebSite");
private IqContactsType contacts;
protected void Page_Load(object sender, System.EventArgs e) {
contacts = (IqContactsType)ViewState["iqContacts"];
}
protected void BtnLoad_Click(object sender, EventArgs e) {
ServiceLocator serviceLocator = new ServiceLocator(
"http://services.iquomi.com/",
UiAccount.Get().Iqid,
UiAccount.Get().Password
);
IqContacts myService = (IqContacts)serviceLocator.GetService(
typeof(IqContacts),
UiAccount.Get().Iqid
);
QueryRequestType q = new QueryRequestType();
q.XpQuery = new XpQueryType[] { new XpQueryType() };
q.XpQuery[0].Select = TbxData.Text;
q.XpQuery[0].MinOccurs = 1;
q.XpQuery[0].MinOccursSpecified = true;
q.XpQuery[0].MaxOccursSpecified = false;
q.XpQuery[0].Options = new QueryOptionsType();
q.XpQuery[0].Options.Sort = new SortType[] { new SortType()/*, new SortType()*/ };
q.XpQuery[0].Options.Sort[0].Key = "concat(m:Name/mp:GivenName/text(), ' ', m:Name/mp:SurName/text())";
q.XpQuery[0].Options.Sort[0].Direction = SortTypeDirection.Ascending;
// q.XpQuery[0].Options.Sort[1].Key = "m:Name/mp:SurName/text()";
// q.XpQuery[0].Options.Sort[1].Direction = SortTypeDirection.Ascending;
try {
QueryResponseType response = myService.Query(q);
if (response.XpQueryResponse[0].Status == ResponseStatus.Success) {
Notification.Success("Contacts read");
//contacts = (IqContactsType)ServiceUtils.GetObject(
// typeof(IqContactsType),
// response.XpQueryResponse[0].Any[0]
// );
//contacts = (IqContactsType)GetObject(
// typeof(IqContactsType),
// response.XpQueryResponse[0].Any[0]
// );
if (response.XpQueryResponse[0].Items != null) {
LblResponse.Text = string.Format("Found {0} contacts:<br />", response.XpQueryResponse[0].Items.Length);
foreach (ContactType contact in response.XpQueryResponse[0].Items) {
LblResponse.Text += contact.Name[0].GivenName.Value + " | " +
contact.Name[0].SurName.Value + "<br />";
}
}
/*
if (response.XpQueryResponse[0].Any != null) {
LblResponse.Text = string.Format("Found {0} contacts:<br />", response.XpQueryResponse[0].Any.Length);
foreach (XmlElement element in response.XpQueryResponse[0].Any) {
ContactType contact = (ContactType)ServiceUtils.GetObject(
typeof(ContactType),
element
);
LblResponse.Text += contact.Name[0].GivenName.Value + " | " +
contact.Name[0].SurName.Value + "<br />";
}
}
*/
//if (contacts.Contact != null) {
// LblResponse.Text = string.Format("Found {0} contacts:<br />", contacts.Contact.Length);
// foreach (ContactType contact in contacts.Contact) {
// LblResponse.Text += contact.Name[0].GivenName.Value + " | " +
// contact.Name[0].SurName.Value + "<br />";
// }
//}
ViewState["iqContacts"] = contacts;
} else {
Notification.Failed("Unable to read contacts.");
}
}
catch (System.Net.WebException x) {
Notification.Failed(x.Message);
}
Notification.Display();
}
/*
private string GetNamespace(Type type) {
object[] cas = type.GetCustomAttributes(typeof(XmlTypeAttribute), false);
return (cas.Length > 0) ? ((XmlTypeAttribute)cas[0]).Namespace : "";
}
protected object GetObject(System.Type type, XmlElement e) {
XmlRootAttribute root = new XmlRootAttribute(e.LocalName);
root.Namespace = GetNamespace(type);
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attributes = new XmlAttributes();
//XmlRootAttribute rattr = new XmlRootAttribute(e.LocalName);
//rattr.Namespace = GetNamespace(type);
//attributes.XmlRoot = rattr;
//overrides.Add(type, attributes);
XmlAttributeAttribute attributeAttribute = new XmlAttributeAttribute();
attributes.XmlAttribute = attributeAttribute;
//overrides.Add(type, "ChangeNumber", attributes);
//overrides.Add(type, "InstanceId", attributes);
// XmlElementAttribute eattr = new XmlElementAttribute();
// attributes.XmlElements.Add(eattr);
// overrides.Add(type, "InstanceId", attributes);
// XmlSerializer serializer = new XmlSerializer(type, overrides);
XmlSerializer serializer = new XmlSerializer(type, root);
// XmlSerializer serializer = new XmlSerializer(type, overrides, new Type[0], root, null);
serializer.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute);
serializer.UnknownElement += new XmlElementEventHandler(serializer_UnknownElement);
XmlNodeReader nr = new XmlNodeReader(e);
return serializer.Deserialize(nr);
}
void serializer_UnknownElement(object sender, XmlElementEventArgs e) {
Notification.Title = _("Validation failed");
Notification.Description = "";
Notification.AddMessage("Element: " + e.Element.Name + ": " + e.Element.Value);
}
void serializer_UnknownAttribute(object sender, XmlAttributeEventArgs e) {
Notification.Title = _("Validation failed");
Notification.Description = "";
Notification.AddMessage("Attribute: " + e.Attr.Name + " = " + e.Attr.Value);
}
protected LocalizableString MyLocalizableString(string v) {
LocalizableString s = new LocalizableString();
s.lang = "en-US";
s.Value = v;
return s;
}
*/
protected void BtnSave_Click(object sender, EventArgs e) {
/*
ServiceLocator serviceLocator = new ServiceLocator(
"http://services.iquomi.com/",
UiAccount.Get().Iqid,
UiAccount.Get().Password
);
IqProfile myService = (IqProfile)serviceLocator.GetService(
typeof(IqProfile),
UiAccount.Get().Iqid
);
if (profile == null) {
Notification.Failed("Cannot create new profile - load first");
return;
}
// update internal structure before updating remotely
NameType name = null;
if (profile.Name == null) {
profile.Name = new NameType[1];
name = new NameType();
name.Id = "";
name.ChangeNumber = "";
name.Creator = Api.CoreUtility.JoinIqid(UiAccount.Get().Iqid);
} else {
name = profile.Name[0];
}
name.GivenName = MyLocalizableString(TbxGivenName.Text);
name.MiddleName = MyLocalizableString(TbxMiddleName.Text);
name.SurName = MyLocalizableString(TbxSurName.Text);
profile.Name[0] = name;
EmailAddressBlueType email = null;
if (profile.EmailAddress == null) {
profile.EmailAddress = new EmailAddressBlueType[1];
email = new EmailAddressBlueType();
email.Id = "";
email.ChangeNumber = "";
email.Creator = Api.CoreUtility.JoinIqid(UiAccount.Get().Iqid);
} else {
email = profile.EmailAddress[0];
}
email.Name = MyLocalizableString("Personal E-mail");
email.Email = TbxEmail.Text;
profile.EmailAddress[0] = email;
ReplaceRequestType req = new ReplaceRequestType();
req.Select = "/m:IqProfile";
req.MinOccurs = 1;
req.MaxOccurs = 1;
req.Any = new XmlElement[] { ServiceUtils.SetObject(
profile,
"IqProfile"
) };
try {
ReplaceResponseType response = myService.Replace(req);
if (response.Status == ResponseStatus.Success) {
Notification.Success("Profile updated.");
}
else {
Notification.Failed("Failed to update profile.");
}
}
catch (System.Net.WebException x) {
Notification.Failed(x.Message);
}
*/
}
protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) {
log.Debug("ObjectDataSource1_Selecting");
return;
ServiceLocator serviceLocator = new ServiceLocator(
"http://services.iquomi.com/",
UiAccount.Get().Iqid,
UiAccount.Get().Password
);
IqContacts myService = (IqContacts)serviceLocator.GetService(
typeof(IqContacts),
UiAccount.Get().Iqid
);
QueryRequestType q = new QueryRequestType();
q.XpQuery = new XpQueryType[1];
q.XpQuery[0] = new XpQueryType();
q.XpQuery[0].Select = TbxData.Text;
q.XpQuery[0].MinOccurs = 1;
q.XpQuery[0].MaxOccursSpecified = false;
QueryResponseType response = myService.Query(q);
if (response.XpQueryResponse[0].Status == ResponseStatus.Success) {
if (response.XpQueryResponse[0].Items != null) {
foreach (ContactType contact in response.XpQueryResponse[0].Items) {
LblResponse.Text += contact.Name[0].GivenName.Value + " | " +
contact.Name[0].SurName.Value + "<br />";
}
}
}
}
protected void ObjectDataSource1_DataBinding(object sender, EventArgs e) {
log.Debug("ObjectDataSource1_DataBinding");
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {
log.Debug("Sorting() SortDirection: " + e.SortDirection + ", SortExpression: " + e.SortExpression);
}
}
}
| |
#region File Information
//-----------------------------------------------------------------------------
// Controls.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;
using DynamicMenu.Transitions;
#endregion
namespace DynamicMenu.Controls
{
/// <summary>
/// The base class for all controls
/// </summary>
public abstract class Control : IControl
{
#region Fields
private List<Transition> activeTransitions = new List<Transition>();
#endregion
#region Properties
/// <summary>
/// The left position of this control relative from its parent
/// </summary>
public int Left { get; set; }
/// <summary>
/// The top position of this control relative from its parent
/// </summary>
public int Top { get; set; }
/// <summary>
/// The width of this control
/// </summary>
public int Width { get; set; }
/// <summary>
/// The height of this control
/// </summary>
public int Height { get; set; }
/// <summary>
/// The bottom position of this control relative from its parent
/// </summary>
[ContentSerializerIgnore]
public int Bottom
{
get { return Top + Height; }
}
/// <summary>
/// The right position of this control relative from its parent
/// </summary>
[ContentSerializerIgnore]
public int Right
{
get { return Left + Width; }
}
/// <summary>
/// The name of this control
/// </summary>
[ContentSerializer(Optional = true)]
public string Name { get; set; }
/// <summary>
/// The name of the background texture for this control
/// </summary>
[ContentSerializer(Optional = true)]
public string BackTextureName { get; set; }
/// <summary>
/// The Background texture for this control
/// </summary>
[ContentSerializerIgnore]
public Texture2D BackTexture { get; set; }
/// <summary>
/// Whether this control is currently visible and enabled
/// </summary>
[ContentSerializer(Optional = true)]
public bool Visible { get; set; }
/// <summary>
/// The hugh applied to this control
/// </summary>
[ContentSerializer(Optional = true)]
public Color Hue { get; set; }
/// <summary>
/// The parent of this control
/// </summary>
[ContentSerializerIgnore]
public IControl Parent { get; set; }
/// <summary>
/// This can be used to store information related to this control
/// </summary>
[ContentSerializerIgnore]
public object Tag { get; set; }
#endregion
#region Initialization
/// <summary>
/// Public constructor
/// </summary>
public Control()
{
Visible = true;
Hue = Color.White;
}
/// <summary>
/// Control initialization
/// </summary>
virtual public void Initialize()
{
// Do nothing here
}
/// <summary>
/// Loads the content for this control
/// </summary>
virtual public void LoadContent(GraphicsDevice _graphics, ContentManager _content)
{
if (!string.IsNullOrEmpty(BackTextureName))
{
BackTexture = _content.Load<Texture2D>(BackTextureName);
}
}
#endregion
#region Update
/// <summary>
/// Updates this control, called once per game frame
/// </summary>
/// <param name="gameTime">The current game time</param>
/// <param name="gestures">The list of recorded gestures for this frame</param>
virtual public void Update(GameTime gameTime, List<GestureSample> gestures)
{
List<Transition> toRemove = new List<Transition>();
List<Transition> curTransitions = new List<Transition>();
curTransitions.AddRange(activeTransitions);
// Update any applied transitions
foreach (Transition transition in curTransitions)
{
transition.Update(gameTime);
if (!transition.TransitionActive)
{
toRemove.Add(transition);
}
}
// Remove any completed transitions
foreach (Transition transition in toRemove)
{
activeTransitions.Remove(transition);
}
}
#endregion
#region Draw
/// <summary>
/// Draws the control, called once per frame
/// </summary>
/// <param name="gameTime">The current game time</param>
/// <param name="spriteBatch">The sprite batch to draw with</param>
virtual public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
Texture2D currTexture = GetCurrTexture();
if (currTexture != null)
{
Rectangle rect = GetAbsoluteRect();
spriteBatch.Draw(currTexture, rect, null, Hue, 0f, new Vector2(), SpriteEffects.None, 0f);
}
}
#endregion
#region Helper Functions
/// <summary>
/// Overridable by decendants. This returns the current texture being used as the background image.
/// </summary>
/// <returns>The current texture</returns>
virtual public Texture2D GetCurrTexture()
{
return BackTexture;
}
/// <summary>
/// Gets the top left position of this control in screen coordinates.
/// </summary>
/// <returns>The top left point</returns>
public Point GetAbsoluteTopLeft()
{
Point absoluteTopLeft = new Point(Left, Top);
if (Parent != null)
{
Point parentTopLeft = Parent.GetAbsoluteTopLeft();
absoluteTopLeft.X += parentTopLeft.X;
absoluteTopLeft.Y += parentTopLeft.Y;
}
return absoluteTopLeft;
}
/// <summary>
/// Gets the boundaries for this control in screen coordinates.
/// </summary>
/// <returns>The rect boundaries</returns>
public Rectangle GetAbsoluteRect()
{
Point topLeft = GetAbsoluteTopLeft();
return new Rectangle(topLeft.X, topLeft.Y, Width, Height);
}
/// <summary>
/// Starts the passed in transition on this control.
/// </summary>
/// <param name="transition">The transition to apply</param>
public void ApplyTransition(Transition transition)
{
activeTransitions.Add(transition);
transition.Control = this;
transition.StartTranstion();
}
/// <summary>
/// Draws the specified text in the center of the control.
/// </summary>
/// <param name="_spriteBatch">The sprite batch to draw with</param>
/// <param name="_font">The font to use for the text</param>
/// <param name="_rect">The boundaries to center the text within</param>
/// <param name="_text">The text to draw</param>
/// <param name="_color">The hue to use for the text</param>
protected void DrawCenteredText(SpriteBatch _spriteBatch, SpriteFont _font, Rectangle _rect, string _text, Color _color)
{
if (_font == null || string.IsNullOrEmpty(_text)) return;
// Center the text in the rect
Vector2 midPoint = new Vector2(_rect.X + _rect.Width / 2, _rect.Y + _rect.Height / 2);
Vector2 stringSize = _font.MeasureString(_text);
Vector2 fontPos = new Vector2(midPoint.X - stringSize.X * .5f, midPoint.Y - stringSize.Y * .5f);
_spriteBatch.DrawString(_font, _text, fontPos, _color);
}
/// <summary>
/// Indicates whether the specified position falls within the control
/// </summary>
/// <param name="pos">The position to check</param>
/// <returns>Whether the position is contained within the control</returns>
protected bool ContainsPos(Vector2 pos)
{
Rectangle rect = GetAbsoluteRect();
return rect.Contains((int)pos.X, (int)pos.Y);
}
#endregion
}
}
| |
#region License
/* The MIT License
*
* Copyright (c) 2011 Red Badger Consulting
*
* 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
namespace RedBadger.Xpf.Controls
{
using System;
using System.Collections.Generic;
using System.Linq;
using RedBadger.Xpf.Internal;
/// <summary>
/// A Grid layout panel consisting of columns and rows.
/// </summary>
public class Grid : Panel
{
/// <summary>
/// Column attached property.
/// </summary>
public static readonly ReactiveProperty<int> ColumnProperty = ReactiveProperty<int>.Register(
"Column", typeof(Grid));
/// <summary>
/// Row attached property.
/// </summary>
public static readonly ReactiveProperty<int> RowProperty = ReactiveProperty<int>.Register("Row", typeof(Grid));
private readonly LinkedList<Cell> allStars = new LinkedList<Cell>();
private readonly LinkedList<Cell> autoPixelHeightStarWidth = new LinkedList<Cell>();
private readonly IList<ColumnDefinition> columnDefinitions = new List<ColumnDefinition>();
private readonly bool[] hasAuto = new bool[2];
private readonly bool[] hasStar = new bool[2];
private readonly LinkedList<Cell> noStars = new LinkedList<Cell>();
private readonly IList<RowDefinition> rowDefinitions = new List<RowDefinition>();
private readonly LinkedList<Cell> starHeightAutoPixelWidth = new LinkedList<Cell>();
private Cell[] cells;
private DefinitionBase[] columns;
private DefinitionBase[] rows;
private enum Dimension
{
Width,
Height
}
private enum UpdateMinLengths
{
SkipHeights,
SkipWidths,
WidthsAndHeights
}
/// <summary>
/// Gets the collection of column definitions.
/// </summary>
/// <value>The column definitions collection.</value>
public IList<ColumnDefinition> ColumnDefinitions
{
get
{
return this.columnDefinitions;
}
}
/// <summary>
/// Gets the collection of row definitions.
/// </summary>
/// <value>The row definitions collection.</value>
public IList<RowDefinition> RowDefinitions
{
get
{
return this.rowDefinitions;
}
}
/// <summary>
/// Gets the value of the Column attached property for the specified element.
/// </summary>
/// <param name = "element">The element for which to read the proerty value.</param>
/// <returns>The value of the Column attached property.</returns>
public static int GetColumn(IElement element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return element.GetValue(ColumnProperty);
}
/// <summary>
/// Gets the value of the Row attached property for the specified element.
/// </summary>
/// <param name = "element">The element for which to read the proerty value.</param>
/// <returns>The value of the Row attached property.</returns>
public static int GetRow(IElement element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return element.GetValue(RowProperty);
}
/// <summary>
/// Sets the value of the Column attached property for the specified element.
/// </summary>
/// <param name = "element">The element for which to write the proerty value.</param>
/// <param name = "value">The value of the Column attached property.</param>
public static void SetColumn(IElement element, int value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(ColumnProperty, value);
}
/// <summary>
/// Sets the value of the Row attached property for the specified element.
/// </summary>
/// <param name = "element">The element for which to write the proerty value.</param>
/// <param name = "value">The value of the Row attached property.</param>
public static void SetRow(IElement element, int value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(RowProperty, value);
}
protected override Size ArrangeOverride(Size finalSize)
{
SetFinalLength(this.columns, finalSize.Width);
SetFinalLength(this.rows, finalSize.Height);
for (int i = 0; i < this.cells.Length; i++)
{
IElement child = this.Children[i];
if (child != null)
{
int columnIndex = this.cells[i].ColumnIndex;
int rowIndex = this.cells[i].RowIndex;
var finalRect = new Rect(
this.columns[columnIndex].FinalOffset,
this.rows[rowIndex].FinalOffset,
this.columns[columnIndex].FinalLength,
this.rows[rowIndex].FinalLength);
child.Arrange(finalRect);
}
}
return finalSize;
}
protected override Size MeasureOverride(Size availableSize)
{
this.columns = this.columnDefinitions.Count == 0
? new DefinitionBase[] { new ColumnDefinition() }
: this.columnDefinitions.ToArray();
this.rows = this.rowDefinitions.Count == 0
? new DefinitionBase[] { new RowDefinition() }
: this.rowDefinitions.ToArray();
bool treatStarAsAutoWidth = double.IsPositiveInfinity(availableSize.Width);
bool treatStarAsAutoHeight = double.IsPositiveInfinity(availableSize.Height);
this.InitializeMeasureData(this.columns, treatStarAsAutoWidth, Dimension.Width);
this.InitializeMeasureData(this.rows, treatStarAsAutoHeight, Dimension.Height);
this.CreateCells();
this.MeasureCells(availableSize);
return new Size(
this.columns.Sum(definition => definition.MinLength), this.rows.Sum(definition => definition.MinLength));
}
private static void AllocateProportionalSpace(IEnumerable<DefinitionBase> definitions, double availableLength)
{
double occupiedLength = 0d;
var stars = new LinkedList<DefinitionBase>();
foreach (DefinitionBase definition in definitions)
{
switch (definition.LengthType)
{
case GridUnitType.Auto:
occupiedLength += definition.MinLength;
break;
case GridUnitType.Pixel:
occupiedLength += definition.AvailableLength;
break;
case GridUnitType.Star:
double numerator = definition.UserLength.Value;
if (numerator.IsCloseTo(0d))
{
definition.Numerator = 0d;
definition.StarAllocationOrder = 0d;
}
else
{
definition.Numerator = numerator;
definition.StarAllocationOrder = Math.Max(definition.MinLength, definition.UserMaxLength) /
numerator;
}
stars.AddLast(definition);
break;
}
}
if (stars.Count > 0)
{
DefinitionBase[] sortedStars = stars.OrderBy(o => o.StarAllocationOrder).ToArray();
double denominator = 0d;
foreach (DefinitionBase definition in sortedStars.Reverse())
{
denominator += definition.Numerator;
definition.Denominator = denominator;
}
foreach (DefinitionBase definition in sortedStars)
{
double length;
if (definition.Numerator.IsCloseTo(0d))
{
length = definition.MinLength;
}
else
{
double remainingLength = (availableLength - occupiedLength).EnsurePositive();
length = remainingLength * (definition.Numerator / definition.Denominator);
length = length.Coerce(definition.MinLength, definition.UserMaxLength);
}
occupiedLength += length;
definition.AvailableLength = length;
}
}
}
private static void SetFinalLength(DefinitionBase[] definitions, double gridFinalLength)
{
double occupiedLength = 0d;
var stars = new LinkedList<DefinitionBase>();
var nonStarDefinitions = new LinkedList<DefinitionBase>();
foreach (DefinitionBase definition in definitions)
{
double minLength;
switch (definition.UserLength.GridUnitType)
{
case GridUnitType.Auto:
minLength = definition.MinLength;
definition.FinalLength = minLength.Coerce(definition.MinLength, definition.UserMaxLength);
occupiedLength += definition.FinalLength;
nonStarDefinitions.AddFirst(definition);
break;
case GridUnitType.Pixel:
minLength = definition.UserLength.Value;
definition.FinalLength = minLength.Coerce(definition.MinLength, definition.UserMaxLength);
occupiedLength += definition.FinalLength;
nonStarDefinitions.AddFirst(definition);
break;
case GridUnitType.Star:
double numerator = definition.UserLength.Value;
if (numerator.IsCloseTo(0d))
{
definition.Numerator = 0d;
definition.StarAllocationOrder = 0d;
}
else
{
definition.Numerator = numerator;
definition.StarAllocationOrder = Math.Max(definition.MinLength, definition.UserMaxLength) /
numerator;
}
stars.AddLast(definition);
break;
}
}
if (stars.Count > 0)
{
DefinitionBase[] sortedStars = stars.OrderBy(o => o.StarAllocationOrder).ToArray();
double denominator = 0d;
foreach (DefinitionBase definitionBase in sortedStars.Reverse())
{
denominator += definitionBase.Numerator;
definitionBase.Denominator = denominator;
}
foreach (DefinitionBase definition in sortedStars)
{
double length;
if (definition.Numerator.IsCloseTo(0d))
{
length = definition.MinLength;
}
else
{
double remainingLength = (gridFinalLength - occupiedLength).EnsurePositive();
length = remainingLength * (definition.Numerator / definition.Denominator);
length = length.Coerce(definition.MinLength, definition.UserMaxLength);
}
occupiedLength += length;
definition.FinalLength = length;
}
}
if (occupiedLength.IsGreaterThan(gridFinalLength))
{
IOrderedEnumerable<DefinitionBase> sortedDefinitions =
stars.Concat(nonStarDefinitions).OrderBy(o => o.FinalLength - o.MinLength);
double excessLength = occupiedLength - gridFinalLength;
int i = 0;
foreach (DefinitionBase definitionBase in sortedDefinitions)
{
double finalLength = definitionBase.FinalLength - (excessLength / (definitions.Length - i));
finalLength = finalLength.Coerce(definitionBase.MinLength, definitionBase.FinalLength);
excessLength -= definitionBase.FinalLength - finalLength;
definitionBase.FinalLength = finalLength;
i++;
}
}
definitions[0].FinalOffset = 0d;
for (int i = 1; i < definitions.Length; i++)
{
DefinitionBase previousDefinition = definitions[i - 1];
definitions[i].FinalOffset = previousDefinition.FinalOffset + previousDefinition.FinalLength;
}
}
private void CreateCells()
{
this.cells = new Cell[this.Children.Count];
this.noStars.Clear();
this.autoPixelHeightStarWidth.Clear();
this.starHeightAutoPixelWidth.Clear();
this.allStars.Clear();
int i = 0;
foreach (IElement child in this.Children)
{
if (child != null)
{
int columnIndex = Math.Min(GetColumn(child), this.columns.Length - 1);
int rowIndex = Math.Min(GetRow(child), this.rows.Length - 1);
var cell = new Cell
{
ColumnIndex = columnIndex,
RowIndex = rowIndex,
Child = child,
WidthType = this.columns[columnIndex].LengthType,
HeightType = this.rows[rowIndex].LengthType,
};
if (cell.HeightType == GridUnitType.Star)
{
if (cell.WidthType == GridUnitType.Star)
{
this.allStars.AddLast(cell);
}
else
{
this.starHeightAutoPixelWidth.AddLast(cell);
}
}
else
{
if (cell.WidthType == GridUnitType.Star)
{
this.autoPixelHeightStarWidth.AddLast(cell);
}
else
{
this.noStars.AddLast(cell);
}
}
this.cells[i] = cell;
}
i++;
}
}
private void InitializeMeasureData(
IEnumerable<DefinitionBase> definitions, bool treatStarAsAuto, Dimension dimension)
{
foreach (DefinitionBase definition in definitions)
{
definition.MinLength = 0d;
double availableLength = 0d;
double userMinLength = definition.UserMinLength;
double userMaxLength = definition.UserMaxLength;
switch (definition.UserLength.GridUnitType)
{
case GridUnitType.Auto:
definition.LengthType = GridUnitType.Auto;
availableLength = double.PositiveInfinity;
this.hasAuto[(int)dimension] = true;
break;
case GridUnitType.Pixel:
definition.LengthType = GridUnitType.Pixel;
availableLength = definition.UserLength.Value;
userMinLength = availableLength.Coerce(userMinLength, userMaxLength);
break;
case GridUnitType.Star:
definition.LengthType = treatStarAsAuto ? GridUnitType.Auto : GridUnitType.Star;
availableLength = double.PositiveInfinity;
this.hasStar[(int)dimension] = true;
break;
}
definition.UpdateMinLength(userMinLength);
definition.AvailableLength = availableLength.Coerce(userMinLength, userMaxLength);
}
}
private void MeasureCell(Cell cell, IElement child, bool shouldChildBeMeasuredWithInfiniteHeight)
{
if (child != null)
{
double x = cell.WidthType == GridUnitType.Auto
? double.PositiveInfinity
: this.columns[cell.ColumnIndex].AvailableLength;
double y = cell.HeightType == GridUnitType.Auto || shouldChildBeMeasuredWithInfiniteHeight
? double.PositiveInfinity
: this.rows[cell.RowIndex].AvailableLength;
child.Measure(new Size(x, y));
}
}
private void MeasureCells(Size availableSize)
{
if (this.noStars.Count > 0)
{
this.MeasureCells(this.noStars, UpdateMinLengths.WidthsAndHeights);
}
if (!this.hasAuto[(int)Dimension.Height])
{
if (this.hasStar[(int)Dimension.Height])
{
AllocateProportionalSpace(this.rows, availableSize.Height);
}
this.MeasureCells(this.starHeightAutoPixelWidth, UpdateMinLengths.WidthsAndHeights);
if (this.hasStar[(int)Dimension.Width])
{
AllocateProportionalSpace(this.columns, availableSize.Width);
}
this.MeasureCells(this.autoPixelHeightStarWidth, UpdateMinLengths.WidthsAndHeights);
}
else if (!this.hasAuto[(int)Dimension.Width])
{
if (this.hasStar[(int)Dimension.Width])
{
AllocateProportionalSpace(this.columns, availableSize.Width);
}
this.MeasureCells(this.autoPixelHeightStarWidth, UpdateMinLengths.WidthsAndHeights);
if (this.hasStar[(int)Dimension.Height])
{
AllocateProportionalSpace(this.rows, availableSize.Height);
}
this.MeasureCells(this.starHeightAutoPixelWidth, UpdateMinLengths.WidthsAndHeights);
}
else
{
this.MeasureCells(this.starHeightAutoPixelWidth, UpdateMinLengths.SkipHeights);
if (this.hasStar[(int)Dimension.Width])
{
AllocateProportionalSpace(this.columns, availableSize.Width);
}
this.MeasureCells(this.autoPixelHeightStarWidth, UpdateMinLengths.WidthsAndHeights);
if (this.hasStar[(int)Dimension.Height])
{
AllocateProportionalSpace(this.rows, availableSize.Height);
}
this.MeasureCells(this.starHeightAutoPixelWidth, UpdateMinLengths.SkipWidths);
}
if (this.allStars.Count > 0)
{
this.MeasureCells(this.allStars, UpdateMinLengths.WidthsAndHeights);
}
}
private void MeasureCells(IEnumerable<Cell> cells, UpdateMinLengths updateMinLengths)
{
foreach (Cell cell in cells)
{
bool shouldChildBeMeasuredWithInfiniteHeight = updateMinLengths == UpdateMinLengths.SkipHeights;
this.MeasureCell(cell, cell.Child, shouldChildBeMeasuredWithInfiniteHeight);
if (updateMinLengths != UpdateMinLengths.SkipWidths)
{
DefinitionBase widthDefinition = this.columns[cell.ColumnIndex];
widthDefinition.UpdateMinLength(
Math.Min(cell.Child.DesiredSize.Width, widthDefinition.UserMaxLength));
}
if (updateMinLengths != UpdateMinLengths.SkipHeights)
{
DefinitionBase heightDefinition = this.rows[cell.RowIndex];
heightDefinition.UpdateMinLength(
Math.Min(cell.Child.DesiredSize.Height, heightDefinition.UserMaxLength));
}
}
}
private struct Cell
{
public IElement Child;
public int ColumnIndex;
public GridUnitType HeightType;
public int RowIndex;
public GridUnitType WidthType;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Pipelines.Yaml.Contracts;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Pipelines.Yaml.TypeConverters
{
internal static partial class ConverterUtil
{
internal static IList<IPhase> ReadPhases(IParser parser, Boolean simpleOnly)
{
var result = new List<IPhase>();
parser.Expect<SequenceStart>();
while (parser.Allow<SequenceEnd>() == null)
{
result.Add(ReadPhase(parser, simpleOnly));
}
return result;
}
internal static IPhase ReadPhase(IParser parser, Boolean simpleOnly)
{
IPhase result;
parser.Expect<MappingStart>();
Scalar scalar = parser.Expect<Scalar>();
if (String.Equals(scalar.Value, YamlConstants.Name, StringComparison.Ordinal))
{
var phase = new Phase { Name = ReadNonEmptyString(parser) };
while (parser.Allow<MappingEnd>() == null)
{
scalar = parser.Expect<Scalar>();
switch (scalar.Value ?? String.Empty)
{
case YamlConstants.DependsOn:
if (parser.Accept<Scalar>())
{
scalar = parser.Expect<Scalar>();
if (!String.IsNullOrEmpty(scalar.Value))
{
phase.DependsOn = new List<String>();
phase.DependsOn.Add(scalar.Value);
}
}
else
{
phase.DependsOn = ReadSequenceOfString(parser);
}
break;
case YamlConstants.Condition:
phase.Condition = ReadNonEmptyString(parser);
break;
case YamlConstants.ContinueOnError:
phase.ContinueOnError = ReadNonEmptyString(parser);
break;
case YamlConstants.EnableAccessToken:
phase.EnableAccessToken = ReadNonEmptyString(parser);
break;
case YamlConstants.Deployment:
if (phase.Target != null)
{
ValidateNull(phase.Target as QueueTarget, YamlConstants.Queue, YamlConstants.Deployment, scalar);
ValidateNull(phase.Target as ServerTarget, YamlConstants.Server, YamlConstants.Deployment, scalar);
throw new NotSupportedException("Unexpected previous target type"); // Should not reach here
}
phase.Target = ReadDeploymentTarget(parser);
break;
case YamlConstants.Queue:
if (phase.Target != null)
{
ValidateNull(phase.Target as DeploymentTarget, YamlConstants.Deployment, YamlConstants.Queue, scalar);
ValidateNull(phase.Target as ServerTarget, YamlConstants.Server, YamlConstants.Queue, scalar);
throw new NotSupportedException("Unexpected previous target type"); // Should not reach here
}
phase.Target = ReadQueueTarget(parser);
break;
case YamlConstants.Server:
if (phase.Target != null)
{
ValidateNull(phase.Target as DeploymentTarget, YamlConstants.Deployment, YamlConstants.Server, scalar);
ValidateNull(phase.Target as QueueTarget, YamlConstants.Queue, YamlConstants.Server, scalar);
throw new NotSupportedException("Unexpected previous target type"); // Should not reach here
}
phase.Target = ReadServerTarget(parser);
break;
case YamlConstants.Variables:
phase.Variables = ReadVariables(parser, simpleOnly: false);
break;
case YamlConstants.Steps:
phase.Steps = ReadSteps(parser, simpleOnly: false);
break;
default:
throw new SyntaxErrorException(scalar.Start, scalar.End, $"Unexpected process property: '{scalar.Value}'");
}
}
result = phase;
}
else if (String.Equals(scalar.Value, YamlConstants.Template, StringComparison.Ordinal))
{
if (simpleOnly)
{
throw new SyntaxErrorException(scalar.Start, scalar.End, $"A phases template cannot reference another phases '{YamlConstants.Template}'.");
}
var reference = new PhasesTemplateReference { Name = ReadNonEmptyString(parser) };
while (parser.Allow<MappingEnd>() == null)
{
scalar = parser.Expect<Scalar>();
SetProperty(parser, reference, scalar);
}
result = reference;
}
else
{
throw new SyntaxErrorException(scalar.Start, scalar.End, $"Unknown phase type: '{scalar.Value}'");
}
return result;
}
internal static DeploymentTarget ReadDeploymentTarget(IParser parser)
{
// Handle the simple case "deployment: group"
if (parser.Accept<Scalar>())
{
return new DeploymentTarget() { Group = ReadNonEmptyString(parser) };
}
var result = new DeploymentTarget();
parser.Expect<MappingStart>();
while (parser.Allow<MappingEnd>() == null)
{
Scalar scalar = parser.Expect<Scalar>();
switch (scalar.Value ?? String.Empty)
{
case YamlConstants.ContinueOnError:
result.ContinueOnError = ReadNonEmptyString(parser);
break;
case YamlConstants.Group:
result.Group = ReadNonEmptyString(parser);
break;
case YamlConstants.HealthOption:
result.HealthOption = ReadNonEmptyString(parser);
break;
case YamlConstants.Percentage:
result.Percentage = ReadNonEmptyString(parser);
break;
case YamlConstants.Tags:
if (parser.Accept<Scalar>())
{
scalar = parser.Expect<Scalar>();
if (!String.IsNullOrEmpty(scalar.Value))
{
result.Tags = new List<String>();
result.Tags.Add(scalar.Value);
}
}
else
{
result.Tags = ReadSequenceOfString(parser);
}
break;
case YamlConstants.TimeoutInMinutes:
result.TimeoutInMinutes = ReadNonEmptyString(parser);
break;
default:
throw new SyntaxErrorException(scalar.Start, scalar.End, $"Unexpected property: '{scalar.Value}'");
}
}
return result;
}
internal static QueueTarget ReadQueueTarget(IParser parser)
{
// Handle the simple case "queue: name"
if (parser.Accept<Scalar>())
{
return new QueueTarget() { Name = ReadNonEmptyString(parser) };
}
var result = new QueueTarget();
parser.Expect<MappingStart>();
while (parser.Allow<MappingEnd>() == null)
{
Scalar scalar = parser.Expect<Scalar>();
switch (scalar.Value ?? String.Empty)
{
case YamlConstants.ContinueOnError:
result.ContinueOnError = ReadNonEmptyString(parser);
break;
case YamlConstants.Demands:
if (parser.Accept<Scalar>())
{
scalar = parser.Expect<Scalar>();
if (!String.IsNullOrEmpty(scalar.Value))
{
result.Demands = new List<String>();
result.Demands.Add(scalar.Value);
}
}
else
{
result.Demands = ReadSequenceOfString(parser);
}
break;
case YamlConstants.Matrix:
parser.Expect<MappingStart>();
result.Matrix = new Dictionary<String, IDictionary<String, String>>(StringComparer.OrdinalIgnoreCase);
while (parser.Allow<MappingEnd>() == null)
{
String key = ReadNonEmptyString(parser);
result.Matrix[key] = ReadMappingOfStringString(parser, StringComparer.OrdinalIgnoreCase);
}
break;
case YamlConstants.Name:
result.Name = ReadNonEmptyString(parser);
break;
case YamlConstants.Parallel:
result.Parallel = ReadNonEmptyString(parser);
break;
case YamlConstants.TimeoutInMinutes:
result.TimeoutInMinutes = ReadNonEmptyString(parser);
break;
default:
throw new SyntaxErrorException(scalar.Start, scalar.End, $"Unexpected property: '{scalar.Value}'");
}
}
return result;
}
internal static ServerTarget ReadServerTarget(IParser parser)
{
// Handle the simple case "server: true"
Scalar scalar = parser.Peek<Scalar>();
if (scalar != null)
{
if (ReadBoolean(parser))
{
return new ServerTarget();
}
return null;
}
var result = new ServerTarget();
parser.Expect<MappingStart>();
while (parser.Allow<MappingEnd>() == null)
{
scalar = parser.Expect<Scalar>();
switch (scalar.Value ?? String.Empty)
{
case YamlConstants.ContinueOnError:
result.ContinueOnError = ReadNonEmptyString(parser);
break;
case YamlConstants.Matrix:
parser.Expect<MappingStart>();
result.Matrix = new Dictionary<String, IDictionary<String, String>>(StringComparer.OrdinalIgnoreCase);
while (parser.Allow<MappingEnd>() == null)
{
String key = ReadNonEmptyString(parser);
result.Matrix[key] = ReadMappingOfStringString(parser, StringComparer.OrdinalIgnoreCase);
}
break;
case YamlConstants.Parallel:
result.Parallel = ReadNonEmptyString(parser);
break;
case YamlConstants.TimeoutInMinutes:
result.TimeoutInMinutes = ReadNonEmptyString(parser);
break;
default:
throw new SyntaxErrorException(scalar.Start, scalar.End, $"Unexpected property: '{scalar.Value}'");
}
}
return result;
}
internal static void SetProperty(IParser parser, PhasesTemplateReference reference, Scalar scalar)
{
if (String.Equals(scalar.Value, YamlConstants.Phases, StringComparison.Ordinal))
{
parser.Expect<SequenceStart>();
var selectors = new List<PhaseSelector>();
while (parser.Allow<SequenceEnd>() == null)
{
var selector = new PhaseSelector();
parser.Expect<MappingStart>();
ReadExactString(parser, YamlConstants.Name);
selector.Name = ReadNonEmptyString(parser);
while (parser.Allow<MappingEnd>() == null)
{
scalar = parser.Expect<Scalar>();
SetProperty(parser, selector, scalar);
}
}
reference.PhaseSelectors = selectors;
}
else
{
SetProperty(parser, reference as StepsTemplateReference, scalar);
}
}
internal static void SetProperty(IParser parser, PhaseSelector selector, Scalar scalar)
{
if (String.Equals(scalar.Value, YamlConstants.Steps, StringComparison.Ordinal))
{
selector.StepOverrides = ReadStepOverrides(parser);
}
else
{
throw new SyntaxErrorException(scalar.Start, scalar.End, $"Unexpected property: '{scalar.Value}'");
}
}
internal static void WritePhases(IEmitter emitter, IList<IPhase> phases)
{
emitter.Emit(new SequenceStart(null, null, true, SequenceStyle.Block));
foreach (IPhase phase in phases)
{
WritePhase(emitter, phase);
}
emitter.Emit(new SequenceEnd());
}
internal static void WritePhase(IEmitter emitter, IPhase phase, Boolean noBootstrap = false)
{
if (!noBootstrap)
{
emitter.Emit(new MappingStart());
}
if (phase is PhasesTemplateReference)
{
var reference = phase as PhasesTemplateReference;
if (!noBootstrap)
{
emitter.Emit(new Scalar(YamlConstants.Template));
emitter.Emit(new Scalar(reference.Name));
if (reference.Parameters != null && reference.Parameters.Count > 0)
{
emitter.Emit(new Scalar(YamlConstants.Parameters));
WriteMapping(emitter, reference.Parameters);
}
}
if (reference.PhaseSelectors != null && reference.PhaseSelectors.Count > 0)
{
emitter.Emit(new Scalar(YamlConstants.Phases));
emitter.Emit(new SequenceStart(null, null, true, SequenceStyle.Block));
foreach (PhaseSelector selector in reference.PhaseSelectors)
{
emitter.Emit(new MappingStart());
if (!String.IsNullOrEmpty(selector.Name))
{
emitter.Emit(new Scalar(YamlConstants.Name));
emitter.Emit(new Scalar(selector.Name));
}
if (selector.StepOverrides != null && selector.StepOverrides.Count > 0)
{
emitter.Emit(new Scalar(YamlConstants.Steps));
WriteStepOverrides(emitter, selector.StepOverrides);
}
emitter.Emit(new MappingEnd());
}
emitter.Emit(new SequenceEnd());
}
WriteStep(emitter, reference as StepsTemplateReference, noBootstrap: true);
}
else
{
var p = phase as Phase;
if (!noBootstrap)
{
emitter.Emit(new Scalar(YamlConstants.Name));
emitter.Emit(new Scalar(p.Name ?? String.Empty));
}
if (p.DependsOn != null && p.DependsOn.Count > 0)
{
emitter.Emit(new Scalar(YamlConstants.DependsOn));
if (p.DependsOn.Count == 1)
{
emitter.Emit(new Scalar(p.DependsOn[0]));
}
else
{
WriteSequence(emitter, p.DependsOn);
}
}
if (!String.IsNullOrEmpty(p.Condition))
{
emitter.Emit(new Scalar(YamlConstants.Condition));
emitter.Emit(new Scalar(p.Condition));
}
if (!String.IsNullOrEmpty(p.ContinueOnError))
{
emitter.Emit(new Scalar(YamlConstants.ContinueOnError));
emitter.Emit(new Scalar(p.ContinueOnError));
}
if (!String.IsNullOrEmpty(p.EnableAccessToken))
{
emitter.Emit(new Scalar(YamlConstants.EnableAccessToken));
emitter.Emit(new Scalar(p.EnableAccessToken));
}
if (p.Target != null)
{
QueueTarget queueTarget = null;
DeploymentTarget deploymentTarget = null;
ServerTarget serverTarget = null;
if ((queueTarget = p.Target as QueueTarget) != null)
{
emitter.Emit(new Scalar(YamlConstants.Queue));
// Test for the simple case "queue: name".
if (!String.IsNullOrEmpty(queueTarget.Name) &&
String.IsNullOrEmpty(queueTarget.ContinueOnError) &&
String.IsNullOrEmpty(queueTarget.Parallel) &&
String.IsNullOrEmpty(queueTarget.TimeoutInMinutes) &&
(queueTarget.Demands == null || queueTarget.Demands.Count == 0) &&
(queueTarget.Matrix == null || queueTarget.Matrix.Count == 0))
{
emitter.Emit(new Scalar(queueTarget.Name));
}
else // Otherwise write the mapping.
{
emitter.Emit(new MappingStart());
if (!String.IsNullOrEmpty(queueTarget.Name))
{
emitter.Emit(new Scalar(YamlConstants.Name));
emitter.Emit(new Scalar(queueTarget.Name));
}
if (!String.IsNullOrEmpty(queueTarget.ContinueOnError))
{
emitter.Emit(new Scalar(YamlConstants.ContinueOnError));
emitter.Emit(new Scalar(queueTarget.ContinueOnError));
}
if (!String.IsNullOrEmpty(queueTarget.Parallel))
{
emitter.Emit(new Scalar(YamlConstants.Parallel));
emitter.Emit(new Scalar(queueTarget.Parallel));
}
if (!String.IsNullOrEmpty(queueTarget.TimeoutInMinutes))
{
emitter.Emit(new Scalar(YamlConstants.TimeoutInMinutes));
emitter.Emit(new Scalar(queueTarget.TimeoutInMinutes));
}
if (queueTarget.Demands != null && queueTarget.Demands.Count > 0)
{
emitter.Emit(new Scalar(YamlConstants.Demands));
if (queueTarget.Demands.Count == 1)
{
emitter.Emit(new Scalar(queueTarget.Demands[0]));
}
else
{
WriteSequence(emitter, queueTarget.Demands);
}
}
if (queueTarget.Matrix != null && queueTarget.Matrix.Count > 0)
{
emitter.Emit(new Scalar(YamlConstants.Matrix));
emitter.Emit(new MappingStart());
foreach (KeyValuePair<String, IDictionary<String, String>> pair in queueTarget.Matrix.OrderBy(x => x.Key, StringComparer.OrdinalIgnoreCase))
{
emitter.Emit(new Scalar(pair.Key));
WriteMapping(emitter, pair.Value);
}
emitter.Emit(new MappingEnd());
}
emitter.Emit(new MappingEnd());
}
}
else if ((deploymentTarget = p.Target as DeploymentTarget) != null)
{
emitter.Emit(new Scalar(YamlConstants.Deployment));
// Test for the simple case "deployment: group".
if (!String.IsNullOrEmpty(deploymentTarget.Group) &&
String.IsNullOrEmpty(deploymentTarget.ContinueOnError) &&
String.IsNullOrEmpty(deploymentTarget.HealthOption) &&
String.IsNullOrEmpty(deploymentTarget.Percentage) &&
String.IsNullOrEmpty(deploymentTarget.TimeoutInMinutes) &&
(deploymentTarget.Tags == null || deploymentTarget.Tags.Count == 0))
{
emitter.Emit(new Scalar(deploymentTarget.Group));
}
else // Otherwise write the mapping.
{
emitter.Emit(new MappingStart());
if (!String.IsNullOrEmpty(deploymentTarget.Group))
{
emitter.Emit(new Scalar(YamlConstants.Group));
emitter.Emit(new Scalar(deploymentTarget.Group));
}
if (!String.IsNullOrEmpty(deploymentTarget.ContinueOnError))
{
emitter.Emit(new Scalar(YamlConstants.ContinueOnError));
emitter.Emit(new Scalar(deploymentTarget.ContinueOnError));
}
if (!String.IsNullOrEmpty(deploymentTarget.HealthOption))
{
emitter.Emit(new Scalar(YamlConstants.HealthOption));
emitter.Emit(new Scalar(deploymentTarget.HealthOption));
}
if (!String.IsNullOrEmpty(deploymentTarget.Percentage))
{
emitter.Emit(new Scalar(YamlConstants.Percentage));
emitter.Emit(new Scalar(deploymentTarget.Percentage));
}
if (!String.IsNullOrEmpty(deploymentTarget.TimeoutInMinutes))
{
emitter.Emit(new Scalar(YamlConstants.TimeoutInMinutes));
emitter.Emit(new Scalar(deploymentTarget.TimeoutInMinutes));
}
if (deploymentTarget.Tags != null && deploymentTarget.Tags.Count > 0)
{
emitter.Emit(new Scalar(YamlConstants.Tags));
if (deploymentTarget.Tags.Count == 1)
{
emitter.Emit(new Scalar(deploymentTarget.Tags[0]));
}
else
{
WriteSequence(emitter, deploymentTarget.Tags);
}
}
emitter.Emit(new MappingEnd());
}
}
else if ((serverTarget = p.Target as ServerTarget) != null)
{
emitter.Emit(new Scalar(YamlConstants.Server));
// Test for the simple case "server: true".
if (String.IsNullOrEmpty(serverTarget.ContinueOnError) &&
String.IsNullOrEmpty(serverTarget.Parallel) &&
String.IsNullOrEmpty(serverTarget.TimeoutInMinutes) &&
(serverTarget.Matrix == null || serverTarget.Matrix.Count == 0))
{
emitter.Emit(new Scalar("true"));
}
else // Otherwise write the mapping.
{
emitter.Emit(new MappingStart());
if (!String.IsNullOrEmpty(serverTarget.ContinueOnError))
{
emitter.Emit(new Scalar(YamlConstants.ContinueOnError));
emitter.Emit(new Scalar(serverTarget.ContinueOnError));
}
if (!String.IsNullOrEmpty(serverTarget.Parallel))
{
emitter.Emit(new Scalar(YamlConstants.Parallel));
emitter.Emit(new Scalar(serverTarget.Parallel));
}
if (!String.IsNullOrEmpty(serverTarget.TimeoutInMinutes))
{
emitter.Emit(new Scalar(YamlConstants.TimeoutInMinutes));
emitter.Emit(new Scalar(serverTarget.TimeoutInMinutes));
}
if (serverTarget.Matrix != null && serverTarget.Matrix.Count > 0)
{
emitter.Emit(new Scalar(YamlConstants.Matrix));
emitter.Emit(new MappingStart());
foreach (KeyValuePair<String, IDictionary<String, String>> pair in serverTarget.Matrix.OrderBy(x => x.Key, StringComparer.OrdinalIgnoreCase))
{
emitter.Emit(new Scalar(pair.Key));
WriteMapping(emitter, pair.Value);
}
emitter.Emit(new MappingEnd());
}
emitter.Emit(new MappingEnd());
}
}
else
{
throw new NotSupportedException($"Unexpected target type: '{p.Target.GetType().FullName}'");
}
}
if (p.Variables != null && p.Variables.Count > 0)
{
emitter.Emit(new Scalar(YamlConstants.Variables));
WriteVariables(emitter, p.Variables);
}
if (p.Steps != null && p.Steps.Count > 0)
{
emitter.Emit(new Scalar(YamlConstants.Steps));
WriteSteps(emitter, p.Steps);
}
}
if (!noBootstrap)
{
emitter.Emit(new MappingEnd());
}
}
internal static void WritePhasesTemplate(IEmitter emitter, PhasesTemplate template, Boolean noBootstrapper = false)
{
if (!noBootstrapper)
{
emitter.Emit(new MappingStart());
}
if (template.Phases != null && template.Phases.Count > 0)
{
emitter.Emit(new Scalar(YamlConstants.Phases));
WritePhases(emitter, template.Phases);
}
WriteStepsTemplate(emitter, template, noBootstrapper: true);
if (!noBootstrapper)
{
emitter.Emit(new MappingEnd());
}
}
}
}
| |
#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;
using System.Collections;
using System.Globalization;
using System.Reflection;
#if !NETMF
using System.Xml;
#endif
using log4net.Appender;
using log4net.Util;
using log4net.Core;
using log4net.ObjectRenderer;
#if !NETMF
namespace log4net.Repository.Hierarchy
{
/// <summary>
/// Initializes the log4net environment using an XML DOM.
/// </summary>
/// <remarks>
/// <para>
/// Configures a <see cref="Hierarchy"/> using an XML DOM.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class XmlHierarchyConfigurator
{
private enum ConfigUpdateMode
{
Merge,
Overwrite
}
#region Public Instance Constructors
/// <summary>
/// Construct the configurator for a hierarchy
/// </summary>
/// <param name="hierarchy">The hierarchy to build.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="XmlHierarchyConfigurator" /> class
/// with the specified <see cref="Hierarchy" />.
/// </para>
/// </remarks>
public XmlHierarchyConfigurator(Hierarchy hierarchy)
{
m_hierarchy = hierarchy;
m_appenderBag = new Hashtable();
}
#endregion Public Instance Constructors
#region Public Instance Methods
/// <summary>
/// Configure the hierarchy by parsing a DOM tree of XML elements.
/// </summary>
/// <param name="element">The root element to parse.</param>
/// <remarks>
/// <para>
/// Configure the hierarchy by parsing a DOM tree of XML elements.
/// </para>
/// </remarks>
public void Configure(XmlElement element)
{
if (element == null || m_hierarchy == null)
{
return;
}
string rootElementName = element.LocalName;
if (rootElementName != CONFIGURATION_TAG)
{
LogLog.Error(declaringType, "Xml element is - not a <" + CONFIGURATION_TAG + "> element.");
return;
}
if (!LogLog.EmitInternalMessages)
{
// Look for a emitDebug attribute to enable internal debug
string emitDebugAttribute = element.GetAttribute(EMIT_INTERNAL_DEBUG_ATTR);
LogLog.Debug(declaringType, EMIT_INTERNAL_DEBUG_ATTR + " attribute [" + emitDebugAttribute + "].");
if (emitDebugAttribute.Length > 0 && emitDebugAttribute != "null")
{
LogLog.EmitInternalMessages = OptionConverter.ToBoolean(emitDebugAttribute, true);
}
else
{
LogLog.Debug(declaringType, "Ignoring " + EMIT_INTERNAL_DEBUG_ATTR + " attribute.");
}
}
if (!LogLog.InternalDebugging)
{
// Look for a debug attribute to enable internal debug
string debugAttribute = element.GetAttribute(INTERNAL_DEBUG_ATTR);
LogLog.Debug(declaringType, INTERNAL_DEBUG_ATTR+" attribute [" + debugAttribute + "].");
if (debugAttribute.Length>0 && debugAttribute != "null")
{
LogLog.InternalDebugging = OptionConverter.ToBoolean(debugAttribute, true);
}
else
{
LogLog.Debug(declaringType, "Ignoring " + INTERNAL_DEBUG_ATTR + " attribute.");
}
string confDebug = element.GetAttribute(CONFIG_DEBUG_ATTR);
if (confDebug.Length>0 && confDebug != "null")
{
LogLog.Warn(declaringType, "The \"" + CONFIG_DEBUG_ATTR + "\" attribute is deprecated.");
LogLog.Warn(declaringType, "Use the \"" + INTERNAL_DEBUG_ATTR + "\" attribute instead.");
LogLog.InternalDebugging = OptionConverter.ToBoolean(confDebug, true);
}
}
// Default mode is merge
ConfigUpdateMode configUpdateMode = ConfigUpdateMode.Merge;
// Look for the config update attribute
string configUpdateModeAttribute = element.GetAttribute(CONFIG_UPDATE_MODE_ATTR);
if (configUpdateModeAttribute != null && configUpdateModeAttribute.Length > 0)
{
// Parse the attribute
try
{
configUpdateMode = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), configUpdateModeAttribute);
}
catch
{
LogLog.Error(declaringType, "Invalid " + CONFIG_UPDATE_MODE_ATTR + " attribute value [" + configUpdateModeAttribute + "]");
}
}
// IMPL: The IFormatProvider argument to Enum.ToString() is deprecated in .NET 2.0
LogLog.Debug(declaringType, "Configuration update mode [" + configUpdateMode.ToString() + "].");
// Only reset configuration if overwrite flag specified
if (configUpdateMode == ConfigUpdateMode.Overwrite)
{
// Reset to original unset configuration
m_hierarchy.ResetConfiguration();
LogLog.Debug(declaringType, "Configuration reset before reading config.");
}
/* Building Appender objects, placing them in a local namespace
for future reference */
/* Process all the top level elements */
foreach (XmlNode currentNode in element.ChildNodes)
{
if (currentNode.NodeType == XmlNodeType.Element)
{
XmlElement currentElement = (XmlElement)currentNode;
if (currentElement.LocalName == LOGGER_TAG)
{
ParseLogger(currentElement);
}
else if (currentElement.LocalName == CATEGORY_TAG)
{
// TODO: deprecated use of category
ParseLogger(currentElement);
}
else if (currentElement.LocalName == ROOT_TAG)
{
ParseRoot(currentElement);
}
else if (currentElement.LocalName == RENDERER_TAG)
{
ParseRenderer(currentElement);
}
else if (currentElement.LocalName == APPENDER_TAG)
{
// We ignore appenders in this pass. They will
// be found and loaded if they are referenced.
}
else
{
// Read the param tags and set properties on the hierarchy
SetParameter(currentElement, m_hierarchy);
}
}
}
// Lastly set the hierarchy threshold
string thresholdStr = element.GetAttribute(THRESHOLD_ATTR);
LogLog.Debug(declaringType, "Hierarchy Threshold [" + thresholdStr + "]");
if (thresholdStr.Length > 0 && thresholdStr != "null")
{
Level thresholdLevel = (Level) ConvertStringTo(typeof(Level), thresholdStr);
if (thresholdLevel != null)
{
m_hierarchy.Threshold = thresholdLevel;
}
else
{
LogLog.Warn(declaringType, "Unable to set hierarchy threshold using value [" + thresholdStr + "] (with acceptable conversion types)");
}
}
// Done reading config
}
#endregion Public Instance Methods
#region Protected Instance Methods
/// <summary>
/// Parse appenders by IDREF.
/// </summary>
/// <param name="appenderRef">The appender ref element.</param>
/// <returns>The instance of the appender that the ref refers to.</returns>
/// <remarks>
/// <para>
/// Parse an XML element that represents an appender and return
/// the appender.
/// </para>
/// </remarks>
protected IAppender FindAppenderByReference(XmlElement appenderRef)
{
string appenderName = appenderRef.GetAttribute(REF_ATTR);
IAppender appender = (IAppender)m_appenderBag[appenderName];
if (appender != null)
{
return appender;
}
else
{
// Find the element with that id
XmlElement element = null;
if (appenderName != null && appenderName.Length > 0)
{
foreach (XmlElement curAppenderElement in appenderRef.OwnerDocument.GetElementsByTagName(APPENDER_TAG))
{
if (curAppenderElement.GetAttribute("name") == appenderName)
{
element = curAppenderElement;
break;
}
}
}
if (element == null)
{
LogLog.Error(declaringType, "XmlHierarchyConfigurator: No appender named [" + appenderName + "] could be found.");
return null;
}
else
{
appender = ParseAppender(element);
if (appender != null)
{
m_appenderBag[appenderName] = appender;
}
return appender;
}
}
}
/// <summary>
/// Parses an appender element.
/// </summary>
/// <param name="appenderElement">The appender element.</param>
/// <returns>The appender instance or <c>null</c> when parsing failed.</returns>
/// <remarks>
/// <para>
/// Parse an XML element that represents an appender and return
/// the appender instance.
/// </para>
/// </remarks>
protected IAppender ParseAppender(XmlElement appenderElement)
{
string appenderName = appenderElement.GetAttribute(NAME_ATTR);
string typeName = appenderElement.GetAttribute(TYPE_ATTR);
LogLog.Debug(declaringType, "Loading Appender [" + appenderName + "] type: [" + typeName + "]");
try
{
IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(typeName, true, true));
appender.Name = appenderName;
foreach (XmlNode currentNode in appenderElement.ChildNodes)
{
/* We're only interested in Elements */
if (currentNode.NodeType == XmlNodeType.Element)
{
XmlElement currentElement = (XmlElement)currentNode;
// Look for the appender ref tag
if (currentElement.LocalName == APPENDER_REF_TAG)
{
string refName = currentElement.GetAttribute(REF_ATTR);
IAppenderAttachable appenderContainer = appender as IAppenderAttachable;
if (appenderContainer != null)
{
LogLog.Debug(declaringType, "Attaching appender named [" + refName + "] to appender named [" + appender.Name + "].");
IAppender referencedAppender = FindAppenderByReference(currentElement);
if (referencedAppender != null)
{
appenderContainer.AddAppender(referencedAppender);
}
}
else
{
LogLog.Error(declaringType, "Requesting attachment of appender named ["+refName+ "] to appender named [" + appender.Name + "] which does not implement log4net.Core.IAppenderAttachable.");
}
}
else
{
// For all other tags we use standard set param method
SetParameter(currentElement, appender);
}
}
}
IOptionHandler optionHandler = appender as IOptionHandler;
if (optionHandler != null)
{
optionHandler.ActivateOptions();
}
LogLog.Debug(declaringType, "Created Appender [" + appenderName + "]");
return appender;
}
catch (Exception ex)
{
// Yes, it's ugly. But all exceptions point to the same problem: we can't create an Appender
LogLog.Error(declaringType, "Could not create Appender [" + appenderName + "] of type [" + typeName + "]. Reported error follows.", ex);
return null;
}
}
/// <summary>
/// Parses a logger element.
/// </summary>
/// <param name="loggerElement">The logger element.</param>
/// <remarks>
/// <para>
/// Parse an XML element that represents a logger.
/// </para>
/// </remarks>
protected void ParseLogger(XmlElement loggerElement)
{
// Create a new log4net.Logger object from the <logger> element.
string loggerName = loggerElement.GetAttribute(NAME_ATTR);
LogLog.Debug(declaringType, "Retrieving an instance of log4net.Repository.Logger for logger [" + loggerName + "].");
Logger log = m_hierarchy.GetLogger(loggerName) as Logger;
// Setting up a logger needs to be an atomic operation, in order
// to protect potential log operations while logger
// configuration is in progress.
lock(log)
{
bool additivity = OptionConverter.ToBoolean(loggerElement.GetAttribute(ADDITIVITY_ATTR), true);
LogLog.Debug(declaringType, "Setting [" + log.Name + "] additivity to [" + additivity + "].");
log.Additivity = additivity;
ParseChildrenOfLoggerElement(loggerElement, log, false);
}
}
/// <summary>
/// Parses the root logger element.
/// </summary>
/// <param name="rootElement">The root element.</param>
/// <remarks>
/// <para>
/// Parse an XML element that represents the root logger.
/// </para>
/// </remarks>
protected void ParseRoot(XmlElement rootElement)
{
Logger root = m_hierarchy.Root;
// logger configuration needs to be atomic
lock(root)
{
ParseChildrenOfLoggerElement(rootElement, root, true);
}
}
/// <summary>
/// Parses the children of a logger element.
/// </summary>
/// <param name="catElement">The category element.</param>
/// <param name="log">The logger instance.</param>
/// <param name="isRoot">Flag to indicate if the logger is the root logger.</param>
/// <remarks>
/// <para>
/// Parse the child elements of a <logger> element.
/// </para>
/// </remarks>
protected void ParseChildrenOfLoggerElement(XmlElement catElement, Logger log, bool isRoot)
{
// Remove all existing appenders from log. They will be
// reconstructed if need be.
log.RemoveAllAppenders();
foreach (XmlNode currentNode in catElement.ChildNodes)
{
if (currentNode.NodeType == XmlNodeType.Element)
{
XmlElement currentElement = (XmlElement) currentNode;
if (currentElement.LocalName == APPENDER_REF_TAG)
{
IAppender appender = FindAppenderByReference(currentElement);
string refName = currentElement.GetAttribute(REF_ATTR);
if (appender != null)
{
LogLog.Debug(declaringType, "Adding appender named [" + refName + "] to logger [" + log.Name + "].");
log.AddAppender(appender);
}
else
{
LogLog.Error(declaringType, "Appender named [" + refName + "] not found.");
}
}
else if (currentElement.LocalName == LEVEL_TAG || currentElement.LocalName == PRIORITY_TAG)
{
ParseLevel(currentElement, log, isRoot);
}
else
{
SetParameter(currentElement, log);
}
}
}
IOptionHandler optionHandler = log as IOptionHandler;
if (optionHandler != null)
{
optionHandler.ActivateOptions();
}
}
/// <summary>
/// Parses an object renderer.
/// </summary>
/// <param name="element">The renderer element.</param>
/// <remarks>
/// <para>
/// Parse an XML element that represents a renderer.
/// </para>
/// </remarks>
protected void ParseRenderer(XmlElement element)
{
string renderingClassName = element.GetAttribute(RENDERING_TYPE_ATTR);
string renderedClassName = element.GetAttribute(RENDERED_TYPE_ATTR);
LogLog.Debug(declaringType, "Rendering class [" + renderingClassName + "], Rendered class [" + renderedClassName + "].");
IObjectRenderer renderer = (IObjectRenderer)OptionConverter.InstantiateByClassName(renderingClassName, typeof(IObjectRenderer), null);
if (renderer == null)
{
LogLog.Error(declaringType, "Could not instantiate renderer [" + renderingClassName + "].");
return;
}
else
{
try
{
m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(renderedClassName, true, true), renderer);
}
catch(Exception e)
{
LogLog.Error(declaringType, "Could not find class [" + renderedClassName + "].", e);
}
}
}
/// <summary>
/// Parses a level element.
/// </summary>
/// <param name="element">The level element.</param>
/// <param name="log">The logger object to set the level on.</param>
/// <param name="isRoot">Flag to indicate if the logger is the root logger.</param>
/// <remarks>
/// <para>
/// Parse an XML element that represents a level.
/// </para>
/// </remarks>
protected void ParseLevel(XmlElement element, Logger log, bool isRoot)
{
string loggerName = log.Name;
if (isRoot)
{
loggerName = "root";
}
string levelStr = element.GetAttribute(VALUE_ATTR);
LogLog.Debug(declaringType, "Logger [" + loggerName + "] Level string is [" + levelStr + "].");
if (INHERITED == levelStr)
{
if (isRoot)
{
LogLog.Error(declaringType, "Root level cannot be inherited. Ignoring directive.");
}
else
{
LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to inherit from parent.");
log.Level = null;
}
}
else
{
log.Level = log.Hierarchy.LevelMap[levelStr];
if (log.Level == null)
{
LogLog.Error(declaringType, "Undefined level [" + levelStr + "] on Logger [" + loggerName + "].");
}
else
{
LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to [name=\"" + log.Level.Name + "\",value=" + log.Level.Value + "].");
}
}
}
/// <summary>
/// Sets a parameter on an object.
/// </summary>
/// <param name="element">The parameter element.</param>
/// <param name="target">The object to set the parameter on.</param>
/// <remarks>
/// The parameter name must correspond to a writable property
/// on the object. The value of the parameter is a string,
/// therefore this function will attempt to set a string
/// property first. If unable to set a string property it
/// will inspect the property and its argument type. It will
/// attempt to call a static method called <c>Parse</c> on the
/// type of the property. This method will take a single
/// string argument and return a value that can be used to
/// set the property.
/// </remarks>
protected void SetParameter(XmlElement element, object target)
{
// Get the property name
string name = element.GetAttribute(NAME_ATTR);
// If the name attribute does not exist then use the name of the element
if (element.LocalName != PARAM_TAG || name == null || name.Length == 0)
{
name = element.LocalName;
}
// Look for the property on the target object
Type targetType = target.GetType();
Type propertyType = null;
PropertyInfo propInfo = null;
MethodInfo methInfo = null;
// Try to find a writable property
propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
if (propInfo != null && propInfo.CanWrite)
{
// found a property
propertyType = propInfo.PropertyType;
}
else
{
propInfo = null;
// look for a method with the signature Add<property>(type)
methInfo = FindMethodInfo(targetType, name);
if (methInfo != null)
{
propertyType = methInfo.GetParameters()[0].ParameterType;
}
}
if (propertyType == null)
{
LogLog.Error(declaringType, "XmlHierarchyConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]");
}
else
{
string propertyValue = null;
if (element.GetAttributeNode(VALUE_ATTR) != null)
{
propertyValue = element.GetAttribute(VALUE_ATTR);
}
else if (element.HasChildNodes)
{
// Concatenate the CDATA and Text nodes together
foreach(XmlNode childNode in element.ChildNodes)
{
if (childNode.NodeType == XmlNodeType.CDATA || childNode.NodeType == XmlNodeType.Text)
{
if (propertyValue == null)
{
propertyValue = childNode.InnerText;
}
else
{
propertyValue += childNode.InnerText;
}
}
}
}
if(propertyValue != null)
{
#if !NETCF
try
{
// Expand environment variables in the string.
IDictionary environmentVariables = Environment.GetEnvironmentVariables();
if (HasCaseInsensitiveEnvironment) {
environmentVariables = CreateCaseInsensitiveWrapper(environmentVariables);
}
propertyValue = OptionConverter.SubstituteVariables(propertyValue, environmentVariables);
}
catch(System.Security.SecurityException)
{
// This security exception will occur if the caller does not have
// unrestricted environment permission. If this occurs the expansion
// will be skipped with the following warning message.
LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion.");
}
#endif
Type parsedObjectConversionTargetType = null;
// Check if a specific subtype is specified on the element using the 'type' attribute
string subTypeString = element.GetAttribute(TYPE_ATTR);
if (subTypeString != null && subTypeString.Length > 0)
{
// Read the explicit subtype
try
{
Type subType = SystemInfo.GetTypeFromString(subTypeString, true, true);
LogLog.Debug(declaringType, "Parameter ["+name+"] specified subtype ["+subType.FullName+"]");
if (!propertyType.IsAssignableFrom(subType))
{
// Check if there is an appropriate type converter
if (OptionConverter.CanConvertTypeTo(subType, propertyType))
{
// Must re-convert to the real property type
parsedObjectConversionTargetType = propertyType;
// Use sub type as intermediary type
propertyType = subType;
}
else
{
LogLog.Error(declaringType, "subtype ["+subType.FullName+"] set on ["+name+"] is not a subclass of property type ["+propertyType.FullName+"] and there are no acceptable type conversions.");
}
}
else
{
// The subtype specified is found and is actually a subtype of the property
// type, therefore we can switch to using this type.
propertyType = subType;
}
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to find type ["+subTypeString+"] set on ["+name+"]", ex);
}
}
// Now try to convert the string value to an acceptable type
// to pass to this property.
object convertedValue = ConvertStringTo(propertyType, propertyValue);
// Check if we need to do an additional conversion
if (convertedValue != null && parsedObjectConversionTargetType != null)
{
LogLog.Debug(declaringType, "Performing additional conversion of value from [" + convertedValue.GetType().Name + "] to [" + parsedObjectConversionTargetType.Name + "]");
convertedValue = OptionConverter.ConvertTypeTo(convertedValue, parsedObjectConversionTargetType);
}
if (convertedValue != null)
{
if (propInfo != null)
{
// Got a converted result
LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]");
try
{
// Pass to the property
propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
}
catch(TargetInvocationException targetInvocationEx)
{
LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException);
}
}
else if (methInfo != null)
{
// Got a converted result
LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]");
try
{
// Pass to the property
methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] {convertedValue}, CultureInfo.InvariantCulture);
}
catch(TargetInvocationException targetInvocationEx)
{
LogLog.Error(declaringType, "Failed to set parameter [" + name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException);
}
}
}
else
{
LogLog.Warn(declaringType, "Unable to set property [" + name + "] on object [" + target + "] using value [" + propertyValue + "] (with acceptable conversion types)");
}
}
else
{
object createdObject = null;
if (propertyType == typeof(string) && !HasAttributesOrElements(element))
{
// If the property is a string and the element is empty (no attributes
// or child elements) then we special case the object value to an empty string.
// This is necessary because while the String is a class it does not have
// a default constructor that creates an empty string, which is the behavior
// we are trying to simulate and would be expected from CreateObjectFromXml
createdObject = "";
}
else
{
// No value specified
Type defaultObjectType = null;
if (IsTypeConstructible(propertyType))
{
defaultObjectType = propertyType;
}
createdObject = CreateObjectFromXml(element, defaultObjectType, propertyType);
}
if (createdObject == null)
{
LogLog.Error(declaringType, "Failed to create object to set param: "+name);
}
else
{
if (propInfo != null)
{
// Got a converted result
LogLog.Debug(declaringType, "Setting Property ["+ propInfo.Name +"] to object ["+ createdObject +"]");
try
{
// Pass to the property
propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
}
catch(TargetInvocationException targetInvocationEx)
{
LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException);
}
}
else if (methInfo != null)
{
// Got a converted result
LogLog.Debug(declaringType, "Setting Collection Property ["+ methInfo.Name +"] to object ["+ createdObject +"]");
try
{
// Pass to the property
methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] {createdObject}, CultureInfo.InvariantCulture);
}
catch(TargetInvocationException targetInvocationEx)
{
LogLog.Error(declaringType, "Failed to set parameter [" + methInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException);
}
}
}
}
}
}
/// <summary>
/// Test if an element has no attributes or child elements
/// </summary>
/// <param name="element">the element to inspect</param>
/// <returns><c>true</c> if the element has any attributes or child elements, <c>false</c> otherwise</returns>
private bool HasAttributesOrElements(XmlElement element)
{
foreach(XmlNode node in element.ChildNodes)
{
if (node.NodeType == XmlNodeType.Attribute || node.NodeType == XmlNodeType.Element)
{
return true;
}
}
return false;
}
/// <summary>
/// Test if a <see cref="Type"/> is constructible with <c>Activator.CreateInstance</c>.
/// </summary>
/// <param name="type">the type to inspect</param>
/// <returns><c>true</c> if the type is creatable using a default constructor, <c>false</c> otherwise</returns>
private static bool IsTypeConstructible(Type type)
{
if (type.IsClass && !type.IsAbstract)
{
ConstructorInfo defaultConstructor = type.GetConstructor(new Type[0]);
if (defaultConstructor != null && !defaultConstructor.IsAbstract && !defaultConstructor.IsPrivate)
{
return true;
}
}
return false;
}
/// <summary>
/// Look for a method on the <paramref name="targetType"/> that matches the <paramref name="name"/> supplied
/// </summary>
/// <param name="targetType">the type that has the method</param>
/// <param name="name">the name of the method</param>
/// <returns>the method info found</returns>
/// <remarks>
/// <para>
/// The method must be a public instance method on the <paramref name="targetType"/>.
/// The method must be named <paramref name="name"/> or "Add" followed by <paramref name="name"/>.
/// The method must take a single parameter.
/// </para>
/// </remarks>
private MethodInfo FindMethodInfo(Type targetType, string name)
{
string requiredMethodNameA = name;
string requiredMethodNameB = "Add" + name;
MethodInfo[] methods = targetType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach(MethodInfo methInfo in methods)
{
if (!methInfo.IsStatic)
{
if (string.Compare(methInfo.Name, requiredMethodNameA, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ||
string.Compare(methInfo.Name, requiredMethodNameB, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
{
// Found matching method name
// Look for version with one arg only
System.Reflection.ParameterInfo[] methParams = methInfo.GetParameters();
if (methParams.Length == 1)
{
return methInfo;
}
}
}
}
return null;
}
/// <summary>
/// Converts a string value to a target type.
/// </summary>
/// <param name="type">The type of object to convert the string to.</param>
/// <param name="value">The string value to use as the value of the object.</param>
/// <returns>
/// <para>
/// An object of type <paramref name="type"/> with value <paramref name="value"/> or
/// <c>null</c> when the conversion could not be performed.
/// </para>
/// </returns>
protected object ConvertStringTo(Type type, string value)
{
// Hack to allow use of Level in property
if (typeof(Level) == type)
{
// Property wants a level
Level levelValue = m_hierarchy.LevelMap[value];
if (levelValue == null)
{
LogLog.Error(declaringType, "XmlHierarchyConfigurator: Unknown Level Specified ["+ value +"]");
}
return levelValue;
}
return OptionConverter.ConvertStringTo(type, value);
}
/// <summary>
/// Creates an object as specified in XML.
/// </summary>
/// <param name="element">The XML element that contains the definition of the object.</param>
/// <param name="defaultTargetType">The object type to use if not explicitly specified.</param>
/// <param name="typeConstraint">The type that the returned object must be or must inherit from.</param>
/// <returns>The object or <c>null</c></returns>
/// <remarks>
/// <para>
/// Parse an XML element and create an object instance based on the configuration
/// data.
/// </para>
/// <para>
/// The type of the instance may be specified in the XML. If not
/// specified then the <paramref name="defaultTargetType"/> is used
/// as the type. However the type is specified it must support the
/// <paramref name="typeConstraint"/> type.
/// </para>
/// </remarks>
protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
{
Type objectType = null;
// Get the object type
string objectTypeString = element.GetAttribute(TYPE_ATTR);
if (objectTypeString == null || objectTypeString.Length == 0)
{
if (defaultTargetType == null)
{
LogLog.Error(declaringType, "Object type not specified. Cannot create object of type ["+typeConstraint.FullName+"]. Missing Value or Type.");
return null;
}
else
{
// Use the default object type
objectType = defaultTargetType;
}
}
else
{
// Read the explicit object type
try
{
objectType = SystemInfo.GetTypeFromString(objectTypeString, true, true);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to find type ["+objectTypeString+"]", ex);
return null;
}
}
bool requiresConversion = false;
// Got the object type. Check that it meets the typeConstraint
if (typeConstraint != null)
{
if (!typeConstraint.IsAssignableFrom(objectType))
{
// Check if there is an appropriate type converter
if (OptionConverter.CanConvertTypeTo(objectType, typeConstraint))
{
requiresConversion = true;
}
else
{
LogLog.Error(declaringType, "Object type ["+objectType.FullName+"] is not assignable to type ["+typeConstraint.FullName+"]. There are no acceptable type conversions.");
return null;
}
}
}
// Create using the default constructor
object createdObject = null;
try
{
createdObject = Activator.CreateInstance(objectType);
}
catch(Exception createInstanceEx)
{
LogLog.Error(declaringType, "XmlHierarchyConfigurator: Failed to construct object of type [" + objectType.FullName + "] Exception: "+createInstanceEx.ToString());
}
// Set any params on object
foreach (XmlNode currentNode in element.ChildNodes)
{
if (currentNode.NodeType == XmlNodeType.Element)
{
SetParameter((XmlElement)currentNode, createdObject);
}
}
// Check if we need to call ActivateOptions
IOptionHandler optionHandler = createdObject as IOptionHandler;
if (optionHandler != null)
{
optionHandler.ActivateOptions();
}
// Ok object should be initialized
if (requiresConversion)
{
// Convert the object type
return OptionConverter.ConvertTypeTo(createdObject, typeConstraint);
}
else
{
// The object is of the correct type
return createdObject;
}
}
#endregion Protected Instance Methods
#if !NETCF
private bool HasCaseInsensitiveEnvironment
{
get
{
#if NET_1_0 || NET_1_1 || CLI_1_0
// actually there is no guarantee, but we don't know better
return true;
#elif MONO_1_0
// see above
return false;
#else
PlatformID platform = Environment.OSVersion.Platform;
return platform != PlatformID.Unix && platform != PlatformID.MacOSX;
#endif
}
}
private IDictionary CreateCaseInsensitiveWrapper(IDictionary dict)
{
if (dict == null)
{
return dict;
}
Hashtable hash = SystemInfo.CreateCaseInsensitiveHashtable();
foreach (DictionaryEntry entry in dict) {
hash[entry.Key] = entry.Value;
}
return hash;
}
#endif
#region Private Constants
// String constants used while parsing the XML data
private const string CONFIGURATION_TAG = "log4net";
private const string RENDERER_TAG = "renderer";
private const string APPENDER_TAG = "appender";
private const string APPENDER_REF_TAG = "appender-ref";
private const string PARAM_TAG = "param";
// TODO: Deprecate use of category tags
private const string CATEGORY_TAG = "category";
// TODO: Deprecate use of priority tag
private const string PRIORITY_TAG = "priority";
private const string LOGGER_TAG = "logger";
private const string NAME_ATTR = "name";
private const string TYPE_ATTR = "type";
private const string VALUE_ATTR = "value";
private const string ROOT_TAG = "root";
private const string LEVEL_TAG = "level";
private const string REF_ATTR = "ref";
private const string ADDITIVITY_ATTR = "additivity";
private const string THRESHOLD_ATTR = "threshold";
private const string CONFIG_DEBUG_ATTR = "configDebug";
private const string INTERNAL_DEBUG_ATTR = "debug";
private const string EMIT_INTERNAL_DEBUG_ATTR = "emitDebug";
private const string CONFIG_UPDATE_MODE_ATTR = "update";
private const string RENDERING_TYPE_ATTR = "renderingClass";
private const string RENDERED_TYPE_ATTR = "renderedClass";
// flag used on the level element
private const string INHERITED = "inherited";
#endregion Private Constants
#region Private Instance Fields
/// <summary>
/// key: appenderName, value: appender.
/// </summary>
private Hashtable m_appenderBag;
/// <summary>
/// The Hierarchy being configured.
/// </summary>
private readonly Hierarchy m_hierarchy;
#endregion Private Instance Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the XmlHierarchyConfigurator class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(XmlHierarchyConfigurator);
#endregion Private Static Fields
}
}
#endif
| |
//
// ModuleDescription.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Specialized;
using Mono.Addins.Serialization;
namespace Mono.Addins.Description
{
/// <summary>
/// A module definition.
/// </summary>
/// <remarks>
/// Optional modules can be used to declare extensions which will be registered only if some
/// specified add-in dependencies can be satisfied.
/// </remarks>
public class ModuleDescription: ObjectDescription
{
StringCollection assemblies;
StringCollection dataFiles;
StringCollection ignorePaths;
DependencyCollection dependencies;
ExtensionCollection extensions;
// Used only at run time
internal RuntimeAddin RuntimeAddin;
internal ModuleDescription (XmlElement element)
{
Element = element;
}
/// <summary>
/// Initializes a new instance of the <see cref="Mono.Addins.Description.ModuleDescription"/> class.
/// </summary>
public ModuleDescription ()
{
}
/// <summary>
/// Checks if this module depends on the specified add-in.
/// </summary>
/// <returns>
/// <c>true</c> if there is a dependency.
/// </returns>
/// <param name='addinId'>
/// Identifier of the add-in
/// </param>
public bool DependsOnAddin (string addinId)
{
AddinDescription desc = Parent as AddinDescription;
if (desc == null)
throw new InvalidOperationException ();
foreach (Dependency dep in Dependencies) {
AddinDependency adep = dep as AddinDependency;
if (adep == null) continue;
if (Addin.GetFullId (desc.Namespace, adep.AddinId, adep.Version) == addinId)
return true;
}
return false;
}
/// <summary>
/// Gets the list of paths to be ignored by the add-in scanner.
/// </summary>
public StringCollection IgnorePaths {
get {
if (ignorePaths == null)
ignorePaths = new StringCollection ();
return ignorePaths;
}
}
/// <summary>
/// Gets all external files
/// </summary>
/// <value>
/// All files.
/// </value>
/// <remarks>
/// External files are data files and assemblies explicitly referenced in the Runtime section of the add-in manifest.
/// </remarks>
public StringCollection AllFiles {
get {
StringCollection col = new StringCollection ();
foreach (string s in Assemblies)
col.Add (s);
foreach (string d in DataFiles)
col.Add (d);
return col;
}
}
/// <summary>
/// Gets the list of external assemblies used by this module.
/// </summary>
public StringCollection Assemblies {
get {
if (assemblies == null) {
if (Element != null)
InitCollections ();
else
assemblies = new StringCollection ();
}
return assemblies;
}
}
/// <summary>
/// Gets the list of external data files used by this module
/// </summary>
public StringCollection DataFiles {
get {
if (dataFiles == null) {
if (Element != null)
InitCollections ();
else
dataFiles = new StringCollection ();
}
return dataFiles;
}
}
/// <summary>
/// Gets the dependencies of this module
/// </summary>
public DependencyCollection Dependencies {
get {
if (dependencies == null) {
dependencies = new DependencyCollection (this);
if (Element != null) {
XmlNodeList elems = Element.SelectNodes ("Dependencies/*");
foreach (XmlNode node in elems) {
XmlElement elem = node as XmlElement;
if (elem == null) continue;
if (elem.Name == "Addin") {
AddinDependency dep = new AddinDependency (elem);
dependencies.Add (dep);
} else if (elem.Name == "Assembly") {
AssemblyDependency dep = new AssemblyDependency (elem);
dependencies.Add (dep);
}
}
}
}
return dependencies;
}
}
/// <summary>
/// Gets the extensions of this module
/// </summary>
public ExtensionCollection Extensions {
get {
if (extensions == null) {
extensions = new ExtensionCollection (this);
if (Element != null) {
foreach (XmlElement elem in Element.SelectNodes ("Extension"))
extensions.Add (new Extension (elem));
}
}
return extensions;
}
}
/// <summary>
/// Adds an extension node to the module.
/// </summary>
/// <returns>
/// The extension node.
/// </returns>
/// <param name='path'>
/// Path that identifies the extension point.
/// </param>
/// <param name='nodeName'>
/// Node name.
/// </param>
/// <remarks>
/// This method creates a new Extension object for the provided path if none exist.
/// </remarks>
public ExtensionNodeDescription AddExtensionNode (string path, string nodeName)
{
ExtensionNodeDescription node = new ExtensionNodeDescription (nodeName);
GetExtension (path).ExtensionNodes.Add (node);
return node;
}
/// <summary>
/// Gets an extension instance.
/// </summary>
/// <returns>
/// The extension instance.
/// </returns>
/// <param name='path'>
/// Path that identifies the extension point that the extension extends.
/// </param>
/// <remarks>
/// This method creates a new Extension object for the provided path if none exist.
/// </remarks>
public Extension GetExtension (string path)
{
foreach (Extension e in Extensions) {
if (e.Path == path)
return e;
}
Extension ex = new Extension (path);
Extensions.Add (ex);
return ex;
}
internal override void SaveXml (XmlElement parent)
{
CreateElement (parent, "Module");
if (assemblies != null || dataFiles != null || ignorePaths != null) {
XmlElement runtime = GetRuntimeElement ();
while (runtime.FirstChild != null)
runtime.RemoveChild (runtime.FirstChild);
if (assemblies != null) {
foreach (string s in assemblies) {
XmlElement asm = Element.OwnerDocument.CreateElement ("Import");
asm.SetAttribute ("assembly", s);
runtime.AppendChild (asm);
}
}
if (dataFiles != null) {
foreach (string s in dataFiles) {
XmlElement asm = Element.OwnerDocument.CreateElement ("Import");
asm.SetAttribute ("file", s);
runtime.AppendChild (asm);
}
}
if (ignorePaths != null) {
foreach (string s in ignorePaths) {
XmlElement asm = Element.OwnerDocument.CreateElement ("ScanExclude");
asm.SetAttribute ("path", s);
runtime.AppendChild (asm);
}
}
runtime.AppendChild (Element.OwnerDocument.CreateTextNode ("\n"));
}
// Save dependency information
if (dependencies != null) {
XmlElement deps = GetDependenciesElement ();
dependencies.SaveXml (deps);
deps.AppendChild (Element.OwnerDocument.CreateTextNode ("\n"));
if (extensions != null)
extensions.SaveXml (Element);
}
}
/// <summary>
/// Adds an add-in reference (there is a typo in the method name)
/// </summary>
/// <param name='id'>
/// Identifier of the add-in.
/// </param>
/// <param name='version'>
/// Version of the add-in.
/// </param>
public void AddAssemblyReference (string id, string version)
{
XmlElement deps = GetDependenciesElement ();
if (deps.SelectSingleNode ("Addin[@id='" + id + "']") != null)
return;
XmlElement dep = Element.OwnerDocument.CreateElement ("Addin");
dep.SetAttribute ("id", id);
dep.SetAttribute ("version", version);
deps.AppendChild (dep);
}
XmlElement GetDependenciesElement ()
{
XmlElement de = Element ["Dependencies"];
if (de != null)
return de;
de = Element.OwnerDocument.CreateElement ("Dependencies");
Element.AppendChild (de);
return de;
}
XmlElement GetRuntimeElement ()
{
XmlElement de = Element ["Runtime"];
if (de != null)
return de;
de = Element.OwnerDocument.CreateElement ("Runtime");
Element.AppendChild (de);
return de;
}
void InitCollections ()
{
dataFiles = new StringCollection ();
assemblies = new StringCollection ();
XmlNodeList elems = Element.SelectNodes ("Runtime/*");
foreach (XmlElement elem in elems) {
if (elem.LocalName == "Import") {
string asm = elem.GetAttribute ("assembly");
if (asm.Length > 0) {
assemblies.Add (asm);
} else {
string file = elem.GetAttribute ("file");
if (file.Length > 0)
dataFiles.Add (file);
}
} else if (elem.LocalName == "ScanExclude") {
string path = elem.GetAttribute ("path");
if (path.Length > 0)
IgnorePaths.Add (path);
}
}
}
internal override void Verify (string location, StringCollection errors)
{
Dependencies.Verify (location + "Module/", errors);
Extensions.Verify (location + "Module/", errors);
}
internal override void Write (BinaryXmlWriter writer)
{
writer.WriteValue ("Assemblies", Assemblies);
writer.WriteValue ("DataFiles", DataFiles);
writer.WriteValue ("Dependencies", Dependencies);
writer.WriteValue ("Extensions", Extensions);
writer.WriteValue ("IgnorePaths", ignorePaths);
}
internal override void Read (BinaryXmlReader reader)
{
assemblies = (StringCollection) reader.ReadValue ("Assemblies", new StringCollection ());
dataFiles = (StringCollection) reader.ReadValue ("DataFiles", new StringCollection ());
dependencies = (DependencyCollection) reader.ReadValue ("Dependencies", new DependencyCollection (this));
extensions = (ExtensionCollection) reader.ReadValue ("Extensions", new ExtensionCollection (this));
ignorePaths = (StringCollection) reader.ReadValue ("IgnorePaths", new StringCollection ());
}
}
}
| |
// 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 Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata;
using Xunit;
using Resources = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.Resources;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class WinMdTests : ExpressionCompilerTestBase
{
/// <summary>
/// Handle runtime assemblies rather than Windows.winmd
/// (compile-time assembly) since those are the assemblies
/// loaded in the debuggee.
/// </summary>
[WorkItem(981104)]
[ConditionalFact(typeof(OSVersionWin8))]
public void Win8RuntimeAssemblies()
{
var source =
@"class C
{
static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p)
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: WinRtRefs);
var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections");
Assert.True(runtimeAssemblies.Length >= 2);
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
var runtime = CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd
exeBytes,
new SymReader(pdbBytes));
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression("(p == null) ? f : null", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0005
IL_0003: ldnull
IL_0004: ret
IL_0005: ldarg.0
IL_0006: ret
}");
}
[ConditionalFact(typeof(OSVersionWin8))]
public void Win8RuntimeAssemblies_ExternAlias()
{
var source =
@"extern alias X;
class C
{
static void M(X::Windows.Storage.StorageFolder f)
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r));
var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage");
Assert.True(runtimeAssemblies.Length >= 1);
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
var runtime = CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd
exeBytes,
new SymReader(pdbBytes));
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}");
}
[Fact]
public void Win8OnWin8()
{
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows.Storage");
}
[Fact]
public void Win8OnWin10()
{
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows.Storage");
}
[WorkItem(1108135)]
[Fact]
public void Win10OnWin10()
{
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows");
}
private void CompileTimeAndRuntimeAssemblies(
ImmutableArray<MetadataReference> compileReferences,
ImmutableArray<MetadataReference> runtimeReferences,
string storageAssemblyName)
{
var source =
@"class C
{
static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f)
{
}
}";
var runtime = CreateRuntime(source, compileReferences, runtimeReferences);
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0010
IL_0004: pop
IL_0005: ldarg.1
IL_0006: dup
IL_0007: brtrue.s IL_0010
IL_0009: pop
IL_000a: ldarg.2
IL_000b: dup
IL_000c: brtrue.s IL_0010
IL_000e: pop
IL_000f: ldarg.3
IL_0010: ret
}");
testData = new CompilationTestData();
var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out error, testData);
Assert.Null(error);
var methodData = testData.GetMethodData("<>x.<>m0");
methodData.VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}");
// Check return type is from runtime assembly.
var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference();
var compilation = CSharpCompilation.Create(
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: runtimeReferences.Concat(ImmutableArray.Create<MetadataReference>(assemblyReference)));
var assembly = ImmutableArray.CreateRange(result.Assembly);
using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly)))
{
var reader = metadata.MetadataReader;
var typeDef = reader.GetTypeDef("<>x");
var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0");
var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule;
var metadataDecoder = new MetadataDecoder(module);
SignatureHeader signatureHeader;
BadImageFormatException metadataException;
var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException);
Assert.Equal(parameters.Length, 5);
var actualReturnType = parameters[0].Type;
Assert.Equal(actualReturnType.TypeKind, TypeKind.Class); // not error
var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder");
Assert.Equal(expectedReturnType, actualReturnType);
Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name);
}
}
/// <summary>
/// Assembly-qualified name containing "ContentType=WindowsRuntime",
/// and referencing runtime assembly.
/// </summary>
[WorkItem(1116143)]
[ConditionalFact(typeof(OSVersionWin8))]
public void AssemblyQualifiedName()
{
var source =
@"class C
{
static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p)
{
}
}";
var runtime = CreateRuntime(
source,
ImmutableArray.CreateRange(WinRtRefs),
ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")));
var context = CreateMethodContext(
runtime,
"C.M");
var aliases = ImmutableArray.Create(
VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"),
VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"));
string error;
var testData = new CompilationTestData();
context.CompileExpression(
"(object)s.Attributes ?? d.UniversalTime",
DkmEvaluationFlags.TreatAsExpression,
aliases,
out error,
testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldstr ""s""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: castclass ""Windows.Storage.StorageFolder""
IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get""
IL_0014: box ""Windows.Storage.FileAttributes""
IL_0019: dup
IL_001a: brtrue.s IL_0036
IL_001c: pop
IL_001d: ldstr ""d""
IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_0027: unbox.any ""Windows.Foundation.DateTime""
IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime""
IL_0031: box ""long""
IL_0036: ret
}");
}
[WorkItem(1117084)]
[Fact(Skip = "1114866")]
public void OtherFrameworkAssembly()
{
var source =
@"class C
{
static void M(Windows.UI.Xaml.FrameworkElement f)
{
}
}";
var runtime = CreateRuntime(
source,
ImmutableArray.CreateRange(WinRtRefs),
ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml")));
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression(
"f.RenderSize",
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
out error,
testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldstr ""s""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: castclass ""Windows.Storage.StorageFolder""
IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get""
IL_0014: box ""Windows.Storage.FileAttributes""
IL_0019: dup
IL_001a: brtrue.s IL_0036
IL_001c: pop
IL_001d: ldstr ""d""
IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_0027: unbox.any ""Windows.Foundation.DateTime""
IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime""
IL_0031: box ""long""
IL_0036: ret
}");
}
[WorkItem(1154988)]
[ConditionalFact(typeof(OSVersionWin8))]
public void WinMdAssemblyReferenceRequiresRedirect()
{
var source =
@"class C : Windows.UI.Xaml.Controls.UserControl
{
static void M(C c)
{
}
}";
var runtime = CreateRuntime(source,
ImmutableArray.Create(WinRtRefs),
ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI", "Windows.UI.Xaml")));
string errorMessage;
var testData = new CompilationTestData();
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
runtime.Modules.SelectAsArray(m => m.MetadataBlock),
"c.Dispatcher",
(metadataBlocks, _) =>
{
return CreateMethodContext(runtime, "C.M");
},
(AssemblyIdentity assembly, out uint size) =>
{
// Compilation should succeed without retry if we redirect assembly refs correctly.
// Throwing so that we don't loop forever (as we did before fix)...
throw ExceptionUtilities.Unreachable;
},
out errorMessage,
out testData);
Assert.Null(errorMessage);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: callvirt ""Windows.UI.Core.CoreDispatcher Windows.UI.Xaml.DependencyObject.Dispatcher.get""
IL_0006: ret
}");
}
private RuntimeInstance CreateRuntime(
string source,
ImmutableArray<MetadataReference> compileReferences,
ImmutableArray<MetadataReference> runtimeReferences)
{
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: compileReferences);
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
return CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
runtimeReferences.AddIntrinsicAssembly(),
exeBytes,
new SymReader(pdbBytes));
}
private static byte[] ToVersion1_3(byte[] bytes)
{
return ExpressionCompilerTestHelpers.ToVersion1_3(bytes);
}
private static byte[] ToVersion1_4(byte[] bytes)
{
return ExpressionCompilerTestHelpers.ToVersion1_4(bytes);
}
}
}
| |
/****************************************************************************
* Class Name : ErrorWarnInfoProvider.cs
* Author : Kenneth J. Koteles
* Created : 10/04/2007 2:14 PM
* C# Version : .NET 2.0
* Description : This code is designed to create a new provider object to
* work specifically with CSLA BusinessBase objects. In
* addition to providing the red error icon for items in the
* BrokenRulesCollection with Csla.Validation.RuleSeverity.Error,
* this object also provides a yellow warning icon for items
* with Csla.Validation.RuleSeverity.Warning and a blue
* information icon for items with
* Csla.Validation.RuleSeverity.Information. Since warnings
* and information type items do not need to be fixed /
* corrected prior to the object being saved, the tooltip
* displayed when hovering over the respective icon contains
* all the control's associated (by severity) broken rules.
* Revised : 11/20/2007 8:32 AM
* Change : Warning and information icons were not being updated for
* dependant properties (controls without the focus) when
* changes were being made to a related property (control with
* the focus). Added a list of controls to be recursed
* through each time a change was made to any control. This
* obviously could result in performance issues; however,
* there is no consistent way to question the BusinessObject
* in order to get a list of dependant properties based on a
* property name. It can be exposed to the UI (using
* ValidationRules.GetRuleDescriptions()); however, it is up
* to each developer to implement their own public method on
* on the Business Object to do so. To make this generic for
* all CSLA Business Objects, I cannot assume the developer
* always exposes the dependant properties (nor do I know what
* they'll call the method); therefore, this is the best I can
* do right now.
* Revised : 11/23/2007 9:02 AM
* Change : Added new property ProcessDependantProperties to allow for
* controlling when all controls are recursed through (for
* dependant properties or not). Default value is 'false'.
* This allows the developer to ba able to choose whether or
* not to use the control in this manner (which could have
* performance implications).
****************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
namespace Example.Utility
{
/// <summary>
/// Windows Forms extender control that automatically
/// displays error, warning, or information icons and
/// text for the form controls based on the
/// BrokenRulesCollection from a CSLA .NET business object.
/// </summary>
[DesignerCategory("")]
[ToolboxItem(true), ToolboxBitmap(typeof(ErrorWarnInfoProvider), "Cascade.ico")]
public partial class ErrorWarnInfoProvider : System.Windows.Forms.ErrorProvider, IExtenderProvider
{
private int _blinkRateInformation;
private int _blinkRateWarning;
private ErrorBlinkStyle _blinkStyleInformation = ErrorBlinkStyle.BlinkIfDifferentError;
private ErrorBlinkStyle _blinkStyleWarning = ErrorBlinkStyle.BlinkIfDifferentError;
private IContainer _container;
private List<Control> _controls = new List<Control>();
private object _dataSource;
private const int _defaultBlinkRateInformation = 250;
private const int _defaultBlinkRateWarning = 250;
private static Icon _defaultIconInformation;
private static Icon _defaultIconWarning;
private Icon _iconInformation;
private Icon _iconWarning;
private int _offsetInformation = 32;
private int _offsetWarning = 16;
private ContainerControl _parentControl;
private bool _processDependantProperties = false;
private EventHandler _propChangedEvent;
private bool _visibleInformation = true;
private bool _visibleWarning = true;
/// <summary>
/// Creates an instance of the object.
/// </summary>
/// <param name="container">The container of the control.</param>
public ErrorWarnInfoProvider(IContainer container)
{
container.Add(this);
this._container = container;
InitializeComponent();
this._propChangedEvent = new EventHandler(this.ParentControl_BindingContextChanged);
this._blinkRateInformation = _defaultBlinkRateInformation;
this._iconInformation = DefaultIconInformation;
this.errorProviderInfo.BlinkRate = this._blinkRateInformation;
this.errorProviderInfo.Icon = this._iconInformation;
this._blinkRateWarning = _defaultBlinkRateWarning;
this._iconWarning = DefaultIconWarning;
this.errorProviderWarn.BlinkRate = this._blinkRateWarning;
this.errorProviderWarn.Icon = _iconWarning;
}
#region IExtenderProvider Members
/// <summary>
/// Gets a value indicating whether the extender control
/// can extend the specified control.
/// </summary>
/// <param name="extendee">The control to be extended.</param>
/// <remarks>
/// Any control implementing either a ReadOnly property or
/// Enabled property can be extended.
/// </remarks>
bool IExtenderProvider.CanExtend(object extendee)
{
//if (extendee is ErrorProvider)
//{
// return true;
//}
if ((extendee is Control && !( extendee is Form)))
{
return !( extendee is ToolBar);
}
else
{
return false;
}
}
#endregion
[DefaultValue(_defaultBlinkRateInformation), Description("The rate in milliseconds at which the information icon blinks.")]
public int BlinkRateInformation
{
get
{
return this._blinkRateInformation;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("BlinkRateInformation", value, "Blink rate must be zero or more");
}
this._blinkRateInformation = value;
this.errorProviderInfo.BlinkRate = this._blinkRateInformation;
if (this._blinkRateInformation == 0)
{
this.BlinkStyleInformation = ErrorBlinkStyle.NeverBlink;
}
}
}
[DefaultValue(_defaultBlinkRateWarning), Description("The rate in milliseconds at which the warning icon blinks.")]
public int BlinkRateWarning
{
get
{
return this._blinkRateWarning;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("BlinkRateWarning", value, "Blink rate must be zero or more");
}
this._blinkRateWarning = value;
this.errorProviderWarn.BlinkRate = this._blinkRateWarning;
if (this._blinkRateWarning == 0)
{
this.BlinkStyleWarning = ErrorBlinkStyle.NeverBlink;
}
}
}
[Description("Controls whether the information icon blinks when information is set.")]
public ErrorBlinkStyle BlinkStyleInformation
{
get
{
if (this._blinkRateInformation == 0)
{
return ErrorBlinkStyle.NeverBlink;
}
return this._blinkStyleInformation;
}
set
{
if (this._blinkRateInformation == 0)
{
value = ErrorBlinkStyle.NeverBlink;
}
if (this._blinkStyleInformation != value)
{
this._blinkStyleInformation = value;
this.errorProviderInfo.BlinkStyle = this._blinkStyleInformation;
}
}
}
[Description("Controls whether the warning icon blinks when a warning is set.")]
public ErrorBlinkStyle BlinkStyleWarning
{
get
{
if (this._blinkRateWarning == 0)
{
return ErrorBlinkStyle.NeverBlink;
}
return this._blinkStyleWarning;
}
set
{
if (this._blinkRateWarning == 0)
{
value = ErrorBlinkStyle.NeverBlink;
}
if (this._blinkStyleWarning != value)
{
this._blinkStyleWarning = value;
this.errorProviderWarn.BlinkStyle = this._blinkStyleWarning;
}
}
}
public new void Clear()
{
base.Clear();
this.errorProviderInfo.Clear();
this.errorProviderWarn.Clear();
}
[DefaultValue((string)null)]
public new object DataSource
{
get
{
return this._dataSource;
}
set
{
if (value != null && this._dataSource != value)
{
this._dataSource = value;
base.DataSource = value;
this._parentControl = this.ContainerControl;
this._parentControl.BindingContextChanged += this._propChangedEvent;
// This was added to ensure warnings and info messages get
// cleared when the DataSource of the BindingSource is changed
foreach (IComponent component in this._container.Components)
{
if (component is BindingSource)
{
BindingSource bs = (BindingSource)component;
if (bs == this._dataSource)
{
bs.DataSourceChanged += this.DataSourceChanged_Event;
}
}
}
}
}
}
private void DataSourceChanged_Event(object sender, EventArgs e)
{
this.errorProviderInfo.Clear();
this.errorProviderWarn.Clear();
//When DataSource changed, clear control list
this._controls.Clear();
}
private Icon DefaultIconInformation
{
get
{
if (_defaultIconInformation == null)
{
lock (typeof(ErrorWarnInfoProvider))
{
if (_defaultIconInformation == null)
{
Bitmap bitmap = (Bitmap)this.imageList1.Images[2];
_defaultIconInformation = Icon.FromHandle(bitmap.GetHicon());
}
}
}
return _defaultIconInformation;
}
}
private Icon DefaultIconWarning
{
get
{
if (_defaultIconWarning == null)
{
lock (typeof(ErrorWarnInfoProvider))
{
if (_defaultIconWarning == null)
{
Bitmap bitmap = (Bitmap)this.imageList1.Images[1];
_defaultIconWarning = Icon.FromHandle(bitmap.GetHicon());
}
}
}
return _defaultIconWarning;
}
}
public string GetInformation(Control control)
{
return this.errorProviderInfo.GetError(control);
}
public string GetWarning(Control control)
{
return this.errorProviderWarn.GetError(control);
}
[Description("The icon used to indicate information.")]
public Icon IconInformation
{
get
{
return this._iconInformation;
}
set
{
if (value == null)
{
value = DefaultIconInformation;
}
this._iconInformation = value;
this.errorProviderInfo.Icon = this._iconInformation;
}
}
[Description("The icon used to indicate a warning.")]
public Icon IconWarning
{
get
{
return this._iconWarning;
}
set
{
if (value == null)
{
value = DefaultIconWarning;
}
this._iconWarning = value;
this.errorProviderWarn.Icon = this._iconWarning;
}
}
private void Initialize(Control.ControlCollection controls)
{
//We don't provide an extended property, so if the control is
// not a Label then 'hook' the validating event here!
foreach (Control control in controls)
{
if (control is Label)
{
}
else if (control.Controls.Count > 0)
{
Initialize(control.Controls);
}
else
{
foreach (Binding binding in control.DataBindings)
{
// get the Binding if appropriate
if (binding.DataSource == this.DataSource)
{
if (binding.DataSourceUpdateMode == DataSourceUpdateMode.OnPropertyChanged)
{
control.KeyUp += this.Validation_Event;
//Add 'involved' control to control list
_controls.Add(control);
}
else if (binding.DataSourceUpdateMode == DataSourceUpdateMode.OnValidation)
{
control.Validated += this.Validation_Event;
//Add 'involved' control to control list
_controls.Add(control);
}
}
}
}
}
}
[DefaultValue(32), Description("The number of pixels the information icon will be offset from the error icon.")]
public int OffsetInformation
{
get
{
return this._offsetInformation;
}
set
{
if (this._offsetInformation != value)
{
this._offsetInformation = value;
}
}
}
[DefaultValue(16), Description("The number of pixels the warning icon will be offset from the error icon.")]
public int OffsetWarning
{
get
{
return this._offsetWarning;
}
set
{
if (this._offsetWarning != value)
{
this._offsetWarning = value;
}
}
}
private void ParentControl_BindingContextChanged(object sender, EventArgs e)
{
Initialize(this._parentControl.Controls);
}
private void ProcessControl(Control control)
{
foreach (Binding binding in control.DataBindings)
{
// get the Binding if appropriate
if (binding.DataSource == this.DataSource)
{
BindingSource bs =
(BindingSource)binding.DataSource;
// we can only deal with CSLA BusinessBase objects
if (bs.Current is Csla.Core.BusinessBase)
{
// get the BusinessBase object
Csla.Core.BusinessBase bb = bs.Current as Csla.Core.BusinessBase;
if (bb != null)
{
// get the object property name
string propertyName =
binding.BindingMemberInfo.BindingField;
//The errors are taking care of themselves in the base
//ErrorProvider - all we need to worry about are the
//Warnings and Information messages
StringBuilder warn = new StringBuilder();
StringBuilder info = new StringBuilder();
bool bError = false;
bool bWarn = false;
foreach (Csla.Validation.BrokenRule br in bb.BrokenRulesCollection)
{
if (br.Property == propertyName)
{
if (this._visibleWarning == true &&
br.Severity == Csla.Validation.RuleSeverity.Warning)
{
warn.AppendLine(br.Description);
bWarn = true;
}
else if (this._visibleInformation == true &&
br.Severity == Csla.Validation.RuleSeverity.Information)
{
info.AppendLine(br.Description);
}
else if (bError == false && br.Severity == Csla.Validation.RuleSeverity.Error)
{
bError = true;
}
}
}
int offsetInformation = this._offsetInformation;
int offsetWarning = this._offsetWarning;
// Set / fix offsets
if (bError == false && bWarn == false)
{
offsetInformation = 0;
}
else if (bError == true && bWarn == false)
{
offsetInformation = this._offsetInformation - this._offsetWarning;
}
else if (bError == false && bWarn == true)
{
offsetInformation = this._offsetInformation - this._offsetWarning;
offsetWarning = 0;
}
if (this._visibleWarning == true && warn.Length > 0)
{
this.errorProviderWarn.SetError(binding.Control,
warn.ToString().Substring(0,
warn.ToString().Length -
2));
this.errorProviderWarn.SetIconPadding(binding.Control,
base.GetIconPadding(binding.Control) +
offsetWarning);
this.errorProviderWarn.SetIconAlignment(binding.Control,
base.GetIconAlignment(binding.Control));
}
else
{
this.errorProviderWarn.SetError(binding.Control, string.Empty);
}
if (this._visibleInformation == true && info.Length > 0)
{
this.errorProviderInfo.SetError(binding.Control,
info.ToString().Substring(0,
info.ToString().Length -
2));
this.errorProviderInfo.SetIconPadding(binding.Control,
base.GetIconPadding(binding.Control) +
offsetInformation);
this.errorProviderInfo.SetIconAlignment(binding.Control,
base.GetIconAlignment(binding.Control));
}
else
{
this.errorProviderInfo.SetError(binding.Control, string.Empty);
}
}
}
}
}
}
[DefaultValue(false), Description("Determines if all controls should be recursed through whenever any control value changes.")]
public bool ProcessDependantProperties
{
get
{
return this._processDependantProperties;
}
set
{
if (this._processDependantProperties != value)
{
this._processDependantProperties = value;
}
}
}
private void ResetBlinkStyleInformation()
{
this.BlinkStyleInformation = ErrorBlinkStyle.BlinkIfDifferentError;
}
private void ResetBlinkStyleWarning()
{
this.BlinkStyleWarning = ErrorBlinkStyle.BlinkIfDifferentError;
}
private void ResetIconInformation()
{
this.IconInformation = DefaultIconInformation;
}
private void ResetIconWarning()
{
this.IconWarning = DefaultIconWarning;
}
public void SetInformation(Control control, string value)
{
this.errorProviderInfo.SetError(control, value);
}
public void SetWarning(Control control, string value)
{
this.errorProviderWarn.SetError(control, value);
}
private bool ShouldSerializeIconInformation()
{
return (this.IconInformation != DefaultIconInformation);
}
private bool ShouldSerializeIconWarning()
{
return (this.IconWarning != DefaultIconWarning);
}
private bool ShouldSerializeBlinkStyleInformation()
{
return (this.BlinkStyleInformation != ErrorBlinkStyle.BlinkIfDifferentError);
}
private bool ShouldSerializeBlinkStyleWarning()
{
return (this.BlinkStyleWarning != ErrorBlinkStyle.BlinkIfDifferentError);
}
public new void UpdateBinding()
{
base.UpdateBinding();
this.errorProviderInfo.UpdateBinding();
this.errorProviderWarn.UpdateBinding();
}
// Following event is hooked for all controls, it sets an error message with the use of ErrorProvider
private void Validation_Event(object sender, EventArgs e)
{
if (this._visibleInformation == true || this._visibleWarning == true)
{
if (ProcessDependantProperties)
{
//Due to the possibility of dependant properties,
// need to check all controls in list
for (int i = 0; i < this._controls.Count; i++)
{
Control control = (Control)this._controls[i];
ProcessControl(control);
}
}
else
{
Control control = (Control)sender;
ProcessControl(control);
}
}
else
{
this.errorProviderWarn.Clear();
this.errorProviderInfo.Clear();
}
}
[DefaultValue(true), Description("Determines if the information icon should be displayed when information exists.")]
public bool VisibleInformation
{
get
{
return this._visibleInformation;
}
set
{
if (this._visibleInformation != value)
{
this._visibleInformation = value;
}
}
}
[DefaultValue(true), Description("Determines if the warning icon should be displayed when warnings exist.")]
public bool VisibleWarning
{
get
{
return this._visibleWarning;
}
set
{
if (this._visibleWarning != value)
{
this._visibleWarning = value;
}
}
}
}
}
| |
#if DNX451
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models;
using OmniSharp.Services;
namespace OmniSharp
{
public class FixUsingsWorker
{
private OmnisharpWorkspace _workspace;
private Document _document;
private SemanticModel _semanticModel;
public async Task<FixUsingsResponse> FixUsings(OmnisharpWorkspace workspace, Document document)
{
_workspace = workspace;
_document = document;
_semanticModel = await document.GetSemanticModelAsync();
await AddMissingUsings();
await RemoveUsings();
await SortUsings();
await TryAddLinqQuerySyntax();
var ambiguous = await GetAmbiguousUsings();
var response = new FixUsingsResponse();
response.AmbiguousResults = ambiguous;
return response;
}
private async Task<List<QuickFix>> GetAmbiguousUsings()
{
var ambiguousNodes = new List<SimpleNameSyntax>();
var ambiguous = new List<QuickFix>();
var syntaxNode = (await _document.GetSyntaxTreeAsync()).GetRoot();
var nodes = syntaxNode.DescendantNodes()
.OfType<SimpleNameSyntax>()
.Where(x => _semanticModel.GetSymbolInfo(x).Symbol == null && !ambiguousNodes.Contains(x)).ToList();
foreach (var node in nodes)
{
var pointDiagnostics = await GetPointDiagnostics(node.Identifier.Span, new List<string>() { "CS0246", "CS1061", "CS0103" });
if (pointDiagnostics.Any())
{
var pointdiagfirst = pointDiagnostics.First().Location.SourceSpan;
if (pointDiagnostics.Any(d => d.Location.SourceSpan != pointdiagfirst))
{
continue;
}
var usingOperations = await GetUsingActions(new RoslynCodeActionProvider(), pointDiagnostics, "using");
if (usingOperations.Count() > 1)
{
//More than one operation - ambiguous
ambiguousNodes.Add(node);
var unresolvedText = node.Identifier.ValueText;
var unresolvedLocation = node.GetLocation().GetLineSpan().StartLinePosition;
ambiguous.Add(new QuickFix
{
Line = unresolvedLocation.Line + 1,
Column = unresolvedLocation.Character + 1,
FileName = _document.FilePath,
Text = "`" + unresolvedText + "`" + " is ambiguous"
});
}
}
}
return ambiguous;
}
private async Task AddMissingUsings()
{
bool processMore = true;
while (processMore)
{
bool updated = false;
var syntaxNode = (await _document.GetSyntaxTreeAsync()).GetRoot();
var nodes = syntaxNode.DescendantNodes()
.OfType<SimpleNameSyntax>()
.Where(x => _semanticModel.GetSymbolInfo(x).Symbol == null).ToList();
foreach (var node in nodes)
{
var pointDiagnostics = await GetPointDiagnostics(node.Identifier.Span, new List<string>() { "CS0246", "CS1061", "CS0103" });
if (pointDiagnostics.Any())
{
var pointdiagfirst = pointDiagnostics.First().Location.SourceSpan;
if (pointDiagnostics.Any(d => d.Location.SourceSpan != pointdiagfirst))
{
continue;
}
var usingOperations = await GetUsingActions(new RoslynCodeActionProvider(), pointDiagnostics, "using");
if (usingOperations.Count() == 1)
{
//Only one operation - apply it
usingOperations.Single().Apply(_workspace, CancellationToken.None);
updated = true;
}
}
}
processMore = updated;
}
return;
}
private async Task RemoveUsings()
{
var codeActionProvider = new RoslynCodeActionProvider();
//Remove unneccessary usings
var syntaxNode = (await _document.GetSyntaxTreeAsync()).GetRoot();
var nodes = syntaxNode.DescendantNodes().Where(x => x is UsingDirectiveSyntax);
foreach (var node in nodes)
{
var sourceText = (await _document.GetTextAsync());
var actions = new List<CodeAction>();
var pointDiagnostics = await GetPointDiagnostics(node.Span, new List<string>() { "CS0105", "CS8019" });
if (pointDiagnostics.Any())
{
var pointdiagfirst = pointDiagnostics.First().Location.SourceSpan;
if (pointDiagnostics.Any(d => d.Location.SourceSpan != pointdiagfirst))
{
continue;
}
var usingActions = await GetUsingActions(codeActionProvider, pointDiagnostics, "Remove Unnecessary Usings");
foreach (var codeOperation in usingActions)
{
if (codeOperation != null)
{
codeOperation.Apply(_workspace, CancellationToken.None);
}
}
}
}
return;
}
private async Task SortUsings()
{
//Sort usings
var nRefactoryProvider = new NRefactoryCodeActionProvider();
var sortActions = new List<CodeAction>();
var refactoringContext = await GetRefactoringContext(_document, sortActions);
if (refactoringContext != null)
{
var sortUsingsAction = nRefactoryProvider.Refactorings
.First(r => r is ICSharpCode.NRefactory6.CSharp.Refactoring.SortUsingsAction);
await sortUsingsAction.ComputeRefactoringsAsync(refactoringContext.Value);
foreach (var action in sortActions)
{
var operations = await action.GetOperationsAsync(CancellationToken.None).ConfigureAwait(false);
if (operations != null)
{
foreach (var codeOperation in operations)
{
if (codeOperation != null)
{
codeOperation.Apply(_workspace, CancellationToken.None);
}
}
}
}
}
}
private async Task TryAddLinqQuerySyntax()
{
var fileName = _document.FilePath;
var syntaxNode = (await _document.GetSyntaxTreeAsync()).GetRoot();
var compilationUnitSyntax = (CompilationUnitSyntax)syntaxNode;
var usings = GetUsings(syntaxNode);
if (HasLinqQuerySyntax(_semanticModel, syntaxNode) && !usings.Contains("using System.Linq;"))
{
var linqName = SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"),
SyntaxFactory.IdentifierName("Linq"));
var linq = SyntaxFactory.UsingDirective(linqName).NormalizeWhitespace()
.WithTrailingTrivia(SyntaxFactory.Whitespace(Environment.NewLine));
var oldSolution = _workspace.CurrentSolution;
_document = _document.WithSyntaxRoot(compilationUnitSyntax.AddUsings(linq));
var newDocText = await _document.GetTextAsync();
var newSolution = oldSolution.WithDocumentText(_document.Id, newDocText);
_workspace.TryApplyChanges(newSolution);
_semanticModel = await _document.GetSemanticModelAsync();
}
}
private static async Task<CodeRefactoringContext?> GetRefactoringContext(Document document, List<CodeAction> actionsDestination)
{
var firstUsing = (await document.GetSyntaxTreeAsync()).GetRoot().DescendantNodes().FirstOrDefault(n => n is UsingDirectiveSyntax);
if (firstUsing == null)
{
return null;
}
var location = firstUsing.GetLocation().SourceSpan;
return new CodeRefactoringContext(document, location, (a) => actionsDestination.Add(a), CancellationToken.None);
}
private async Task<IEnumerable<CodeActionOperation>> GetUsingActions(ICodeActionProvider codeActionProvider,
ImmutableArray<Diagnostic> pointDiagnostics, string actionPrefix)
{
var actions = new List<CodeAction>();
var context = new CodeFixContext(_document, pointDiagnostics.First().Location.SourceSpan, pointDiagnostics, (a, d) => actions.Add(a), CancellationToken.None);
var providers = codeActionProvider.CodeFixes;
//Disable await warning since we dont need the result of the call. Else we need to use a throwaway variable.
#pragma warning disable 4014
foreach (var provider in providers)
{
provider.RegisterCodeFixesAsync(context);
}
#pragma warning restore 4014
var tasks = actions.Where(a => a.Title.StartsWith(actionPrefix))
.Select(async a => await a.GetOperationsAsync(CancellationToken.None)).ToList();
return (await Task.WhenAll(tasks)).SelectMany(x => x);
}
private static HashSet<string> GetUsings(SyntaxNode root)
{
var usings = root.DescendantNodes().OfType<UsingDirectiveSyntax>().Select(u => u.ToString().Trim());
return new HashSet<string>(usings);
}
private async Task<ImmutableArray<Diagnostic>> GetPointDiagnostics(TextSpan location, List<string> diagnosticIds)
{
_document = _workspace.GetDocument(_document.FilePath);
_semanticModel = await _document.GetSemanticModelAsync();
var diagnostics = _semanticModel.GetDiagnostics();
//Restrict diagnostics only to missing usings
return diagnostics.Where(d => d.Location.SourceSpan.Contains(location) &&
diagnosticIds.Contains(d.Id)).ToImmutableArray();
}
private bool HasLinqQuerySyntax(SemanticModel semanticModel, SyntaxNode syntaxNode)
{
return syntaxNode.DescendantNodes()
.Any(x => x.Kind() == SyntaxKind.QueryExpression
|| x.Kind() == SyntaxKind.QueryBody
|| x.Kind() == SyntaxKind.FromClause
|| x.Kind() == SyntaxKind.LetClause
|| x.Kind() == SyntaxKind.JoinClause
|| x.Kind() == SyntaxKind.JoinClause
|| x.Kind() == SyntaxKind.JoinIntoClause
|| x.Kind() == SyntaxKind.WhereClause
|| x.Kind() == SyntaxKind.OrderByClause
|| x.Kind() == SyntaxKind.AscendingOrdering
|| x.Kind() == SyntaxKind.DescendingOrdering
|| x.Kind() == SyntaxKind.SelectClause
|| x.Kind() == SyntaxKind.GroupClause
|| x.Kind() == SyntaxKind.QueryContinuation
);
}
}
}
#endif
| |
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics;
using osu.Framework.IO.Stores;
using OpenTK;
using OpenTK.Graphics;
using osu.Framework.Caching;
namespace osu.Game.Graphics
{
public class SpriteIcon : CompositeDrawable
{
private Sprite spriteShadow;
private Sprite spriteMain;
private Cached layout = new Cached();
private Container shadowVisibility;
private FontStore store;
[BackgroundDependencyLoader]
private void load(FontStore store)
{
this.store = store;
InternalChildren = new Drawable[]
{
shadowVisibility = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Child = spriteShadow = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
Y = 2,
Colour = new Color4(0f, 0f, 0f, 0.2f),
},
Alpha = shadow ? 1 : 0,
},
spriteMain = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit
},
};
updateTexture();
}
protected override void LoadComplete()
{
base.LoadComplete();
updateTexture();
}
private FontAwesome loadedIcon;
private void updateTexture()
{
var loadableIcon = icon;
if (loadableIcon == loadedIcon) return;
var texture = store?.Get(((char)loadableIcon).ToString());
spriteMain.Texture = texture;
spriteShadow.Texture = texture;
if (Size == Vector2.Zero)
Size = new Vector2(texture?.DisplayWidth ?? 0, texture?.DisplayHeight ?? 0);
loadedIcon = loadableIcon;
}
public override bool Invalidate(Invalidation invalidation = Invalidation.All, Drawable source = null, bool shallPropagate = true)
{
if ((invalidation & Invalidation.Colour) > 0 && Shadow)
layout.Invalidate();
return base.Invalidate(invalidation, source, shallPropagate);
}
protected override void Update()
{
if (!layout.IsValid)
{
//adjust shadow alpha based on highest component intensity to avoid muddy display of darker text.
//squared result for quadratic fall-off seems to give the best result.
var avgColour = (Color4)DrawInfo.Colour.AverageColour;
spriteShadow.Alpha = (float)Math.Pow(Math.Max(Math.Max(avgColour.R, avgColour.G), avgColour.B), 2);
layout.Validate();
}
}
private bool shadow;
public bool Shadow
{
get { return shadow; }
set
{
shadow = value;
if (shadowVisibility != null)
shadowVisibility.Alpha = value ? 1 : 0;
}
}
private FontAwesome icon;
public FontAwesome Icon
{
get
{
return icon;
}
set
{
if (icon == value) return;
icon = value;
if (IsLoaded)
updateTexture();
}
}
}
public enum FontAwesome
{
fa_500px = 0xf26e,
fa_address_book = 0xf2b9,
fa_address_book_o = 0xf2ba,
fa_address_card = 0xf2bb,
fa_address_card_o = 0xf2bc,
fa_adjust = 0xf042,
fa_adn = 0xf170,
fa_align_center = 0xf037,
fa_align_justify = 0xf039,
fa_align_left = 0xf036,
fa_align_right = 0xf038,
fa_amazon = 0xf270,
fa_ambulance = 0xf0f9,
fa_american_sign_language_interpreting = 0xf2a3,
fa_anchor = 0xf13d,
fa_android = 0xf17b,
fa_angellist = 0xf209,
fa_angle_double_down = 0xf103,
fa_angle_double_left = 0xf100,
fa_angle_double_right = 0xf101,
fa_angle_double_up = 0xf102,
fa_angle_down = 0xf107,
fa_angle_left = 0xf104,
fa_angle_right = 0xf105,
fa_angle_up = 0xf106,
fa_apple = 0xf179,
fa_archive = 0xf187,
fa_area_chart = 0xf1fe,
fa_arrow_circle_down = 0xf0ab,
fa_arrow_circle_left = 0xf0a8,
fa_arrow_circle_o_down = 0xf01a,
fa_arrow_circle_o_left = 0xf190,
fa_arrow_circle_o_right = 0xf18e,
fa_arrow_circle_o_up = 0xf01b,
fa_arrow_circle_right = 0xf0a9,
fa_arrow_circle_up = 0xf0aa,
fa_arrow_down = 0xf063,
fa_arrow_left = 0xf060,
fa_arrow_right = 0xf061,
fa_arrow_up = 0xf062,
fa_arrows = 0xf047,
fa_arrows_alt = 0xf0b2,
fa_arrows_h = 0xf07e,
fa_arrows_v = 0xf07d,
fa_asl_interpreting = 0xf2a3,
fa_assistive_listening_systems = 0xf2a2,
fa_asterisk = 0xf069,
fa_at = 0xf1fa,
fa_audio_description = 0xf29e,
fa_automobile = 0xf1b9,
fa_backward = 0xf04a,
fa_balance_scale = 0xf24e,
fa_ban = 0xf05e,
fa_bandcamp = 0xf2d5,
fa_bank = 0xf19c,
fa_bar_chart = 0xf080,
fa_bar_chart_o = 0xf080,
fa_barcode = 0xf02a,
fa_bars = 0xf0c9,
fa_bath = 0xf2cd,
fa_bathtub = 0xf2cd,
fa_battery = 0xf240,
fa_battery_0 = 0xf244,
fa_battery_1 = 0xf243,
fa_battery_2 = 0xf242,
fa_battery_3 = 0xf241,
fa_battery_4 = 0xf240,
fa_battery_empty = 0xf244,
fa_battery_full = 0xf240,
fa_battery_half = 0xf242,
fa_battery_quarter = 0xf243,
fa_battery_three_quarters = 0xf241,
fa_bed = 0xf236,
fa_beer = 0xf0fc,
fa_behance = 0xf1b4,
fa_behance_square = 0xf1b5,
fa_bell = 0xf0f3,
fa_bell_o = 0xf0a2,
fa_bell_slash = 0xf1f6,
fa_bell_slash_o = 0xf1f7,
fa_bicycle = 0xf206,
fa_binoculars = 0xf1e5,
fa_birthday_cake = 0xf1fd,
fa_bitbucket = 0xf171,
fa_bitbucket_square = 0xf172,
fa_bitcoin = 0xf15a,
fa_black_tie = 0xf27e,
fa_blind = 0xf29d,
fa_bluetooth = 0xf293,
fa_bluetooth_b = 0xf294,
fa_bold = 0xf032,
fa_bolt = 0xf0e7,
fa_bomb = 0xf1e2,
fa_book = 0xf02d,
fa_bookmark = 0xf02e,
fa_bookmark_o = 0xf097,
fa_braille = 0xf2a1,
fa_briefcase = 0xf0b1,
fa_btc = 0xf15a,
fa_bug = 0xf188,
fa_building = 0xf1ad,
fa_building_o = 0xf0f7,
fa_bullhorn = 0xf0a1,
fa_bullseye = 0xf140,
fa_bus = 0xf207,
fa_buysellads = 0xf20d,
fa_cab = 0xf1ba,
fa_calculator = 0xf1ec,
fa_calendar = 0xf073,
fa_calendar_check_o = 0xf274,
fa_calendar_minus_o = 0xf272,
fa_calendar_o = 0xf133,
fa_calendar_plus_o = 0xf271,
fa_calendar_times_o = 0xf273,
fa_camera = 0xf030,
fa_camera_retro = 0xf083,
fa_car = 0xf1b9,
fa_caret_down = 0xf0d7,
fa_caret_left = 0xf0d9,
fa_caret_right = 0xf0da,
fa_caret_square_o_down = 0xf150,
fa_caret_square_o_left = 0xf191,
fa_caret_square_o_right = 0xf152,
fa_caret_square_o_up = 0xf151,
fa_caret_up = 0xf0d8,
fa_cart_arrow_down = 0xf218,
fa_cart_plus = 0xf217,
fa_cc = 0xf20a,
fa_cc_amex = 0xf1f3,
fa_cc_diners_club = 0xf24c,
fa_cc_discover = 0xf1f2,
fa_cc_jcb = 0xf24b,
fa_cc_mastercard = 0xf1f1,
fa_cc_paypal = 0xf1f4,
fa_cc_stripe = 0xf1f5,
fa_cc_visa = 0xf1f0,
fa_certificate = 0xf0a3,
fa_chain = 0xf0c1,
fa_chain_broken = 0xf127,
fa_check = 0xf00c,
fa_check_circle = 0xf058,
fa_check_circle_o = 0xf05d,
fa_check_square = 0xf14a,
fa_check_square_o = 0xf046,
fa_chevron_circle_down = 0xf13a,
fa_chevron_circle_left = 0xf137,
fa_chevron_circle_right = 0xf138,
fa_chevron_circle_up = 0xf139,
fa_chevron_down = 0xf078,
fa_chevron_left = 0xf053,
fa_chevron_right = 0xf054,
fa_chevron_up = 0xf077,
fa_child = 0xf1ae,
fa_chrome = 0xf268,
fa_circle = 0xf111,
fa_circle_o = 0xf10c,
fa_circle_o_notch = 0xf1ce,
fa_circle_thin = 0xf1db,
fa_clipboard = 0xf0ea,
fa_clock_o = 0xf017,
fa_clone = 0xf24d,
fa_close = 0xf00d,
fa_cloud = 0xf0c2,
fa_cloud_download = 0xf0ed,
fa_cloud_upload = 0xf0ee,
fa_cny = 0xf157,
fa_code = 0xf121,
fa_code_fork = 0xf126,
fa_codepen = 0xf1cb,
fa_codiepie = 0xf284,
fa_coffee = 0xf0f4,
fa_cog = 0xf013,
fa_cogs = 0xf085,
fa_columns = 0xf0db,
fa_comment = 0xf075,
fa_comment_o = 0xf0e5,
fa_commenting = 0xf27a,
fa_commenting_o = 0xf27b,
fa_comments = 0xf086,
fa_comments_o = 0xf0e6,
fa_compass = 0xf14e,
fa_compress = 0xf066,
fa_connectdevelop = 0xf20e,
fa_contao = 0xf26d,
fa_copy = 0xf0c5,
fa_copyright = 0xf1f9,
fa_creative_commons = 0xf25e,
fa_credit_card = 0xf09d,
fa_credit_card_alt = 0xf283,
fa_crop = 0xf125,
fa_crosshairs = 0xf05b,
fa_css3 = 0xf13c,
fa_cube = 0xf1b2,
fa_cubes = 0xf1b3,
fa_cut = 0xf0c4,
fa_cutlery = 0xf0f5,
fa_dashboard = 0xf0e4,
fa_dashcube = 0xf210,
fa_database = 0xf1c0,
fa_deaf = 0xf2a4,
fa_deafness = 0xf2a4,
fa_dedent = 0xf03b,
fa_delicious = 0xf1a5,
fa_desktop = 0xf108,
fa_deviantart = 0xf1bd,
fa_diamond = 0xf219,
fa_digg = 0xf1a6,
fa_dollar = 0xf155,
fa_dot_circle_o = 0xf192,
fa_download = 0xf019,
fa_dribbble = 0xf17d,
fa_drivers_license = 0xf2c2,
fa_drivers_license_o = 0xf2c3,
fa_dropbox = 0xf16b,
fa_drupal = 0xf1a9,
fa_edge = 0xf282,
fa_edit = 0xf044,
fa_eercast = 0xf2da,
fa_eject = 0xf052,
fa_ellipsis_h = 0xf141,
fa_ellipsis_v = 0xf142,
fa_empire = 0xf1d1,
fa_envelope = 0xf0e0,
fa_envelope_o = 0xf003,
fa_envelope_open = 0xf2b6,
fa_envelope_open_o = 0xf2b7,
fa_envelope_square = 0xf199,
fa_envira = 0xf299,
fa_eraser = 0xf12d,
fa_etsy = 0xf2d7,
fa_eur = 0xf153,
fa_euro = 0xf153,
fa_exchange = 0xf0ec,
fa_exclamation = 0xf12a,
fa_exclamation_circle = 0xf06a,
fa_exclamation_triangle = 0xf071,
fa_expand = 0xf065,
fa_expeditedssl = 0xf23e,
fa_external_link = 0xf08e,
fa_external_link_square = 0xf14c,
fa_eye = 0xf06e,
fa_eye_slash = 0xf070,
fa_eyedropper = 0xf1fb,
fa_fa = 0xf2b4,
fa_facebook = 0xf09a,
fa_facebook_f = 0xf09a,
fa_facebook_official = 0xf230,
fa_facebook_square = 0xf082,
fa_fast_backward = 0xf049,
fa_fast_forward = 0xf050,
fa_fax = 0xf1ac,
fa_feed = 0xf09e,
fa_female = 0xf182,
fa_fighter_jet = 0xf0fb,
fa_file = 0xf15b,
fa_file_archive_o = 0xf1c6,
fa_file_audio_o = 0xf1c7,
fa_file_code_o = 0xf1c9,
fa_file_excel_o = 0xf1c3,
fa_file_image_o = 0xf1c5,
fa_file_movie_o = 0xf1c8,
fa_file_o = 0xf016,
fa_file_pdf_o = 0xf1c1,
fa_file_photo_o = 0xf1c5,
fa_file_picture_o = 0xf1c5,
fa_file_powerpoint_o = 0xf1c4,
fa_file_sound_o = 0xf1c7,
fa_file_text = 0xf15c,
fa_file_text_o = 0xf0f6,
fa_file_video_o = 0xf1c8,
fa_file_word_o = 0xf1c2,
fa_file_zip_o = 0xf1c6,
fa_files_o = 0xf0c5,
fa_film = 0xf008,
fa_filter = 0xf0b0,
fa_fire = 0xf06d,
fa_fire_extinguisher = 0xf134,
fa_firefox = 0xf269,
fa_first_order = 0xf2b0,
fa_flag = 0xf024,
fa_flag_checkered = 0xf11e,
fa_flag_o = 0xf11d,
fa_flash = 0xf0e7,
fa_flask = 0xf0c3,
fa_flickr = 0xf16e,
fa_floppy_o = 0xf0c7,
fa_folder = 0xf07b,
fa_folder_o = 0xf114,
fa_folder_open = 0xf07c,
fa_folder_open_o = 0xf115,
fa_font = 0xf031,
fa_font_awesome = 0xf2b4,
fa_fonticons = 0xf280,
fa_fort_awesome = 0xf286,
fa_forumbee = 0xf211,
fa_forward = 0xf04e,
fa_foursquare = 0xf180,
fa_free_code_camp = 0xf2c5,
fa_frown_o = 0xf119,
fa_futbol_o = 0xf1e3,
fa_gamepad = 0xf11b,
fa_gavel = 0xf0e3,
fa_gbp = 0xf154,
fa_ge = 0xf1d1,
fa_gear = 0xf013,
fa_gears = 0xf085,
fa_genderless = 0xf22d,
fa_get_pocket = 0xf265,
fa_gg = 0xf260,
fa_gg_circle = 0xf261,
fa_gift = 0xf06b,
fa_git = 0xf1d3,
fa_git_square = 0xf1d2,
fa_github = 0xf09b,
fa_github_alt = 0xf113,
fa_github_square = 0xf092,
fa_gitlab = 0xf296,
fa_gittip = 0xf184,
fa_glass = 0xf000,
fa_glide = 0xf2a5,
fa_glide_g = 0xf2a6,
fa_globe = 0xf0ac,
fa_google = 0xf1a0,
fa_google_plus = 0xf0d5,
fa_google_plus_circle = 0xf2b3,
fa_google_plus_official = 0xf2b3,
fa_google_plus_square = 0xf0d4,
fa_google_wallet = 0xf1ee,
fa_graduation_cap = 0xf19d,
fa_gratipay = 0xf184,
fa_grav = 0xf2d6,
fa_group = 0xf0c0,
fa_h_square = 0xf0fd,
fa_hacker_news = 0xf1d4,
fa_hand_grab_o = 0xf255,
fa_hand_lizard_o = 0xf258,
fa_hand_o_down = 0xf0a7,
fa_hand_o_left = 0xf0a5,
fa_hand_o_right = 0xf0a4,
fa_hand_o_up = 0xf0a6,
fa_hand_paper_o = 0xf256,
fa_hand_peace_o = 0xf25b,
fa_hand_pointer_o = 0xf25a,
fa_hand_rock_o = 0xf255,
fa_hand_scissors_o = 0xf257,
fa_hand_spock_o = 0xf259,
fa_hand_stop_o = 0xf256,
fa_handshake_o = 0xf2b5,
fa_hard_of_hearing = 0xf2a4,
fa_hashtag = 0xf292,
fa_hdd_o = 0xf0a0,
fa_header = 0xf1dc,
fa_headphones = 0xf025,
fa_heart = 0xf004,
fa_heart_o = 0xf08a,
fa_heartbeat = 0xf21e,
fa_history = 0xf1da,
fa_home = 0xf015,
fa_hospital_o = 0xf0f8,
fa_hotel = 0xf236,
fa_hourglass = 0xf254,
fa_hourglass_1 = 0xf251,
fa_hourglass_2 = 0xf252,
fa_hourglass_3 = 0xf253,
fa_hourglass_end = 0xf253,
fa_hourglass_half = 0xf252,
fa_hourglass_o = 0xf250,
fa_hourglass_start = 0xf251,
fa_houzz = 0xf27c,
fa_html5 = 0xf13b,
fa_i_cursor = 0xf246,
fa_id_badge = 0xf2c1,
fa_id_card = 0xf2c2,
fa_id_card_o = 0xf2c3,
fa_ils = 0xf20b,
fa_image = 0xf03e,
fa_imdb = 0xf2d8,
fa_inbox = 0xf01c,
fa_indent = 0xf03c,
fa_industry = 0xf275,
fa_info = 0xf129,
fa_info_circle = 0xf05a,
fa_inr = 0xf156,
fa_instagram = 0xf16d,
fa_institution = 0xf19c,
fa_internet_explorer = 0xf26b,
fa_intersex = 0xf224,
fa_ioxhost = 0xf208,
fa_italic = 0xf033,
fa_joomla = 0xf1aa,
fa_jpy = 0xf157,
fa_jsfiddle = 0xf1cc,
fa_key = 0xf084,
fa_keyboard_o = 0xf11c,
fa_krw = 0xf159,
fa_language = 0xf1ab,
fa_laptop = 0xf109,
fa_lastfm = 0xf202,
fa_lastfm_square = 0xf203,
fa_leaf = 0xf06c,
fa_leanpub = 0xf212,
fa_legal = 0xf0e3,
fa_lemon_o = 0xf094,
fa_level_down = 0xf149,
fa_level_up = 0xf148,
fa_life_bouy = 0xf1cd,
fa_life_buoy = 0xf1cd,
fa_life_ring = 0xf1cd,
fa_life_saver = 0xf1cd,
fa_lightbulb_o = 0xf0eb,
fa_line_chart = 0xf201,
fa_link = 0xf0c1,
fa_linkedin = 0xf0e1,
fa_linkedin_square = 0xf08c,
fa_linode = 0xf2b8,
fa_linux = 0xf17c,
fa_list = 0xf03a,
fa_list_alt = 0xf022,
fa_list_ol = 0xf0cb,
fa_list_ul = 0xf0ca,
fa_location_arrow = 0xf124,
fa_lock = 0xf023,
fa_long_arrow_down = 0xf175,
fa_long_arrow_left = 0xf177,
fa_long_arrow_right = 0xf178,
fa_long_arrow_up = 0xf176,
fa_low_vision = 0xf2a8,
fa_magic = 0xf0d0,
fa_magnet = 0xf076,
fa_mail_forward = 0xf064,
fa_mail_reply = 0xf112,
fa_mail_reply_all = 0xf122,
fa_male = 0xf183,
fa_map = 0xf279,
fa_map_marker = 0xf041,
fa_map_o = 0xf278,
fa_map_pin = 0xf276,
fa_map_signs = 0xf277,
fa_mars = 0xf222,
fa_mars_double = 0xf227,
fa_mars_stroke = 0xf229,
fa_mars_stroke_h = 0xf22b,
fa_mars_stroke_v = 0xf22a,
fa_maxcdn = 0xf136,
fa_meanpath = 0xf20c,
fa_medium = 0xf23a,
fa_medkit = 0xf0fa,
fa_meetup = 0xf2e0,
fa_meh_o = 0xf11a,
fa_mercury = 0xf223,
fa_microchip = 0xf2db,
fa_microphone = 0xf130,
fa_microphone_slash = 0xf131,
fa_minus = 0xf068,
fa_minus_circle = 0xf056,
fa_minus_square = 0xf146,
fa_minus_square_o = 0xf147,
fa_mixcloud = 0xf289,
fa_mobile = 0xf10b,
fa_mobile_phone = 0xf10b,
fa_modx = 0xf285,
fa_money = 0xf0d6,
fa_moon_o = 0xf186,
fa_mortar_board = 0xf19d,
fa_motorcycle = 0xf21c,
fa_mouse_pointer = 0xf245,
fa_music = 0xf001,
fa_navicon = 0xf0c9,
fa_neuter = 0xf22c,
fa_newspaper_o = 0xf1ea,
fa_object_group = 0xf247,
fa_object_ungroup = 0xf248,
fa_odnoklassniki = 0xf263,
fa_odnoklassniki_square = 0xf264,
fa_opencart = 0xf23d,
fa_openid = 0xf19b,
fa_opera = 0xf26a,
fa_optin_monster = 0xf23c,
fa_outdent = 0xf03b,
fa_pagelines = 0xf18c,
fa_paint_brush = 0xf1fc,
fa_paper_plane = 0xf1d8,
fa_paper_plane_o = 0xf1d9,
fa_paperclip = 0xf0c6,
fa_paragraph = 0xf1dd,
fa_paste = 0xf0ea,
fa_pause = 0xf04c,
fa_pause_circle = 0xf28b,
fa_pause_circle_o = 0xf28c,
fa_paw = 0xf1b0,
fa_paypal = 0xf1ed,
fa_pencil = 0xf040,
fa_pencil_square = 0xf14b,
fa_pencil_square_o = 0xf044,
fa_percent = 0xf295,
fa_phone = 0xf095,
fa_phone_square = 0xf098,
fa_photo = 0xf03e,
fa_picture_o = 0xf03e,
fa_pie_chart = 0xf200,
fa_pied_piper = 0xf2ae,
fa_pied_piper_alt = 0xf1a8,
fa_pied_piper_pp = 0xf1a7,
fa_pinterest = 0xf0d2,
fa_pinterest_p = 0xf231,
fa_pinterest_square = 0xf0d3,
fa_plane = 0xf072,
fa_play = 0xf04b,
fa_play_circle = 0xf144,
fa_play_circle_o = 0xf01d,
fa_plug = 0xf1e6,
fa_plus = 0xf067,
fa_plus_circle = 0xf055,
fa_plus_square = 0xf0fe,
fa_plus_square_o = 0xf196,
fa_podcast = 0xf2ce,
fa_power_off = 0xf011,
fa_print = 0xf02f,
fa_product_hunt = 0xf288,
fa_puzzle_piece = 0xf12e,
fa_qq = 0xf1d6,
fa_qrcode = 0xf029,
fa_question = 0xf128,
fa_question_circle = 0xf059,
fa_question_circle_o = 0xf29c,
fa_quora = 0xf2c4,
fa_quote_left = 0xf10d,
fa_quote_right = 0xf10e,
fa_ra = 0xf1d0,
fa_random = 0xf074,
fa_ravelry = 0xf2d9,
fa_rebel = 0xf1d0,
fa_recycle = 0xf1b8,
fa_reddit = 0xf1a1,
fa_reddit_alien = 0xf281,
fa_reddit_square = 0xf1a2,
fa_refresh = 0xf021,
fa_registered = 0xf25d,
fa_remove = 0xf00d,
fa_renren = 0xf18b,
fa_reorder = 0xf0c9,
fa_repeat = 0xf01e,
fa_reply = 0xf112,
fa_reply_all = 0xf122,
fa_resistance = 0xf1d0,
fa_retweet = 0xf079,
fa_rmb = 0xf157,
fa_road = 0xf018,
fa_rocket = 0xf135,
fa_rotate_left = 0xf0e2,
fa_rotate_right = 0xf01e,
fa_rouble = 0xf158,
fa_rss = 0xf09e,
fa_rss_square = 0xf143,
fa_rub = 0xf158,
fa_ruble = 0xf158,
fa_rupee = 0xf156,
fa_s15 = 0xf2cd,
fa_safari = 0xf267,
fa_save = 0xf0c7,
fa_scissors = 0xf0c4,
fa_scribd = 0xf28a,
fa_search = 0xf002,
fa_search_minus = 0xf010,
fa_search_plus = 0xf00e,
fa_sellsy = 0xf213,
fa_send = 0xf1d8,
fa_send_o = 0xf1d9,
fa_server = 0xf233,
fa_share = 0xf064,
fa_share_alt = 0xf1e0,
fa_share_alt_square = 0xf1e1,
fa_share_square = 0xf14d,
fa_share_square_o = 0xf045,
fa_shekel = 0xf20b,
fa_sheqel = 0xf20b,
fa_shield = 0xf132,
fa_ship = 0xf21a,
fa_shirtsinbulk = 0xf214,
fa_shopping_bag = 0xf290,
fa_shopping_basket = 0xf291,
fa_shopping_cart = 0xf07a,
fa_shower = 0xf2cc,
fa_sign_in = 0xf090,
fa_sign_language = 0xf2a7,
fa_sign_out = 0xf08b,
fa_signal = 0xf012,
fa_signing = 0xf2a7,
fa_simplybuilt = 0xf215,
fa_sitemap = 0xf0e8,
fa_skyatlas = 0xf216,
fa_skype = 0xf17e,
fa_slack = 0xf198,
fa_sliders = 0xf1de,
fa_slideshare = 0xf1e7,
fa_smile_o = 0xf118,
fa_snapchat = 0xf2ab,
fa_snapchat_ghost = 0xf2ac,
fa_snapchat_square = 0xf2ad,
fa_snowflake_o = 0xf2dc,
fa_soccer_ball_o = 0xf1e3,
fa_sort = 0xf0dc,
fa_sort_alpha_asc = 0xf15d,
fa_sort_alpha_desc = 0xf15e,
fa_sort_amount_asc = 0xf160,
fa_sort_amount_desc = 0xf161,
fa_sort_asc = 0xf0de,
fa_sort_desc = 0xf0dd,
fa_sort_down = 0xf0dd,
fa_sort_numeric_asc = 0xf162,
fa_sort_numeric_desc = 0xf163,
fa_sort_up = 0xf0de,
fa_soundcloud = 0xf1be,
fa_space_shuttle = 0xf197,
fa_spinner = 0xf110,
fa_spoon = 0xf1b1,
fa_spotify = 0xf1bc,
fa_square = 0xf0c8,
fa_square_o = 0xf096,
fa_stack_exchange = 0xf18d,
fa_stack_overflow = 0xf16c,
fa_star = 0xf005,
fa_star_half = 0xf089,
fa_star_half_empty = 0xf123,
fa_star_half_full = 0xf123,
fa_star_half_o = 0xf123,
fa_star_o = 0xf006,
fa_steam = 0xf1b6,
fa_steam_square = 0xf1b7,
fa_step_backward = 0xf048,
fa_step_forward = 0xf051,
fa_stethoscope = 0xf0f1,
fa_sticky_note = 0xf249,
fa_sticky_note_o = 0xf24a,
fa_stop = 0xf04d,
fa_stop_circle = 0xf28d,
fa_stop_circle_o = 0xf28e,
fa_street_view = 0xf21d,
fa_strikethrough = 0xf0cc,
fa_stumbleupon = 0xf1a4,
fa_stumbleupon_circle = 0xf1a3,
fa_subscript = 0xf12c,
fa_subway = 0xf239,
fa_suitcase = 0xf0f2,
fa_sun_o = 0xf185,
fa_superpowers = 0xf2dd,
fa_superscript = 0xf12b,
fa_support = 0xf1cd,
fa_table = 0xf0ce,
fa_tablet = 0xf10a,
fa_tachometer = 0xf0e4,
fa_tag = 0xf02b,
fa_tags = 0xf02c,
fa_tasks = 0xf0ae,
fa_taxi = 0xf1ba,
fa_telegram = 0xf2c6,
fa_television = 0xf26c,
fa_tencent_weibo = 0xf1d5,
fa_terminal = 0xf120,
fa_text_height = 0xf034,
fa_text_width = 0xf035,
fa_th = 0xf00a,
fa_th_large = 0xf009,
fa_th_list = 0xf00b,
fa_themeisle = 0xf2b2,
fa_thermometer = 0xf2c7,
fa_thermometer_0 = 0xf2cb,
fa_thermometer_1 = 0xf2ca,
fa_thermometer_2 = 0xf2c9,
fa_thermometer_3 = 0xf2c8,
fa_thermometer_4 = 0xf2c7,
fa_thermometer_empty = 0xf2cb,
fa_thermometer_full = 0xf2c7,
fa_thermometer_half = 0xf2c9,
fa_thermometer_quarter = 0xf2ca,
fa_thermometer_three_quarters = 0xf2c8,
fa_thumb_tack = 0xf08d,
fa_thumbs_down = 0xf165,
fa_thumbs_o_down = 0xf088,
fa_thumbs_o_up = 0xf087,
fa_thumbs_up = 0xf164,
fa_ticket = 0xf145,
fa_times = 0xf00d,
fa_times_circle = 0xf057,
fa_times_circle_o = 0xf05c,
fa_times_rectangle = 0xf2d3,
fa_times_rectangle_o = 0xf2d4,
fa_tint = 0xf043,
fa_toggle_down = 0xf150,
fa_toggle_left = 0xf191,
fa_toggle_off = 0xf204,
fa_toggle_on = 0xf205,
fa_toggle_right = 0xf152,
fa_toggle_up = 0xf151,
fa_trademark = 0xf25c,
fa_train = 0xf238,
fa_transgender = 0xf224,
fa_transgender_alt = 0xf225,
fa_trash = 0xf1f8,
fa_trash_o = 0xf014,
fa_tree = 0xf1bb,
fa_trello = 0xf181,
fa_tripadvisor = 0xf262,
fa_trophy = 0xf091,
fa_truck = 0xf0d1,
fa_try = 0xf195,
fa_tty = 0xf1e4,
fa_tumblr = 0xf173,
fa_tumblr_square = 0xf174,
fa_turkish_lira = 0xf195,
fa_tv = 0xf26c,
fa_twitch = 0xf1e8,
fa_twitter = 0xf099,
fa_twitter_square = 0xf081,
fa_umbrella = 0xf0e9,
fa_underline = 0xf0cd,
fa_undo = 0xf0e2,
fa_universal_access = 0xf29a,
fa_university = 0xf19c,
fa_unlink = 0xf127,
fa_unlock = 0xf09c,
fa_unlock_alt = 0xf13e,
fa_unsorted = 0xf0dc,
fa_upload = 0xf093,
fa_usb = 0xf287,
fa_usd = 0xf155,
fa_user = 0xf007,
fa_user_circle = 0xf2bd,
fa_user_circle_o = 0xf2be,
fa_user_md = 0xf0f0,
fa_user_o = 0xf2c0,
fa_user_plus = 0xf234,
fa_user_secret = 0xf21b,
fa_user_times = 0xf235,
fa_users = 0xf0c0,
fa_vcard = 0xf2bb,
fa_vcard_o = 0xf2bc,
fa_venus = 0xf221,
fa_venus_double = 0xf226,
fa_venus_mars = 0xf228,
fa_viacoin = 0xf237,
fa_viadeo = 0xf2a9,
fa_viadeo_square = 0xf2aa,
fa_video_camera = 0xf03d,
fa_vimeo = 0xf27d,
fa_vimeo_square = 0xf194,
fa_vine = 0xf1ca,
fa_vk = 0xf189,
fa_volume_control_phone = 0xf2a0,
fa_volume_down = 0xf027,
fa_volume_off = 0xf026,
fa_volume_up = 0xf028,
fa_warning = 0xf071,
fa_wechat = 0xf1d7,
fa_weibo = 0xf18a,
fa_weixin = 0xf1d7,
fa_whatsapp = 0xf232,
fa_wheelchair = 0xf193,
fa_wheelchair_alt = 0xf29b,
fa_wifi = 0xf1eb,
fa_wikipedia_w = 0xf266,
fa_window_close = 0xf2d3,
fa_window_close_o = 0xf2d4,
fa_window_maximize = 0xf2d0,
fa_window_minimize = 0xf2d1,
fa_window_restore = 0xf2d2,
fa_windows = 0xf17a,
fa_won = 0xf159,
fa_wordpress = 0xf19a,
fa_wpbeginner = 0xf297,
fa_wpexplorer = 0xf2de,
fa_wpforms = 0xf298,
fa_wrench = 0xf0ad,
fa_xing = 0xf168,
fa_xing_square = 0xf169,
fa_y_combinator = 0xf23b,
fa_y_combinator_square = 0xf1d4,
fa_yahoo = 0xf19e,
fa_yc = 0xf23b,
fa_yc_square = 0xf1d4,
fa_yelp = 0xf1e9,
fa_yen = 0xf157,
fa_yoast = 0xf2b1,
fa_youtube = 0xf167,
fa_youtube_play = 0xf16a,
fa_youtube_square = 0xf166,
// ruleset icons in circles
fa_osu_osu_o = 0xe000,
fa_osu_mania_o = 0xe001,
fa_osu_fruits_o = 0xe002,
fa_osu_taiko_o = 0xe003,
// ruleset icons without circles
fa_osu_filled_circle = 0xe004,
fa_osu_cross_o = 0xe005,
fa_osu_logo = 0xe006,
fa_osu_chevron_down_o = 0xe007,
fa_osu_edit_o = 0xe033,
fa_osu_left_o = 0xe034,
fa_osu_right_o = 0xe035,
fa_osu_charts = 0xe036,
fa_osu_solo = 0xe037,
fa_osu_multi = 0xe038,
fa_osu_gear = 0xe039,
// misc icons
fa_osu_bat = 0xe008,
fa_osu_bubble = 0xe009,
fa_osu_bubble_pop = 0xe02e,
fa_osu_dice = 0xe011,
fa_osu_heart1 = 0xe02f,
fa_osu_heart1_break = 0xe030,
fa_osu_hot = 0xe031,
fa_osu_list_search = 0xe032,
//osu! playstyles
fa_osu_playstyle_tablet = 0xe02a,
fa_osu_playstyle_mouse = 0xe029,
fa_osu_playstyle_keyboard = 0xe02b,
fa_osu_playstyle_touch = 0xe02c,
// osu! difficulties
fa_osu_easy_osu = 0xe015,
fa_osu_normal_osu = 0xe016,
fa_osu_hard_osu = 0xe017,
fa_osu_insane_osu = 0xe018,
fa_osu_expert_osu = 0xe019,
// taiko difficulties
fa_osu_easy_taiko = 0xe01a,
fa_osu_normal_taiko = 0xe01b,
fa_osu_hard_taiko = 0xe01c,
fa_osu_insane_taiko = 0xe01d,
fa_osu_expert_taiko = 0xe01e,
// fruits difficulties
fa_osu_easy_fruits = 0xe01f,
fa_osu_normal_fruits = 0xe020,
fa_osu_hard_fruits = 0xe021,
fa_osu_insane_fruits = 0xe022,
fa_osu_expert_fruits = 0xe023,
// mania difficulties
fa_osu_easy_mania = 0xe024,
fa_osu_normal_mania = 0xe025,
fa_osu_hard_mania = 0xe026,
fa_osu_insane_mania = 0xe027,
fa_osu_expert_mania = 0xe028,
// mod icons
fa_osu_mod_perfect = 0xe049,
fa_osu_mod_autopilot = 0xe03a,
fa_osu_mod_auto = 0xe03b,
fa_osu_mod_cinema = 0xe03c,
fa_osu_mod_doubletime = 0xe03d,
fa_osu_mod_easy = 0xe03e,
fa_osu_mod_flashlight = 0xe03f,
fa_osu_mod_halftime = 0xe040,
fa_osu_mod_hardrock = 0xe041,
fa_osu_mod_hidden = 0xe042,
fa_osu_mod_nightcore = 0xe043,
fa_osu_mod_nofail = 0xe044,
fa_osu_mod_relax = 0xe045,
fa_osu_mod_spunout = 0xe046,
fa_osu_mod_suddendeath = 0xe047,
fa_osu_mod_target = 0xe048,
fa_osu_mod_bg = 0xe04a,
}
}
| |
// 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.Reflection.Internal;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Reflection.Metadata
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
public unsafe struct BlobReader
{
/// <summary>An array containing the '\0' character.</summary>
private static readonly char[] s_nullCharArray = new char[1] { '\0' };
internal const int InvalidCompressedInteger = int.MaxValue;
private readonly MemoryBlock _block;
// Points right behind the last byte of the block.
private readonly byte* _endPointer;
private byte* _currentPointer;
/// <summary>
/// Creates a reader of the specified memory block.
/// </summary>
/// <param name="buffer">Pointer to the start of the memory block.</param>
/// <param name="length">Length in bytes of the memory block.</param>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null and <paramref name="length"/> is greater than zero.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is negative.</exception>
/// <exception cref="PlatformNotSupportedException">The current platform is not little-endian.</exception>
public BlobReader(byte* buffer, int length)
: this(MemoryBlock.CreateChecked(buffer, length))
{
}
internal BlobReader(MemoryBlock block)
{
Debug.Assert(BitConverter.IsLittleEndian && block.Length >= 0 && (block.Pointer != null || block.Length == 0));
_block = block;
_currentPointer = block.Pointer;
_endPointer = block.Pointer + block.Length;
}
internal string GetDebuggerDisplay()
{
if (_block.Pointer == null)
{
return "<null>";
}
int displayedBytes;
string display = _block.GetDebuggerDisplay(out displayedBytes);
if (this.Offset < displayedBytes)
{
display = display.Insert(this.Offset * 3, "*");
}
else if (displayedBytes == _block.Length)
{
display += "*";
}
else
{
display += "*...";
}
return display;
}
#region Offset, Skipping, Marking, Alignment, Bounds Checking
/// <summary>
/// Pointer to the byte at the start of the underlying memory block.
/// </summary>
public byte* StartPointer => _block.Pointer;
/// <summary>
/// Pointer to the byte at the current position of the reader.
/// </summary>
public byte* CurrentPointer => _currentPointer;
/// <summary>
/// The total length of the underlying memory block.
/// </summary>
public int Length => _block.Length;
/// <summary>
/// Gets or sets the offset from start of the blob to the current position.
/// </summary>
/// <exception cref="BadImageFormatException">Offset is set outside the bounds of underlying reader.</exception>
public int Offset
{
get
{
return (int)(_currentPointer - _block.Pointer);
}
set
{
if (unchecked((uint)value) > (uint)_block.Length)
{
Throw.OutOfBounds();
}
_currentPointer = _block.Pointer + value;
}
}
/// <summary>
/// Bytes remaining from current position to end of underlying memory block.
/// </summary>
public int RemainingBytes => (int)(_endPointer - _currentPointer);
/// <summary>
/// Repositions the reader to the start of the underluing memory block.
/// </summary>
public void Reset()
{
_currentPointer = _block.Pointer;
}
/// <summary>
/// Repositions the reader forward by the number of bytes required to satisfy the given alignment.
/// </summary>
public void Align(byte alignment)
{
if (!TryAlign(alignment))
{
Throw.OutOfBounds();
}
}
internal bool TryAlign(byte alignment)
{
int remainder = this.Offset & (alignment - 1);
Debug.Assert((alignment & (alignment - 1)) == 0, "Alignment must be a power of two.");
Debug.Assert(remainder >= 0 && remainder < alignment);
if (remainder != 0)
{
int bytesToSkip = alignment - remainder;
if (bytesToSkip > RemainingBytes)
{
return false;
}
_currentPointer += bytesToSkip;
}
return true;
}
internal MemoryBlock GetMemoryBlockAt(int offset, int length)
{
CheckBounds(offset, length);
return new MemoryBlock(_currentPointer + offset, length);
}
#endregion
#region Bounds Checking
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int offset, int byteCount)
{
if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)(_endPointer - _currentPointer))
{
Throw.OutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int byteCount)
{
if (unchecked((uint)byteCount) > (_endPointer - _currentPointer))
{
Throw.OutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance(int length)
{
byte* p = _currentPointer;
if (unchecked((uint)length) > (uint)(_endPointer - p))
{
Throw.OutOfBounds();
}
_currentPointer = p + length;
return p;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance1()
{
byte* p = _currentPointer;
if (p == _endPointer)
{
Throw.OutOfBounds();
}
_currentPointer = p + 1;
return p;
}
#endregion
#region Read Methods
public bool ReadBoolean()
{
// It's not clear from the ECMA spec what exactly is the encoding of Boolean.
// Some metadata writers encode "true" as 0xff, others as 1. So we treat all non-zero values as "true".
//
// We propose to clarify and relax the current wording in the spec as follows:
//
// Chapter II.16.2 "Field init metadata"
// ... bool '(' true | false ')' Boolean value stored in a single byte, 0 represents false, any non-zero value represents true ...
//
// Chapter 23.3 "Custom attributes"
// ... A bool is a single byte with value 0 representing false and any non-zero value representing true ...
return ReadByte() != 0;
}
public sbyte ReadSByte()
{
return *(sbyte*)GetCurrentPointerAndAdvance1();
}
public byte ReadByte()
{
return *(byte*)GetCurrentPointerAndAdvance1();
}
public char ReadChar()
{
return *(char*)GetCurrentPointerAndAdvance(sizeof(char));
}
public short ReadInt16()
{
return *(short*)GetCurrentPointerAndAdvance(sizeof(short));
}
public ushort ReadUInt16()
{
return *(ushort*)GetCurrentPointerAndAdvance(sizeof(ushort));
}
public int ReadInt32()
{
return *(int*)GetCurrentPointerAndAdvance(sizeof(int));
}
public uint ReadUInt32()
{
return *(uint*)GetCurrentPointerAndAdvance(sizeof(uint));
}
public long ReadInt64()
{
return *(long*)GetCurrentPointerAndAdvance(sizeof(long));
}
public ulong ReadUInt64()
{
return *(ulong*)GetCurrentPointerAndAdvance(sizeof(ulong));
}
public float ReadSingle()
{
int val = ReadInt32();
return *(float*)&val;
}
public double ReadDouble()
{
long val = ReadInt64();
return *(double*)&val;
}
public Guid ReadGuid()
{
const int size = 16;
return *(Guid*)GetCurrentPointerAndAdvance(size);
}
/// <summary>
/// Reads <see cref="decimal"/> number.
/// </summary>
/// <remarks>
/// Decimal number is encoded in 13 bytes as follows:
/// - byte 0: highest bit indicates sign (1 for negative, 0 for non-negative); the remaining 7 bits encode scale
/// - bytes 1..12: 96-bit unsigned integer in little endian encoding.
/// </remarks>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid <see cref="decimal"/> number.</exception>
public decimal ReadDecimal()
{
byte* ptr = GetCurrentPointerAndAdvance(13);
byte scale = (byte)(*ptr & 0x7f);
if (scale > 28)
{
throw new BadImageFormatException(SR.ValueTooLarge);
}
return new decimal(
*(int*)(ptr + 1),
*(int*)(ptr + 5),
*(int*)(ptr + 9),
isNegative: (*ptr & 0x80) != 0,
scale: scale);
}
public DateTime ReadDateTime()
{
return new DateTime(ReadInt64());
}
public SignatureHeader ReadSignatureHeader()
{
return new SignatureHeader(ReadByte());
}
/// <summary>
/// Finds specified byte in the blob following the current position.
/// </summary>
/// <returns>
/// Index relative to the current position, or -1 if the byte is not found in the blob following the current position.
/// </returns>
/// <remarks>
/// Doesn't change the current position.
/// </remarks>
public int IndexOf(byte value)
{
int start = Offset;
int absoluteIndex = _block.IndexOfUnchecked(value, start);
return (absoluteIndex >= 0) ? absoluteIndex - start : -1;
}
/// <summary>
/// Reads UTF8 encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF8(int byteCount)
{
string s = _block.PeekUtf8(this.Offset, byteCount);
_currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads UTF16 (little-endian) encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF16(int byteCount)
{
string s = _block.PeekUtf16(this.Offset, byteCount);
_currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads bytes starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The byte array.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public byte[] ReadBytes(int byteCount)
{
byte[] bytes = _block.PeekBytes(this.Offset, byteCount);
_currentPointer += byteCount;
return bytes;
}
/// <summary>
/// Reads bytes starting at the current position in to the given buffer at the given offset;
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <param name="buffer">The destination buffer the bytes read will be written.</param>
/// <param name="bufferOffset">The offset in the destination buffer where the bytes read will be written.</param>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public void ReadBytes(int byteCount, byte[] buffer, int bufferOffset)
{
Marshal.Copy((IntPtr)GetCurrentPointerAndAdvance(byteCount), buffer, bufferOffset, byteCount);
}
internal string ReadUtf8NullTerminated()
{
int bytesRead;
string value = _block.PeekUtf8NullTerminated(this.Offset, null, MetadataStringDecoder.DefaultUTF8, out bytesRead, '\0');
_currentPointer += bytesRead;
return value;
}
private int ReadCompressedIntegerOrInvalid()
{
int bytesRead;
int value = _block.PeekCompressedInteger(this.Offset, out bytesRead);
_currentPointer += bytesRead;
return value;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedInteger(out int value)
{
value = ReadCompressedIntegerOrInvalid();
return value != InvalidCompressedInteger;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedInteger()
{
int value;
if (!TryReadCompressedInteger(out value))
{
Throw.InvalidCompressedInteger();
}
return value;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedSignedInteger(out int value)
{
int bytesRead;
value = _block.PeekCompressedInteger(this.Offset, out bytesRead);
if (value == InvalidCompressedInteger)
{
return false;
}
bool signExtend = (value & 0x1) != 0;
value >>= 1;
if (signExtend)
{
switch (bytesRead)
{
case 1:
value |= unchecked((int)0xffffffc0);
break;
case 2:
value |= unchecked((int)0xffffe000);
break;
default:
Debug.Assert(bytesRead == 4);
value |= unchecked((int)0xf0000000);
break;
}
}
_currentPointer += bytesRead;
return true;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedSignedInteger()
{
int value;
if (!TryReadCompressedSignedInteger(out value))
{
Throw.InvalidCompressedInteger();
}
return value;
}
/// <summary>
/// Reads type code encoded in a serialized custom attribute value.
/// </summary>
/// <returns><see cref="SerializationTypeCode.Invalid"/> if the encoding is invalid.</returns>
public SerializationTypeCode ReadSerializationTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
if (value > byte.MaxValue)
{
return SerializationTypeCode.Invalid;
}
return unchecked((SerializationTypeCode)value);
}
/// <summary>
/// Reads type code encoded in a signature.
/// </summary>
/// <returns><see cref="SignatureTypeCode.Invalid"/> if the encoding is invalid.</returns>
public SignatureTypeCode ReadSignatureTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
switch (value)
{
case (int)CorElementType.ELEMENT_TYPE_CLASS:
case (int)CorElementType.ELEMENT_TYPE_VALUETYPE:
return SignatureTypeCode.TypeHandle;
default:
if (value > byte.MaxValue)
{
return SignatureTypeCode.Invalid;
}
return unchecked((SignatureTypeCode)value);
}
}
/// <summary>
/// Reads a string encoded as a compressed integer containing its length followed by
/// its contents in UTF8. Null strings are encoded as a single 0xFF byte.
/// </summary>
/// <remarks>Defined as a 'SerString' in the ECMA CLI specification.</remarks>
/// <returns>String value or null.</returns>
/// <exception cref="BadImageFormatException">If the encoding is invalid.</exception>
public string ReadSerializedString()
{
int length;
if (TryReadCompressedInteger(out length))
{
// Removal of trailing '\0' is a departure from the spec, but required
// for compatibility with legacy compilers.
return ReadUTF8(length).TrimEnd(s_nullCharArray);
}
if (ReadByte() != 0xFF)
{
Throw.InvalidSerializedString();
}
return null;
}
/// <summary>
/// Reads a type handle encoded in a signature as TypeDefOrRefOrSpecEncoded (see ECMA-335 II.23.2.8).
/// </summary>
/// <returns>The handle or nil if the encoding is invalid.</returns>
public EntityHandle ReadTypeHandle()
{
uint value = (uint)ReadCompressedIntegerOrInvalid();
uint tokenType = s_corEncodeTokenArray[value & 0x3];
if (value == InvalidCompressedInteger || tokenType == 0)
{
return default(EntityHandle);
}
return new EntityHandle(tokenType | (value >> 2));
}
private static readonly uint[] s_corEncodeTokenArray = new uint[] { TokenTypeIds.TypeDef, TokenTypeIds.TypeRef, TokenTypeIds.TypeSpec, 0 };
/// <summary>
/// Reads a #Blob heap handle encoded as a compressed integer.
/// </summary>
/// <remarks>
/// Blobs that contain references to other blobs are used in Portable PDB format, for example <see cref="Document.Name"/>.
/// </remarks>
public BlobHandle ReadBlobHandle()
{
return BlobHandle.FromOffset(ReadCompressedInteger());
}
/// <summary>
/// Reads a constant value (see ECMA-335 Partition II section 22.9) from the current position.
/// </summary>
/// <exception cref="BadImageFormatException">Error while reading from the blob.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="typeCode"/> is not a valid <see cref="ConstantTypeCode"/>.</exception>
/// <returns>
/// Boxed constant value. To avoid allocating the object use Read* methods directly.
/// Constants of type <see cref="ConstantTypeCode.String"/> are encoded as UTF16 strings, use <see cref="ReadUTF16(int)"/> to read them.
/// </returns>
public object ReadConstant(ConstantTypeCode typeCode)
{
// Partition II section 22.9:
//
// Type shall be exactly one of: ELEMENT_TYPE_BOOLEAN, ELEMENT_TYPE_CHAR, ELEMENT_TYPE_I1,
// ELEMENT_TYPE_U1, ELEMENT_TYPE_I2, ELEMENT_TYPE_U2, ELEMENT_TYPE_I4, ELEMENT_TYPE_U4,
// ELEMENT_TYPE_I8, ELEMENT_TYPE_U8, ELEMENT_TYPE_R4, ELEMENT_TYPE_R8, or ELEMENT_TYPE_STRING;
// or ELEMENT_TYPE_CLASS with a Value of zero (23.1.16)
switch (typeCode)
{
case ConstantTypeCode.Boolean:
return ReadBoolean();
case ConstantTypeCode.Char:
return ReadChar();
case ConstantTypeCode.SByte:
return ReadSByte();
case ConstantTypeCode.Int16:
return ReadInt16();
case ConstantTypeCode.Int32:
return ReadInt32();
case ConstantTypeCode.Int64:
return ReadInt64();
case ConstantTypeCode.Byte:
return ReadByte();
case ConstantTypeCode.UInt16:
return ReadUInt16();
case ConstantTypeCode.UInt32:
return ReadUInt32();
case ConstantTypeCode.UInt64:
return ReadUInt64();
case ConstantTypeCode.Single:
return ReadSingle();
case ConstantTypeCode.Double:
return ReadDouble();
case ConstantTypeCode.String:
return ReadUTF16(RemainingBytes);
case ConstantTypeCode.NullReference:
// Partition II section 22.9:
// The encoding of Type for the nullref value is ELEMENT_TYPE_CLASS with a Value of a 4-byte zero.
// Unlike uses of ELEMENT_TYPE_CLASS in signatures, this one is not followed by a type token.
if (ReadUInt32() != 0)
{
throw new BadImageFormatException(SR.InvalidConstantValue);
}
return null;
default:
throw new ArgumentOutOfRangeException(nameof(typeCode));
}
}
#endregion
}
}
| |
using Xunit;
using System.Xml;
namespace XmlDocumentTests.XmlNodeTests
{
public static class PreviousSiblingTests
{
[Fact]
public static void OnElementNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><elem1/><elem2/><elem3/></root>");
var elem1 = xmlDocument.DocumentElement.ChildNodes[0];
var elem2 = xmlDocument.DocumentElement.ChildNodes[1];
var elem3 = xmlDocument.DocumentElement.ChildNodes[2];
Assert.Null(elem1.PreviousSibling);
Assert.Same(elem1, elem2.PreviousSibling);
Assert.Same(elem2, elem3.PreviousSibling);
}
[Fact]
public static void OnTextNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/>some text</root>");
Assert.Equal(XmlNodeType.Text, xmlDocument.DocumentElement.ChildNodes[1].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[1].PreviousSibling, xmlDocument.DocumentElement.ChildNodes[0]);
}
[Fact]
public static void OnTextNodeSplit()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>some text</root>");
var textNode = (XmlText)xmlDocument.DocumentElement.FirstChild;
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Null(textNode.PreviousSibling);
var split = textNode.SplitText(4);
Assert.Equal(2, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(textNode, split.PreviousSibling);
Assert.Null(textNode.PreviousSibling);
}
[Fact]
public static void OnCommentNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><!--some text--></root>");
Assert.Equal(XmlNodeType.Comment, xmlDocument.DocumentElement.ChildNodes[1].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[0], xmlDocument.DocumentElement.ChildNodes[1].PreviousSibling);
}
[Fact]
public static void SiblingOfLastChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>some text<child1/><child2/></root>");
Assert.Same(xmlDocument.DocumentElement.ChildNodes[1], xmlDocument.DocumentElement.LastChild.PreviousSibling);
}
[Fact]
public static void OnCDataNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><![CDATA[ <opentag> without an </endtag> and & <! are all ok here ]]></root>");
Assert.Equal(XmlNodeType.CDATA, xmlDocument.DocumentElement.ChildNodes[1].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[0], xmlDocument.DocumentElement.ChildNodes[1].PreviousSibling);
}
[Fact]
public static void OnDocumentFragment()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/>some text<child2/><child3/></root>");
var documentFragment = xmlDocument.CreateDocumentFragment();
documentFragment.AppendChild(xmlDocument.DocumentElement);
Assert.Null(documentFragment.PreviousSibling);
}
[Fact]
public static void OnDocumentElement()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<?PI pi info?><root/>");
var piInfo = xmlDocument.ChildNodes[0];
Assert.Equal(XmlNodeType.ProcessingInstruction, piInfo.NodeType);
Assert.Equal(piInfo, xmlDocument.DocumentElement.PreviousSibling);
}
[Fact]
public static void OnAttributeNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root attr1='test' attr2='test2' />");
var attr1 = xmlDocument.DocumentElement.Attributes[0];
var attr2 = xmlDocument.DocumentElement.Attributes[1];
Assert.Equal("attr1", attr1.Name);
Assert.Equal("attr2", attr2.Name);
Assert.Null(attr1.PreviousSibling);
Assert.Null(attr2.PreviousSibling);
}
[Fact]
public static void OnAttributeNodeWithChildren()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root attr1='test' attr2='test2'><child1/><child2/><child3/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
var child3 = xmlDocument.DocumentElement.ChildNodes[2];
Assert.Null(child1.PreviousSibling);
Assert.Same(child1, child2.PreviousSibling);
Assert.Same(child2, child3.PreviousSibling);
}
[Fact]
public static void ElementOneChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child/></root>");
Assert.Null(xmlDocument.DocumentElement.ChildNodes[0].PreviousSibling);
}
[Fact]
public static void OnAllSiblings()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3 attr='1'/>Some Text<child4/><!-- comment --><?PI processing info?></root>");
var count = xmlDocument.DocumentElement.ChildNodes.Count;
var nextNode = xmlDocument.DocumentElement.ChildNodes[count - 1];
for (var idx = count - 2; idx >= 0; idx--)
{
var currentNode = xmlDocument.DocumentElement.ChildNodes[idx];
Assert.Equal(currentNode, nextNode.PreviousSibling);
nextNode = currentNode;
}
Assert.Null(nextNode.PreviousSibling);
}
[Fact]
public static void RemoveChildCheckSibling()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
Assert.Equal("child1", child1.Name);
Assert.Equal("child2", child2.Name);
Assert.Equal(child1, child2.PreviousSibling);
Assert.Null(child1.PreviousSibling);
xmlDocument.DocumentElement.RemoveChild(child2);
Assert.Null(child2.PreviousSibling);
Assert.Null(child1.PreviousSibling);
}
[Fact]
public static void ReplaceChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
var child3 = xmlDocument.DocumentElement.ChildNodes[2];
Assert.Null(child1.PreviousSibling);
Assert.Same(child1, child2.PreviousSibling);
Assert.Same(child2, child3.PreviousSibling);
var newNode = xmlDocument.CreateElement("child4");
xmlDocument.DocumentElement.ReplaceChild(newNode, child2);
Assert.Null(child1.PreviousSibling);
Assert.Same(child1, newNode.PreviousSibling);
Assert.Same(newNode, child3.PreviousSibling);
Assert.Null(child2.PreviousSibling);
}
[Fact]
public static void InsertChildAfter()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var newNode = xmlDocument.CreateElement("child2");
Assert.Null(child1.PreviousSibling);
xmlDocument.DocumentElement.InsertAfter(newNode, child1);
Assert.Null(child1.PreviousSibling);
Assert.Same(child1, newNode.PreviousSibling);
}
[Fact]
public static void InsertChildBefore()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var newNode = xmlDocument.CreateElement("child2");
Assert.Null(child1.PreviousSibling);
xmlDocument.DocumentElement.InsertBefore(newNode, child1);
Assert.Same(newNode, child1.PreviousSibling);
Assert.Null(newNode.PreviousSibling);
}
[Fact]
public static void AppendChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var newNode = xmlDocument.CreateElement("child2");
Assert.Null(child1.PreviousSibling);
xmlDocument.DocumentElement.AppendChild(newNode);
Assert.Same(child1, newNode.PreviousSibling);
Assert.Null(child1.PreviousSibling);
}
[Fact]
public static void NewlyCreatedElement()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateElement("element");
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void NewlyCreatedAttribute()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateAttribute("attribute");
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void NewlyCreatedTextNode()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateTextNode("textnode");
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void NewlyCreatedCDataNode()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateCDataSection("cdata section");
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void NewlyCreatedProcessingInstruction()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateProcessingInstruction("PI", "data");
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void NewlyCreatedComment()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateComment("comment");
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void NewlyCreatedDocumentFragment()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateDocumentFragment();
Assert.Null(node.PreviousSibling);
}
[Fact]
public static void FirstChildNextSibling()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
Assert.Null(xmlDocument.DocumentElement.FirstChild.PreviousSibling);
}
}
}
| |
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(SplineMesh))]
public class SplineMeshInspector : InstantInspector
{
private SerializedProperty splineProp;
private SerializedProperty updateModeProp;
private SerializedProperty deltaFramesProp;
private SerializedProperty deltaTimeProp;
private SerializedProperty startMeshProp;
private SerializedProperty baseMeshProp;
private SerializedProperty endMeshProp;
private SerializedProperty xyScaleProp;
private SerializedProperty uvScaleProp;
private SerializedProperty uvModeProp;
private SerializedProperty highAccuracyProp;
private SerializedProperty segmentCountProp;
private SerializedProperty splineSegmentProp;
private SerializedProperty segmentStartProp;
private SerializedProperty segmentEndProp;
private SerializedProperty splitModeProp;
private GUIStyle buttonGUIStyleLeft;
private GUIStyle buttonGUIStyleRight;
private const string noSplineHint = "Please select the spline that shall be used for mesh generation.";
private const string noMeshHint = "Please specify a base mesh. A middle mesh is required.";
private const string highAccuracyHint = "If \"High Accuracy\" is enabled the mesh generation will be slower and shouldn't be performed every frame! " +
"\nConsider exporting the generated mesh or changing the \"Update Mode\" to \"DontUpdate\", \"EveryXSeconds\" or \"EveryXFrames\"!";
public void OnEnable( )
{
splineProp = serializedObject.FindProperty( "spline" );
startMeshProp = serializedObject.FindProperty( "startBaseMesh" );
baseMeshProp = serializedObject.FindProperty( "baseMesh" );
endMeshProp = serializedObject.FindProperty( "endBaseMesh" );
uvScaleProp = serializedObject.FindProperty( "uvScale" );
xyScaleProp = serializedObject.FindProperty( "xyScale" );
uvModeProp = serializedObject.FindProperty( "uvMode" );
splitModeProp = serializedObject.FindProperty( "splitMode" );
highAccuracyProp = serializedObject.FindProperty( "highAccuracy" );
updateModeProp = serializedObject.FindProperty( "updateMode" );
deltaFramesProp = serializedObject.FindProperty( "deltaFrames" );
deltaTimeProp = serializedObject.FindProperty( "deltaTime" );
segmentCountProp = serializedObject.FindProperty( "segmentCount" );
splineSegmentProp = serializedObject.FindProperty( "splineSegment" );
segmentStartProp = serializedObject.FindProperty( "segmentStart" );
segmentEndProp = serializedObject.FindProperty( "segmentEnd" );
}
public override void OnInspectorGUIInner( )
{
DrawSplineField( );
DrawUpdateOptions( );
DrawBaseMeshes( );
DrawMeshOptions( );
DrawSegmentOptions( );
DrawMeshTools( );
}
private void DrawUpdateOptions( )
{
EditorGUILayout.PrefixLabel( "Update Options", EditorStyles.label, EditorStyles.boldLabel );
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField( updateModeProp, new GUIContent( "Update Mode" ), true );
switch( (Spline.UpdateMode) updateModeProp.enumValueIndex )
{
case Spline.UpdateMode.EveryXFrames:
EditorGUILayout.PropertyField( deltaFramesProp, new GUIContent( "Delta Frames" ) );
deltaFramesProp.intValue = Mathf.Max( deltaFramesProp.intValue, 2 );
break;
case Spline.UpdateMode.EveryXSeconds:
EditorGUILayout.PropertyField( deltaTimeProp, new GUIContent( "Delta Seconds" ) );
deltaTimeProp.floatValue = Mathf.Max( deltaTimeProp.floatValue, 0.01f );
break;
}
--EditorGUI.indentLevel;
}
private void DrawSegmentOptions( )
{
if( targets.Length != 1 )
{
EditorGUILayout.HelpBox( "Multi-editing is not supported for some options. Please select only one SplineMesh!", MessageType.Warning );
return;
}
EditorGUILayout.PrefixLabel( "Segmentation Options", EditorStyles.label, EditorStyles.boldLabel );
++EditorGUI.indentLevel;
EditorGUILayout.IntSlider( segmentCountProp, 2, MaxSegmentCount( ), new GUIContent( "Segment Count" ) );
SmallSpace( );
EditorGUILayout.PropertyField( splitModeProp, new GUIContent( "Split Mode" ) );
++EditorGUI.indentLevel;
switch( (SplineMesh.SplitMode) splitModeProp.enumValueIndex )
{
case SplineMesh.SplitMode.BySplineParameter:
EditorGUI.BeginChangeCheck( );
float start = segmentStartProp.floatValue;
float end = segmentEndProp.floatValue;
EditorGUILayout.MinMaxSlider( new GUIContent( "Spline Parameter" ), ref start, ref end, 0, 1 );
segmentStartProp.floatValue = start;
segmentEndProp.floatValue = end;
EditorGUI.EndChangeCheck( );
DrawHorizontalFields( segmentStartProp, segmentEndProp, "Values", "S", "E" );
break;
case SplineMesh.SplitMode.BySplineSegment:
Spline targetSpline = splineProp.objectReferenceValue as Spline;
int maxSegments = (targetSpline != null ) ? targetSpline.SegmentCount-1 : 1;
EditorGUILayout.IntSlider( splineSegmentProp, 0, maxSegments, new GUIContent( "Segment Index" ) );
break;
case SplineMesh.SplitMode.DontSplit:
break;
}
--EditorGUI.indentLevel;
SmallSpace( );
SmallSpace( );
--EditorGUI.indentLevel;
}
private void DrawSplineField( )
{
//Spline Property
EditorGUILayout.PrefixLabel( "Spline", EditorStyles.label, EditorStyles.boldLabel );
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField( splineProp, GUIContent.none );
--EditorGUI.indentLevel;
if( splineProp.objectReferenceValue == null )
EditorGUILayout.HelpBox( noSplineHint, MessageType.Warning, true );
SmallSpace( );
}
private void DrawBaseMeshes( )
{
//Mesh property
EditorGUILayout.PrefixLabel( "Base Meshes", EditorStyles.label, EditorStyles.boldLabel );
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField( startMeshProp, new GUIContent( "Start Mesh" ) );
EditorGUILayout.PropertyField( baseMeshProp, new GUIContent( "Middle Mesh" ) );
EditorGUILayout.PropertyField( endMeshProp, new GUIContent( "End Mesh" ) );
--EditorGUI.indentLevel;
if( baseMeshProp.objectReferenceValue == null )
EditorGUILayout.HelpBox( noMeshHint, MessageType.Warning, false );
SmallSpace( );
}
private void DrawMeshOptions( )
{
EditorGUILayout.PrefixLabel( "Mesh Options", EditorStyles.label, EditorStyles.boldLabel );
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField( uvModeProp, new GUIContent( "UV-Mode" ) );
DrawVectorFields( uvScaleProp, "UV Scale", "U", "V" );
DrawVectorFields( xyScaleProp, "Mesh Scale", "X", "Y" );
SmallSpace( );
EditorGUILayout.PropertyField( highAccuracyProp, new GUIContent( "High Accuracy" ) );
if( highAccuracyProp.boolValue && ((SplineMesh.UpdateMode)updateModeProp.enumValueIndex) == SplineMesh.UpdateMode.WhenSplineChanged )
EditorGUILayout.HelpBox( highAccuracyHint, MessageType.Info, false );
--EditorGUI.indentLevel;
SmallSpace( );
}
private void DrawVectorFields( SerializedProperty property, string label, string xLabel, string yLabel )
{
EditorGUILayout.LabelField( label );
++EditorGUI.indentLevel;
DrawHorizontalFields( property.FindPropertyRelative( "x" ), property.FindPropertyRelative( "y" ), label, xLabel, yLabel );
--EditorGUI.indentLevel;
}
private void DrawHorizontalFields( SerializedProperty property1, SerializedProperty property2, string label, string label1, string label2 )
{
EditorGUILayout.BeginHorizontal( );
EditorGUIUtility.LookLikeControls(60, 40);
EditorGUILayout.PropertyField( property1, new GUIContent( label1 ) );
PushIndentLevel( );
EditorGUI.indentLevel = 1;
EditorGUIUtility.LookLikeControls(25, 40);
EditorGUILayout.PropertyField( property2, new GUIContent( label2 ) );
PopIndentLevel( );
DefaultWidths( );
EditorGUILayout.EndHorizontal( );
}
private void DrawMeshTools( )
{
EditorGUILayout.BeginHorizontal( );
GUILayout.Space( 15 );
SplineMesh sMesh = target as SplineMesh;
if( GUILayout.Button( "Export Mesh", GetLeftButtonGUIStyle( ), GUILayout.Height( 23f ) ) )
{
string filePath = EditorUtility.SaveFilePanelInProject( "Export Spline Mesh", "Spline Mesh (" + target.name + ")", "asset", "" );
if( filePath.Trim( ) != "" )
{
Mesh mesh = new Mesh( );
mesh.vertices = sMesh.BentMesh.vertices;
mesh.normals = sMesh.BentMesh.normals;
mesh.tangents = sMesh.BentMesh.tangents;
mesh.uv = sMesh.BentMesh.uv;
mesh.triangles = sMesh.BentMesh.triangles;
AssetDatabase.CreateAsset( mesh, filePath );
AssetDatabase.SaveAssets( );
mesh.hideFlags = HideFlags.HideAndDontSave;
}
}
if( GUILayout.Button( "View Mesh", GetRightButtonGUIStyle( ), GUILayout.Height( 23f ) ) )
Selection.activeObject = sMesh.BentMesh;
EditorGUILayout.EndHorizontal( );
}
public override void OnInspectorChanged( )
{
foreach( Object targetObject in serializedObject.targetObjects )
(targetObject as SplineMesh).UpdateMesh( );
}
private int MaxSegmentCount( )
{
int unusedVertices = 65000;
SplineMesh splineMesh = target as SplineMesh;
if( splineMesh.spline == null )
return unusedVertices;
else if( splineMesh.baseMesh == null )
return unusedVertices;
if( splineMesh.startBaseMesh != null && splineMesh.splineSegment <= 0 )
unusedVertices -= splineMesh.startBaseMesh.vertexCount;
if( splineMesh.endBaseMesh != null && (splineMesh.splineSegment == -1 || splineMesh.splineSegment == splineMesh.spline.SegmentCount-1) )
unusedVertices -= splineMesh.endBaseMesh.vertexCount;
return (unusedVertices - (unusedVertices % splineMesh.baseMesh.vertexCount)) / splineMesh.baseMesh.vertexCount;
}
private int MaxSplineSegment( )
{
Spline spline = splineProp.objectReferenceValue as Spline;
if( spline != null )
return spline.SegmentCount-1;
else
return 0;
}
private GUIStyle GetLeftButtonGUIStyle( )
{
if( buttonGUIStyleLeft == null )
{
buttonGUIStyleLeft = new GUIStyle( EditorStyles.miniButtonLeft );
buttonGUIStyleLeft.alignment = TextAnchor.MiddleCenter;
buttonGUIStyleLeft.wordWrap = true;
buttonGUIStyleLeft.border = new RectOffset( 3, 3, 3, 3 );
buttonGUIStyleLeft.contentOffset = - Vector2.up * 2f;
buttonGUIStyleLeft.fontSize = 12;
}
return buttonGUIStyleLeft;
}
private GUIStyle GetRightButtonGUIStyle( )
{
if( buttonGUIStyleRight == null )
{
buttonGUIStyleRight = new GUIStyle( EditorStyles.miniButtonRight );
buttonGUIStyleRight.alignment = TextAnchor.MiddleCenter;
buttonGUIStyleRight.wordWrap = true;
buttonGUIStyleRight.border = new RectOffset( 3, 3, 3, 3 );
buttonGUIStyleRight.contentOffset = - Vector2.up * 2f;
buttonGUIStyleRight.fontSize = 12;
}
return buttonGUIStyleRight;
}
}
| |
using System;
using System.Diagnostics;
using System.Drawing;
using System.Collections;
using System.IO;
using System.ComponentModel;
using System.Windows.Forms;
using PdfSharp.Pdf;
using PdfSharp.Pdf.Advanced;
using PdfSharp.Pdf.Annotations;
namespace PdfSharp.Explorer
{
/// <summary>
/// MainForm.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.Panel clientArea;
private System.Windows.Forms.StatusBarPanel statusBarPanel1;
private System.Windows.Forms.StatusBarPanel statusBarPanel2;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.MenuItem miOpen;
private System.Windows.Forms.MenuItem miClose;
private System.Windows.Forms.MenuItem miExit;
private System.Windows.Forms.ImageList ilToolBar;
private System.Windows.Forms.ToolBarButton tbbOpen;
private System.Windows.Forms.ToolBarButton tbbSave;
private System.Windows.Forms.ToolBarButton tbbBack;
private System.Windows.Forms.ToolBarButton tbbForward;
private System.Windows.Forms.ToolBarButton separator1;
private System.Windows.Forms.ToolBar mainToolBar;
private System.Windows.Forms.StatusBar mainStatusBar;
private System.Windows.Forms.ToolBarButton separator2;
private System.Windows.Forms.ToolBarButton tbbCopy;
private System.ComponentModel.IContainer components;
public MainForm(ExplorerProcess process)
{
this.process = process;
InitializeComponent();
this.explorer = new ExplorerPanel(this);
explorer.Dock = DockStyle.Fill;
this.clientArea.Controls.Add(explorer);
this.title = this.Text;
}
string title;
ExplorerPanel explorer;
public ExplorerProcess Process
{
get {return this.process;}
}
ExplorerProcess process;
void OpenDocument(string path)
{
try
{
Process.OpenDocument(path);
this.Text = Path.GetFullPath(path) + " - " + this.title;
this.explorer.OnNewDocument();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, this.title);
}
}
void UpdateUI()
{
try
{
//this.tbbOpen.Enabled = false;
//this.tbbSave.Enabled = false;
//this.tbbBack.Enabled = this.process.Navigator.CanMoveBack;
//this.tbbForward.Enabled = this.process.Navigator.CanMoveForward;
}
finally
{
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
//OpenDocument("../../Output.pdf");
if (this.process.Document != null)
{
this.Text = this.process.Filename + " - " + this.title;
this.explorer.OnNewDocument();
}
UpdateUI();
}
void OpenFile()
{
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.RestoreDirectory = true;
dialog.CheckFileExists = true;
dialog.CheckPathExists = true;
dialog.Multiselect = false;
dialog.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
if (dialog.ShowDialog() == DialogResult.OK)
{
string fileName = dialog.FileName;
OpenDocument(fileName);
this.process.FormatDocument(fileName);
}
}
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
this.mainMenu = new System.Windows.Forms.MainMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.miOpen = new System.Windows.Forms.MenuItem();
this.miClose = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.miExit = new System.Windows.Forms.MenuItem();
this.mainToolBar = new System.Windows.Forms.ToolBar();
this.tbbOpen = new System.Windows.Forms.ToolBarButton();
this.tbbSave = new System.Windows.Forms.ToolBarButton();
this.separator1 = new System.Windows.Forms.ToolBarButton();
this.tbbBack = new System.Windows.Forms.ToolBarButton();
this.tbbForward = new System.Windows.Forms.ToolBarButton();
this.ilToolBar = new System.Windows.Forms.ImageList(this.components);
this.mainStatusBar = new System.Windows.Forms.StatusBar();
this.statusBarPanel1 = new System.Windows.Forms.StatusBarPanel();
this.statusBarPanel2 = new System.Windows.Forms.StatusBarPanel();
this.clientArea = new System.Windows.Forms.Panel();
this.separator2 = new System.Windows.Forms.ToolBarButton();
this.tbbCopy = new System.Windows.Forms.ToolBarButton();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel2)).BeginInit();
this.SuspendLayout();
//
// mainMenu
//
this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miOpen,
this.miClose,
this.menuItem3,
this.miExit});
this.menuItem1.Text = "&File";
//
// miOpen
//
this.miOpen.Index = 0;
this.miOpen.Text = "&Open";
this.miOpen.Click += new System.EventHandler(this.miOpen_Click);
//
// miClose
//
this.miClose.Index = 1;
this.miClose.Text = "&Close";
this.miClose.Click += new System.EventHandler(this.miClose_Click);
//
// menuItem3
//
this.menuItem3.Index = 2;
this.menuItem3.Text = "-";
//
// miExit
//
this.miExit.Index = 3;
this.miExit.Text = "E&xit";
this.miExit.Click += new System.EventHandler(this.miExit_Click);
//
// mainToolBar
//
this.mainToolBar.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
this.mainToolBar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.tbbOpen,
this.separator1,
this.tbbCopy,
this.tbbSave,
this.separator2,
this.tbbBack,
this.tbbForward});
this.mainToolBar.DropDownArrows = true;
this.mainToolBar.ImageList = this.ilToolBar;
this.mainToolBar.Location = new System.Drawing.Point(0, 0);
this.mainToolBar.Name = "mainToolBar";
this.mainToolBar.ShowToolTips = true;
this.mainToolBar.Size = new System.Drawing.Size(992, 28);
this.mainToolBar.TabIndex = 0;
this.mainToolBar.TextAlign = System.Windows.Forms.ToolBarTextAlign.Right;
this.mainToolBar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.mainToolBar_ButtonClick);
//
// tbbOpen
//
this.tbbOpen.ImageIndex = 0;
this.tbbOpen.Tag = "Open";
this.tbbOpen.Text = "Open";
this.tbbOpen.ToolTipText = "Open PDF file";
//
// tbbSave
//
this.tbbSave.ImageIndex = 1;
this.tbbSave.Tag = "Save";
this.tbbSave.Text = "Save";
this.tbbSave.ToolTipText = "Save stream to file";
//
// separator1
//
this.separator1.Enabled = false;
this.separator1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// tbbBack
//
this.tbbBack.ImageIndex = 2;
this.tbbBack.Tag = "Back";
this.tbbBack.Text = "Back";
this.tbbBack.ToolTipText = "Move to previous item";
//
// tbbForward
//
this.tbbForward.ImageIndex = 3;
this.tbbForward.Tag = "Forward";
this.tbbForward.Text = "Forward";
this.tbbForward.ToolTipText = "Move to next item";
//
// ilToolBar
//
this.ilToolBar.ImageSize = new System.Drawing.Size(16, 16);
this.ilToolBar.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ilToolBar.ImageStream")));
this.ilToolBar.TransparentColor = System.Drawing.Color.Lime;
//
// mainStatusBar
//
this.mainStatusBar.Location = new System.Drawing.Point(0, 673);
this.mainStatusBar.Name = "mainStatusBar";
this.mainStatusBar.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
this.statusBarPanel1,
this.statusBarPanel2});
this.mainStatusBar.ShowPanels = true;
this.mainStatusBar.Size = new System.Drawing.Size(992, 22);
this.mainStatusBar.TabIndex = 1;
this.mainStatusBar.Text = "statusBar1";
//
// clientArea
//
this.clientArea.Dock = System.Windows.Forms.DockStyle.Fill;
this.clientArea.Location = new System.Drawing.Point(0, 28);
this.clientArea.Name = "clientArea";
this.clientArea.Size = new System.Drawing.Size(992, 645);
this.clientArea.TabIndex = 2;
//
// separator2
//
this.separator2.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// tbbCopy
//
this.tbbCopy.ImageIndex = 4;
this.tbbCopy.Tag = "Copy";
this.tbbCopy.Text = "Copy";
this.tbbCopy.ToolTipText = "Copy stream to clipboard";
//
// MainForm
//
this.AllowDrop = true;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(992, 695);
this.Controls.Add(this.clientArea);
this.Controls.Add(this.mainStatusBar);
this.Controls.Add(this.mainToolBar);
this.Menu = this.mainMenu;
this.MinimumSize = new System.Drawing.Size(800, 600);
this.Name = "MainForm";
this.Text = "PDFsharp Document Explorer";
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel2)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void miOpen_Click(object sender, System.EventArgs e)
{
OpenFile();
}
private void miClose_Click(object sender, System.EventArgs e)
{
}
private void miExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void mainToolBar_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
#if true_
PdfDocument document = PdfSharp.Pdf.IO.PdfReader.Open(@"G:\!StLa\PDFsharp Problems\06-05-22\Test1.pdf");
PdfPage page = document.Pages[0];
PdfAnnotations annotations = page.Annotations;
object o = annotations[0];
foreach (PdfAnnotation annotation in annotations)
{
annotation.GetType();
string s = annotation.Contents;
Debug.WriteLine(s);
}
#endif
switch ((string)e.Button.Tag)
{
case "Open":
OpenFile();
break;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Worker;
using Moq;
using Xunit;
using Expressions = Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Expressions;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker
{
public sealed class ExpressionManagerL0
{
private Mock<IExecutionContext> _ec;
private ExpressionManager _expressionManager;
private Variables _variables;
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void AlwaysFunction()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new { JobStatus = (TaskResult?)null, Expected = true },
new { JobStatus = (TaskResult?)TaskResult.Canceled, Expected = true },
new { JobStatus = (TaskResult?)TaskResult.Failed, Expected = true },
new { JobStatus = (TaskResult?)TaskResult.Succeeded, Expected = true },
new { JobStatus = (TaskResult?)TaskResult.SucceededWithIssues, Expected = true },
};
foreach (var variableSet in variableSets)
{
InitializeExecutionContext(hc);
_ec.Object.Variables.Agent_JobStatus = variableSet.JobStatus;
Expressions.INode condition = _expressionManager.Parse(_ec.Object, "always()");
// Act.
bool actual = _expressionManager.Evaluate(_ec.Object, condition);
// Assert.
Assert.Equal(variableSet.Expected, actual);
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void CanceledFunction()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new { JobStatus = (TaskResult?)TaskResult.Canceled, Expected = true },
new { JobStatus = (TaskResult?)null, Expected = false },
new { JobStatus = (TaskResult?)TaskResult.Failed, Expected = false },
new { JobStatus = (TaskResult?)TaskResult.Succeeded, Expected = false },
new { JobStatus = (TaskResult?)TaskResult.SucceededWithIssues, Expected = false },
};
foreach (var variableSet in variableSets)
{
InitializeExecutionContext(hc);
_ec.Object.Variables.Agent_JobStatus = variableSet.JobStatus;
Expressions.INode condition = _expressionManager.Parse(_ec.Object, "canceled()");
// Act.
bool actual = _expressionManager.Evaluate(_ec.Object, condition);
// Assert.
Assert.Equal(variableSet.Expected, actual);
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void FailedFunction()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new { JobStatus = (TaskResult?)TaskResult.Failed, Expected = true },
new { JobStatus = (TaskResult?)null, Expected = false },
new { JobStatus = (TaskResult?)TaskResult.Canceled, Expected = false },
new { JobStatus = (TaskResult?)TaskResult.Succeeded, Expected = false },
new { JobStatus = (TaskResult?)TaskResult.SucceededWithIssues, Expected = false },
};
foreach (var variableSet in variableSets)
{
InitializeExecutionContext(hc);
_ec.Object.Variables.Agent_JobStatus = variableSet.JobStatus;
Expressions.INode condition = _expressionManager.Parse(_ec.Object, "failed()");
// Act.
bool actual = _expressionManager.Evaluate(_ec.Object, condition);
// Assert.
Assert.Equal(variableSet.Expected, actual);
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void SucceededFunction()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new { JobStatus = (TaskResult?)null, Expected = true },
new { JobStatus = (TaskResult?)TaskResult.Succeeded, Expected = true },
new { JobStatus = (TaskResult?)TaskResult.SucceededWithIssues, Expected = true },
new { JobStatus = (TaskResult?)TaskResult.Canceled, Expected = false },
new { JobStatus = (TaskResult?)TaskResult.Failed, Expected = false },
};
foreach (var variableSet in variableSets)
{
InitializeExecutionContext(hc);
_ec.Object.Variables.Agent_JobStatus = variableSet.JobStatus;
Expressions.INode condition = _expressionManager.Parse(_ec.Object, "succeeded()");
// Act.
bool actual = _expressionManager.Evaluate(_ec.Object, condition);
// Assert.
Assert.Equal(variableSet.Expected, actual);
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void SucceededOrFailedFunction()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new { JobStatus = (TaskResult?)null, Expected = true },
new { JobStatus = (TaskResult?)TaskResult.Succeeded, Expected = true },
new { JobStatus = (TaskResult?)TaskResult.SucceededWithIssues, Expected = true },
new { JobStatus = (TaskResult?)TaskResult.Failed, Expected = true },
new { JobStatus = (TaskResult?)TaskResult.Canceled, Expected = false },
};
foreach (var variableSet in variableSets)
{
InitializeExecutionContext(hc);
_ec.Object.Variables.Agent_JobStatus = variableSet.JobStatus;
Expressions.INode condition = _expressionManager.Parse(_ec.Object, "succeededOrFailed()");
// Act.
bool actual = _expressionManager.Evaluate(_ec.Object, condition);
// Assert.
Assert.Equal(variableSet.Expected, actual);
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void VariablesNamedValue()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new { Condition = "eq(variables.someVARIABLE, 'someVALUE')", VariableName = "SOMEvariable", VariableValue = "SOMEvalue", Expected = true },
new { Condition = "eq(variables['some.VARIABLE'], 'someVALUE')", VariableName = "SOME.variable", VariableValue = "SOMEvalue", Expected = true },
new { Condition = "eq(variables.nosuch, '')", VariableName = "SomeVariable", VariableValue = "SomeValue", Expected = true },
new { Condition = "eq(variables['some.VARIABLE'], 'other value')", VariableName = "SOME.variable", VariableValue = "SOMEvalue", Expected = false },
new { Condition = "eq(variables.nosuch, 'SomeValue')", VariableName = "SomeVariable", VariableValue = "SomeValue", Expected = false },
};
foreach (var variableSet in variableSets)
{
InitializeExecutionContext(hc);
_ec.Object.Variables.Set(variableSet.VariableName, variableSet.VariableValue);
Expressions.INode condition = _expressionManager.Parse(_ec.Object, variableSet.Condition);
// Act.
bool actual = _expressionManager.Evaluate(_ec.Object, condition);
// Assert.
Assert.Equal(variableSet.Expected, actual);
}
}
}
private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
{
var hc = new TestHostContext(this, testName);
_expressionManager = new ExpressionManager();
_expressionManager.Initialize(hc);
return hc;
}
private void InitializeExecutionContext(TestHostContext hc)
{
List<string> warnings;
_variables = new Variables(
hostContext: hc,
copy: new Dictionary<string, string>(),
maskHints: new List<MaskHint>(),
warnings: out warnings);
_ec = new Mock<IExecutionContext>();
_ec.SetupAllProperties();
_ec.Setup(x => x.Variables).Returns(_variables);
}
}
}
| |
using System;
using System.Collections;
namespace Test.Framework
{
/// <class>TestCase</class>
/// <date>Jun 16, 2004</date>
/// <brief></brief>
public abstract class TestCase
{
protected string testcaseId;
protected string component;
protected string function;
protected string title;
protected string purpose;
protected string input;
protected TestFramework testFramework;
private readonly ArrayList preItems = new ArrayList();
private readonly ArrayList postItems = new ArrayList();
private readonly Hashtable registered = new Hashtable();
public virtual string Function
{
get
{
return function;
}
}
public virtual string Input
{
get
{
return input;
}
}
public virtual string Purpose
{
get
{
return purpose;
}
}
public virtual string TestcaseId
{
get
{
return testcaseId;
}
}
public virtual string Title
{
get
{
return title;
}
}
public virtual string Component
{
get
{
return component;
}
}
public TestCase(string testcaseId, string component, string function, string title,
string purpose, string input)
{
this.testcaseId = testcaseId;
this.component = component;
this.function = function;
this.title = title;
this.purpose = purpose;
this.input = input;
}
public void AddPreItem(TestItem item)
{
preItems.Add(item);
}
public void AddPostItem(TestItem item)
{
postItems.Add(item);
}
public TestResult Execute(TestFramework fw)
{
TestItem item;
TestResult result = null;
TestResult itemResult;
bool proceed = true;
int i;
this.testFramework = fw;
for (i = 0; i < preItems.Count && proceed; i++)
{
item = (TestItem)preItems[i];
fw.TestItem(item.title);
try
{
itemResult = item.Run(this);
fw.ItemComposeVerdict(itemResult.ExpectedVerdict, itemResult.Verdict);
proceed = item.MayProceed(itemResult);
}
catch (System.Exception exc)
{
fw.TestMessage(TestMessage.Error, GetExceptionReport(exc));
itemResult = new TestResult("UNKNOWN", exc.Message, TestVerdict
.Pass, TestVerdict.Fail);
fw.ItemComposeVerdict(itemResult.ExpectedVerdict, itemResult.Verdict);
proceed = false;
}
}
while (i < preItems.Count)
{
item = (TestItem)preItems[i];
fw.TestItem(item.title);
fw.ItemComposeVerdict(TestVerdict.Unresolved, TestVerdict
.Unresolved);
i++;
}
if (proceed)
{
try
{
result = this.Run();
}
catch (System.Exception exc)
{
fw.TestMessage(TestMessage.Error, GetExceptionReport(exc));
result = new TestResult("UNKNOWN", exc.Message, TestVerdict.Pass,
TestVerdict.Fail);
}
}
else
{
result = new TestResult("Test succeeded", "Test could not be initialized",
TestVerdict.Unresolved, TestVerdict.Unresolved);
}
proceed = true;
for (i = 0; i < postItems.Count && proceed; i++)
{
item = (TestItem)postItems[i];
fw.TestItem(item.title);
try
{
itemResult = item.Run(this);
fw.ItemComposeVerdict(itemResult.ExpectedVerdict, itemResult.Verdict);
proceed = item.MayProceed(itemResult);
}
catch (System.Exception exc)
{
fw.TestMessage(TestMessage.Error, GetExceptionReport(exc));
itemResult = new TestResult("UNKNOWN", exc.Message, TestVerdict.Pass,
TestVerdict.Fail);
fw.ItemComposeVerdict(itemResult.ExpectedVerdict, itemResult.Verdict);
proceed = false;
}
}
if (i < postItems.Count)
{
result.Verdict = TestVerdict.Unresolved;
}
while (i < postItems.Count)
{
item = (TestItem)postItems[i];
fw.TestItem(item.title);
fw.ItemComposeVerdict(TestVerdict.Unresolved, TestVerdict.Unresolved);
i++;
}
return result;
}
public object ResolveObject(string name)
{
return registered[name];
}
public void RegisterObject(string name, object obj)
{
registered[name] = obj;
}
public bool UnregisterObject(string name)
{
if (registered.ContainsKey(name))
{
registered.Remove(name);
return true;
}
else
return false;
}
public abstract TestResult Run();
private string GetExceptionReport(System.Exception exc)
{
return exc.ToString();
//string result;
//result = "Unhandled exception(" + exc.ToString() + ") occurred:\n";
//java.lang.StackTraceElement[] elements = exc.st.getStackTrace();
//for (int i = 0; i < elements.Length; i++)
//{
// result += " at " + elements[i].getFileName() + ", line "
// + elements[i].getLineNumber() + " (method '" + elements[i].getMethodName() + "')\n";
//}
//return result;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: ActivationWorker
**
** Purpose: Created in the remote AppDomain, this worker is
** used to start up & shut down the add-in.
**
===========================================================*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
namespace System.AddIn.Hosting
{
internal sealed class ActivationWorker : MarshalByRefObject, IDisposable
{
private AddInToken _pipeline;
private ResolveEventHandler _assemblyResolver;
private PipelineComponentType _currentComponentType;
private bool _usingHostAppDomain;
internal ActivationWorker(AddInToken pipeline)
{
System.Diagnostics.Contracts.Contract.Requires(pipeline != null);
System.Diagnostics.Contracts.Contract.Requires(pipeline.PipelineRootDirectory != null);
_pipeline = pipeline;
}
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="AppDomain.remove_AssemblyResolve(System.ResolveEventHandler):System.Void" />
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification="Reviewed")]
[System.Security.SecuritySafeCritical]
public void Dispose()
{
if (_assemblyResolver != null) {
AppDomain.CurrentDomain.AssemblyResolve -= _assemblyResolver;
_assemblyResolver = null;
}
}
// Don't let this object time out in Remoting. We need this object to be
// alive until we clean up the appdomain, and we want to unhook our assembly
// resolve event.
public override Object InitializeLifetimeService()
{
return null;
}
internal bool UsingHostAppDomain
{
set { _usingHostAppDomain = value; }
}
// This method should return System.AddIn.Contract.IContract, instead of Object. This gives
// Remoting half a chance at setting up the transparent proxy to contain
// the appropriate interface method table. Then, hopefully Reflection
// is built to check that interface method table first. (hopefully.)
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="AppDomain.add_AssemblyResolve(System.ResolveEventHandler):System.Void" />
// <Asserts Name="Imperative: System.Security.PermissionSet" />
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity", Justification="Reviewed"),
System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification="Reviewed"),
System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Justification="LoadFrom was explicitly designed for addin loading")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2128:SecurityTransparentCodeShouldNotAssert", Justification = "This is a SecurityRules.Level1 assembly, in which this rule is being incorrectly applied")]
[System.Security.SecuritySafeCritical]
internal System.AddIn.Contract.IContract Activate()
{
// Assert permission to the contracts, AddInSideAdapters, AddInViews and specific Addin directories only.
PermissionSet permissionSet = new PermissionSet(PermissionState.None);
permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery,
Path.Combine(_pipeline.PipelineRootDirectory, AddInStore.ContractsDirName)));
permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery,
Path.Combine(_pipeline.PipelineRootDirectory, AddInStore.AddInAdaptersDirName)));
permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery,
Path.Combine(_pipeline.PipelineRootDirectory, AddInStore.AddInBasesDirName)));
permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery,
Path.GetDirectoryName(_pipeline._addin.Location)));
permissionSet.Assert();
// Let's be very deliberate about loading precisely the components we want,
// instead of relying on an assembly resolve event. We may still need the
// resolve event, but let's ensure we load the right files from the right
// places in the right loader contexts.
Assembly.LoadFrom(_pipeline._contract.Location);
// only load the AddInBase in the LoadFrom context if there is no copy
// of the assembly loaded already in the Load context. Otherwise there would be an InvalidCastException
// when returning it to the host in the single appdomain, non direct-connect scenario, when
// the HVA assembly is also used as the AddInBase assembly.
// Since the reflection call to determine whether the assembly is loaded is expensive, only
// do it when we are in the single-appdomain scenario.
bool alreadyPresent = false;
if (_usingHostAppDomain)
alreadyPresent = IsAssemblyLoaded(_pipeline._addinBase._assemblyName);
if (!alreadyPresent)
Assembly.LoadFrom(_pipeline._addinBase.Location);
Assembly addInAssembly = Assembly.LoadFrom(_pipeline._addin.Location);
Assembly addinAdapterAssembly = Assembly.LoadFrom(_pipeline._addinAdapter.Location);
CodeAccessPermission.RevertAssert();
// Create instances of all the interesting objects.
// Either we don't need this here, or it may need to exist for the duration of
// the add-in's lifetime.
//
// The assembly resolve event will be removed when the addin
// controller's Shutdown method is run.
_assemblyResolver = new ResolveEventHandler(ResolveAssembly);
AppDomain.CurrentDomain.AssemblyResolve += _assemblyResolver;
// Create the AddIn
_currentComponentType = PipelineComponentType.AddIn;
Type addinType = addInAssembly.GetType(_pipeline._addin.TypeInfo.FullName, true);
Object addIn = addinType.GetConstructor(new Type[0]).Invoke(new Object[0]);
System.Diagnostics.Contracts.Contract.Assert(addIn != null, "CreateInstance didn't create the add-in");
return CreateAddInAdapter(addIn, addinAdapterAssembly);
}
// Return true if the assembly of the given name has already been loaded, perhaps
// from a different path.
[System.Security.SecuritySafeCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2128:SecurityTransparentCodeShouldNotAssert", Justification = "This is a SecurityRules.Level1 assembly, in which this rule is being incorrectly applied")]
private static bool IsAssemblyLoaded(String assemblyName)
{
// Since there is no managed API for finding the GAC path, I
// assert path discovery for all local files.
FileIOPermission permission = new FileIOPermission(PermissionState.None);
permission.AllLocalFiles = FileIOPermissionAccess.PathDiscovery;
permission.Assert();
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (assembly.FullName.Equals(assemblyName, StringComparison.OrdinalIgnoreCase)) {
return true;
}
// Warn if they have the same assembly with different versions. If we don't do this,
// they will get an InvalidCastException instead.
AssemblyName name1 = new AssemblyName(assemblyName);
AssemblyName name2 = assembly.GetName();
if (name1.Name == name2.Name &&
name1.CultureInfo.Equals(name2.CultureInfo) &&
Utils.PublicKeyMatches(name1, name2) &&
name1.Version != name2.Version)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Res.IncompatibleAddInBaseAssembly, assemblyName));
}
}
return false;
}
//<SecurityKernel Critical="True" Ring="0">
//<Asserts Name="Imperative: System.Security.Permissions.ReflectionPermission" />
//</SecurityKernel>
[System.Security.SecuritySafeCritical]
internal System.AddIn.Contract.IContract CreateAddInAdapter(Object addIn, Assembly addinAdapterAssembly)
{
System.Diagnostics.Contracts.Contract.Ensures(System.Diagnostics.Contracts.Contract.Result<System.AddIn.Contract.IContract>() != null);
// Create the AddIn Adapter
System.AddIn.Contract.IContract addInAdapter = null;
_currentComponentType = PipelineComponentType.AddInAdapter;
Type adapterType = addinAdapterAssembly.GetType(_pipeline._addinAdapter.TypeInfo.FullName, true);
Type addInBaseType = Type.GetType(_pipeline._addinBase.TypeInfo.AssemblyQualifiedName, true);
AddInActivator.InvokerDelegate myInvokerDelegate = AddInActivator.CreateConsInvoker(adapterType, addIn.GetType());
addInAdapter = (System.AddIn.Contract.IContract)myInvokerDelegate(addIn);
System.Diagnostics.Contracts.Contract.Assert(addInAdapter != null, "CreateInstance didn't create the add-in adapter");
return addInAdapter;
}
// This is necessary if an add-in or an add-in adapter depends on other
// assemblies within the same directory.
// <SecurityKernel Critical="True" Ring="0">
// <Asserts Name="Imperative: System.Security.PermissionSet" />
// </SecurityKernel>
[System.Security.SecuritySafeCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2128:SecurityTransparentCodeShouldNotAssert", Justification = "This is a SecurityRules.Level1 assembly, in which this rule is being incorrectly applied")]
internal Assembly ResolveAssembly(Object sender, ResolveEventArgs args)
{
System.Diagnostics.Contracts.Contract.Assert(_pipeline != null);
String assemblyRef = args.Name;
//Console.WriteLine("ResolveAssembly (in add-in's AD) called for {0}", assemblyRef);
// Two purposes here:
// 1) Ensure that our already-loaded pipeline components get upgraded
// from the LoadFrom context to the default loader context.
// 2) Any dependencies of our already-loaded pipeline components would
// have been loaded in the LoadFrom context, and need to also be
// manually upgraded to the default loader context.
// We can do both of the above by calling LoadFrom on the appropriate
// assemblies on disk, or by walking the list of already-loaded
// assemblies, looking for the ones we need to upgrade.
// Since we'll have multiple add-ins in the same AD, it may make the
// most sense to simply look for an already-loaded assembly instead of
// looking in directories on disk, to avoid conflicts.
// Check to see if this assembly was already loaded in the
// LoadFrom context. If so, upgrade it.
Assembly a = Utils.FindLoadedAssemblyRef(assemblyRef);
if (a != null)
return a;
// It wasn't found in memory, so look on disk
String rootDir = _pipeline.PipelineRootDirectory;
List<String> dirsToLookIn = new List<String>();
switch (_currentComponentType)
{
case PipelineComponentType.AddInAdapter:
// Look in contract directory and addin base directory.
dirsToLookIn.Add(Path.Combine(rootDir, AddInStore.ContractsDirName));
dirsToLookIn.Add(Path.Combine(rootDir, AddInStore.AddInBasesDirName));
break;
case PipelineComponentType.AddIn:
dirsToLookIn.Add(Path.Combine(rootDir, AddInStore.AddInBasesDirName));
break;
default:
System.Diagnostics.Contracts.Contract.Assert(false);
throw new InvalidOperationException("Fell through switch in assembly resolve event!");
}
// ARROWHEAD START
// In the LoadFrom context, assemblies we depend on in the same folder are loaded automatically.
// We don't have that behavior in Arrowhead.
//String addinFolder = Path.GetDirectoryName(_pipeline._addin.Location);
//dirsToLookIn.Add(addinFolder);
// ARROWHEAD END
// Assert permission to read from addinBase folder (and maybe contracts folder).
PermissionSet permissionSet = new PermissionSet(PermissionState.None);
foreach (string dir in dirsToLookIn)
{
permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, dir));
}
permissionSet.Assert();
return Utils.LoadAssemblyFrom(dirsToLookIn, assemblyRef);
//Console.WriteLine("Couldn't resolve assembly {0} while loading a {1}", simpleName, _currentComponentType);
}
}
}
| |
// 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 Xunit;
/// <summary>
/// NOTE: All tests checking the output file should always call Stop before checking because Stop will flush the file to disk.
/// </summary>
namespace System.ServiceProcess.Tests
{
[OuterLoop(/* Modifies machine state */)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Persistent issues starting test service on NETFX")]
public class ServiceBaseTests : IDisposable
{
private const int connectionTimeout = 30000;
private readonly TestServiceProvider _testService;
private static readonly Lazy<bool> s_isElevated = new Lazy<bool>(() => AdminHelpers.IsProcessElevated());
protected static bool IsProcessElevated => s_isElevated.Value;
protected static bool IsElevatedAndSupportsEventLogs => IsProcessElevated && PlatformDetection.IsNotWindowsNanoServer;
private bool _disposed;
public ServiceBaseTests()
{
_testService = new TestServiceProvider();
}
private void AssertExpectedProperties(ServiceController testServiceController)
{
var comparer = PlatformDetection.IsFullFramework ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; // Full framework upper cases the name
Assert.Equal(_testService.TestServiceName, testServiceController.ServiceName, comparer);
Assert.Equal(_testService.TestServiceDisplayName, testServiceController.DisplayName);
Assert.Equal(_testService.TestMachineName, testServiceController.MachineName);
Assert.Equal(ServiceType.Win32OwnProcess, testServiceController.ServiceType);
Assert.True(testServiceController.CanPauseAndContinue);
Assert.True(testServiceController.CanStop);
Assert.True(testServiceController.CanShutdown);
}
// [Fact]
// To cleanup lingering Test Services uncomment the Fact attribute and run the following command
// msbuild /t:rebuildandtest /p:XunitMethodName=System.ServiceProcess.Tests.ServiceBaseTests.Cleanup /p:OuterLoop=true
// Remember to comment out the Fact again before running tests otherwise it will cleanup tests running in parallel
// and cause them to fail.
public void Cleanup()
{
string currentService = "";
foreach (ServiceController controller in ServiceController.GetServices())
{
try
{
currentService = controller.DisplayName;
if (controller.DisplayName.StartsWith("Test Service"))
{
Console.WriteLine("Trying to clean-up " + currentService);
TestServiceInstaller deleteService = new TestServiceInstaller()
{
ServiceName = controller.ServiceName
};
deleteService.RemoveService();
Console.WriteLine("Cleaned up " + currentService);
}
}
catch (Exception ex)
{
Console.WriteLine("Failed " + ex.Message);
}
}
}
[ConditionalFact(nameof(IsProcessElevated))]
public void TestOnStartThenStop()
{
ServiceController controller = ConnectToServer();
controller.Stop();
Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte());
controller.WaitForStatus(ServiceControllerStatus.Stopped);
}
[ConditionalFact(nameof(IsProcessElevated))]
public void TestOnStartWithArgsThenStop()
{
ServiceController controller = ConnectToServer();
controller.Stop();
Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte());
controller.WaitForStatus(ServiceControllerStatus.Stopped);
controller.Start(new string[] { "StartWithArguments", "a", "b", "c" });
_testService.Client = null;
_testService.Client.Connect();
// There is no definite order between start and connected when tests are running on multiple threads.
// In this case we dont care much about the order, so we are just checking whether the appropiate bytes have been sent.
Assert.Equal((int)(PipeMessageByteCode.Connected | PipeMessageByteCode.Start), _testService.GetByte() | _testService.GetByte());
controller.WaitForStatus(ServiceControllerStatus.Running);
controller.Stop();
Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte());
controller.WaitForStatus(ServiceControllerStatus.Stopped);
}
[ConditionalFact(nameof(IsProcessElevated))]
public void TestOnPauseThenStop()
{
ServiceController controller = ConnectToServer();
controller.Pause();
Assert.Equal((int)PipeMessageByteCode.Pause, _testService.GetByte());
controller.WaitForStatus(ServiceControllerStatus.Paused);
controller.Stop();
Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte());
controller.WaitForStatus(ServiceControllerStatus.Stopped);
}
[ConditionalFact(nameof(IsProcessElevated))]
public void TestOnPauseAndContinueThenStop()
{
ServiceController controller = ConnectToServer();
controller.Pause();
Assert.Equal((int)PipeMessageByteCode.Pause, _testService.GetByte());
controller.WaitForStatus(ServiceControllerStatus.Paused);
controller.Continue();
Assert.Equal((int)PipeMessageByteCode.Continue, _testService.GetByte());
controller.WaitForStatus(ServiceControllerStatus.Running);
controller.Stop();
Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte());
controller.WaitForStatus(ServiceControllerStatus.Stopped);
}
[ConditionalFact(nameof(IsProcessElevated))]
public void TestOnExecuteCustomCommand()
{
ServiceController controller = ConnectToServer();
controller.ExecuteCommand(128);
Assert.Equal(128, _testService.GetByte());
controller.Stop();
Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte());
controller.WaitForStatus(ServiceControllerStatus.Stopped);
}
[ConditionalFact(nameof(IsProcessElevated))]
public void TestOnContinueBeforePause()
{
ServiceController controller = ConnectToServer();
controller.Continue();
controller.WaitForStatus(ServiceControllerStatus.Running);
controller.Stop();
Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte());
controller.WaitForStatus(ServiceControllerStatus.Stopped);
}
[ConditionalFact(nameof(IsElevatedAndSupportsEventLogs))]
public void LogWritten()
{
string serviceName = Guid.NewGuid().ToString();
// The default username for installing the service is NT AUTHORITY\\LocalService which does not have access to EventLog.
// If the username is null, then the service is created under LocalSystem Account which have access to EventLog.
var testService = new TestServiceProvider(serviceName, userName: null);
Assert.True(EventLog.SourceExists(serviceName));
testService.DeleteTestServices();
}
[ConditionalFact(nameof(IsElevatedAndSupportsEventLogs))]
public void LogWritten_AutoLog_False()
{
string serviceName = nameof(LogWritten_AutoLog_False) + Guid.NewGuid().ToString();
var testService = new TestServiceProvider(serviceName);
Assert.False(EventLog.SourceExists(serviceName));
testService.DeleteTestServices();
}
[ConditionalFact(nameof(IsProcessElevated))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework receives the Connected Byte Code after the Exception Thrown Byte Code")]
public void PropagateExceptionFromOnStart()
{
string serviceName = nameof(PropagateExceptionFromOnStart) + Guid.NewGuid().ToString();
var testService = new TestServiceProvider(serviceName);
testService.Client.Connect(connectionTimeout);
Assert.Equal((int)PipeMessageByteCode.Connected, testService.GetByte());
Assert.Equal((int)PipeMessageByteCode.ExceptionThrown, testService.GetByte());
testService.DeleteTestServices();
}
private ServiceController ConnectToServer()
{
_testService.Client.Connect(connectionTimeout);
Assert.Equal((int)PipeMessageByteCode.Connected, _testService.GetByte());
ServiceController controller = new ServiceController(_testService.TestServiceName);
AssertExpectedProperties(controller);
return controller;
}
public void Dispose()
{
if (!_disposed)
{
_testService.DeleteTestServices();
_disposed = true;
}
}
}
}
| |
#nullable enable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Mime;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Client;
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.Filters;
using BTCPayServer.HostedServices;
using BTCPayServer.Models;
using BTCPayServer.Models.InvoicingModels;
using BTCPayServer.Payments;
using BTCPayServer.Rating;
using BTCPayServer.Services.Apps;
using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Invoices.Export;
using BTCPayServer.Services.Rates;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using NBitcoin;
using NBitpayClient;
using NBXplorer;
using NBXplorer.Models;
using Newtonsoft.Json.Linq;
using BitpayCreateInvoiceRequest = BTCPayServer.Models.BitpayCreateInvoiceRequest;
using StoreData = BTCPayServer.Data.StoreData;
namespace BTCPayServer.Controllers
{
public partial class UIInvoiceController
{
[HttpGet("invoices/{invoiceId}/deliveries/{deliveryId}/request")]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> WebhookDelivery(string invoiceId, string deliveryId)
{
var invoice = (await _InvoiceRepository.GetInvoices(new InvoiceQuery
{
InvoiceId = new[] { invoiceId },
UserId = GetUserId()
})).FirstOrDefault();
if (invoice is null)
return NotFound();
var delivery = await _InvoiceRepository.GetWebhookDelivery(invoiceId, deliveryId);
if (delivery is null)
return NotFound();
return File(delivery.GetBlob().Request, "application/json");
}
[HttpPost("invoices/{invoiceId}/deliveries/{deliveryId}/redeliver")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> RedeliverWebhook(string storeId, string invoiceId, string deliveryId)
{
var invoice = (await _InvoiceRepository.GetInvoices(new InvoiceQuery()
{
InvoiceId = new[] { invoiceId },
StoreId = new[] { storeId },
UserId = GetUserId()
})).FirstOrDefault();
if (invoice is null)
return NotFound();
var delivery = await _InvoiceRepository.GetWebhookDelivery(invoiceId, deliveryId);
if (delivery is null)
return NotFound();
var newDeliveryId = await WebhookNotificationManager.Redeliver(deliveryId);
if (newDeliveryId is null)
return NotFound();
TempData[WellKnownTempData.SuccessMessage] = "Successfully planned a redelivery";
return RedirectToAction(nameof(Invoice),
new
{
invoiceId
});
}
[HttpGet("invoices/{invoiceId}")]
[Authorize(Policy = Policies.CanViewStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> Invoice(string invoiceId)
{
var invoice = (await _InvoiceRepository.GetInvoices(new InvoiceQuery()
{
InvoiceId = new[] { invoiceId },
UserId = GetUserId(),
IncludeAddresses = true,
IncludeEvents = true,
IncludeArchived = true,
})).FirstOrDefault();
if (invoice == null)
return NotFound();
var store = await _StoreRepository.FindStore(invoice.StoreId);
var invoiceState = invoice.GetInvoiceState();
var model = new InvoiceDetailsModel
{
StoreId = store.Id,
StoreName = store.StoreName,
StoreLink = Url.Action(nameof(UIStoresController.GeneralSettings), "UIStores", new { storeId = store.Id }),
PaymentRequestLink = Url.Action(nameof(UIPaymentRequestController.ViewPaymentRequest), "UIPaymentRequest", new { payReqId = invoice.Metadata.PaymentRequestId }),
Id = invoice.Id,
State = invoiceState,
TransactionSpeed = invoice.SpeedPolicy == SpeedPolicy.HighSpeed ? "high" :
invoice.SpeedPolicy == SpeedPolicy.MediumSpeed ? "medium" :
invoice.SpeedPolicy == SpeedPolicy.LowMediumSpeed ? "low-medium" :
"low",
RefundEmail = invoice.RefundMail,
CreatedDate = invoice.InvoiceTime,
ExpirationDate = invoice.ExpirationTime,
MonitoringDate = invoice.MonitoringExpiration,
Fiat = _CurrencyNameTable.DisplayFormatCurrency(invoice.Price, invoice.Currency),
TaxIncluded = _CurrencyNameTable.DisplayFormatCurrency(invoice.Metadata.TaxIncluded ?? 0.0m, invoice.Currency),
NotificationUrl = invoice.NotificationURL?.AbsoluteUri,
RedirectUrl = invoice.RedirectURL?.AbsoluteUri,
TypedMetadata = invoice.Metadata,
StatusException = invoice.ExceptionStatus,
Events = invoice.Events,
PosData = PosDataParser.ParsePosData(invoice.Metadata.PosData),
Archived = invoice.Archived,
CanRefund = CanRefund(invoiceState),
ShowCheckout = invoice.Status == InvoiceStatusLegacy.New,
Deliveries = (await _InvoiceRepository.GetWebhookDeliveries(invoiceId))
.Select(c => new Models.StoreViewModels.DeliveryViewModel(c))
.ToList(),
CanMarkInvalid = invoiceState.CanMarkInvalid(),
CanMarkSettled = invoiceState.CanMarkComplete(),
};
model.Addresses = invoice.HistoricalAddresses.Select(h =>
new InvoiceDetailsModel.AddressModel
{
Destination = h.GetAddress(),
PaymentMethod = h.GetPaymentMethodId().ToPrettyString(),
Current = !h.UnAssigned.HasValue
}).ToArray();
var details = InvoicePopulatePayments(invoice);
model.CryptoPayments = details.CryptoPayments;
model.Payments = details.Payments;
return View(model);
}
bool CanRefund(InvoiceState invoiceState)
{
return invoiceState.Status == InvoiceStatusLegacy.Confirmed ||
invoiceState.Status == InvoiceStatusLegacy.Complete ||
(invoiceState.Status == InvoiceStatusLegacy.Expired &&
(invoiceState.ExceptionStatus == InvoiceExceptionStatus.PaidLate ||
invoiceState.ExceptionStatus == InvoiceExceptionStatus.PaidOver ||
invoiceState.ExceptionStatus == InvoiceExceptionStatus.PaidPartial)) ||
invoiceState.Status == InvoiceStatusLegacy.Invalid;
}
[HttpGet("invoices/{invoiceId}/refund")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> Refund([FromServices] IEnumerable<IPayoutHandler> payoutHandlers, string invoiceId, CancellationToken cancellationToken)
{
await using var ctx = _dbContextFactory.CreateContext();
ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
var invoice = await ctx.Invoices.Include(i => i.Payments)
.Include(i => i.CurrentRefund)
.Include(i => i.StoreData)
.ThenInclude(data => data.UserStores)
.Include(i => i.CurrentRefund.PullPaymentData)
.Where(i => i.Id == invoiceId)
.FirstOrDefaultAsync(cancellationToken);
if (invoice is null)
return NotFound();
if (invoice.CurrentRefund?.PullPaymentDataId is null && GetUserId() is null)
return NotFound();
if (!CanRefund(invoice.GetInvoiceState()))
return NotFound();
if (invoice.CurrentRefund?.PullPaymentDataId is string ppId && !invoice.CurrentRefund.PullPaymentData.Archived)
{
// TODO: Having dedicated UI later on
return RedirectToAction(nameof(UIPullPaymentController.ViewPullPayment),
"UIPullPayment",
new { pullPaymentId = ppId });
}
var paymentMethods = invoice.GetBlob(_NetworkProvider).GetPaymentMethods();
var pmis = paymentMethods.Select(method => method.GetId()).ToList();
var options = (await payoutHandlers.GetSupportedPaymentMethods(invoice.StoreData)).Where(id => pmis.Contains(id)).ToList();
if (!options.Any())
{
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Severity = StatusMessageModel.StatusSeverity.Error,
Message = "There were no payment methods available to provide refunds with for this invoice."
});
return RedirectToAction(nameof(Invoice), new { invoiceId });
}
var defaultRefund = invoice.Payments
.Select(p => p.GetBlob(_NetworkProvider))
.Select(p => p?.GetPaymentMethodId())
.FirstOrDefault(p => p != null && options.Contains(p));
// TODO: What if no option?
var refund = new RefundModel
{
Title = "Select a payment method",
AvailablePaymentMethods =
new SelectList(options.Select(id => new SelectListItem(id.ToPrettyString(), id.ToString())),
"Value", "Text"),
SelectedPaymentMethod = defaultRefund?.ToString() ?? options.First().ToString()
};
// Nothing to select, skip to next
if (refund.AvailablePaymentMethods.Count() == 1)
{
return await Refund(invoiceId, refund, cancellationToken);
}
return View(refund);
}
[HttpPost("invoices/{invoiceId}/refund")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> Refund(string invoiceId, RefundModel model, CancellationToken cancellationToken)
{
using var ctx = _dbContextFactory.CreateContext();
var invoice = GetCurrentInvoice();
if (invoice == null)
return NotFound();
if (!CanRefund(invoice.GetInvoiceState()))
return NotFound();
var store = GetCurrentStore();
var paymentMethodId = PaymentMethodId.Parse(model.SelectedPaymentMethod);
var cdCurrency = _CurrencyNameTable.GetCurrencyData(invoice.Currency, true);
var paymentMethodDivisibility = _CurrencyNameTable.GetCurrencyData(paymentMethodId.CryptoCode, false)?.Divisibility ?? 8;
RateRules rules;
RateResult rateResult;
CreatePullPayment createPullPayment;
switch (model.RefundStep)
{
case RefundSteps.SelectPaymentMethod:
model.RefundStep = RefundSteps.SelectRate;
model.Title = "What to refund?";
var pms = invoice.GetPaymentMethods();
var paymentMethod = pms.SingleOrDefault(method => method.GetId() == paymentMethodId);
//TODO: Make this clean
if (paymentMethod is null && paymentMethodId.PaymentType == LightningPaymentType.Instance)
{
paymentMethod = pms[new PaymentMethodId(paymentMethodId.CryptoCode, PaymentTypes.LNURLPay)];
}
if (paymentMethod != null)
{
var cryptoPaid = paymentMethod.Calculate().Paid.ToDecimal(MoneyUnit.BTC);
var paidCurrency = Math.Round(cryptoPaid * paymentMethod.Rate, cdCurrency.Divisibility);
model.CryptoAmountThen = cryptoPaid.RoundToSignificant(paymentMethodDivisibility);
model.RateThenText =
_CurrencyNameTable.DisplayFormatCurrency(model.CryptoAmountThen, paymentMethodId.CryptoCode);
rules = store.GetStoreBlob().GetRateRules(_NetworkProvider);
rateResult = await _RateProvider.FetchRate(
new CurrencyPair(paymentMethodId.CryptoCode, invoice.Currency), rules,
cancellationToken);
//TODO: What if fetching rate failed?
if (rateResult.BidAsk is null)
{
ModelState.AddModelError(nameof(model.SelectedRefundOption),
$"Impossible to fetch rate: {rateResult.EvaluatedRule}");
return View(model);
}
model.CryptoAmountNow = Math.Round(paidCurrency / rateResult.BidAsk.Bid, paymentMethodDivisibility);
model.CurrentRateText =
_CurrencyNameTable.DisplayFormatCurrency(model.CryptoAmountNow, paymentMethodId.CryptoCode);
model.FiatAmount = paidCurrency;
}
model.FiatText = _CurrencyNameTable.DisplayFormatCurrency(model.FiatAmount, invoice.Currency);
return View(model);
case RefundSteps.SelectRate:
createPullPayment = new CreatePullPayment
{
Name = $"Refund {invoice.Id}",
PaymentMethodIds = new[] { paymentMethodId },
StoreId = invoice.StoreId,
BOLT11Expiration = store.GetStoreBlob().RefundBOLT11Expiration
};
switch (model.SelectedRefundOption)
{
case "RateThen":
createPullPayment.Currency = paymentMethodId.CryptoCode;
createPullPayment.Amount = model.CryptoAmountThen;
break;
case "CurrentRate":
createPullPayment.Currency = paymentMethodId.CryptoCode;
createPullPayment.Amount = model.CryptoAmountNow;
break;
case "Fiat":
createPullPayment.Currency = invoice.Currency;
createPullPayment.Amount = model.FiatAmount;
break;
case "Custom":
model.Title = "How much to refund?";
model.CustomCurrency = invoice.Currency;
model.CustomAmount = model.FiatAmount;
model.RefundStep = RefundSteps.SelectCustomAmount;
return View(model);
default:
ModelState.AddModelError(nameof(model.SelectedRefundOption), "Invalid choice");
return View(model);
}
break;
case RefundSteps.SelectCustomAmount:
if (model.CustomAmount <= 0)
{
model.AddModelError(refundModel => refundModel.CustomAmount, "Amount must be greater than 0", this);
}
if (string.IsNullOrEmpty(model.CustomCurrency) ||
_CurrencyNameTable.GetCurrencyData(model.CustomCurrency, false) == null)
{
ModelState.AddModelError(nameof(model.CustomCurrency), "Invalid currency");
}
if (!ModelState.IsValid)
{
return View(model);
}
rules = store.GetStoreBlob().GetRateRules(_NetworkProvider);
rateResult = await _RateProvider.FetchRate(
new CurrencyPair(paymentMethodId.CryptoCode, model.CustomCurrency), rules,
cancellationToken);
//TODO: What if fetching rate failed?
if (rateResult.BidAsk is null)
{
ModelState.AddModelError(nameof(model.SelectedRefundOption),
$"Impossible to fetch rate: {rateResult.EvaluatedRule}");
return View(model);
}
createPullPayment = new CreatePullPayment
{
Name = $"Refund {invoice.Id}",
PaymentMethodIds = new[] { paymentMethodId },
StoreId = invoice.StoreId,
Currency = model.CustomCurrency,
Amount = model.CustomAmount
};
break;
default:
throw new ArgumentOutOfRangeException();
}
var ppId = await _paymentHostedService.CreatePullPayment(createPullPayment);
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Html = "Refund successfully created!<br />Share the link to this page with a customer.<br />The customer needs to enter their address and claim the refund.<br />Once a customer claims the refund, you will get a notification and would need to approve and initiate it from your Store > Payouts.",
Severity = StatusMessageModel.StatusSeverity.Success
});
(await ctx.Invoices.FindAsync(new[] { invoice.Id }, cancellationToken))!.CurrentRefundId = ppId;
ctx.Refunds.Add(new RefundData()
{
InvoiceDataId = invoice.Id,
PullPaymentDataId = ppId
});
await ctx.SaveChangesAsync(cancellationToken);
// TODO: Having dedicated UI later on
return RedirectToAction(nameof(UIPullPaymentController.ViewPullPayment),
"UIPullPayment",
new { pullPaymentId = ppId });
}
private InvoiceDetailsModel InvoicePopulatePayments(InvoiceEntity invoice)
{
return new InvoiceDetailsModel
{
Archived = invoice.Archived,
Payments = invoice.GetPayments(false),
CryptoPayments = invoice.GetPaymentMethods().Select(
data =>
{
var accounting = data.Calculate();
var paymentMethodId = data.GetId();
return new InvoiceDetailsModel.CryptoPayment
{
PaymentMethodId = paymentMethodId,
PaymentMethod = paymentMethodId.ToPrettyString(),
Due = _CurrencyNameTable.DisplayFormatCurrency(accounting.Due.ToDecimal(MoneyUnit.BTC),
paymentMethodId.CryptoCode),
Paid = _CurrencyNameTable.DisplayFormatCurrency(
accounting.CryptoPaid.ToDecimal(MoneyUnit.BTC),
paymentMethodId.CryptoCode),
Overpaid = _CurrencyNameTable.DisplayFormatCurrency(
accounting.OverpaidHelper.ToDecimal(MoneyUnit.BTC), paymentMethodId.CryptoCode),
Address = data.GetPaymentMethodDetails().GetPaymentDestination(),
Rate = ExchangeRate(data),
PaymentMethodRaw = data
};
}).ToList()
};
}
[HttpPost("invoices/{invoiceId}/archive")]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanViewInvoices)]
[BitpayAPIConstraint(false)]
public async Task<IActionResult> ToggleArchive(string invoiceId)
{
var invoice = (await _InvoiceRepository.GetInvoices(new InvoiceQuery
{
InvoiceId = new[] { invoiceId },
UserId = GetUserId(),
IncludeAddresses = true,
IncludeEvents = true,
IncludeArchived = true,
})).FirstOrDefault();
if (invoice == null)
return NotFound();
await _InvoiceRepository.ToggleInvoiceArchival(invoiceId, !invoice.Archived);
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Severity = StatusMessageModel.StatusSeverity.Success,
Message = invoice.Archived ? "The invoice has been unarchived and will appear in the invoice list by default again." : "The invoice has been archived and will no longer appear in the invoice list by default."
});
return RedirectToAction(nameof(invoice), new { invoiceId });
}
[HttpPost]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanViewInvoices)]
public async Task<IActionResult> MassAction(string command, string[] selectedItems, string? storeId = null)
{
if (selectedItems != null)
{
switch (command)
{
case "archive":
await _InvoiceRepository.MassArchive(selectedItems);
TempData[WellKnownTempData.SuccessMessage] = $"{selectedItems.Length} invoice{(selectedItems.Length == 1 ? "" : "s")} archived.";
break;
case "unarchive":
await _InvoiceRepository.MassArchive(selectedItems, false);
TempData[WellKnownTempData.SuccessMessage] = $"{selectedItems.Length} invoice{(selectedItems.Length == 1 ? "" : "s")} unarchived.";
break;
case "cpfp":
if (selectedItems.Length == 0)
return NotSupported("No invoice has been selected");
var network = _NetworkProvider.DefaultNetwork;
var explorer = _ExplorerClients.GetExplorerClient(network);
IActionResult NotSupported(string err)
{
TempData[WellKnownTempData.ErrorMessage] = err;
return RedirectToAction(nameof(ListInvoices), new { storeId });
}
if (explorer is null)
return NotSupported("This feature is only available to BTC wallets");
if (this.GetCurrentStore().Role != StoreRoles.Owner)
return Forbid();
var settings = (this.GetCurrentStore().GetDerivationSchemeSettings(_NetworkProvider, network.CryptoCode));
var derivationScheme = settings.AccountDerivation;
if (derivationScheme is null)
return NotSupported("This feature is only available to BTC wallets");
var bumpableAddresses = (await GetAddresses(selectedItems))
.Where(p => p.GetPaymentMethodId().IsBTCOnChain)
.Select(p => p.GetAddress()).ToHashSet();
var utxos = await explorer.GetUTXOsAsync(derivationScheme);
var bumpableUTXOs = utxos.GetUnspentUTXOs().Where(u => u.Confirmations == 0 && bumpableAddresses.Contains(u.ScriptPubKey.Hash.ToString())).ToArray();
var parameters = new MultiValueDictionary<string, string>();
foreach (var utxo in bumpableUTXOs)
{
parameters.Add($"outpoints[]", utxo.Outpoint.ToString());
}
return View("PostRedirect", new PostRedirectViewModel
{
AspController = "UIWallets",
AspAction = nameof(UIWalletsController.WalletCPFP),
RouteParameters = {
{ "walletId", new WalletId(storeId, network.CryptoCode).ToString() },
{ "returnUrl", Url.Action(nameof(ListInvoices), new { storeId }) }
},
FormParameters = parameters,
});
}
}
return RedirectToAction(nameof(ListInvoices), new { storeId });
}
private async Task<AddressInvoiceData[]> GetAddresses(string[] selectedItems)
{
using var ctx = _dbContextFactory.CreateContext();
return await ctx.AddressInvoices.Where(i => selectedItems.Contains(i.InvoiceDataId)).ToArrayAsync();
}
[HttpGet("i/{invoiceId}")]
[HttpGet("i/{invoiceId}/{paymentMethodId}")]
[HttpGet("invoice")]
[AcceptMediaTypeConstraint("application/bitcoin-paymentrequest", false)]
[XFrameOptionsAttribute(null)]
[ReferrerPolicyAttribute("origin")]
public async Task<IActionResult> Checkout(string? invoiceId, string? id = null, string? paymentMethodId = null,
[FromQuery] string? view = null, [FromQuery] string? lang = null)
{
//Keep compatibility with Bitpay
invoiceId = invoiceId ?? id;
//
if (invoiceId is null)
return NotFound();
var model = await GetInvoiceModel(invoiceId, paymentMethodId == null ? null : PaymentMethodId.Parse(paymentMethodId), lang);
if (model == null)
return NotFound();
if (view == "modal")
model.IsModal = true;
return View(nameof(Checkout), model);
}
[HttpGet("invoice-noscript")]
public async Task<IActionResult> CheckoutNoScript(string? invoiceId, string? id = null, string? paymentMethodId = null, [FromQuery] string? lang = null)
{
//Keep compatibility with Bitpay
invoiceId = invoiceId ?? id;
//
if (invoiceId is null)
return NotFound();
var model = await GetInvoiceModel(invoiceId, paymentMethodId is null ? null : PaymentMethodId.Parse(paymentMethodId), lang);
if (model == null)
return NotFound();
return View(model);
}
private async Task<PaymentModel?> GetInvoiceModel(string invoiceId, PaymentMethodId? paymentMethodId, string? lang)
{
var invoice = await _InvoiceRepository.GetInvoice(invoiceId);
if (invoice == null)
return null;
var store = await _StoreRepository.FindStore(invoice.StoreId);
bool isDefaultPaymentId = false;
if (paymentMethodId is null)
{
var enabledPaymentIds = store.GetEnabledPaymentIds(_NetworkProvider);
PaymentMethodId? invoicePaymentId = invoice.GetDefaultPaymentMethod();
PaymentMethodId? storePaymentId = store.GetDefaultPaymentId();
if (invoicePaymentId is not null)
{
if (enabledPaymentIds.Contains(invoicePaymentId))
paymentMethodId = invoicePaymentId;
}
if (paymentMethodId is null && storePaymentId is not null)
{
if (enabledPaymentIds.Contains(storePaymentId))
paymentMethodId = storePaymentId;
}
if (paymentMethodId is null && invoicePaymentId is not null)
{
paymentMethodId = invoicePaymentId.FindNearest(enabledPaymentIds);
}
if (paymentMethodId is null && storePaymentId is not null)
{
paymentMethodId = storePaymentId.FindNearest(enabledPaymentIds);
}
if (paymentMethodId is null)
{
paymentMethodId = enabledPaymentIds.FirstOrDefault(e => e.CryptoCode == "BTC" && e.PaymentType == PaymentTypes.BTCLike) ??
enabledPaymentIds.FirstOrDefault(e => e.CryptoCode == "BTC" && e.PaymentType == PaymentTypes.LightningLike) ??
enabledPaymentIds.FirstOrDefault();
}
isDefaultPaymentId = true;
}
if (paymentMethodId is null)
return null;
BTCPayNetworkBase network = _NetworkProvider.GetNetwork<BTCPayNetworkBase>(paymentMethodId.CryptoCode);
if (network is null || !invoice.Support(paymentMethodId))
{
if (!isDefaultPaymentId)
return null;
var paymentMethodTemp = invoice
.GetPaymentMethods()
.FirstOrDefault(c => paymentMethodId.CryptoCode == c.GetId().CryptoCode);
if (paymentMethodTemp == null)
paymentMethodTemp = invoice.GetPaymentMethods().FirstOrDefault();
if (paymentMethodTemp is null)
return null;
network = paymentMethodTemp.Network;
paymentMethodId = paymentMethodTemp.GetId();
}
var paymentMethod = invoice.GetPaymentMethod(paymentMethodId);
var paymentMethodDetails = paymentMethod.GetPaymentMethodDetails();
if (!paymentMethodDetails.Activated)
{
if (await _InvoiceRepository.ActivateInvoicePaymentMethod(_EventAggregator, _NetworkProvider,
_paymentMethodHandlerDictionary, store, invoice, paymentMethod.GetId()))
{
return await GetInvoiceModel(invoiceId, paymentMethodId, lang);
}
}
var dto = invoice.EntityToDTO();
var storeBlob = store.GetStoreBlob();
var accounting = paymentMethod.Calculate();
var paymentMethodHandler = _paymentMethodHandlerDictionary[paymentMethodId];
var divisibility = _CurrencyNameTable.GetNumberFormatInfo(paymentMethod.GetId().CryptoCode, false)?.CurrencyDecimalDigits;
switch (lang?.ToLowerInvariant())
{
case "auto":
case null when storeBlob.AutoDetectLanguage:
lang = _languageService.AutoDetectLanguageUsingHeader(HttpContext.Request.Headers, null).Code;
break;
case { } langs when !string.IsNullOrEmpty(langs):
{
lang = _languageService.FindLanguage(langs)?.Code;
break;
}
}
lang ??= storeBlob.DefaultLang;
var model = new PaymentModel
{
Activated = paymentMethodDetails.Activated,
CryptoCode = network.CryptoCode,
RootPath = Request.PathBase.Value.WithTrailingSlash(),
OrderId = invoice.Metadata.OrderId,
InvoiceId = invoice.Id,
DefaultLang = lang ?? invoice.DefaultLanguage ?? storeBlob.DefaultLang ?? "en",
CustomCSSLink = storeBlob.CustomCSS,
CustomLogoLink = storeBlob.CustomLogo,
HtmlTitle = storeBlob.HtmlTitle ?? "BTCPay Invoice",
CryptoImage = Request.GetRelativePathOrAbsolute(paymentMethodHandler.GetCryptoImage(paymentMethodId)),
BtcAddress = paymentMethodDetails.GetPaymentDestination(),
BtcDue = accounting.Due.ShowMoney(divisibility),
InvoiceCurrency = invoice.Currency,
OrderAmount = (accounting.TotalDue - accounting.NetworkFee).ShowMoney(divisibility),
IsUnsetTopUp = invoice.IsUnsetTopUp(),
OrderAmountFiat = OrderAmountFromInvoice(network.CryptoCode, invoice),
CustomerEmail = invoice.RefundMail,
RequiresRefundEmail = invoice.RequiresRefundEmail ?? storeBlob.RequiresRefundEmail,
ExpirationSeconds = Math.Max(0, (int)(invoice.ExpirationTime - DateTimeOffset.UtcNow).TotalSeconds),
MaxTimeSeconds = (int)(invoice.ExpirationTime - invoice.InvoiceTime).TotalSeconds,
MaxTimeMinutes = (int)(invoice.ExpirationTime - invoice.InvoiceTime).TotalMinutes,
ItemDesc = invoice.Metadata.ItemDesc,
Rate = ExchangeRate(paymentMethod),
MerchantRefLink = invoice.RedirectURL?.AbsoluteUri ?? "/",
RedirectAutomatically = invoice.RedirectAutomatically,
StoreName = store.StoreName,
TxCount = accounting.TxRequired,
TxCountForFee = storeBlob.NetworkFeeMode switch
{
NetworkFeeMode.Always => accounting.TxRequired,
NetworkFeeMode.MultiplePaymentsOnly => accounting.TxRequired - 1,
NetworkFeeMode.Never => 0,
_ => throw new NotImplementedException()
},
BtcPaid = accounting.Paid.ShowMoney(divisibility),
#pragma warning disable CS0618 // Type or member is obsolete
Status = invoice.StatusString,
#pragma warning restore CS0618 // Type or member is obsolete
NetworkFee = paymentMethodDetails.GetNextNetworkFee(),
IsMultiCurrency = invoice.GetPayments(false).Select(p => p.GetPaymentMethodId()).Concat(new[] { paymentMethod.GetId() }).Distinct().Count() > 1,
StoreId = store.Id,
AvailableCryptos = invoice.GetPaymentMethods()
.Where(i => i.Network != null)
.Select(kv =>
{
var availableCryptoPaymentMethodId = kv.GetId();
var availableCryptoHandler = _paymentMethodHandlerDictionary[availableCryptoPaymentMethodId];
return new PaymentModel.AvailableCrypto()
{
PaymentMethodId = kv.GetId().ToString(),
CryptoCode = kv.Network?.CryptoCode ?? kv.GetId().CryptoCode,
PaymentMethodName = availableCryptoHandler.GetPaymentMethodName(availableCryptoPaymentMethodId),
IsLightning =
kv.GetId().PaymentType == PaymentTypes.LightningLike,
CryptoImage = Request.GetRelativePathOrAbsolute(availableCryptoHandler.GetCryptoImage(availableCryptoPaymentMethodId)),
Link = Url.Action(nameof(Checkout),
new
{
invoiceId,
paymentMethodId = kv.GetId().ToString()
})
};
}).Where(c => c.CryptoImage != "/")
.OrderByDescending(a => a.CryptoCode == "BTC").ThenBy(a => a.PaymentMethodName).ThenBy(a => a.IsLightning ? 1 : 0)
.ToList()
};
paymentMethodHandler.PreparePaymentModel(model, dto, storeBlob, paymentMethod);
model.UISettings = paymentMethodHandler.GetCheckoutUISettings();
model.PaymentMethodId = paymentMethodId.ToString();
var expiration = TimeSpan.FromSeconds(model.ExpirationSeconds);
model.TimeLeft = expiration.PrettyPrint();
return model;
}
private string? OrderAmountFromInvoice(string cryptoCode, InvoiceEntity invoiceEntity)
{
// if invoice source currency is the same as currently display currency, no need for "order amount from invoice"
if (cryptoCode == invoiceEntity.Currency)
return null;
return _CurrencyNameTable.DisplayFormatCurrency(invoiceEntity.Price, invoiceEntity.Currency);
}
private string ExchangeRate(PaymentMethod paymentMethod)
{
string currency = paymentMethod.ParentEntity.Currency;
return _CurrencyNameTable.DisplayFormatCurrency(paymentMethod.Rate, currency);
}
[HttpGet("i/{invoiceId}/status")]
[HttpGet("i/{invoiceId}/{implicitPaymentMethodId}/status")]
[HttpGet("invoice/{invoiceId}/status")]
[HttpGet("invoice/{invoiceId}/{implicitPaymentMethodId}/status")]
[HttpGet("invoice/status")]
public async Task<IActionResult> GetStatus(string invoiceId, string? paymentMethodId = null, string? implicitPaymentMethodId = null, [FromQuery] string? lang = null)
{
if (string.IsNullOrEmpty(paymentMethodId))
paymentMethodId = implicitPaymentMethodId;
var model = await GetInvoiceModel(invoiceId, paymentMethodId == null ? null : PaymentMethodId.Parse(paymentMethodId), lang);
if (model == null)
return NotFound();
return Json(model);
}
[HttpGet("i/{invoiceId}/status/ws")]
[HttpGet("i/{invoiceId}/{paymentMethodId}/status/ws")]
[HttpGet("invoice/{invoiceId}/status/ws")]
[HttpGet("invoice/{invoiceId}/{paymentMethodId}/status")]
[HttpGet("invoice/status/ws")]
public async Task<IActionResult> GetStatusWebSocket(string invoiceId, CancellationToken cancellationToken)
{
if (!HttpContext.WebSockets.IsWebSocketRequest)
return NotFound();
var invoice = await _InvoiceRepository.GetInvoice(invoiceId);
if (invoice == null || invoice.Status == InvoiceStatusLegacy.Complete || invoice.Status == InvoiceStatusLegacy.Invalid || invoice.Status == InvoiceStatusLegacy.Expired)
return NotFound();
var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
CompositeDisposable leases = new CompositeDisposable();
try
{
leases.Add(_EventAggregator.SubscribeAsync<Events.InvoiceDataChangedEvent>(async o => await NotifySocket(webSocket, o.InvoiceId, invoiceId)));
leases.Add(_EventAggregator.SubscribeAsync<Events.InvoiceNewPaymentDetailsEvent>(async o => await NotifySocket(webSocket, o.InvoiceId, invoiceId)));
leases.Add(_EventAggregator.SubscribeAsync<Events.InvoiceEvent>(async o => await NotifySocket(webSocket, o.Invoice.Id, invoiceId)));
while (true)
{
var message = await webSocket.ReceiveAndPingAsync(DummyBuffer);
if (message.MessageType == WebSocketMessageType.Close)
break;
}
}
catch (WebSocketException) { }
finally
{
leases.Dispose();
await webSocket.CloseSocket();
}
return new EmptyResult();
}
readonly ArraySegment<Byte> DummyBuffer = new ArraySegment<Byte>(new Byte[1]);
public string? CreatedInvoiceId;
private async Task NotifySocket(WebSocket webSocket, string invoiceId, string expectedId)
{
if (invoiceId != expectedId || webSocket.State != WebSocketState.Open)
return;
using CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(5000);
try
{
await webSocket.SendAsync(DummyBuffer, WebSocketMessageType.Binary, true, cts.Token);
}
catch { try { webSocket.Dispose(); } catch { } }
}
[HttpPost("i/{invoiceId}/UpdateCustomer")]
[HttpPost("invoice/UpdateCustomer")]
public async Task<IActionResult> UpdateCustomer(string invoiceId, [FromBody] UpdateCustomerModel data)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
await _InvoiceRepository.UpdateInvoice(invoiceId, data).ConfigureAwait(false);
return Ok("{}");
}
[HttpGet("/stores/{storeId}/invoices")]
[HttpGet("invoices")]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanViewInvoices)]
[BitpayAPIConstraint(false)]
public async Task<IActionResult> ListInvoices(InvoicesModel? model = null)
{
model = this.ParseListQuery(model ?? new InvoicesModel());
var fs = new SearchString(model.SearchTerm);
string? storeId = model.StoreId;
var storeIds = new HashSet<string>();
if (fs.GetFilterArray("storeid") is string[] l)
{
foreach (var i in l)
storeIds.Add(i);
}
if (storeId is not null)
{
storeIds.Add(storeId);
model.StoreId = storeId;
}
model.StoreIds = storeIds.ToArray();
InvoiceQuery invoiceQuery = GetInvoiceQuery(model.SearchTerm, model.TimezoneOffset ?? 0);
invoiceQuery.StoreId = model.StoreIds;
var counting = _InvoiceRepository.GetInvoicesTotal(invoiceQuery);
invoiceQuery.Take = model.Count;
invoiceQuery.Skip = model.Skip;
var list = await _InvoiceRepository.GetInvoices(invoiceQuery);
model.IncludeArchived = invoiceQuery.IncludeArchived;
foreach (var invoice in list)
{
var state = invoice.GetInvoiceState();
model.Invoices.Add(new InvoiceModel()
{
Status = state,
ShowCheckout = invoice.Status == InvoiceStatusLegacy.New,
Date = invoice.InvoiceTime,
InvoiceId = invoice.Id,
OrderId = invoice.Metadata.OrderId ?? string.Empty,
RedirectUrl = invoice.RedirectURL?.AbsoluteUri ?? string.Empty,
AmountCurrency = _CurrencyNameTable.DisplayFormatCurrency(invoice.Price, invoice.Currency),
CanMarkInvalid = state.CanMarkInvalid(),
CanMarkSettled = state.CanMarkComplete(),
Details = InvoicePopulatePayments(invoice),
});
}
model.Total = await counting;
return View(model);
}
private InvoiceQuery GetInvoiceQuery(string? searchTerm = null, int timezoneOffset = 0)
{
var fs = new SearchString(searchTerm);
var invoiceQuery = new InvoiceQuery()
{
TextSearch = fs.TextSearch,
UserId = GetUserId(),
Unusual = fs.GetFilterBool("unusual"),
IncludeArchived = fs.GetFilterBool("includearchived") ?? false,
Status = fs.GetFilterArray("status"),
ExceptionStatus = fs.GetFilterArray("exceptionstatus"),
StoreId = fs.GetFilterArray("storeid"),
ItemCode = fs.GetFilterArray("itemcode"),
OrderId = fs.GetFilterArray("orderid"),
StartDate = fs.GetFilterDate("startdate", timezoneOffset),
EndDate = fs.GetFilterDate("enddate", timezoneOffset)
};
return invoiceQuery;
}
[HttpGet]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanViewInvoices)]
[BitpayAPIConstraint(false)]
public async Task<IActionResult> Export(string format, string? searchTerm = null, int timezoneOffset = 0)
{
var model = new InvoiceExport(_CurrencyNameTable);
InvoiceQuery invoiceQuery = GetInvoiceQuery(searchTerm, timezoneOffset);
invoiceQuery.StoreId = new[] { GetCurrentStore().Id };
invoiceQuery.Skip = 0;
invoiceQuery.Take = int.MaxValue;
var invoices = await _InvoiceRepository.GetInvoices(invoiceQuery);
var res = model.Process(invoices, format);
var cd = new ContentDisposition
{
FileName = $"btcpay-export-{DateTime.UtcNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture)}.{format}",
Inline = true
};
Response.Headers.Add("Content-Disposition", cd.ToString());
Response.Headers.Add("X-Content-Type-Options", "nosniff");
return Content(res, "application/" + format);
}
private SelectList GetPaymentMethodsSelectList()
{
var store = GetCurrentStore();
var excludeFilter = store.GetStoreBlob().GetExcludedPaymentMethods();
return new SelectList(store.GetSupportedPaymentMethods(_NetworkProvider)
.Where(s => !excludeFilter.Match(s.PaymentId))
.Select(method => new SelectListItem(method.PaymentId.ToPrettyString(), method.PaymentId.ToString())),
nameof(SelectListItem.Value),
nameof(SelectListItem.Text));
}
private bool AnyPaymentMethodAvailable(StoreData store)
{
var storeBlob = store.GetStoreBlob();
var excludeFilter = storeBlob.GetExcludedPaymentMethods();
return store.GetSupportedPaymentMethods(_NetworkProvider).Where(s => !excludeFilter.Match(s.PaymentId)).Any();
}
[HttpGet("/stores/{storeId}/invoices/create")]
[HttpGet("invoices/create")]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)]
[BitpayAPIConstraint(false)]
public async Task<IActionResult> CreateInvoice(InvoicesModel? model = null)
{
var stores = new SelectList(
await _StoreRepository.GetStoresByUserId(GetUserId()),
nameof(StoreData.Id),
nameof(StoreData.StoreName),
new SearchString(model?.SearchTerm).GetFilterArray("storeid")?.ToArray().FirstOrDefault()
);
if (!stores.Any())
{
TempData[WellKnownTempData.ErrorMessage] = "You need to create at least one store before creating a transaction";
return RedirectToAction(nameof(UIHomeController.Index), "UIHome");
}
if (model?.StoreId != null)
{
var store = await _StoreRepository.FindStore(model.StoreId, GetUserId());
if (store == null)
return NotFound();
if (!AnyPaymentMethodAvailable(store))
{
TempData.SetStatusMessageModel(new StatusMessageModel
{
Severity = StatusMessageModel.StatusSeverity.Error,
Html = $"To create an invoice, you need to <a href='{Url.Action(nameof(UIStoresController.SetupWallet), "UIStores", new { cryptoCode = _NetworkProvider.DefaultNetwork.CryptoCode, storeId = store.Id })}' class='alert-link'>set up a wallet</a> first",
AllowDismiss = false
});
}
HttpContext.SetStoreData(store);
}
var vm = new CreateInvoiceModel
{
Stores = stores,
StoreId = model?.StoreId,
AvailablePaymentMethods = GetPaymentMethodsSelectList()
};
return View(vm);
}
[HttpPost("/stores/{storeId}/invoices/create")]
[HttpPost("invoices/create")]
[Authorize(Policy = Policies.CanCreateInvoice, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
[BitpayAPIConstraint(false)]
public async Task<IActionResult> CreateInvoice(CreateInvoiceModel model, CancellationToken cancellationToken)
{
var stores = await _StoreRepository.GetStoresByUserId(GetUserId());
model.Stores = new SelectList(stores, nameof(StoreData.Id), nameof(StoreData.StoreName), model.StoreId);
model.AvailablePaymentMethods = GetPaymentMethodsSelectList();
var store = HttpContext.GetStoreData();
if (!ModelState.IsValid)
{
return View(model);
}
if (!AnyPaymentMethodAvailable(store))
{
TempData.SetStatusMessageModel(new StatusMessageModel
{
Severity = StatusMessageModel.StatusSeverity.Error,
Html = $"To create an invoice, you need to <a href='{Url.Action(nameof(UIStoresController.SetupWallet), "UIStores", new { cryptoCode = _NetworkProvider.DefaultNetwork.CryptoCode, storeId = store.Id })}' class='alert-link'>set up a wallet</a> first",
AllowDismiss = false
});
return View(model);
}
try
{
var result = await CreateInvoiceCore(new BitpayCreateInvoiceRequest()
{
Price = model.Amount,
Currency = model.Currency,
PosData = model.PosData,
OrderId = model.OrderId,
//RedirectURL = redirect + "redirect",
NotificationURL = model.NotificationUrl,
ItemDesc = model.ItemDesc,
FullNotifications = true,
BuyerEmail = model.BuyerEmail,
SupportedTransactionCurrencies = model.SupportedTransactionCurrencies?.ToDictionary(s => s, s => new InvoiceSupportedTransactionCurrency()
{
Enabled = true
}),
DefaultPaymentMethod = model.DefaultPaymentMethod,
NotificationEmail = model.NotificationEmail,
ExtendedNotifications = model.NotificationEmail != null,
RequiresRefundEmail = model.RequiresRefundEmail == RequiresRefundEmail.InheritFromStore
? store.GetStoreBlob().RequiresRefundEmail
: model.RequiresRefundEmail == RequiresRefundEmail.On
}, store, HttpContext.Request.GetAbsoluteRoot(), cancellationToken: cancellationToken);
TempData[WellKnownTempData.SuccessMessage] = $"Invoice {result.Data.Id} just created!";
CreatedInvoiceId = result.Data.Id;
return RedirectToAction(nameof(ListInvoices), new { result.Data.StoreId });
}
catch (BitpayHttpException ex)
{
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Severity = StatusMessageModel.StatusSeverity.Error,
Message = ex.Message
});
return View(model);
}
}
[HttpPost]
[Route("invoices/{invoiceId}/changestate/{newState}")]
[Route("stores/{storeId}/invoices/{invoiceId}/changestate/{newState}")]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanViewInvoices)]
[BitpayAPIConstraint(false)]
public async Task<IActionResult> ChangeInvoiceState(string invoiceId, string newState)
{
var invoice = (await _InvoiceRepository.GetInvoices(new InvoiceQuery
{
InvoiceId = new[] { invoiceId },
UserId = GetUserId()
})).FirstOrDefault();
var model = new InvoiceStateChangeModel();
if (invoice == null)
{
model.NotFound = true;
return NotFound(model);
}
if (newState == "invalid")
{
await _InvoiceRepository.MarkInvoiceStatus(invoiceId, InvoiceStatus.Invalid);
model.StatusString = new InvoiceState(InvoiceStatusLegacy.Invalid, InvoiceExceptionStatus.Marked).ToString();
}
else if (newState == "settled")
{
await _InvoiceRepository.MarkInvoiceStatus(invoiceId, InvoiceStatus.Settled);
model.StatusString = new InvoiceState(InvoiceStatusLegacy.Complete, InvoiceExceptionStatus.Marked).ToString();
}
return Json(model);
}
public class InvoiceStateChangeModel
{
public bool NotFound { get; set; }
public string? StatusString { get; set; }
}
private StoreData GetCurrentStore() => HttpContext.GetStoreData();
private InvoiceEntity GetCurrentInvoice() => HttpContext.GetInvoiceData();
private string GetUserId() => _UserManager.GetUserId(User);
public class PosDataParser
{
public static Dictionary<string, object> ParsePosData(string posData)
{
var result = new Dictionary<string, object>();
if (string.IsNullOrEmpty(posData))
{
return result;
}
try
{
var jObject = JObject.Parse(posData);
foreach (var item in jObject)
{
switch (item.Value?.Type)
{
case JTokenType.Array:
var items = item.Value.AsEnumerable().ToList();
for (var i = 0; i < items.Count; i++)
{
result.TryAdd($"{item.Key}[{i}]", ParsePosData(items[i].ToString()));
}
break;
case JTokenType.Object:
result.TryAdd(item.Key, ParsePosData(item.Value.ToString()));
break;
case null:
break;
default:
result.TryAdd(item.Key, item.Value.ToString());
break;
}
}
}
catch
{
result.TryAdd(string.Empty, posData);
}
return result;
}
}
}
}
| |
/*
* Copyright 1999-2012 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Sharpen;
using Tup.Cobar4Net.Parser.Recognizer.Mysql.Lexer;
namespace Tup.Cobar4Net.Parser.Recognizer.Mysql.Syntax
{
/// <author>
/// <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a>
/// </author>
internal class SoloParser : MySqlParser
{
public SoloParser(MySqlLexer lexer)
: base(lexer)
{
}
/// <exception cref="System.SqlSyntaxErrorException" />
public virtual Refs Refs()
{
var refs = new Refs();
for (;;)
{
var @ref = Ref();
refs.AddRef(@ref);
if (lexer.Token() == MySqlToken.PuncComma)
{
lexer.NextToken();
}
else
{
return refs;
}
}
}
/// <exception cref="System.SqlSyntaxErrorException" />
public virtual Ref BuildRef(Ref
first)
{
for (; lexer.Token() == MySqlToken.KwJoin;)
{
lexer.NextToken();
var temp = Factor();
first = new Join(first, temp);
}
return first;
}
/// <exception cref="System.SqlSyntaxErrorException" />
public virtual Ref Ref()
{
return BuildRef(Factor());
}
/// <exception cref="System.SqlSyntaxErrorException" />
public virtual Ref Factor()
{
string alias;
if (lexer.Token() == MySqlToken.PuncLeftParen)
{
lexer.NextToken();
var queryRefs = RefsOrQuery();
Match(MySqlToken.PuncRightParen);
if (queryRefs is Query)
{
Match(MySqlToken.KwAs);
alias = lexer.GetStringValue();
lexer.NextToken();
return new SubQuery((Query)queryRefs, alias);
}
return queryRefs;
}
var tableName = lexer.GetStringValue();
lexer.NextToken();
if (lexer.Token() == MySqlToken.KwAs)
{
lexer.NextToken();
alias = lexer.GetStringValue();
lexer.NextToken();
return new Factor(tableName, alias);
}
return new Factor(tableName, null);
}
/// <summary>first <code>(</code> has been consumed</summary>
/// <exception cref="System.SqlSyntaxErrorException" />
public virtual Ref RefsOrQuery()
{
Ref temp;
Refs rst;
Union u;
switch (lexer.Token())
{
case MySqlToken.KwSelect:
{
u = new Union();
for (;;)
{
var s = SelectPrimary();
u.AddSelect(s);
if (lexer.Token() == MySqlToken.KwUnion)
{
lexer.NextToken();
}
else
{
break;
}
}
if (u.selects.Count == 1)
{
return u.selects[0];
}
return u;
}
case MySqlToken.PuncLeftParen:
{
lexer.NextToken();
temp = RefsOrQuery();
Match(MySqlToken.PuncRightParen);
if (temp is Query)
{
if (temp is Select)
{
if (lexer.Token() == MySqlToken.KwUnion)
{
u = new Union();
u.AddSelect((Select)temp);
while (lexer.Token() == MySqlToken.KwUnion)
{
lexer.NextToken();
temp = SelectPrimary();
u.AddSelect((Select)temp);
}
return u;
}
}
if (lexer.Token() == MySqlToken.KwAs)
{
lexer.NextToken();
var alias = lexer.GetStringValue();
temp = new SubQuery((Query)temp, alias);
lexer.NextToken();
}
else
{
return temp;
}
}
// ---- build factor complete---------------
temp = BuildRef(temp);
// ---- build ref complete---------------
break;
}
default:
{
temp = Ref();
break;
}
}
if (lexer.Token() == MySqlToken.PuncComma)
{
rst = new Refs();
rst.AddRef(temp);
for (; lexer.Token() == MySqlToken.PuncComma;)
{
lexer.NextToken();
temp = Ref();
rst.AddRef(temp);
}
return rst;
}
return temp;
}
/// <summary>first <code>SELECT</code> or <code>(</code> has not been consumed</summary>
/// <exception cref="System.SqlSyntaxErrorException" />
private Select SelectPrimary()
{
Select s = null;
if (lexer.Token() == MySqlToken.PuncLeftParen)
{
lexer.NextToken();
s = SelectPrimary();
Match(MySqlToken.PuncRightParen);
return s;
}
Match(MySqlToken.KwSelect);
return new Select();
}
/// <exception cref="System.SqlSyntaxErrorException" />
public static void Main(string[] args)
{
var sql =
" ( ( select union select union select) as j join (((select union (select)) as t ) join t2 ) ,(select)as d), t3)";
// String sql =
// "((select) as s1, (((( select union select ) as t2)) join (((t2),t4 as t))) ), t1 aS T1";
// String sql =
// " (( select union select union select) as j ,(select)as d), t3";
Console.Out.WriteLine(sql);
var lexer = new MySqlLexer(sql);
lexer.NextToken();
var p = new SoloParser(lexer);
var refs = p.Refs();
Console.Out.WriteLine(refs);
}
}
internal interface Ref
{
}
internal class Factor : Ref
{
internal string alias;
internal string tableName;
public Factor(string tableName, string alias)
{
this.tableName = tableName;
this.alias = alias;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(tableName);
sb.Append(" AS ");
sb.Append(alias);
return sb.ToString();
}
}
internal class SubQuery : Ref
{
internal string alias;
internal Query u;
public SubQuery(Query u, string alias)
{
this.u = u;
this.alias = alias;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("(");
sb.Append(u);
sb.Append(") AS ");
sb.Append(alias);
return sb.ToString();
}
}
internal class Join : Ref
{
internal Ref left;
internal Ref right;
public Join(Ref left, Ref right)
{
this.left = left;
this.right = right;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("<");
sb.Append(left);
sb.Append(" JOIN ");
sb.Append(right);
sb.Append(">");
return sb.ToString();
}
}
internal class Refs : Ref
{
internal IList<Ref> refs = new List<Ref>();
public virtual void AddRef(Ref @ref)
{
refs.Add(@ref);
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("[");
for (var i = 0; i < refs.Count; ++i)
{
if (i > 0)
{
sb.Append(", ");
}
sb.Append(refs[i]);
}
sb.Append("]");
return sb.ToString();
}
}
internal interface Query
{
}
internal class Union : Query, Ref
{
internal IList<Select> selects = new List<Select>();
public virtual void AddSelect(Select select)
{
selects.Add(select);
}
public override string ToString()
{
var sb = new StringBuilder();
foreach (var s in selects)
{
sb.Append(" UNION SELECT");
}
var rst = sb.ToString();
var i = rst.IndexOf("UNION", StringComparison.Ordinal);
if (i >= 0)
{
rst = Runtime.Substring(rst, i + "UNION".Length);
}
return rst;
}
}
internal class Select : Query, Ref
{
public override string ToString()
{
return "SELECT";
}
}
}
| |
//
// 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.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// Represents all the operations for Azure SQL Database Server Upgrade
/// </summary>
internal partial class ServerUpgradeOperations : IServiceOperations<SqlManagementClient>, IServerUpgradeOperations
{
/// <summary>
/// Initializes a new instance of the ServerUpgradeOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ServerUpgradeOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Cancel a pending upgrade for the Azure SQL Database server.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to cancel
/// upgrade.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CancelAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
TracingAdapter.Enter(invocationId, this, "CancelAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/operationResults/versionUpgrade";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about Upgrade status of an Azure SQL Database
/// Server.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to upgrade.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get request for Upgrade status of an
/// Azure SQL Database Server.
/// </returns>
public async Task<ServerUpgradeGetResponse> GetAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/operationResults/versionUpgrade";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
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 && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerUpgradeGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerUpgradeGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken statusValue = responseDoc["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
result.Status = statusInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Start an Azure SQL Database Server Upgrade.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to upgrade.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for the Azure SQL Database Server
/// Upgrade.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> StartAsync(string resourceGroupName, string serverName, ServerUpgradeStartParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
if (parameters.Properties.Version == null)
{
throw new ArgumentNullException("parameters.Properties.Version");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "StartAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/upgrade";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
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.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject serverUpgradeStartParametersValue = new JObject();
requestDoc = serverUpgradeStartParametersValue;
JObject serverUpgradePropertiesValue = new JObject();
serverUpgradeStartParametersValue["serverUpgradeProperties"] = serverUpgradePropertiesValue;
serverUpgradePropertiesValue["Version"] = parameters.Properties.Version;
if (parameters.Properties.ScheduleUpgradeAfterUtcDateTime != null)
{
serverUpgradePropertiesValue["ScheduleUpgradeAfterUtcDateTime"] = parameters.Properties.ScheduleUpgradeAfterUtcDateTime.Value;
}
if (parameters.Properties.DatabaseCollection != null)
{
if (parameters.Properties.DatabaseCollection is ILazyCollection == false || ((ILazyCollection)parameters.Properties.DatabaseCollection).IsInitialized)
{
JArray databaseCollectionArray = new JArray();
foreach (RecommendedDatabaseProperties databaseCollectionItem in parameters.Properties.DatabaseCollection)
{
JObject recommendedDatabasePropertiesValue = new JObject();
databaseCollectionArray.Add(recommendedDatabasePropertiesValue);
if (databaseCollectionItem.Name != null)
{
recommendedDatabasePropertiesValue["Name"] = databaseCollectionItem.Name;
}
if (databaseCollectionItem.TargetEdition != null)
{
recommendedDatabasePropertiesValue["TargetEdition"] = databaseCollectionItem.TargetEdition;
}
if (databaseCollectionItem.TargetServiceLevelObjective != null)
{
recommendedDatabasePropertiesValue["TargetServiceLevelObjective"] = databaseCollectionItem.TargetServiceLevelObjective;
}
}
serverUpgradePropertiesValue["DatabaseCollection"] = databaseCollectionArray;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* @author Valentin Simonov / http://va.lent.in/
*/
using System.Collections.Generic;
using UnityEngine;
namespace TouchScript.Debugging
{
/// <summary>
/// Visual debugger to show touches as GUI elements.
/// </summary>
[AddComponentMenu("TouchScript/Touch Debugger")]
public class TouchDebugger : MonoBehaviour
{
#region Public properties
/// <summary>
/// Show touch id near touch circles.
/// </summary>
public bool ShowTouchId
{
get { return showTouchId; }
set { showTouchId = value; }
}
/// <summary>
/// Show tag list near touch circles.
/// </summary>
public bool ShowTags
{
get { return showTags; }
set { showTags = value; }
}
/// <summary>Gets or sets the texture to use.</summary>
public Texture2D TouchTexture
{
get { return texture; }
set
{
texture = value;
update();
}
}
/// <summary>Gets or sets whether <see cref="TouchDebugger"/> is using DPI to scale touch cursors.</summary>
/// <value><c>true</c> if dpi value is used; otherwise, <c>false</c>.</value>
public bool UseDPI
{
get { return useDPI; }
set
{
useDPI = value;
update();
}
}
/// <summary>Gets or sets the size of touch cursors in cm.</summary>
/// <value>The size of touch cursors in cm.</value>
public float TouchSize
{
get { return touchSize; }
set
{
touchSize = value;
update();
}
}
/// <summary>Gets or sets font color for touch ids.</summary>
public Color FontColor
{
get { return fontColor; }
set { fontColor = value; }
}
#endregion
#region Private variables
[SerializeField]
private bool showTouchId = true;
[SerializeField]
private bool showTags = false;
[SerializeField]
private Texture2D texture;
[SerializeField]
private bool useDPI = true;
[SerializeField]
private float touchSize = 1f;
[SerializeField]
private Color fontColor = new Color(0, 1, 1, 1);
private Dictionary<int, ITouch> dummies = new Dictionary<int, ITouch>(10);
private Dictionary<int, string> tags = new Dictionary<int, string>(10);
private float textureDPI, scale, dpi, shadowOffset;
private int textureWidth, textureHeight, halfTextureWidth, halfTextureHeight, xOffset, yOffset, labelWidth, labelHeight, fontSize;
private GUIStyle style;
#endregion
#region Unity methods
private void OnEnable()
{
if (TouchTexture == null)
{
Debug.LogError("Touch Debugger doesn't have touch texture assigned!");
return;
}
update();
if (TouchManager.Instance != null)
{
TouchManager.Instance.TouchesBegan += touchesBeganHandler;
TouchManager.Instance.TouchesEnded += touchesEndedHandler;
TouchManager.Instance.TouchesMoved += touchesMovedHandler;
TouchManager.Instance.TouchesCancelled += touchesCancelledHandler;
}
}
private void OnDisable()
{
if (TouchManager.Instance != null)
{
TouchManager.Instance.TouchesBegan -= touchesBeganHandler;
TouchManager.Instance.TouchesEnded -= touchesEndedHandler;
TouchManager.Instance.TouchesMoved -= touchesMovedHandler;
TouchManager.Instance.TouchesCancelled -= touchesCancelledHandler;
}
}
private void OnGUI()
{
if (TouchTexture == null) return;
if (style == null) style = new GUIStyle(GUI.skin.label);
checkDPI();
style.fontSize = fontSize;
foreach (KeyValuePair<int, ITouch> dummy in dummies)
{
var x = dummy.Value.Position.x;
var y = Screen.height - dummy.Value.Position.y;
GUI.DrawTexture(new Rect(x - halfTextureWidth, y - halfTextureHeight, textureWidth, textureHeight), TouchTexture, ScaleMode.ScaleToFit);
string text;
int id = dummy.Value.Id;
int line = 0;
if (ShowTouchId)
{
text = "id: " + id;
GUI.color = Color.black;
GUI.Label(new Rect(x + xOffset + shadowOffset, y + yOffset + shadowOffset, labelWidth, labelHeight), text, style);
GUI.color = fontColor;
GUI.Label(new Rect(x + xOffset, y + yOffset, labelWidth, labelHeight), text, style);
line++;
}
if (ShowTags && tags.ContainsKey(id))
{
text = "tags: " + tags[id];
GUI.color = Color.black;
GUI.Label(new Rect(x + xOffset + shadowOffset, y + yOffset + fontSize * line + shadowOffset, labelWidth, labelHeight), text, style);
GUI.color = fontColor;
GUI.Label(new Rect(x + xOffset, y + yOffset + fontSize * line, labelWidth, labelHeight), text, style);
}
}
}
#endregion
#region Private functions
private void checkDPI()
{
if (useDPI && !Mathf.Approximately(dpi, TouchManager.Instance.DPI)) update();
}
private void update()
{
if (useDPI)
{
dpi = TouchManager.Instance.DPI;
textureDPI = texture.width * TouchManager.INCH_TO_CM / touchSize;
scale = dpi / textureDPI;
textureWidth = (int)(texture.width * scale);
textureHeight = (int)(texture.height * scale);
computeConsts();
}
else
{
textureWidth = 32;
textureHeight = 32;
scale = 1 / 4f;
computeConsts();
}
}
private void computeConsts()
{
halfTextureWidth = textureWidth / 2;
halfTextureHeight = textureHeight / 2;
xOffset = (int)(textureWidth * .35f);
yOffset = (int)(textureHeight * .35f);
fontSize = (int)(32 * scale);
shadowOffset = 2 * scale;
labelWidth = 20 * fontSize;
labelHeight = 2 * fontSize;
}
private void updateDummy(ITouch dummy)
{
dummies[dummy.Id] = dummy;
}
#endregion
#region Event handlers
private void touchesBeganHandler(object sender, TouchEventArgs e)
{
foreach (var touch in e.Touches)
{
dummies.Add(touch.Id, touch);
if (touch.Tags.Count > 0)
{
tags.Add(touch.Id, touch.Tags.ToString());
}
}
}
private void touchesMovedHandler(object sender, TouchEventArgs e)
{
foreach (var touch in e.Touches)
{
ITouch dummy;
if (!dummies.TryGetValue(touch.Id, out dummy)) return;
updateDummy(touch);
}
}
private void touchesEndedHandler(object sender, TouchEventArgs e)
{
foreach (var touch in e.Touches)
{
ITouch dummy;
if (!dummies.TryGetValue(touch.Id, out dummy)) return;
dummies.Remove(touch.Id);
}
}
private void touchesCancelledHandler(object sender, TouchEventArgs e)
{
touchesEndedHandler(sender, e);
}
#endregion
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
the Utilities SDK except in compliance with the License, which is provided at the time of installation
or download, or which otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/utilities-1.31
Unless required by applicable law or agreed to in writing, the Utilities SDK 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;
namespace UnityEngine.EventSystems
{
/// <summary>
/// VR extension of PointerInputModule which supports gaze and controller pointing.
/// </summary>
public class OVRInputModule : PointerInputModule
{
[Tooltip("Object which points with Z axis. E.g. CentreEyeAnchor from OVRCameraRig")]
public Transform rayTransform;
public OVRCursor m_Cursor;
[Tooltip("Gamepad button to act as gaze click")]
public OVRInput.Button joyPadClickButton = OVRInput.Button.One;
[Tooltip("Keyboard button to act as gaze click")]
public KeyCode gazeClickKey = KeyCode.Space;
[Header("Physics")]
[Tooltip("Perform an sphere cast to determine correct depth for gaze pointer")]
public bool performSphereCastForGazepointer;
[Header("Gamepad Stick Scroll")]
[Tooltip("Enable scrolling with the right stick on a gamepad")]
public bool useRightStickScroll = true;
[Tooltip("Deadzone for right stick to prevent accidental scrolling")]
public float rightStickDeadZone = 0.15f;
[Header("Touchpad Swipe Scroll")]
[Tooltip("Enable scrolling by swiping the GearVR touchpad")]
public bool useSwipeScroll = true;
[Tooltip("Minimum trackpad movement in pixels to start swiping")]
public float swipeDragThreshold = 2;
[Tooltip("Distance scrolled when swipe scroll occurs")]
public float swipeDragScale = 1f;
/* It's debatable which way left and right are on the Gear VR touchpad since it's facing away from you
* the following bool allows this to be swapped*/
[Tooltip("Invert X axis on touchpad")]
public bool InvertSwipeXAxis = false;
// The raycaster that gets to do pointer interaction (e.g. with a mouse), gaze interaction always works
[NonSerialized]
public OVRRaycaster activeGraphicRaycaster;
[Header("Dragging")]
[Tooltip("Minimum pointer movement in degrees to start dragging")]
public float angleDragThreshold = 1;
[SerializeField]
private float m_SpherecastRadius = 1.0f;
// The following region contains code exactly the same as the implementation
// of StandaloneInputModule. It is copied here rather than inheriting from StandaloneInputModule
// because most of StandaloneInputModule is private so it isn't possible to easily derive from.
// Future changes from Unity to StandaloneInputModule will make it possible for this class to
// derive from StandaloneInputModule instead of PointerInput module.
//
// The following functions are not present in the following region since they have modified
// versions in the next region:
// Process
// ProcessMouseEvent
// UseMouse
#region StandaloneInputModule code
private float m_NextAction;
private Vector2 m_LastMousePosition;
private Vector2 m_MousePosition;
protected OVRInputModule()
{}
#if UNITY_EDITOR
protected override void Reset()
{
allowActivationOnMobileDevice = true;
}
#endif
[Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)]
public enum InputMode
{
Mouse,
Buttons
}
[Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)]
public InputMode inputMode
{
get { return InputMode.Mouse; }
}
[Header("Standalone Input Module")]
[SerializeField]
private string m_HorizontalAxis = "Horizontal";
/// <summary>
/// Name of the vertical axis for movement (if axis events are used).
/// </summary>
[SerializeField]
private string m_VerticalAxis = "Vertical";
/// <summary>
/// Name of the submit button.
/// </summary>
[SerializeField]
private string m_SubmitButton = "Submit";
/// <summary>
/// Name of the submit button.
/// </summary>
[SerializeField]
private string m_CancelButton = "Cancel";
[SerializeField]
private float m_InputActionsPerSecond = 10;
[SerializeField]
private bool m_AllowActivationOnMobileDevice;
public bool allowActivationOnMobileDevice
{
get { return m_AllowActivationOnMobileDevice; }
set { m_AllowActivationOnMobileDevice = value; }
}
public float inputActionsPerSecond
{
get { return m_InputActionsPerSecond; }
set { m_InputActionsPerSecond = value; }
}
/// <summary>
/// Name of the horizontal axis for movement (if axis events are used).
/// </summary>
public string horizontalAxis
{
get { return m_HorizontalAxis; }
set { m_HorizontalAxis = value; }
}
/// <summary>
/// Name of the vertical axis for movement (if axis events are used).
/// </summary>
public string verticalAxis
{
get { return m_VerticalAxis; }
set { m_VerticalAxis = value; }
}
public string submitButton
{
get { return m_SubmitButton; }
set { m_SubmitButton = value; }
}
public string cancelButton
{
get { return m_CancelButton; }
set { m_CancelButton = value; }
}
public override void UpdateModule()
{
m_LastMousePosition = m_MousePosition;
m_MousePosition = Input.mousePosition;
}
public override bool IsModuleSupported()
{
// Check for mouse presence instead of whether touch is supported,
// as you can connect mouse to a tablet and in that case we'd want
// to use StandaloneInputModule for non-touch input events.
return m_AllowActivationOnMobileDevice || Input.mousePresent;
}
public override bool ShouldActivateModule()
{
if (!base.ShouldActivateModule())
return false;
var shouldActivate = Input.GetButtonDown(m_SubmitButton);
shouldActivate |= Input.GetButtonDown(m_CancelButton);
shouldActivate |= !Mathf.Approximately(Input.GetAxisRaw(m_HorizontalAxis), 0.0f);
shouldActivate |= !Mathf.Approximately(Input.GetAxisRaw(m_VerticalAxis), 0.0f);
shouldActivate |= (m_MousePosition - m_LastMousePosition).sqrMagnitude > 0.0f;
shouldActivate |= Input.GetMouseButtonDown(0);
return shouldActivate;
}
public override void ActivateModule()
{
base.ActivateModule();
m_MousePosition = Input.mousePosition;
m_LastMousePosition = Input.mousePosition;
var toSelect = eventSystem.currentSelectedGameObject;
if (toSelect == null)
toSelect = eventSystem.firstSelectedGameObject;
eventSystem.SetSelectedGameObject(toSelect, GetBaseEventData());
}
public override void DeactivateModule()
{
base.DeactivateModule();
ClearSelection();
}
/// <summary>
/// Process submit keys.
/// </summary>
private bool SendSubmitEventToSelectedObject()
{
if (eventSystem.currentSelectedGameObject == null)
return false;
var data = GetBaseEventData();
if (Input.GetButtonDown(m_SubmitButton))
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.submitHandler);
if (Input.GetButtonDown(m_CancelButton))
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.cancelHandler);
return data.used;
}
private bool AllowMoveEventProcessing(float time)
{
bool allow = Input.GetButtonDown(m_HorizontalAxis);
allow |= Input.GetButtonDown(m_VerticalAxis);
allow |= (time > m_NextAction);
return allow;
}
private Vector2 GetRawMoveVector()
{
Vector2 move = Vector2.zero;
move.x = Input.GetAxisRaw(m_HorizontalAxis);
move.y = Input.GetAxisRaw(m_VerticalAxis);
if (Input.GetButtonDown(m_HorizontalAxis))
{
if (move.x < 0)
move.x = -1f;
if (move.x > 0)
move.x = 1f;
}
if (Input.GetButtonDown(m_VerticalAxis))
{
if (move.y < 0)
move.y = -1f;
if (move.y > 0)
move.y = 1f;
}
return move;
}
/// <summary>
/// Process keyboard events.
/// </summary>
private bool SendMoveEventToSelectedObject()
{
float time = Time.unscaledTime;
if (!AllowMoveEventProcessing(time))
return false;
Vector2 movement = GetRawMoveVector();
// Debug.Log(m_ProcessingEvent.rawType + " axis:" + m_AllowAxisEvents + " value:" + "(" + x + "," + y + ")");
var axisEventData = GetAxisEventData(movement.x, movement.y, 0.6f);
if (!Mathf.Approximately(axisEventData.moveVector.x, 0f)
|| !Mathf.Approximately(axisEventData.moveVector.y, 0f))
{
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, axisEventData, ExecuteEvents.moveHandler);
}
m_NextAction = time + 1f / m_InputActionsPerSecond;
return axisEventData.used;
}
private bool SendUpdateEventToSelectedObject()
{
if (eventSystem.currentSelectedGameObject == null)
return false;
var data = GetBaseEventData();
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.updateSelectedHandler);
return data.used;
}
/// <summary>
/// Process the current mouse press.
/// </summary>
private void ProcessMousePress(MouseButtonEventData data)
{
var pointerEvent = data.buttonData;
var currentOverGo = pointerEvent.pointerCurrentRaycast.gameObject;
// PointerDown notification
if (data.PressedThisFrame())
{
pointerEvent.eligibleForClick = true;
pointerEvent.delta = Vector2.zero;
pointerEvent.dragging = false;
pointerEvent.useDragThreshold = true;
pointerEvent.pressPosition = pointerEvent.position;
if (pointerEvent.IsVRPointer())
{
pointerEvent.SetSwipeStart(Input.mousePosition);
}
pointerEvent.pointerPressRaycast = pointerEvent.pointerCurrentRaycast;
DeselectIfSelectionChanged(currentOverGo, pointerEvent);
// search for the control that will receive the press
// if we can't find a press handler set the press
// handler to be what would receive a click.
var newPressed = ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.pointerDownHandler);
// didnt find a press handler... search for a click handler
if (newPressed == null)
newPressed = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
// Debug.Log("Pressed: " + newPressed);
float time = Time.unscaledTime;
if (newPressed == pointerEvent.lastPress)
{
var diffTime = time - pointerEvent.clickTime;
if (diffTime < 0.3f)
++pointerEvent.clickCount;
else
pointerEvent.clickCount = 1;
pointerEvent.clickTime = time;
}
else
{
pointerEvent.clickCount = 1;
}
pointerEvent.pointerPress = newPressed;
pointerEvent.rawPointerPress = currentOverGo;
pointerEvent.clickTime = time;
// Save the drag handler as well
pointerEvent.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(currentOverGo);
if (pointerEvent.pointerDrag != null)
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.initializePotentialDrag);
}
// PointerUp notification
if (data.ReleasedThisFrame())
{
// Debug.Log("Executing pressup on: " + pointer.pointerPress);
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
// Debug.Log("KeyCode: " + pointer.eventData.keyCode);
// see if we mouse up on the same element that we clicked on...
var pointerUpHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
// PointerClick and Drop events
if (pointerEvent.pointerPress == pointerUpHandler && pointerEvent.eligibleForClick)
{
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerClickHandler);
}
else if (pointerEvent.pointerDrag != null)
{
ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.dropHandler);
}
pointerEvent.eligibleForClick = false;
pointerEvent.pointerPress = null;
pointerEvent.rawPointerPress = null;
if (pointerEvent.pointerDrag != null && pointerEvent.dragging)
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.endDragHandler);
pointerEvent.dragging = false;
pointerEvent.pointerDrag = null;
// redo pointer enter / exit to refresh state
// so that if we moused over somethign that ignored it before
// due to having pressed on something else
// it now gets it.
if (currentOverGo != pointerEvent.pointerEnter)
{
HandlePointerExitAndEnter(pointerEvent, null);
HandlePointerExitAndEnter(pointerEvent, currentOverGo);
}
}
}
#endregion
#region Modified StandaloneInputModule methods
/// <summary>
/// Process all mouse events. This is the same as the StandaloneInputModule version except that
/// it takes MouseState as a parameter, allowing it to be used for both Gaze and Mouse
/// pointerss.
/// </summary>
private void ProcessMouseEvent(MouseState mouseData)
{
var pressed = mouseData.AnyPressesThisFrame();
var released = mouseData.AnyReleasesThisFrame();
var leftButtonData = mouseData.GetButtonState(PointerEventData.InputButton.Left).eventData;
if (!UseMouse(pressed, released, leftButtonData.buttonData))
return;
// Process the first mouse button fully
ProcessMousePress(leftButtonData);
ProcessMove(leftButtonData.buttonData);
ProcessDrag(leftButtonData.buttonData);
// Now process right / middle clicks
ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData);
ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData.buttonData);
ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData);
ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData.buttonData);
if (!Mathf.Approximately(leftButtonData.buttonData.scrollDelta.sqrMagnitude, 0.0f))
{
var scrollHandler = ExecuteEvents.GetEventHandler<IScrollHandler>(leftButtonData.buttonData.pointerCurrentRaycast.gameObject);
ExecuteEvents.ExecuteHierarchy(scrollHandler, leftButtonData.buttonData, ExecuteEvents.scrollHandler);
}
}
/// <summary>
/// Process this InputModule. Same as the StandaloneInputModule version, except that it calls
/// ProcessMouseEvent twice, once for gaze pointers, and once for mouse pointers.
/// </summary>
public override void Process()
{
bool usedEvent = SendUpdateEventToSelectedObject();
if (eventSystem.sendNavigationEvents)
{
if (!usedEvent)
usedEvent |= SendMoveEventToSelectedObject();
if (!usedEvent)
SendSubmitEventToSelectedObject();
}
ProcessMouseEvent(GetGazePointerData());
#if !UNITY_ANDROID
ProcessMouseEvent(GetCanvasPointerData());
#endif
}
/// <summary>
/// Decide if mouse events need to be processed this frame. Same as StandloneInputModule except
/// that the IsPointerMoving method from this class is used, instead of the method on PointerEventData
/// </summary>
private static bool UseMouse(bool pressed, bool released, PointerEventData pointerData)
{
if (pressed || released || IsPointerMoving(pointerData) || pointerData.IsScrolling())
return true;
return false;
}
#endregion
/// <summary>
/// Convenience function for cloning PointerEventData
/// </summary>
/// <param name="from">Copy this value</param>
/// <param name="to">to this object</param>
protected void CopyFromTo(OVRPointerEventData @from, OVRPointerEventData @to)
{
@to.position = @from.position;
@to.delta = @from.delta;
@to.scrollDelta = @from.scrollDelta;
@to.pointerCurrentRaycast = @from.pointerCurrentRaycast;
@to.pointerEnter = @from.pointerEnter;
@to.worldSpaceRay = @from.worldSpaceRay;
}
/// <summary>
/// Convenience function for cloning PointerEventData
/// </summary>
/// <param name="from">Copy this value</param>
/// <param name="to">to this object</param>
protected new void CopyFromTo(PointerEventData @from, PointerEventData @to)
{
@to.position = @from.position;
@to.delta = @from.delta;
@to.scrollDelta = @from.scrollDelta;
@to.pointerCurrentRaycast = @from.pointerCurrentRaycast;
@to.pointerEnter = @from.pointerEnter;
}
// In the following region we extend the PointerEventData system implemented in PointerInputModule
// We define an additional dictionary for ray(e.g. gaze) based pointers. Mouse pointers still use the dictionary
// in PointerInputModule
#region PointerEventData pool
// Pool for OVRRayPointerEventData for ray based pointers
protected Dictionary<int, OVRPointerEventData> m_VRRayPointerData = new Dictionary<int, OVRPointerEventData>();
protected bool GetPointerData(int id, out OVRPointerEventData data, bool create)
{
if (!m_VRRayPointerData.TryGetValue(id, out data) && create)
{
data = new OVRPointerEventData(eventSystem)
{
pointerId = id,
};
m_VRRayPointerData.Add(id, data);
return true;
}
return false;
}
/// <summary>
/// Clear pointer state for both types of pointer
/// </summary>
protected new void ClearSelection()
{
var baseEventData = GetBaseEventData();
foreach (var pointer in m_PointerData.Values)
{
// clear all selection
HandlePointerExitAndEnter(pointer, null);
}
foreach (var pointer in m_VRRayPointerData.Values)
{
// clear all selection
HandlePointerExitAndEnter(pointer, null);
}
m_PointerData.Clear();
eventSystem.SetSelectedGameObject(null, baseEventData);
}
#endregion
/// <summary>
/// For RectTransform, calculate it's normal in world space
/// </summary>
static Vector3 GetRectTransformNormal(RectTransform rectTransform)
{
Vector3[] corners = new Vector3[4];
rectTransform.GetWorldCorners(corners);
Vector3 BottomEdge = corners[3] - corners[0];
Vector3 LeftEdge = corners[1] - corners[0];
rectTransform.GetWorldCorners(corners);
return Vector3.Cross(BottomEdge, LeftEdge).normalized;
}
private readonly MouseState m_MouseState = new MouseState();
// The following 2 functions are equivalent to PointerInputModule.GetMousePointerEventData but are customized to
// get data for ray pointers and canvas mouse pointers.
/// <summary>
/// State for a pointer controlled by a world space ray. E.g. gaze pointer
/// </summary>
/// <returns></returns>
virtual protected MouseState GetGazePointerData()
{
// Get the OVRRayPointerEventData reference
OVRPointerEventData leftData;
GetPointerData(kMouseLeftId, out leftData, true );
leftData.Reset();
//Now set the world space ray. This ray is what the user uses to point at UI elements
leftData.worldSpaceRay = new Ray(rayTransform.position, rayTransform.forward);
leftData.scrollDelta = GetExtraScrollDelta();
//Populate some default values
leftData.button = PointerEventData.InputButton.Left;
leftData.useDragThreshold = true;
// Perform raycast to find intersections with world
eventSystem.RaycastAll(leftData, m_RaycastResultCache);
var raycast = FindFirstRaycast(m_RaycastResultCache);
leftData.pointerCurrentRaycast = raycast;
m_RaycastResultCache.Clear();
m_Cursor.SetCursorRay(rayTransform);
OVRRaycaster ovrRaycaster = raycast.module as OVRRaycaster;
// We're only interested in intersections from OVRRaycasters
if (ovrRaycaster)
{
// The Unity UI system expects event data to have a screen position
// so even though this raycast came from a world space ray we must get a screen
// space position for the camera attached to this raycaster for compatability
leftData.position = ovrRaycaster.GetScreenPosition(raycast);
// Find the world position and normal the Graphic the ray intersected
RectTransform graphicRect = raycast.gameObject.GetComponent<RectTransform>();
if (graphicRect != null)
{
// Set are gaze indicator with this world position and normal
Vector3 worldPos = raycast.worldPosition;
Vector3 normal = GetRectTransformNormal(graphicRect);
m_Cursor.SetCursorStartDest(rayTransform.position, worldPos, normal);
}
}
// Now process physical raycast intersections
OVRPhysicsRaycaster physicsRaycaster = raycast.module as OVRPhysicsRaycaster;
if (physicsRaycaster)
{
Vector3 position = raycast.worldPosition;
if (performSphereCastForGazepointer)
{
// Here we cast a sphere into the scene rather than a ray. This gives a more accurate depth
// for positioning a circular gaze pointer
List<RaycastResult> results = new List<RaycastResult>();
physicsRaycaster.Spherecast(leftData, results, m_SpherecastRadius);
if (results.Count > 0 && results[0].distance < raycast.distance)
{
position = results[0].worldPosition;
}
}
leftData.position = physicsRaycaster.GetScreenPos(raycast.worldPosition);
m_Cursor.SetCursorStartDest(rayTransform.position, position, raycast.worldNormal);
}
// Stick default data values in right and middle slots for compatability
// copy the apropriate data into right and middle slots
OVRPointerEventData rightData;
GetPointerData(kMouseRightId, out rightData, true );
CopyFromTo(leftData, rightData);
rightData.button = PointerEventData.InputButton.Right;
OVRPointerEventData middleData;
GetPointerData(kMouseMiddleId, out middleData, true );
CopyFromTo(leftData, middleData);
middleData.button = PointerEventData.InputButton.Middle;
m_MouseState.SetButtonState(PointerEventData.InputButton.Left, GetGazeButtonState(), leftData);
m_MouseState.SetButtonState(PointerEventData.InputButton.Right, PointerEventData.FramePressState.NotChanged, rightData);
m_MouseState.SetButtonState(PointerEventData.InputButton.Middle, PointerEventData.FramePressState.NotChanged, middleData);
return m_MouseState;
}
/// <summary>
/// Get state for pointer which is a pointer moving in world space across the surface of a world space canvas.
/// </summary>
/// <returns></returns>
protected MouseState GetCanvasPointerData()
{
// Get the OVRRayPointerEventData reference
PointerEventData leftData;
GetPointerData(kMouseLeftId, out leftData, true );
leftData.Reset();
// Setup default values here. Set position to zero because we don't actually know the pointer
// positions. Each canvas knows the position of its canvas pointer.
leftData.position = Vector2.zero;
leftData.scrollDelta = Input.mouseScrollDelta;
leftData.button = PointerEventData.InputButton.Left;
if (activeGraphicRaycaster)
{
// Let the active raycaster find intersections on its canvas
activeGraphicRaycaster.RaycastPointer(leftData, m_RaycastResultCache);
var raycast = FindFirstRaycast(m_RaycastResultCache);
leftData.pointerCurrentRaycast = raycast;
m_RaycastResultCache.Clear();
OVRRaycaster ovrRaycaster = raycast.module as OVRRaycaster;
if (ovrRaycaster) // raycast may not actually contain a result
{
// The Unity UI system expects event data to have a screen position
// so even though this raycast came from a world space ray we must get a screen
// space position for the camera attached to this raycaster for compatability
Vector2 position = ovrRaycaster.GetScreenPosition(raycast);
leftData.delta = position - leftData.position;
leftData.position = position;
}
}
// copy the apropriate data into right and middle slots
PointerEventData rightData;
GetPointerData(kMouseRightId, out rightData, true );
CopyFromTo(leftData, rightData);
rightData.button = PointerEventData.InputButton.Right;
PointerEventData middleData;
GetPointerData(kMouseMiddleId, out middleData, true );
CopyFromTo(leftData, middleData);
middleData.button = PointerEventData.InputButton.Middle;
m_MouseState.SetButtonState(PointerEventData.InputButton.Left, StateForMouseButton(0), leftData);
m_MouseState.SetButtonState(PointerEventData.InputButton.Right, StateForMouseButton(1), rightData);
m_MouseState.SetButtonState(PointerEventData.InputButton.Middle, StateForMouseButton(2), middleData);
return m_MouseState;
}
/// <summary>
/// New version of ShouldStartDrag implemented first in PointerInputModule. This version differs in that
/// for ray based pointers it makes a decision about whether a drag should start based on the angular change
/// the pointer has made so far, as seen from the camera. This also works when the world space ray is
/// translated rather than rotated, since the beginning and end of the movement are considered as angle from
/// the same point.
/// </summary>
private bool ShouldStartDrag(PointerEventData pointerEvent)
{
if (!pointerEvent.useDragThreshold)
return true;
if (!pointerEvent.IsVRPointer())
{
// Same as original behaviour for canvas based pointers
return (pointerEvent.pressPosition - pointerEvent.position).sqrMagnitude >= eventSystem.pixelDragThreshold * eventSystem.pixelDragThreshold;
}
else
{
#if UNITY_ANDROID && !UNITY_EDITOR // On android allow swiping to start drag
if (useSwipeScroll && ((Vector3)pointerEvent.GetSwipeStart() - Input.mousePosition).magnitude > swipeDragThreshold)
{
return true;
}
#endif
// When it's not a screen space pointer we have to look at the angle it moved rather than the pixels distance
// For gaze based pointing screen-space distance moved will always be near 0
Vector3 cameraPos = pointerEvent.pressEventCamera.transform.position;
Vector3 pressDir = (pointerEvent.pointerPressRaycast.worldPosition - cameraPos).normalized;
Vector3 currentDir = (pointerEvent.pointerCurrentRaycast.worldPosition - cameraPos).normalized;
return Vector3.Dot(pressDir, currentDir) < Mathf.Cos(Mathf.Deg2Rad * (angleDragThreshold));
}
}
/// <summary>
/// The purpose of this function is to allow us to switch between using the standard IsPointerMoving
/// method for mouse driven pointers, but to always return true when it's a ray based pointer.
/// All real-world ray-based input devices are always moving so for simplicity we just return true
/// for them.
///
/// If PointerEventData.IsPointerMoving was virtual we could just override that in
/// OVRRayPointerEventData.
/// </summary>
/// <param name="pointerEvent"></param>
/// <returns></returns>
static bool IsPointerMoving(PointerEventData pointerEvent)
{
if (pointerEvent.IsVRPointer())
return true;
else
return pointerEvent.IsPointerMoving();
}
protected Vector2 SwipeAdjustedPosition(Vector2 originalPosition, PointerEventData pointerEvent)
{
#if UNITY_ANDROID && !UNITY_EDITOR
// On android we use the touchpad position (accessed through Input.mousePosition) to modify
// the effective cursor position for events related to dragging. This allows the user to
// use the touchpad to drag draggable UI elements
if (useSwipeScroll)
{
Vector2 delta = (Vector2)Input.mousePosition - pointerEvent.GetSwipeStart();
if (InvertSwipeXAxis)
delta.x *= -1;
return originalPosition + delta * swipeDragScale;
}
#endif
// If not Gear VR or swipe scroll isn't enabled just return original position
return originalPosition;
}
/// <summary>
/// Exactly the same as the code from PointerInputModule, except that we call our own
/// IsPointerMoving.
///
/// This would also not be necessary if PointerEventData.IsPointerMoving was virtual
/// </summary>
/// <param name="pointerEvent"></param>
protected override void ProcessDrag(PointerEventData pointerEvent)
{
Vector2 originalPosition = pointerEvent.position;
bool moving = IsPointerMoving(pointerEvent);
if (moving && pointerEvent.pointerDrag != null
&& !pointerEvent.dragging
&& ShouldStartDrag(pointerEvent))
{
if (pointerEvent.IsVRPointer())
{
//adjust the position used based on swiping action. Allowing the user to
//drag items by swiping on the GearVR touchpad
pointerEvent.position = SwipeAdjustedPosition (originalPosition, pointerEvent);
}
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.beginDragHandler);
pointerEvent.dragging = true;
}
// Drag notification
if (pointerEvent.dragging && moving && pointerEvent.pointerDrag != null)
{
if (pointerEvent.IsVRPointer())
{
pointerEvent.position = SwipeAdjustedPosition(originalPosition, pointerEvent);
}
// Before doing drag we should cancel any pointer down state
// And clear selection!
if (pointerEvent.pointerPress != pointerEvent.pointerDrag)
{
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
pointerEvent.eligibleForClick = false;
pointerEvent.pointerPress = null;
pointerEvent.rawPointerPress = null;
}
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.dragHandler);
}
}
/// <summary>
/// Get state of button corresponding to gaze pointer
/// </summary>
/// <returns></returns>
virtual protected PointerEventData.FramePressState GetGazeButtonState()
{
var pressed = Input.GetKeyDown(gazeClickKey) || OVRInput.GetDown(joyPadClickButton);
var released = Input.GetKeyUp(gazeClickKey) || OVRInput.GetUp(joyPadClickButton);
#if UNITY_ANDROID && !UNITY_EDITOR
// On Gear VR the mouse button events correspond to touch pad events. We only use these as gaze pointer clicks
// on Gear VR because on PC the mouse clicks are used for actual mouse pointer interactions.
pressed |= Input.GetMouseButtonDown(0);
released |= Input.GetMouseButtonUp(0);
#endif
if (pressed && released)
return PointerEventData.FramePressState.PressedAndReleased;
if (pressed)
return PointerEventData.FramePressState.Pressed;
if (released)
return PointerEventData.FramePressState.Released;
return PointerEventData.FramePressState.NotChanged;
}
/// <summary>
/// Get extra scroll delta from gamepad
/// </summary>
protected Vector2 GetExtraScrollDelta()
{
Vector2 scrollDelta = new Vector2();
if (useRightStickScroll)
{
Vector2 s = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick);
if (Mathf.Abs(s.x) < rightStickDeadZone) s.x = 0;
if (Mathf.Abs(s.y) < rightStickDeadZone) s.y = 0;
scrollDelta = s;
}
return scrollDelta;
}
};
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Ntfs
{
using System;
using System.Collections.Generic;
using System.IO;
internal class File
{
protected INtfsContext _context;
private MasterFileTable _mft;
private List<FileRecord> _records;
private ObjectCache<string, Index> _indexCache;
private List<NtfsAttribute> _attributes;
private bool _dirty;
public File(INtfsContext context, FileRecord baseRecord)
{
_context = context;
_mft = _context.Mft;
_records = new List<FileRecord>();
_records.Add(baseRecord);
_indexCache = new ObjectCache<string, Index>();
_attributes = new List<NtfsAttribute>();
LoadAttributes();
}
public uint IndexInMft
{
get { return _records[0].MasterFileTableIndex; }
}
public uint MaxMftRecordSize
{
get { return _records[0].AllocatedSize; }
}
public FileRecordReference MftReference
{
get { return _records[0].Reference; }
}
public List<string> Names
{
get
{
List<string> result = new List<string>();
if (IndexInMft == MasterFileTable.RootDirIndex)
{
result.Add(string.Empty);
}
else
{
foreach (StructuredNtfsAttribute<FileNameRecord> attr in GetAttributes(AttributeType.FileName))
{
string name = attr.Content.FileName;
Directory parentDir = _context.GetDirectoryByRef(attr.Content.ParentDirectory);
if (parentDir != null)
{
foreach (string dirName in parentDir.Names)
{
result.Add(Utilities.CombinePaths(dirName, name));
}
}
}
}
return result;
}
}
public bool HasWin32OrDosName
{
get
{
foreach (StructuredNtfsAttribute<FileNameRecord> attr in GetAttributes(AttributeType.FileName))
{
FileNameRecord fnr = attr.Content;
if (fnr.FileNameNamespace != FileNameNamespace.Posix)
{
return true;
}
}
return false;
}
}
public bool MftRecordIsDirty
{
get
{
return _dirty;
}
}
public ushort HardLinkCount
{
get { return _records[0].HardLinkCount; }
set { _records[0].HardLinkCount = value; }
}
public IEnumerable<NtfsStream> AllStreams
{
get
{
foreach (var attr in _attributes)
{
yield return new NtfsStream(this, attr);
}
}
}
public DirectoryEntry DirectoryEntry
{
get
{
if (_context.GetDirectoryByRef == null)
{
return null;
}
NtfsStream stream = GetStream(AttributeType.FileName, null);
if (stream == null)
{
return null;
}
FileNameRecord record = stream.GetContent<FileNameRecord>();
// Root dir is stored without root directory flag set in FileNameRecord, simulate it.
if (_records[0].MasterFileTableIndex == MasterFileTable.RootDirIndex)
{
record.Flags |= FileAttributeFlags.Directory;
}
return new DirectoryEntry(_context.GetDirectoryByRef(record.ParentDirectory), MftReference, record);
}
}
public string BestName
{
get
{
NtfsAttribute[] attrs = GetAttributes(AttributeType.FileName);
string bestName = null;
if (attrs != null && attrs.Length != 0)
{
bestName = attrs[0].ToString();
for (int i = 1; i < attrs.Length; ++i)
{
string name = attrs[i].ToString();
if (Utilities.Is8Dot3(bestName))
{
bestName = name;
}
}
}
return bestName;
}
}
public bool IsDirectory
{
get { return (_records[0].Flags & FileRecordFlags.IsDirectory) != 0; }
}
public StandardInformation StandardInformation
{
get { return GetStream(AttributeType.StandardInformation, null).GetContent<StandardInformation>(); }
}
internal INtfsContext Context
{
get
{
return _context;
}
}
/// <summary>
/// Gets an enumeration of all the attributes.
/// </summary>
internal IEnumerable<NtfsAttribute> AllAttributes
{
get { return _attributes; }
}
public static File CreateNew(INtfsContext context, FileAttributeFlags dirFlags)
{
return CreateNew(context, FileRecordFlags.None, dirFlags);
}
public static File CreateNew(INtfsContext context, FileRecordFlags flags, FileAttributeFlags dirFlags)
{
File newFile = context.AllocateFile(flags);
FileAttributeFlags fileFlags =
FileAttributeFlags.Archive
| FileRecord.ConvertFlags(flags)
| (dirFlags & FileAttributeFlags.Compressed);
AttributeFlags dataAttrFlags = AttributeFlags.None;
if ((dirFlags & FileAttributeFlags.Compressed) != 0)
{
dataAttrFlags |= AttributeFlags.Compressed;
}
StandardInformation.InitializeNewFile(newFile, fileFlags);
if (context.ObjectIds != null)
{
Guid newId = CreateNewGuid(context);
NtfsStream stream = newFile.CreateStream(AttributeType.ObjectId, null);
ObjectId objId = new ObjectId();
objId.Id = newId;
stream.SetContent(objId);
context.ObjectIds.Add(newId, newFile.MftReference, newId, Guid.Empty, Guid.Empty);
}
newFile.CreateAttribute(AttributeType.Data, dataAttrFlags);
newFile.UpdateRecordInMft();
return newFile;
}
public int MftRecordFreeSpace(AttributeType attrType, string attrName)
{
foreach (var record in _records)
{
if (record.GetAttribute(attrType, attrName) != null)
{
return _mft.RecordSize - record.Size;
}
}
throw new IOException("Attempt to determine free space for non-existent attribute");
}
public void Modified()
{
DateTime now = DateTime.UtcNow;
NtfsStream siStream = GetStream(AttributeType.StandardInformation, null);
StandardInformation si = siStream.GetContent<StandardInformation>();
si.LastAccessTime = now;
si.ModificationTime = now;
siStream.SetContent(si);
MarkMftRecordDirty();
}
public void Accessed()
{
DateTime now = DateTime.UtcNow;
NtfsStream siStream = GetStream(AttributeType.StandardInformation, null);
StandardInformation si = siStream.GetContent<StandardInformation>();
si.LastAccessTime = now;
siStream.SetContent(si);
MarkMftRecordDirty();
}
public void MarkMftRecordDirty()
{
_dirty = true;
}
public void UpdateRecordInMft()
{
if (_dirty)
{
if (NtfsTransaction.Current != null)
{
NtfsStream stream = GetStream(AttributeType.StandardInformation, null);
StandardInformation si = stream.GetContent<StandardInformation>();
si.MftChangedTime = NtfsTransaction.Current.Timestamp;
stream.SetContent(si);
}
bool fixesApplied = true;
while (fixesApplied)
{
fixesApplied = false;
for (int i = 0; i < _records.Count; ++i)
{
var record = _records[i];
bool fixedAttribute = true;
while (record.Size > _mft.RecordSize && fixedAttribute)
{
fixedAttribute = false;
if (!fixedAttribute && !record.IsMftRecord)
{
foreach (var attr in record.Attributes)
{
if (!attr.IsNonResident && !_context.AttributeDefinitions.MustBeResident(attr.AttributeType))
{
MakeAttributeNonResident(new AttributeReference(record.Reference, attr.AttributeId), (int)attr.DataLength);
fixedAttribute = true;
break;
}
}
}
if (!fixedAttribute)
{
foreach (var attr in record.Attributes)
{
if (attr.AttributeType == AttributeType.IndexRoot
&& ShrinkIndexRoot(attr.Name))
{
fixedAttribute = true;
break;
}
}
}
if (!fixedAttribute)
{
if (record.Attributes.Count == 1)
{
fixedAttribute = SplitAttribute(record);
}
else
{
if (_records.Count == 1)
{
CreateAttributeList();
}
fixedAttribute = ExpelAttribute(record);
}
}
fixesApplied |= fixedAttribute;
}
}
}
_dirty = false;
foreach (var record in _records)
{
_mft.WriteRecord(record);
}
}
}
public Index CreateIndex(string name, AttributeType attrType, AttributeCollationRule collRule)
{
Index.Create(attrType, collRule, this, name);
return GetIndex(name);
}
public Index GetIndex(string name)
{
Index idx = _indexCache[name];
if (idx == null)
{
idx = new Index(this, name, _context.BiosParameterBlock, _context.UpperCase);
_indexCache[name] = idx;
}
return idx;
}
public void Delete()
{
if (_records[0].HardLinkCount != 0)
{
throw new InvalidOperationException("Attempt to delete in-use file: " + ToString());
}
_context.ForgetFile(this);
NtfsStream objIdStream = GetStream(AttributeType.ObjectId, null);
if (objIdStream != null)
{
ObjectId objId = objIdStream.GetContent<ObjectId>();
Context.ObjectIds.Remove(objId.Id);
}
// Truncate attributes, allowing for truncation silently removing the AttributeList attribute
// in some cases (large file with all attributes first extent in the first MFT record). This
// releases all allocated clusters in most cases.
List<NtfsAttribute> truncateAttrs = new List<NtfsAttribute>(_attributes.Count);
foreach (var attr in _attributes)
{
if (attr.Type != AttributeType.AttributeList)
{
truncateAttrs.Add(attr);
}
}
foreach (NtfsAttribute attr in truncateAttrs)
{
attr.GetDataBuffer().SetCapacity(0);
}
// If the attribute list record remains, free any possible clusters it owns. We've now freed
// all clusters.
NtfsAttribute attrList = GetAttribute(AttributeType.AttributeList, null);
if (attrList != null)
{
attrList.GetDataBuffer().SetCapacity(0);
}
// Now go through the MFT records, freeing them up
foreach (var mftRecord in _records)
{
_context.Mft.RemoveRecord(mftRecord.Reference);
}
_attributes.Clear();
_records.Clear();
}
public bool StreamExists(AttributeType attrType, string name)
{
return GetStream(attrType, name) != null;
}
public NtfsStream GetStream(AttributeType attrType, string name)
{
foreach (NtfsStream stream in GetStreams(attrType, name))
{
return stream;
}
return null;
}
public IEnumerable<NtfsStream> GetStreams(AttributeType attrType, string name)
{
foreach (var attr in _attributes)
{
if (attr.Type == attrType && attr.Name == name)
{
yield return new NtfsStream(this, attr);
}
}
}
public NtfsStream CreateStream(AttributeType attrType, string name)
{
return new NtfsStream(this, CreateAttribute(attrType, name, AttributeFlags.None));
}
public NtfsStream CreateStream(AttributeType attrType, string name, long firstCluster, ulong numClusters, uint bytesPerCluster)
{
return new NtfsStream(this, CreateAttribute(attrType, name, AttributeFlags.None, firstCluster, numClusters, bytesPerCluster));
}
public SparseStream OpenStream(AttributeType attrType, string name, FileAccess access)
{
NtfsAttribute attr = GetAttribute(attrType, name);
if (attr != null)
{
return new FileStream(this, attr, access);
}
return null;
}
public void RemoveStream(NtfsStream stream)
{
RemoveAttribute(stream.Attribute);
}
public FileNameRecord GetFileNameRecord(string name, bool freshened)
{
NtfsAttribute[] attrs = GetAttributes(AttributeType.FileName);
StructuredNtfsAttribute<FileNameRecord> attr = null;
if (String.IsNullOrEmpty(name))
{
if (attrs.Length != 0)
{
attr = (StructuredNtfsAttribute<FileNameRecord>)attrs[0];
}
}
else
{
foreach (StructuredNtfsAttribute<FileNameRecord> a in attrs)
{
if (_context.UpperCase.Compare(a.Content.FileName, name) == 0)
{
attr = a;
}
}
if (attr == null)
{
throw new FileNotFoundException("File name not found on file", name);
}
}
FileNameRecord fnr = attr == null ? new FileNameRecord() : new FileNameRecord(attr.Content);
if (freshened)
{
FreshenFileName(fnr, false);
}
return fnr;
}
public virtual void Dump(TextWriter writer, string indent)
{
writer.WriteLine(indent + "FILE (" + ToString() + ")");
writer.WriteLine(indent + " File Number: " + _records[0].MasterFileTableIndex);
_records[0].Dump(writer, indent + " ");
foreach (AttributeRecord attrRec in _records[0].Attributes)
{
NtfsAttribute.FromRecord(this, MftReference, attrRec).Dump(writer, indent + " ");
}
}
public override string ToString()
{
string bestName = BestName;
if (bestName == null)
{
return "?????";
}
else
{
return bestName;
}
}
internal void RemoveAttributeExtents(NtfsAttribute attr)
{
attr.GetDataBuffer().SetCapacity(0);
foreach (var extentRef in attr.Extents.Keys)
{
RemoveAttributeExtent(extentRef);
}
}
internal void RemoveAttributeExtent(AttributeReference extentRef)
{
FileRecord fileRec = GetFileRecord(extentRef.File);
if (fileRec != null)
{
fileRec.RemoveAttribute(extentRef.AttributeId);
// Remove empty non-primary MFT records
if (fileRec.Attributes.Count == 0 && fileRec.BaseFile.Value != 0)
{
RemoveFileRecord(extentRef.File);
}
}
}
/// <summary>
/// Gets an attribute by reference.
/// </summary>
/// <param name="attrRef">Reference to the attribute.</param>
/// <returns>The attribute.</returns>
internal NtfsAttribute GetAttribute(AttributeReference attrRef)
{
foreach (var attr in _attributes)
{
if (attr.Reference.Equals(attrRef))
{
return attr;
}
}
return null;
}
/// <summary>
/// Gets the first (if more than one) instance of a named attribute.
/// </summary>
/// <param name="type">The attribute type.</param>
/// <param name="name">The attribute's name.</param>
/// <returns>The attribute of <c>null</c>.</returns>
internal NtfsAttribute GetAttribute(AttributeType type, string name)
{
foreach (var attr in _attributes)
{
if (attr.PrimaryRecord.AttributeType == type && attr.Name == name)
{
return attr;
}
}
return null;
}
/// <summary>
/// Gets all instances of an unnamed attribute.
/// </summary>
/// <param name="type">The attribute type.</param>
/// <returns>The attributes.</returns>
internal NtfsAttribute[] GetAttributes(AttributeType type)
{
List<NtfsAttribute> matches = new List<NtfsAttribute>();
foreach (var attr in _attributes)
{
if (attr.PrimaryRecord.AttributeType == type && string.IsNullOrEmpty(attr.Name))
{
matches.Add(attr);
}
}
return matches.ToArray();
}
internal void MakeAttributeNonResident(AttributeReference attrRef, int maxData)
{
NtfsAttribute attr = GetAttribute(attrRef);
if (attr.IsNonResident)
{
throw new InvalidOperationException("Attribute is already non-resident");
}
ushort id = _records[0].CreateNonResidentAttribute(attr.Type, attr.Name, attr.Flags);
AttributeRecord newAttrRecord = _records[0].GetAttribute(id);
IBuffer attrBuffer = attr.GetDataBuffer();
byte[] tempData = Utilities.ReadFully(attrBuffer, 0, (int)Math.Min(maxData, attrBuffer.Capacity));
RemoveAttributeExtents(attr);
attr.SetExtent(_records[0].Reference, newAttrRecord);
attr.GetDataBuffer().Write(0, tempData, 0, tempData.Length);
UpdateAttributeList();
}
internal void FreshenFileName(FileNameRecord fileName, bool updateMftRecord)
{
//
// Freshen the record from the definitive info in the other attributes
//
StandardInformation si = StandardInformation;
NtfsAttribute anonDataAttr = GetAttribute(AttributeType.Data, null);
fileName.CreationTime = si.CreationTime;
fileName.ModificationTime = si.ModificationTime;
fileName.MftChangedTime = si.MftChangedTime;
fileName.LastAccessTime = si.LastAccessTime;
fileName.Flags = si.FileAttributes;
if (_dirty && NtfsTransaction.Current != null)
{
fileName.MftChangedTime = NtfsTransaction.Current.Timestamp;
}
// Directories don't have directory flag set in StandardInformation, so set from MFT record
if ((_records[0].Flags & FileRecordFlags.IsDirectory) != 0)
{
fileName.Flags |= FileAttributeFlags.Directory;
}
if (anonDataAttr != null)
{
fileName.RealSize = (ulong)anonDataAttr.PrimaryRecord.DataLength;
fileName.AllocatedSize = (ulong)anonDataAttr.PrimaryRecord.AllocatedLength;
}
if (updateMftRecord)
{
foreach (NtfsStream stream in GetStreams(AttributeType.FileName, null))
{
FileNameRecord fnr = stream.GetContent<FileNameRecord>();
if (fnr.Equals(fileName))
{
fnr = new FileNameRecord(fileName);
fnr.Flags &= ~FileAttributeFlags.ReparsePoint;
stream.SetContent(fnr);
}
}
}
}
internal long GetAttributeOffset(AttributeReference attrRef)
{
long recordOffset = _mft.GetRecordOffset(attrRef.File);
FileRecord frs = GetFileRecord(attrRef.File);
return recordOffset + frs.GetAttributeOffset(attrRef.AttributeId);
}
private static Guid CreateNewGuid(INtfsContext context)
{
Random rng = context.Options.RandomNumberGenerator;
if (rng != null)
{
byte[] buffer = new byte[16];
rng.NextBytes(buffer);
return new Guid(buffer);
}
else
{
return Guid.NewGuid();
}
}
private void LoadAttributes()
{
Dictionary<long, FileRecord> extraFileRecords = new Dictionary<long, FileRecord>();
AttributeRecord attrListRec = _records[0].GetAttribute(AttributeType.AttributeList);
if (attrListRec != null)
{
NtfsAttribute lastAttr = null;
StructuredNtfsAttribute<AttributeList> attrListAttr = (StructuredNtfsAttribute<AttributeList>)NtfsAttribute.FromRecord(this, MftReference, attrListRec);
var attrList = attrListAttr.Content;
_attributes.Add(attrListAttr);
foreach (var record in attrList)
{
FileRecord attrFileRecord = _records[0];
if (record.BaseFileReference.MftIndex != _records[0].MasterFileTableIndex)
{
if (!extraFileRecords.TryGetValue(record.BaseFileReference.MftIndex, out attrFileRecord))
{
attrFileRecord = _context.Mft.GetRecord(record.BaseFileReference);
if (attrFileRecord != null)
{
extraFileRecords[attrFileRecord.MasterFileTableIndex] = attrFileRecord;
}
}
}
if (attrFileRecord != null)
{
AttributeRecord attrRec = attrFileRecord.GetAttribute(record.AttributeId);
if (attrRec != null)
{
if (record.StartVcn == 0)
{
lastAttr = NtfsAttribute.FromRecord(this, record.BaseFileReference, attrRec);
_attributes.Add(lastAttr);
}
else
{
lastAttr.AddExtent(record.BaseFileReference, attrRec);
}
}
}
}
foreach (var extraFileRecord in extraFileRecords)
{
_records.Add(extraFileRecord.Value);
}
}
else
{
foreach (var record in _records[0].Attributes)
{
_attributes.Add(NtfsAttribute.FromRecord(this, MftReference, record));
}
}
}
private bool SplitAttribute(FileRecord record)
{
if (record.Attributes.Count != 1)
{
throw new InvalidOperationException("Attempting to split attribute in MFT record containing multiple attributes");
}
return SplitAttribute(record, (NonResidentAttributeRecord)record.FirstAttribute, false);
}
private bool SplitAttribute(FileRecord record, NonResidentAttributeRecord targetAttr, bool atStart)
{
if (targetAttr.DataRuns.Count <= 1)
{
return false;
}
int splitIndex = 1;
if (!atStart)
{
List<DataRun> runs = targetAttr.DataRuns;
splitIndex = runs.Count - 1;
int saved = runs[splitIndex].Size;
while (splitIndex > 1 && record.Size - saved > record.AllocatedSize)
{
--splitIndex;
saved += runs[splitIndex].Size;
}
}
AttributeRecord newAttr = targetAttr.Split(splitIndex);
// Find a home for the new attribute record
FileRecord newAttrHome = null;
foreach (var targetRecord in _records)
{
if (!targetRecord.IsMftRecord && _mft.RecordSize - targetRecord.Size >= newAttr.Size)
{
targetRecord.AddAttribute(newAttr);
newAttrHome = targetRecord;
}
}
if (newAttrHome == null)
{
newAttrHome = _mft.AllocateRecord(_records[0].Flags & (~FileRecordFlags.InUse), record.IsMftRecord);
newAttrHome.BaseFile = record.BaseFile.IsNull ? record.Reference : record.BaseFile;
_records.Add(newAttrHome);
newAttrHome.AddAttribute(newAttr);
}
// Add the new attribute record as an extent on the attribute it split from
bool added = false;
foreach (var attr in _attributes)
{
foreach (var existingRecord in attr.Extents)
{
if (existingRecord.Key.File == record.Reference && existingRecord.Key.AttributeId == targetAttr.AttributeId)
{
attr.AddExtent(newAttrHome.Reference, newAttr);
added = true;
break;
}
}
if (added)
{
break;
}
}
UpdateAttributeList();
return true;
}
private bool ExpelAttribute(FileRecord record)
{
if (record.MasterFileTableIndex == MasterFileTable.MftIndex)
{
// Special case for MFT - can't fully expel attributes, instead split most of the data runs off.
List<AttributeRecord> attrs = record.Attributes;
for (int i = attrs.Count - 1; i >= 0; --i)
{
AttributeRecord attr = attrs[i];
if (attr.AttributeType == AttributeType.Data)
{
if (SplitAttribute(record, (NonResidentAttributeRecord)attr, true))
{
return true;
}
}
}
}
else
{
List<AttributeRecord> attrs = record.Attributes;
for (int i = attrs.Count - 1; i >= 0; --i)
{
AttributeRecord attr = attrs[i];
if (attr.AttributeType > AttributeType.AttributeList)
{
foreach (var targetRecord in _records)
{
if (_mft.RecordSize - targetRecord.Size >= attr.Size)
{
MoveAttribute(record, attr, targetRecord);
return true;
}
}
FileRecord newFileRecord = _mft.AllocateRecord(FileRecordFlags.None, record.IsMftRecord);
newFileRecord.BaseFile = record.Reference;
_records.Add(newFileRecord);
MoveAttribute(record, attr, newFileRecord);
return true;
}
}
}
return false;
}
private void MoveAttribute(FileRecord record, AttributeRecord attrRec, FileRecord targetRecord)
{
AttributeReference oldRef = new AttributeReference(record.Reference, attrRec.AttributeId);
record.RemoveAttribute(attrRec.AttributeId);
targetRecord.AddAttribute(attrRec);
AttributeReference newRef = new AttributeReference(targetRecord.Reference, attrRec.AttributeId);
foreach (var attr in _attributes)
{
attr.ReplaceExtent(oldRef, newRef, attrRec);
}
UpdateAttributeList();
}
private void CreateAttributeList()
{
ushort id = _records[0].CreateAttribute(AttributeType.AttributeList, null, false, AttributeFlags.None);
StructuredNtfsAttribute<AttributeList> newAttr = (StructuredNtfsAttribute<AttributeList>)NtfsAttribute.FromRecord(this, MftReference, _records[0].GetAttribute(id));
_attributes.Add(newAttr);
UpdateAttributeList();
}
private void UpdateAttributeList()
{
if (_records.Count > 1)
{
AttributeList attrList = new AttributeList();
foreach (var attr in _attributes)
{
if (attr.Type != AttributeType.AttributeList)
{
foreach (var extent in attr.Extents)
{
attrList.Add(AttributeListRecord.FromAttribute(extent.Value, extent.Key.File));
}
}
}
StructuredNtfsAttribute<AttributeList> alAttr;
alAttr = (StructuredNtfsAttribute<AttributeList>)GetAttribute(AttributeType.AttributeList, null);
alAttr.Content = attrList;
alAttr.Save();
}
}
/// <summary>
/// Creates a new unnamed attribute.
/// </summary>
/// <param name="type">The type of the new attribute.</param>
/// <param name="flags">The flags of the new attribute.</param>
/// <returns>The new attribute.</returns>
private NtfsAttribute CreateAttribute(AttributeType type, AttributeFlags flags)
{
return CreateAttribute(type, null, flags);
}
/// <summary>
/// Creates a new attribute.
/// </summary>
/// <param name="type">The type of the new attribute.</param>
/// <param name="name">The name of the new attribute.</param>
/// <param name="flags">The flags of the new attribute.</param>
/// <returns>The new attribute.</returns>
private NtfsAttribute CreateAttribute(AttributeType type, string name, AttributeFlags flags)
{
bool indexed = _context.AttributeDefinitions.IsIndexed(type);
ushort id = _records[0].CreateAttribute(type, name, indexed, flags);
AttributeRecord newAttrRecord = _records[0].GetAttribute(id);
NtfsAttribute newAttr = NtfsAttribute.FromRecord(this, MftReference, newAttrRecord);
_attributes.Add(newAttr);
UpdateAttributeList();
MarkMftRecordDirty();
return newAttr;
}
/// <summary>
/// Creates a new attribute at a fixed cluster.
/// </summary>
/// <param name="type">The type of the new attribute.</param>
/// <param name="name">The name of the new attribute.</param>
/// <param name="flags">The flags of the new attribute.</param>
/// <param name="firstCluster">The first cluster to assign to the attribute.</param>
/// <param name="numClusters">The number of sequential clusters to assign to the attribute.</param>
/// <param name="bytesPerCluster">The number of bytes in each cluster.</param>
/// <returns>The new attribute.</returns>
private NtfsAttribute CreateAttribute(AttributeType type, string name, AttributeFlags flags, long firstCluster, ulong numClusters, uint bytesPerCluster)
{
bool indexed = _context.AttributeDefinitions.IsIndexed(type);
ushort id = _records[0].CreateNonResidentAttribute(type, name, flags, firstCluster, numClusters, bytesPerCluster);
AttributeRecord newAttrRecord = _records[0].GetAttribute(id);
NtfsAttribute newAttr = NtfsAttribute.FromRecord(this, MftReference, newAttrRecord);
_attributes.Add(newAttr);
UpdateAttributeList();
MarkMftRecordDirty();
return newAttr;
}
private void RemoveAttribute(NtfsAttribute attr)
{
if (attr != null)
{
if (attr.PrimaryRecord.AttributeType == AttributeType.IndexRoot)
{
_indexCache.Remove(attr.PrimaryRecord.Name);
}
RemoveAttributeExtents(attr);
_attributes.Remove(attr);
UpdateAttributeList();
}
}
private bool ShrinkIndexRoot(string indexName)
{
NtfsAttribute attr = GetAttribute(AttributeType.IndexRoot, indexName);
// Nothing to win, can't make IndexRoot smaller than this
// 8 = min size of entry that points to IndexAllocation...
if (attr.Length <= IndexRoot.HeaderOffset + IndexHeader.Size + 8)
{
return false;
}
Index idx = GetIndex(indexName);
return idx.ShrinkRoot();
}
private void MakeAttributeResident(AttributeReference attrRef, int maxData)
{
NtfsAttribute attr = GetAttribute(attrRef);
if (!attr.IsNonResident)
{
throw new InvalidOperationException("Attribute is already resident");
}
ushort id = _records[0].CreateAttribute(attr.Type, attr.Name, _context.AttributeDefinitions.IsIndexed(attr.Type), attr.Flags);
AttributeRecord newAttrRecord = _records[0].GetAttribute(id);
IBuffer attrBuffer = attr.GetDataBuffer();
byte[] tempData = Utilities.ReadFully(attrBuffer, 0, (int)Math.Min(maxData, attrBuffer.Capacity));
RemoveAttributeExtents(attr);
attr.SetExtent(_records[0].Reference, newAttrRecord);
attr.GetDataBuffer().Write(0, tempData, 0, tempData.Length);
UpdateAttributeList();
}
private FileRecord GetFileRecord(FileRecordReference fileReference)
{
foreach (var record in _records)
{
if (record.MasterFileTableIndex == fileReference.MftIndex)
{
return record;
}
}
return null;
}
private void RemoveFileRecord(FileRecordReference fileReference)
{
for (int i = 0; i < _records.Count; ++i)
{
if (_records[i].MasterFileTableIndex == fileReference.MftIndex)
{
FileRecord record = _records[i];
if (record.Attributes.Count > 0)
{
throw new IOException("Attempting to remove non-empty MFT record");
}
_context.Mft.RemoveRecord(fileReference);
_records.Remove(record);
if (_records.Count == 1)
{
NtfsAttribute attrListAttr = GetAttribute(AttributeType.AttributeList, null);
if (attrListAttr != null)
{
RemoveAttribute(attrListAttr);
}
}
}
}
}
/// <summary>
/// Wrapper for Resident/Non-Resident attribute streams, that remains valid
/// despite the attribute oscillating between resident and not.
/// </summary>
private class FileStream : SparseStream
{
private File _file;
private NtfsAttribute _attr;
private SparseStream _wrapped;
public FileStream(File file, NtfsAttribute attr, FileAccess access)
{
_file = file;
_attr = attr;
_wrapped = attr.Open(access);
}
public override IEnumerable<StreamExtent> Extents
{
get
{
return _wrapped.Extents;
}
}
public override bool CanRead
{
get
{
return _wrapped.CanRead;
}
}
public override bool CanSeek
{
get
{
return _wrapped.CanSeek;
}
}
public override bool CanWrite
{
get
{
return _wrapped.CanWrite;
}
}
public override long Length
{
get
{
return _wrapped.Length;
}
}
public override long Position
{
get
{
return _wrapped.Position;
}
set
{
_wrapped.Position = value;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_wrapped.Dispose();
}
public override void Flush()
{
_wrapped.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _wrapped.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _wrapped.Seek(offset, origin);
}
public override void SetLength(long value)
{
ChangeAttributeResidencyByLength(value);
_wrapped.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
if (_wrapped.Position + count > Length)
{
ChangeAttributeResidencyByLength(_wrapped.Position + count);
}
_wrapped.Write(buffer, offset, count);
}
public override void Clear(int count)
{
if (_wrapped.Position + count > Length)
{
ChangeAttributeResidencyByLength(_wrapped.Position + count);
}
_wrapped.Clear(count);
}
public override string ToString()
{
return _file.ToString() + ".attr[" + _attr.Id + "]";
}
/// <summary>
/// Change attribute residency if it gets too big (or small).
/// </summary>
/// <param name="value">The new (anticipated) length of the stream.</param>
/// <remarks>Has hysteresis - the decision is based on the input and the current
/// state, not the current state alone.</remarks>
private void ChangeAttributeResidencyByLength(long value)
{
// This is a bit of a hack - but it's really important the bitmap file remains non-resident
if (_file._records[0].MasterFileTableIndex == MasterFileTable.BitmapIndex)
{
return;
}
if (!_attr.IsNonResident && value >= _file.MaxMftRecordSize)
{
_file.MakeAttributeNonResident(_attr.Reference, (int)Math.Min(value, _wrapped.Length));
}
else if (_attr.IsNonResident && value <= _file.MaxMftRecordSize / 4)
{
// Use of 1/4 of record size here is just a heuristic - the important thing is not to end up with
// zero-length non-resident attributes
_file.MakeAttributeResident(_attr.Reference, (int)value);
}
}
}
}
}
| |
//
// ButtonBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt.Drawing;
#if MONOMAC
using nint = System.Int32;
using nfloat = System.Single;
using MonoMac.AppKit;
using MonoMac.ObjCRuntime;
using CGRect = System.Drawing.RectangleF;
#else
using AppKit;
using CoreGraphics;
#endif
namespace Xwt.Mac
{
public class ButtonBackend: ViewBackend<NSButton,IButtonEventSink>, IButtonBackend
{
ButtonType currentType;
ButtonStyle currentStyle;
public ButtonBackend ()
{
}
#region IButtonBackend implementation
public override void Initialize ()
{
ViewObject = new MacButton (EventSink, ApplicationContext);
Widget.SetButtonType (NSButtonType.MomentaryPushIn);
}
public void EnableEvent (Xwt.Backends.ButtonEvent ev)
{
((MacButton)Widget).EnableEvent (ev);
}
public void DisableEvent (Xwt.Backends.ButtonEvent ev)
{
((MacButton)Widget).DisableEvent (ev);
}
public void SetContent (string label, bool useMnemonic, ImageDescription image, ContentPosition imagePosition)
{
switch (((Button)Frontend).Type) {
case ButtonType.Help:
case ButtonType.Disclosure:
return;
}
if (useMnemonic)
label = label.RemoveMnemonic ();
Widget.Title = label ?? "";
if (string.IsNullOrEmpty (label))
imagePosition = ContentPosition.Center;
if (!image.IsNull) {
var img = image.ToNSImage ();
Widget.Image = (NSImage)img;
Widget.Cell.ImageScale = NSImageScale.None;
switch (imagePosition) {
case ContentPosition.Bottom: Widget.ImagePosition = NSCellImagePosition.ImageBelow; break;
case ContentPosition.Left: Widget.ImagePosition = NSCellImagePosition.ImageLeft; break;
case ContentPosition.Right: Widget.ImagePosition = NSCellImagePosition.ImageRight; break;
case ContentPosition.Top: Widget.ImagePosition = NSCellImagePosition.ImageAbove; break;
case ContentPosition.Center: Widget.ImagePosition = string.IsNullOrEmpty (label) ? NSCellImagePosition.ImageOnly : NSCellImagePosition.ImageOverlaps; break;
}
}
SetButtonStyle (currentStyle);
ResetFittingSize ();
}
public virtual void SetButtonStyle (ButtonStyle style)
{
currentStyle = style;
if (currentType == ButtonType.Normal)
{
switch (style) {
case ButtonStyle.Normal:
if (Widget.Image != null
|| Frontend.MinHeight > 0
|| Frontend.HeightRequest > 0
|| Widget.Title.Contains (Environment.NewLine))
Widget.BezelStyle = NSBezelStyle.RegularSquare;
else
Widget.BezelStyle = NSBezelStyle.Rounded;
#if MONOMAC
Messaging.void_objc_msgSend_bool (Widget.Handle, selSetShowsBorderOnlyWhileMouseInside.Handle, false);
#else
Widget.ShowsBorderOnlyWhileMouseInside = false;
#endif
break;
case ButtonStyle.Borderless:
case ButtonStyle.Flat:
Widget.BezelStyle = NSBezelStyle.ShadowlessSquare;
#if MONOMAC
Messaging.void_objc_msgSend_bool (Widget.Handle, selSetShowsBorderOnlyWhileMouseInside.Handle, true);
#else
Widget.ShowsBorderOnlyWhileMouseInside = true;
#endif
break;
}
}
}
#if MONOMAC
protected static Selector selSetShowsBorderOnlyWhileMouseInside = new Selector ("setShowsBorderOnlyWhileMouseInside:");
#endif
public void SetButtonType (ButtonType type)
{
currentType = type;
switch (type) {
case ButtonType.Disclosure:
Widget.BezelStyle = NSBezelStyle.Disclosure;
Widget.Title = "";
break;
case ButtonType.Help:
Widget.BezelStyle = NSBezelStyle.HelpButton;
Widget.Title = "";
break;
default:
SetButtonStyle (currentStyle);
break;
}
}
#endregion
public override Color BackgroundColor {
get { return ((MacButton)Widget).BackgroundColor; }
set { ((MacButton)Widget).BackgroundColor = value; }
}
}
class MacButton: NSButton, IViewObject
{
//
// This is necessary since the Activated event for NSControl in AppKit does
// not take a list of handlers, instead it supports only one handler.
//
// This event is used by the RadioButton backend to implement radio groups
//
internal event Action <MacButton> ActivatedInternal;
public MacButton (IntPtr p): base (p)
{
}
public MacButton (IButtonEventSink eventSink, ApplicationContext context)
{
Cell = new ColoredButtonCell ();
BezelStyle = NSBezelStyle.Rounded;
Activated += delegate {
context.InvokeUserCode (delegate {
eventSink.OnClicked ();
});
OnActivatedInternal ();
};
}
public MacButton ()
{
Activated += delegate {
OnActivatedInternal ();
};
}
public MacButton (IRadioButtonEventSink eventSink, ApplicationContext context)
{
Activated += delegate {
context.InvokeUserCode (delegate {
eventSink.OnClicked ();
});
OnActivatedInternal ();
};
}
public ViewBackend Backend { get; set; }
public NSView View {
get { return this; }
}
public void EnableEvent (ButtonEvent ev)
{
}
public void DisableEvent (ButtonEvent ev)
{
}
void OnActivatedInternal ()
{
if (ActivatedInternal == null)
return;
ActivatedInternal (this);
}
public override void ResetCursorRects ()
{
base.ResetCursorRects ();
if (Backend.Cursor != null)
AddCursorRect (Bounds, Backend.Cursor);
}
public Color BackgroundColor {
get {
return ((ColoredButtonCell)Cell).Color.GetValueOrDefault ();
}
set {
((ColoredButtonCell)Cell).Color = value;
}
}
class ColoredButtonCell : NSButtonCell
{
public Color? Color { get; set; }
public override void DrawBezelWithFrame (CGRect frame, NSView controlView)
{
controlView.DrawWithColorTransform(Color, delegate { base.DrawBezelWithFrame (frame, controlView); });
}
}
}
}
| |
// Copyright (c) Oleg Zudov. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// This file is based on or incorporates material from the Chromium Projects, licensed under the BSD-style license. More info in THIRD-PARTY-NOTICES file.
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using System.Globalization;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Zu.ChromeDevTools.DOM;
using Zu.ChromeDevTools.Input;
using Zu.ChromeDevTools.Page;
using Zu.ChromeDevTools.Runtime;
using Zu.WebBrowser.BasicTypes;
namespace Zu.Chrome.DriverCore
{
[SuppressMessage("ReSharper", "InconsistentNaming")]
public class WebView
{
public ChromeDevToolsConnection DevTools;
private FrameTracker FrameTracker;
private AsyncChromeDriver _asyncChromeDriver;
public WebView(ChromeDevToolsConnection devTools, FrameTracker frameTracker, AsyncChromeDriver asyncChromeDriver)
{
DevTools = devTools;
FrameTracker = frameTracker;
_asyncChromeDriver = asyncChromeDriver;
}
public async Task<EvaluateCommandResponse> CallFunction(string function, /*JToken*/
string /*[]*/ args, string frame = null, bool returnByValue = true, bool w3c = false, CancellationToken cancellationToken = default (CancellationToken))
{
var expression = $"({call_function.JsSource}).apply(null, [null, {function}, [{args}], {w3c.ToString().ToLower()}])";
var res = await EvaluateScript(expression, frame, returnByValue, cancellationToken).ConfigureAwait(false);
//var res = await devTools?.Session.Runtime.CallFunctionOn(new CallFunctionOnCommand
//{
// FunctionDeclaration = function,
// Arguments = args,
//});
return res;
}
public async Task<EvaluateCommandResponse> CallFunctionInContext(string function, string args, long ? contextId = null, bool returnByValue = true, bool w3c = false, CancellationToken cancellationToken = default (CancellationToken))
{
var expression = $"({call_function.JsSource}).apply(null, [null, {function}, [{args}], {w3c.ToString().ToLower()}])";
var res = await EvaluateScriptInContext(expression, contextId, returnByValue, cancellationToken).ConfigureAwait(false);
return res;
}
public async Task<string> CallFunctionInContextAndGetObject(string function, string args, long ? contextId = null, bool w3c = false, CancellationToken cancellationToken = default (CancellationToken))
{
var res = await CallFunctionInContext(function, args, contextId, false, w3c, cancellationToken).ConfigureAwait(false);
return res?.Result?.ObjectId;
}
public async Task<object> CallUserAsyncFunction(string function, /*JToken*/
string /*[]*/ args, TimeSpan? scriptTimeout, string frame = null, bool returnByValue = true, bool w3c = false, CancellationToken cancellationToken = default (CancellationToken))
{
var asyncArgsList = new List<string>{"\"return (" + function + ").apply(null, arguments);\"", $"[{args}]", "true", scriptTimeout == null || scriptTimeout == default (TimeSpan) ? "0" : ((TimeSpan)scriptTimeout).TotalMilliseconds.ToString()};
var asyncArgs = string.Join(", ", asyncArgsList);
//var expression = $"({execute_async_script.JsSource}).apply(null, [null, {function}, [{args}], {w3c.ToString().ToLower()}])";
//var res = await EvaluateScript(expression, frame, returnByValue, cancellationToken);
var r1 = await CallFunction(execute_async_script.JsSource, asyncArgs, _asyncChromeDriver.Session?.GetCurrentFrameId()).ConfigureAwait(false);
var kDocUnloadError = "document unloaded while waiting for result";
var kJavaScriptError = 17;
string kQueryResult = string.Format("function() {{" + " var info = document.$chrome_asyncScriptInfo;" + " if (!info)" + " return {{status: {0}, value: '{1}' }};" + " var result = info.result;" + " if (!result)" + " return {{status: 0}};" + " delete info.result;" + " return result;" + "}}", kJavaScriptError, kDocUnloadError);
while (true)
{
var queryValue = await CallFunction(kQueryResult, "", frame).ConfigureAwait(false);
if (queryValue.Result?.Value != null)
{
return queryValue.Result.Value;
}
await Task.Delay(100).ConfigureAwait(false);
}
}
public async Task<EvaluateCommandResponse> EvaluateScript(string expression, string frame = null, bool returnByValue = true, CancellationToken cancellationToken = default (CancellationToken))
{
if (_asyncChromeDriver != null)
await _asyncChromeDriver.CheckConnected().ConfigureAwait(false);
var contextId = string.IsNullOrWhiteSpace(frame) ? null : (long ? )FrameTracker.GetContextIdForFrame(frame);
return await DevTools.Runtime.Evaluate(new EvaluateCommand{Expression = expression, ContextId = contextId, ReturnByValue = returnByValue}, cancellationToken).ConfigureAwait(false);
}
public async Task<EvaluateCommandResponse> EvaluateScriptInContext(string expression, long ? contextId = null, bool returnByValue = true, CancellationToken cancellationToken = default (CancellationToken))
{
if (_asyncChromeDriver != null)
await _asyncChromeDriver.CheckConnected().ConfigureAwait(false);
return await DevTools.Runtime.Evaluate(new EvaluateCommand{Expression = expression, ContextId = contextId, ReturnByValue = returnByValue}, cancellationToken).ConfigureAwait(false);
}
public async Task<string> EvaluateScriptAndGetObject(string expression, string frame = null, //bool returnByValue = true,
CancellationToken cancellationToken = default (CancellationToken))
{
var res = await EvaluateScript(expression, frame, false, cancellationToken).ConfigureAwait(false);
return res?.Result?.ObjectId;
}
public async Task<string> EvaluateScriptAndGetObjectInContext(string expression, long ? contextId = null, //bool returnByValue = true,
CancellationToken cancellationToken = default (CancellationToken))
{
var res = await EvaluateScriptInContext(expression, contextId, false, cancellationToken).ConfigureAwait(false);
return res?.Result?.ObjectId;
}
public async Task<string> GetUrl(CancellationToken cancellationToken = default (CancellationToken))
{
if (_asyncChromeDriver != null)
await _asyncChromeDriver.CheckConnected(cancellationToken).ConfigureAwait(false);
var res = await DevTools.Page.GetNavigationHistory(new GetNavigationHistoryCommand(), cancellationToken).ConfigureAwait(false);
return res.Entries?.ElementAtOrDefault((int)res.CurrentIndex)?.Url;
}
public async Task<NavigateCommandResponse> Load(string url, int ? timeout = null, CancellationToken cancellationToken = default (CancellationToken))
{
if (_asyncChromeDriver != null)
await _asyncChromeDriver.CheckConnected(cancellationToken).ConfigureAwait(false);
var res = await DevTools.Page.Navigate(new NavigateCommand{Url = url}, cancellationToken, timeout).ConfigureAwait(false);
return res;
}
public async Task<string> Reload(CancellationToken cancellationToken = default (CancellationToken))
{
if (_asyncChromeDriver != null)
await _asyncChromeDriver.CheckConnected().ConfigureAwait(false);
var res = await DevTools.Page.Reload(new ReloadCommand(), cancellationToken).ConfigureAwait(false);
return res.ToString();
}
public async Task<NavigateToHistoryEntryCommandResponse> TraverseHistory(int delta, CancellationToken cancellationToken = default (CancellationToken))
{
if (_asyncChromeDriver != null)
await _asyncChromeDriver.CheckConnected().ConfigureAwait(false);
var res = await DevTools.Page.GetNavigationHistory(new GetNavigationHistoryCommand(), cancellationToken).ConfigureAwait(false);
if (delta == -1)
{
if (res.CurrentIndex > 0)
{
return await DevTools.Page.NavigateToHistoryEntry(new NavigateToHistoryEntryCommand{EntryId = res.Entries[res.CurrentIndex + delta].Id}, cancellationToken).ConfigureAwait(false);
//return await EvaluateScript("window.history.back();");
}
else
{
return null;
}
}
else if (delta == 1)
if (res.CurrentIndex + 1 < res.Entries.Count())
{
return await DevTools.Page.NavigateToHistoryEntry(new NavigateToHistoryEntryCommand{EntryId = res.Entries[res.CurrentIndex + delta].Id}, cancellationToken).ConfigureAwait(false);
//return await EvaluateScript("window.history.forward();");
}
else
{
return null;
}
else
return null;
//else throw new ArgumentOutOfRangeException(nameof(delta));
}
internal string SetFileInputFiles(string elementId, string keys, CancellationToken cancellationToken = default (CancellationToken))
{
throw new NotImplementedException();
}
public Task<EvaluateCommandResponse> TraverseHistoryWithJavaScript(int delta, CancellationToken cancellationToken = default (CancellationToken))
{
if (delta == -1)
return EvaluateScript("window.history.back();", null, true, cancellationToken);
else if (delta == 1)
return EvaluateScript("window.history.forward();", null, true, cancellationToken);
else
return null;
//else throw new ArgumentOutOfRangeException(nameof(delta));
}
public async Task DispatchKeyEvents(string keys, CancellationToken cancellationToken = default (CancellationToken))
{
if (_asyncChromeDriver != null)
await _asyncChromeDriver.CheckConnected().ConfigureAwait(false);
foreach (var key in keys)
{
//var index = (int)key - 0xE000U; > 0
if (Keys.KeyToVirtualKeyCode.ContainsKey(key))
{
var virtualKeyCode = Keys.KeyToVirtualKeyCode[key];
//if (index == 7 || index == 6)
//{
// await DevTools?.Session.Input.DispatchKeyEvent(new DispatchKeyEventCommand
// {
// Type = "char",
// Text = Convert.ToString("\r", CultureInfo.InvariantCulture)
// });
//}
//else
//{
if (virtualKeyCode == 0)
continue;
var res = await DevTools.Input.DispatchKeyEvent(new DispatchKeyEventCommand{Type = "rawKeyDown", //NativeVirtualKeyCode = virtualKeyCode,
WindowsVirtualKeyCode = virtualKeyCode, }, cancellationToken).ConfigureAwait(false);
await DevTools.Input.DispatchKeyEvent(new DispatchKeyEventCommand{Type = "keyUp", //NativeVirtualKeyCode = virtualKeyCode,
WindowsVirtualKeyCode = virtualKeyCode, }, cancellationToken).ConfigureAwait(false);
//}
}
else
{
await DevTools.Input.DispatchKeyEvent(new DispatchKeyEventCommand{Type = "char", Text = Convert.ToString(key, CultureInfo.InvariantCulture)}, cancellationToken).ConfigureAwait(false);
}
}
}
public async Task<string> GetFrameByFunction(string frame, string function, List<string> args, CancellationToken cancellationToken = default (CancellationToken))
{
long ? contextId = FrameTracker.GetContextIdForFrame(frame);
try
{
var nodeId = await GetNodeIdFromFunction(contextId, function, args, cancellationToken).ConfigureAwait(false);
return await _asyncChromeDriver.DomTracker.GetFrameIdForNode(nodeId).ConfigureAwait(false);
}
catch
{
throw;
}
}
public async Task<int> GetNodeIdFromFunction(long ? contextId, string function, List<string> args, CancellationToken cancellationToken = default (CancellationToken))
{
var argsJson = Newtonsoft.Json.JsonConvert.SerializeObject(args);
var w3 = _asyncChromeDriver.Session.W3CCompliant ? "true" : "false";
var expression = $"({call_function.JsSource}).apply(null, [null, {function}, {argsJson}, {w3}, true])";
try
{
var elementId = await EvaluateScriptAndGetObjectInContext(expression, null /*context_id*/, cancellationToken).ConfigureAwait(false);
//var element_id = await CallFunctionInContextAndGetObject(function, argsJson, context_id, asyncChromeDriver.Session.w3c_compliant, cancellationToken);
long ? nodeId = null;
var nodeResp = await DevTools.DOM.RequestNode(new RequestNodeCommand{ObjectId = elementId}, cancellationToken).ConfigureAwait(false);
nodeId = nodeResp?.NodeId;
if (nodeId == null)
throw new Exception("DOM.requestNode missing int 'nodeId'");
var releaseResp = await DevTools.Runtime.ReleaseObject(new ReleaseObjectCommand{ObjectId = elementId}, cancellationToken).ConfigureAwait(false);
return (int)nodeId;
}
catch
{
throw;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace StigSchmidtNielsson.Utils {
/// <summary>
/// BCrypt implements OpenBSD-style Blowfish password hashing
/// using the scheme described in "A Future-Adaptable Password Scheme"
/// by Niels Provos and David Mazieres.
/// </summary>
/// <remarks>
/// <para>
/// This password hashing system tries to thwart offline
/// password cracking using a computationally-intensive hashing
/// algorithm, based on Bruce Schneier's Blowfish cipher. The work
/// factor of the algorithm is parameterized, so it can be increased as
/// computers get faster.
/// </para>
/// <para>
/// To hash a password for the first time, call the
/// <c>HashPassword</c> method with a random salt, like this:
/// </para>
/// <code>
/// string hashed = BCrypt.HashPassword(plainPassword, BCrypt.GenerateSalt());
/// </code>
/// <para>
/// To check whether a plaintext password matches one that has
/// been hashed previously, use the <c>CheckPassword</c> method:
/// </para>
/// <code>
/// if (BCrypt.CheckPassword(candidatePassword, storedHash)) {
/// Console.WriteLine("It matches");
/// } else {
/// Console.WriteLine("It does not match");
/// }
/// </code>
/// <para>
/// The <c>GenerateSalt</c> method takes an optional parameter
/// (logRounds) that determines the computational complexity of the
/// hashing:
/// </para>
/// <code>
/// string strongSalt = BCrypt.GenerateSalt(10);
/// string strongerSalt = BCrypt.GenerateSalt(12);
/// </code>
/// <para>
/// The amount of work increases exponentially (2**log_rounds), so
/// each increment is twice as much work. The default log_rounds is
/// 10, and the valid range is 4 to 31.
/// </para>
/// </remarks>
public class BCrypt {
private const int GENSALT_DEFAULT_LOG2_ROUNDS = 10;
private const int BCRYPT_SALT_LEN = 16;
// Blowfish parameters.
private const int BLOWFISH_NUM_ROUNDS = 16;
// Initial contents of key schedule.
private static readonly uint[] p_orig = {
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
0x9216d5d9, 0x8979fb1b
};
private static readonly uint[] s_orig = {
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
};
// bcrypt IV: "OrpheanBeholderScryDoubt".
private static readonly uint[] bf_crypt_ciphertext = {
0x4f727068, 0x65616e42, 0x65686f6c,
0x64657253, 0x63727944, 0x6f756274
};
// Table for Base64 encoding.
private static readonly char[] base64_code = {
'.', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9'
};
// Table for Base64 decoding.
private static readonly int[] index_64 = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 0, 1, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63, -1, -1,
-1, -1, -1, -1, -1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
-1, -1, -1, -1, -1, -1, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51, 52, 53, -1, -1, -1, -1, -1
};
// Expanded Blowfish key.
private uint[] p;
private uint[] s;
/// <summary>
/// Encode a byte array using bcrypt's slightly-modified
/// Base64 encoding scheme. Note that this is _not_ compatible
/// with the standard MIME-Base64 encoding.
/// </summary>
/// <param name="d">The byte array to encode</param>
/// <param name="length">The number of bytes to encode</param>
/// <returns>A Base64-encoded string</returns>
private static string EncodeBase64(byte[] d, int length) {
if (length <= 0 || length > d.Length) throw new ArgumentOutOfRangeException("length", length, null);
var rs = new StringBuilder(length*2);
for (int offset = 0, c1, c2; offset < length;) {
c1 = d[offset++] & 0xff;
rs.Append(base64_code[(c1 >> 2) & 0x3f]);
c1 = (c1 & 0x03) << 4;
if (offset >= length) {
rs.Append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[offset++] & 0xff;
c1 |= (c2 >> 4) & 0x0f;
rs.Append(base64_code[c1 & 0x3f]);
c1 = (c2 & 0x0f) << 2;
if (offset >= length) {
rs.Append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[offset++] & 0xff;
c1 |= (c2 >> 6) & 0x03;
rs.Append(base64_code[c1 & 0x3f]);
rs.Append(base64_code[c2 & 0x3f]);
}
return rs.ToString();
}
/// <summary>
/// Look up the 3 bits base64-encoded by the specified
/// character, range-checking against the conversion
/// table.
/// </summary>
/// <param name="c">The Base64-encoded value</param>
/// <returns>
/// The decoded value of <c>x</c>
/// </returns>
private static int Char64(char c) {
int i = c;
return (i < 0 || i > index_64.Length) ? -1 : index_64[i];
}
/// <summary>
/// Decode a string encoded using BCrypt's Base64 scheme to a
/// byte array. Note that this is _not_ compatible with the standard
/// MIME-Base64 encoding.
/// </summary>
/// <param name="s">The string to decode</param>
/// <param name="maximumLength">The maximum number of bytes to decode</param>
/// <returns>An array containing the decoded bytes</returns>
private static byte[] DecodeBase64(string s, int maximumLength) {
var bytes = new List<byte>(Math.Min(maximumLength, s.Length));
if (maximumLength <= 0) throw new ArgumentOutOfRangeException("maximumLength", maximumLength, null);
for (int offset = 0, slen = s.Length, length = 0; offset < slen - 1 && length < maximumLength;) {
var c1 = Char64(s[offset++]);
var c2 = Char64(s[offset++]);
if (c1 == -1 || c2 == -1) break;
bytes.Add((byte) ((c1 << 2) | ((c2 & 0x30) >> 4)));
if (++length >= maximumLength || offset >= s.Length) break;
var c3 = Char64(s[offset++]);
if (c3 == -1) break;
bytes.Add((byte) (((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2)));
if (++length >= maximumLength || offset >= s.Length) break;
var c4 = Char64(s[offset++]);
bytes.Add((byte) (((c3 & 0x03) << 6) | c4));
++length;
}
return bytes.ToArray();
}
/// <summary>
/// Blowfish encipher a single 64-bit block encoded as two 32-bit
/// halves.
/// </summary>
/// <param name="block">
/// An array containing the two 32-bit half
/// blocks.
/// </param>
/// <param name="offset">
/// The position in the array of the
/// blocks.
/// </param>
private void Encipher(uint[] block, int offset) {
uint i, n, l = block[offset], r = block[offset + 1];
l ^= p[0];
for (i = 0; i <= BLOWFISH_NUM_ROUNDS - 2;) {
// Feistel substitution on left word
n = s[(l >> 24) & 0xff];
n += s[0x100 | ((l >> 16) & 0xff)];
n ^= s[0x200 | ((l >> 8) & 0xff)];
n += s[0x300 | (l & 0xff)];
r ^= n ^ p[++i];
// Feistel substitution on right word
n = s[(r >> 24) & 0xff];
n += s[0x100 | ((r >> 16) & 0xff)];
n ^= s[0x200 | ((r >> 8) & 0xff)];
n += s[0x300 | (r & 0xff)];
l ^= n ^ p[++i];
}
block[offset] = r ^ p[BLOWFISH_NUM_ROUNDS + 1];
block[offset + 1] = l;
}
/// <summary>
/// Cycically extract a word of key material.
/// </summary>
/// <param name="data">
/// The string to extract the data
/// from.
/// </param>
/// <param name="offset">The current offset into data.</param>
/// <returns>The next work of material from data.</returns>
private static uint StreamToWord(byte[] data, ref int offset) {
uint word = 0;
for (var i = 0; i < 4; i++) {
word = (word << 8) | data[offset];
offset = (offset + 1)%data.Length;
}
return word;
}
/// <summary>
/// Initialize the Blowfish key schedule.
/// </summary>
private void InitKey() {
p = new uint[p_orig.Length];
p_orig.CopyTo(p, 0);
s = new uint[s_orig.Length];
s_orig.CopyTo(s, 0);
}
/// <summary>
/// Key the Blowfish cipher.
/// </summary>
/// <param name="key">An array containing the key.</param>
private void Key(byte[] key) {
uint[] lr = {0, 0};
int plen = p.Length, slen = s.Length;
var offset = 0;
for (var i = 0; i < plen; i++) {
p[i] = p[i] ^ StreamToWord(key, ref offset);
}
for (var i = 0; i < plen; i += 2) {
Encipher(lr, 0);
p[i] = lr[0];
p[i + 1] = lr[1];
}
for (var i = 0; i < slen; i += 2) {
Encipher(lr, 0);
s[i] = lr[0];
s[i + 1] = lr[1];
}
}
/// <summary>
/// Perform the "enhanced key schedule" step described by Provos
/// and Mazieres in "A Future-Adaptable Password Scheme"
/// (http://www.openbsd.org/papers/bcrypt-paper.ps).
/// </summary>
/// <param name="data">Salt information.</param>
/// <param name="key">Password information.</param>
private void EksKey(byte[] data, byte[] key) {
uint[] lr = {0, 0};
int plen = p.Length, slen = s.Length;
var keyOffset = 0;
for (var i = 0; i < plen; i++) {
p[i] = p[i] ^ StreamToWord(key, ref keyOffset);
}
var dataOffset = 0;
for (var i = 0; i < plen; i += 2) {
lr[0] ^= StreamToWord(data, ref dataOffset);
lr[1] ^= StreamToWord(data, ref dataOffset);
Encipher(lr, 0);
p[i] = lr[0];
p[i + 1] = lr[1];
}
for (var i = 0; i < slen; i += 2) {
lr[0] ^= StreamToWord(data, ref dataOffset);
lr[1] ^= StreamToWord(data, ref dataOffset);
Encipher(lr, 0);
s[i] = lr[0];
s[i + 1] = lr[1];
}
}
/// <summary>
/// Perform the central password hashing step in the bcrypt
/// scheme.
/// </summary>
/// <param name="password">The password to hash.</param>
/// <param name="salt">
/// The binary salt to hash with the
/// password.
/// </param>
/// <param name="logRounds">
/// The binary logarithm of the number of
/// rounds of hashing to apply.
/// </param>
/// <returns>An array containing the binary hashed password.</returns>
private byte[] CryptRaw(byte[] password, byte[] salt, int logRounds) {
var cdata = new uint[bf_crypt_ciphertext.Length];
bf_crypt_ciphertext.CopyTo(cdata, 0);
var clen = cdata.Length;
byte[] ret;
if (logRounds < 4 || logRounds > 31) throw new ArgumentOutOfRangeException("logRounds", logRounds, null);
var rounds = 1 << logRounds;
if (salt.Length != BCRYPT_SALT_LEN) throw new ArgumentException("Invalid salt length.", "salt");
InitKey();
EksKey(salt, password);
for (var i = 0; i < rounds; i++) {
Key(password);
Key(salt);
}
for (var i = 0; i < 64; i++) {
for (var j = 0; j < (clen >> 1); j++) {
Encipher(cdata, j << 1);
}
}
ret = new byte[clen*4];
for (int i = 0, j = 0; i < clen; i++) {
ret[j++] = (byte) ((cdata[i] >> 24) & 0xff);
ret[j++] = (byte) ((cdata[i] >> 16) & 0xff);
ret[j++] = (byte) ((cdata[i] >> 8) & 0xff);
ret[j++] = (byte) (cdata[i] & 0xff);
}
return ret;
}
/// <summary>
/// Hash a password using the OpenBSD bcrypt scheme.
/// </summary>
/// <param name="password">The password to hash.</param>
/// <param name="salt">
/// The salt to hash with (perhaps generated
/// using <c>BCrypt.GenerateSalt</c>).
/// </param>
/// <returns>The hashed password.</returns>
public static string HashPassword(string password, string salt) {
if (password == null) throw new ArgumentNullException("password");
if (salt == null) throw new ArgumentNullException("salt");
var minor = (char) 0;
if (salt[0] != '$' || salt[1] != '2') throw new ArgumentException("Invalid salt version");
int offset;
if (salt[2] == '$') offset = 3;
else {
minor = salt[2];
if (minor != 'a' || salt[3] != '$') throw new ArgumentException("Invalid salt revision");
offset = 4;
}
// Extract number of rounds
if (salt[offset + 2] > '$') throw new ArgumentException("Missing salt rounds");
var rounds = Int32.Parse(salt.Substring(offset, 2), NumberFormatInfo.InvariantInfo);
var passwordBytes = Encoding.UTF8.GetBytes(password + (minor >= 'a' ? "\0" : String.Empty));
var saltBytes = DecodeBase64(salt.Substring(offset + 3, 22),
BCRYPT_SALT_LEN);
var bcrypt = new BCrypt();
var hashed = bcrypt.CryptRaw(passwordBytes, saltBytes, rounds);
var rs = new StringBuilder();
rs.Append("$2");
if (minor >= 'a') rs.Append(minor);
rs.Append('$');
if (rounds < 10) rs.Append('0');
rs.Append(rounds);
rs.Append('$');
rs.Append(EncodeBase64(saltBytes, saltBytes.Length));
rs.Append(EncodeBase64(hashed,
(bf_crypt_ciphertext.Length*4) - 1));
return rs.ToString();
}
/// <summary>
/// Generate a salt for use with the BCrypt.HashPassword() method.
/// </summary>
/// <param name="logRounds">
/// The log2 of the number of rounds of
/// hashing to apply. The work factor therefore increases as (2 **
/// logRounds).
/// </param>
/// <param name="random">An instance of RandomNumberGenerator to use.</param>
/// <returns>An encoded salt value.</returns>
public static string GenerateSalt(int logRounds, RandomNumberGenerator random) {
var randomBytes = new byte[BCRYPT_SALT_LEN];
random.GetBytes(randomBytes);
var rs = new StringBuilder((randomBytes.Length*2) + 8);
rs.Append("$2a$");
if (logRounds < 10) rs.Append('0');
rs.Append(logRounds);
rs.Append('$');
rs.Append(EncodeBase64(randomBytes, randomBytes.Length));
return rs.ToString();
}
/// <summary>
/// Generate a salt for use with the <c>BCrypt.HashPassword()</c> method.
/// </summary>
/// <param name="logRounds">
/// The log2 of the number of rounds of
/// hashing to apply. The work factor therefore increases as (2 **
/// logRounds).
/// </param>
/// <returns>An encoded salt value.</returns>
public static string GenerateSalt(int logRounds) {
return GenerateSalt(logRounds, RandomNumberGenerator.Create());
}
/// <summary>
/// Generate a salt for use with the <c>BCrypt.HashPassword()</c>
/// method, selecting a reasonable default for the number of hashing
/// rounds to apply.
/// </summary>
/// <returns>An encoded salt value.</returns>
public static string GenerateSalt() {
return GenerateSalt(GENSALT_DEFAULT_LOG2_ROUNDS);
}
/// <summary>
/// Check that a plaintext password matches a previously hashed
/// one.
/// </summary>
/// <param name="plaintext">The plaintext password to verify.</param>
/// <param name="hashed">The previously hashed password.</param>
/// <returns>
/// <c>true</c> if the passwords, <c>false</c>
/// otherwise.
/// </returns>
public static bool CheckPassword(string plaintext, string hashed) {
return StringComparer.Ordinal.Compare(hashed, HashPassword(plaintext, hashed)) == 0;
}
}
}
| |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace Fluent
{
using Fluent.Internal;
/// <summary>
/// Represent panel with ribbon group.
/// It is automatically adjusting size of controls
/// </summary>
public class RibbonGroupsContainer : Panel, IScrollInfo
{
#region Reduce Order
/// <summary>
/// Gets or sets reduce order of group in the ribbon panel.
/// It must be enumerated with comma from the first to reduce to
/// the last to reduce (use Control.Name as group name in the enum).
/// Enclose in parentheses as (Control.Name) to reduce/enlarge
/// scalable elements in the given group
/// </summary>
public string ReduceOrder
{
get { return (string)this.GetValue(ReduceOrderProperty); }
set { this.SetValue(ReduceOrderProperty, value); }
}
/// <summary>
/// Using a DependencyProperty as the backing store for ReduceOrder.
/// This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty ReduceOrderProperty =
DependencyProperty.Register("ReduceOrder", typeof(string), typeof(RibbonGroupsContainer), new UIPropertyMetadata(ReduceOrderPropertyChanged));
// handles ReduseOrder property changed
static void ReduceOrderPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
RibbonGroupsContainer ribbonPanel = (RibbonGroupsContainer)d;
ribbonPanel.reduceOrder = ((string)e.NewValue).Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
ribbonPanel.reduceOrderIndex = ribbonPanel.reduceOrder.Length - 1;
ribbonPanel.InvalidateMeasure();
ribbonPanel.InvalidateArrange();
}
#endregion
#region Fields
private string[] reduceOrder = new string[0];
private int reduceOrderIndex;
#endregion
#region Initialization
/// <summary>
/// Default constructor
/// </summary>
public RibbonGroupsContainer()
: base()
{
this.Focusable = false;
}
#endregion
#region Layout Overridings
/// <summary>
/// Returns a collection of the panel's UIElements.
/// </summary>
/// <param name="logicalParent">The logical parent of the collection to be created.</param>
/// <returns>Returns an ordered collection of elements that have the specified logical parent.</returns>
protected override UIElementCollection CreateUIElementCollection(FrameworkElement logicalParent)
{
return new UIElementCollection(this, /*Parent as FrameworkElement*/this);
}
/// <summary>
/// Measures all of the RibbonGroupBox, and resize them appropriately
/// to fit within the available room
/// </summary>
/// <param name="availableSize">The available size that this element can give to child elements.</param>
/// <returns>The size that the groups container determines it needs during
/// layout, based on its calculations of child element sizes.
/// </returns>
protected override Size MeasureOverride(Size availableSize)
{
var desiredSize = this.GetChildrenDesiredSizeIntermediate();
if (this.reduceOrder.Length == 0)
{
this.VerifyScrollData(availableSize.Width, desiredSize.Width);
return desiredSize;
}
// If we have more available space - try to expand groups
while (desiredSize.Width <= availableSize.Width)
{
var hasMoreVariants = this.reduceOrderIndex < this.reduceOrder.Length - 1;
if (!hasMoreVariants)
{
break;
}
// Increase size of another item
this.reduceOrderIndex++;
this.IncreaseGroupBoxSize(this.reduceOrder[this.reduceOrderIndex]);
desiredSize = this.GetChildrenDesiredSizeIntermediate();
}
// If not enough space - go to next variant
while (desiredSize.Width > availableSize.Width)
{
var hasMoreVariants = this.reduceOrderIndex >= 0;
if (!hasMoreVariants)
{
break;
}
// Decrease size of another item
this.DecreaseGroupBoxSize(this.reduceOrder[this.reduceOrderIndex]);
this.reduceOrderIndex--;
desiredSize = this.GetChildrenDesiredSizeIntermediate();
}
// Set find values
foreach (var item in this.InternalChildren)
{
var groupBox = item as RibbonGroupBox;
if (groupBox == null)
{
continue;
}
if ((groupBox.State != groupBox.StateIntermediate) ||
(groupBox.Scale != groupBox.ScaleIntermediate))
{
groupBox.SuppressCacheReseting = true;
groupBox.State = groupBox.StateIntermediate;
groupBox.Scale = groupBox.ScaleIntermediate;
groupBox.InvalidateLayout();
groupBox.Measure(new Size(double.PositiveInfinity, availableSize.Height));
groupBox.SuppressCacheReseting = false;
}
// Something wrong with cache?
if (groupBox.DesiredSizeIntermediate != groupBox.DesiredSize)
{
// Reset cache and reinvoke masure
groupBox.ClearCache();
return this.MeasureOverride(availableSize);
}
}
this.VerifyScrollData(availableSize.Width, desiredSize.Width);
return desiredSize;
}
private Size GetChildrenDesiredSizeIntermediate()
{
double width = 0;
double height = 0;
foreach (UIElement child in this.InternalChildren)
{
var groupBox = child as RibbonGroupBox;
if (groupBox == null)
{
continue;
}
var desiredSize = groupBox.DesiredSizeIntermediate;
width += desiredSize.Width;
height = Math.Max(height, desiredSize.Height);
}
return new Size(width, height);
}
// Increase size of the item
private void IncreaseGroupBoxSize(string name)
{
var groupBox = this.FindGroup(name);
var scale = name.StartsWith("(", StringComparison.OrdinalIgnoreCase);
if (groupBox == null)
{
return;
}
if (scale)
{
groupBox.ScaleIntermediate++;
}
else
{
groupBox.StateIntermediate = groupBox.StateIntermediate != RibbonGroupBoxState.Large
? groupBox.StateIntermediate - 1
: RibbonGroupBoxState.Large;
}
}
// Decrease size of the item
private void DecreaseGroupBoxSize(string name)
{
var groupBox = this.FindGroup(name);
var scale = name.StartsWith("(", StringComparison.OrdinalIgnoreCase);
if (groupBox == null)
{
return;
}
if (scale)
{
groupBox.ScaleIntermediate--;
}
else
{
groupBox.StateIntermediate = groupBox.StateIntermediate != RibbonGroupBoxState.Collapsed
? groupBox.StateIntermediate + 1
: groupBox.StateIntermediate;
}
}
private RibbonGroupBox FindGroup(string name)
{
if (name.StartsWith("(", StringComparison.OrdinalIgnoreCase))
{
name = name.Substring(1, name.Length - 2);
}
foreach (FrameworkElement child in this.InternalChildren)
{
if (child.Name == name)
{
return child as RibbonGroupBox;
}
}
return null;
}
/// <summary>
/// When overridden in a derived class, positions child elements and determines
/// a size for a System.Windows.FrameworkElement derived class.
/// </summary>
/// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
/// <returns>The actual size used.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
var finalRect = new Rect(finalSize)
{
X = -this.HorizontalOffset
};
foreach (UIElement item in this.InternalChildren)
{
finalRect.Width = item.DesiredSize.Width;
finalRect.Height = Math.Max(finalSize.Height, item.DesiredSize.Height);
item.Arrange(finalRect);
finalRect.X += item.DesiredSize.Width;
}
return finalSize;
}
#endregion
#region IScrollInfo Members
/// <summary>
/// Gets or sets a System.Windows.Controls.ScrollViewer element that controls scrolling behavior.
/// </summary>
public ScrollViewer ScrollOwner
{
get { return this.ScrollData.ScrollOwner; }
set { this.ScrollData.ScrollOwner = value; }
}
/// <summary>
/// Sets the amount of horizontal offset.
/// </summary>
/// <param name="offset">The degree to which content is horizontally offset from the containing viewport.</param>
public void SetHorizontalOffset(double offset)
{
var newValue = CoerceOffset(ValidateInputOffset(offset, "HorizontalOffset"), this.scrollData.ExtentWidth, this.scrollData.ViewportWidth);
if (DoubleUtil.AreClose(this.ScrollData.OffsetX, newValue) == false)
{
this.scrollData.OffsetX = newValue;
this.InvalidateArrange();
}
}
/// <summary>
/// Gets the horizontal size of the extent.
/// </summary>
public double ExtentWidth
{
get { return this.ScrollData.ExtentWidth; }
}
/// <summary>
/// Gets the horizontal offset of the scrolled content.
/// </summary>
public double HorizontalOffset
{
get { return this.ScrollData.OffsetX; }
}
/// <summary>
/// Gets the horizontal size of the viewport for this content.
/// </summary>
public double ViewportWidth
{
get { return this.ScrollData.ViewportWidth; }
}
/// <summary>
/// Scrolls left within content by one logical unit.
/// </summary>
public void LineLeft()
{
this.SetHorizontalOffset(this.HorizontalOffset - 16.0);
}
/// <summary>
/// Scrolls right within content by one logical unit.
/// </summary>
public void LineRight()
{
this.SetHorizontalOffset(this.HorizontalOffset + 16.0);
}
/// <summary>
/// Forces content to scroll until the coordinate space of a System.Windows.Media.Visual object is visible.
/// This is optimized for horizontal scrolling only
/// </summary>
/// <param name="visual">A System.Windows.Media.Visual that becomes visible.</param>
/// <param name="rectangle">A bounding rectangle that identifies the coordinate space to make visible.</param>
/// <returns>A System.Windows.Rect that is visible.</returns>
public Rect MakeVisible(Visual visual, Rect rectangle)
{
// We can only work on visuals that are us or children.
// An empty rect has no size or position. We can't meaningfully use it.
if (rectangle.IsEmpty
|| visual == null
|| ReferenceEquals(visual, this)
|| !this.IsAncestorOf(visual))
{
return Rect.Empty;
}
// Compute the child's rect relative to (0,0) in our coordinate space.
GeneralTransform childTransform = visual.TransformToAncestor(this);
rectangle = childTransform.TransformBounds(rectangle);
// Initialize the viewport
Rect viewport = new Rect(this.HorizontalOffset, rectangle.Top, this.ViewportWidth, rectangle.Height);
rectangle.X += viewport.X;
// Compute the offsets required to minimally scroll the child maximally into view.
double minX = ComputeScrollOffsetWithMinimalScroll(viewport.Left, viewport.Right, rectangle.Left, rectangle.Right);
// We have computed the scrolling offsets; scroll to them.
this.SetHorizontalOffset(minX);
// Compute the visible rectangle of the child relative to the viewport.
viewport.X = minX;
rectangle.Intersect(viewport);
rectangle.X -= viewport.X;
// Return the rectangle
return rectangle;
}
static double ComputeScrollOffsetWithMinimalScroll(
double topView,
double bottomView,
double topChild,
double bottomChild)
{
// # CHILD POSITION CHILD SIZE SCROLL REMEDY
// 1 Above viewport <= viewport Down Align top edge of child & viewport
// 2 Above viewport > viewport Down Align bottom edge of child & viewport
// 3 Below viewport <= viewport Up Align bottom edge of child & viewport
// 4 Below viewport > viewport Up Align top edge of child & viewport
// 5 Entirely within viewport NA No scroll.
// 6 Spanning viewport NA No scroll.
//
// Note: "Above viewport" = childTop above viewportTop, childBottom above viewportBottom
// "Below viewport" = childTop below viewportTop, childBottom below viewportBottom
// These child thus may overlap with the viewport, but will scroll the same direction
/*bool fAbove = DoubleUtil.LessThan(topChild, topView) && DoubleUtil.LessThan(bottomChild, bottomView);
bool fBelow = DoubleUtil.GreaterThan(bottomChild, bottomView) && DoubleUtil.GreaterThan(topChild, topView);*/
bool fAbove = (topChild < topView) && (bottomChild < bottomView);
bool fBelow = (bottomChild > bottomView) && (topChild > topView);
bool fLarger = (bottomChild - topChild) > (bottomView - topView);
// Handle Cases: 1 & 4 above
if ((fAbove && !fLarger)
|| (fBelow && fLarger))
{
return topChild;
}
// Handle Cases: 2 & 3 above
if (fAbove || fBelow)
{
return bottomChild - (bottomView - topView);
}
// Handle cases: 5 & 6 above.
return topView;
}
/// <summary>
/// Not implemented
/// </summary>
public void MouseWheelDown()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void MouseWheelLeft()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void MouseWheelRight()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void MouseWheelUp()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void LineDown()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void LineUp()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void PageDown()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void PageLeft()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void PageRight()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void PageUp()
{
}
/// <summary>
/// Not implemented
/// </summary>
/// <param name="offset"></param>
public void SetVerticalOffset(double offset)
{
}
/// <summary>
/// Gets or sets a value that indicates whether scrolling on the vertical axis is possible.
/// </summary>
public bool CanVerticallyScroll
{
get { return false; }
set { }
}
/// <summary>
/// Gets or sets a value that indicates whether scrolling on the horizontal axis is possible.
/// </summary>
public bool CanHorizontallyScroll
{
get { return true; }
set { }
}
/// <summary>
/// Not implemented
/// </summary>
public double ExtentHeight
{
get { return 0.0; }
}/// <summary>
/// Not implemented
/// </summary>
public double VerticalOffset
{
get { return 0.0; }
}
/// <summary>
/// Not implemented
/// </summary>
public double ViewportHeight
{
get { return 0.0; }
}
// Gets scroll data info
private ScrollData ScrollData
{
get
{
return this.scrollData ?? (this.scrollData = new ScrollData());
}
}
// Scroll data info
private ScrollData scrollData;
// Validates input offset
static double ValidateInputOffset(double offset, string parameterName)
{
if (double.IsNaN(offset))
{
throw new ArgumentOutOfRangeException(parameterName);
}
return Math.Max(0.0, offset);
}
// Verifies scrolling data using the passed viewport and extent as newly computed values.
// Checks the X/Y offset and coerces them into the range [0, Extent - ViewportSize]
// If extent, viewport, or the newly coerced offsets are different than the existing offset,
// cachces are updated and InvalidateScrollInfo() is called.
private void VerifyScrollData(double viewportWidth, double extentWidth)
{
bool isValid = true;
if (double.IsInfinity(viewportWidth))
{
viewportWidth = extentWidth;
}
double offsetX = CoerceOffset(this.ScrollData.OffsetX, extentWidth, viewportWidth);
isValid &= DoubleUtil.AreClose(viewportWidth, this.ScrollData.ViewportWidth);
isValid &= DoubleUtil.AreClose(extentWidth, this.ScrollData.ExtentWidth);
isValid &= DoubleUtil.AreClose(this.ScrollData.OffsetX, offsetX);
this.ScrollData.ViewportWidth = viewportWidth;
this.ScrollData.ExtentWidth = extentWidth;
this.ScrollData.OffsetX = offsetX;
if (!isValid)
{
if (this.ScrollOwner != null)
{
this.ScrollOwner.InvalidateScrollInfo();
}
}
}
// Returns an offset coerced into the [0, Extent - Viewport] range.
static double CoerceOffset(double offset, double extent, double viewport)
{
if (offset > extent - viewport)
{
offset = extent - viewport;
}
if (offset < 0)
{
offset = 0;
}
return offset;
}
#endregion
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2015 CoreTweet Development Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using CoreTweet.Core;
#if !NET35
using System.Threading;
using System.Threading.Tasks;
#endif
namespace CoreTweet.Streaming
{
/// <summary>
/// Provides the types of the Twitter Streaming API.
/// </summary>
public enum StreamingType
{
/// <summary>
/// The user stream.
/// </summary>
User,
/// <summary>
/// The site stream.
/// </summary>
Site,
/// <summary>
/// The filter stream.
/// </summary>
Filter,
/// <summary>
/// The sample stream.
/// </summary>
Sample,
/// <summary>
/// The firehose stream.
/// </summary>
Firehose
}
/// <summary>
/// Represents the wrapper for the Twitter Streaming API.
/// </summary>
public class StreamingApi : ApiProviderBase
{
/// <summary>
/// Initializes a new instance of the <see cref="StreamingApi"/> class with a specified token.
/// </summary>
/// <param name="tokens"></param>
protected internal StreamingApi(TokensBase tokens) : base(tokens) { }
internal string GetUrl(StreamingType type)
{
var options = Tokens.ConnectionOptions ?? new ConnectionOptions();
string baseUrl;
string apiName;
switch(type)
{
case StreamingType.User:
baseUrl = options.UserStreamUrl;
apiName = "user.json";
break;
case StreamingType.Site:
baseUrl = options.SiteStreamUrl;
apiName = "site.json";
break;
case StreamingType.Filter:
baseUrl = options.StreamUrl;
apiName = "statuses/filter.json";
break;
case StreamingType.Sample:
baseUrl = options.StreamUrl;
apiName = "statuses/sample.json";
break;
case StreamingType.Firehose:
baseUrl = options.StreamUrl;
apiName = "statuses/firehose.json";
break;
default:
throw new ArgumentException("Invalid StreamingType.");
}
return InternalUtils.GetUrl(options, baseUrl, true, apiName);
}
internal static MethodType GetMethodType(StreamingType type)
{
return type == StreamingType.Filter ? MethodType.Post : MethodType.Get;
}
private static IEnumerable<StreamingMessage> EnumerateMessages(Stream stream)
{
using(var reader = new StreamReader(stream))
{
foreach(var s in reader.EnumerateLines())
{
if(!string.IsNullOrEmpty(s))
{
StreamingMessage m;
try
{
m = StreamingMessage.Parse(s);
}
catch(ParsingException ex)
{
m = RawJsonMessage.Create(s, ex);
}
yield return m;
}
}
}
}
#region Obsolete
#if !(PCL || WIN_RT || WP)
/// <summary>
/// Starts the Twitter stream.
/// </summary>
/// <param name="type">Type of streaming.</param>
/// <param name="parameters">The parameters of streaming.</param>
/// <returns>The stream messages.</returns>
[Obsolete]
public IEnumerable<StreamingMessage> StartStream(StreamingType type, StreamingParameters parameters = null)
{
if(parameters == null)
parameters = new StreamingParameters();
return this.AccessStreamingApiImpl(type, parameters.Parameters);
}
#endif
#if !NET35
/// <summary>
/// Starts the Twitter stream asynchronously.
/// </summary>
/// <param name="type">Type of streaming.</param>
/// <param name="parameters">The parameters of streaming.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The stream messages.</returns>
[Obsolete]
public Task<IEnumerable<StreamingMessage>> StartStreamAsync(StreamingType type, StreamingParameters parameters = null, CancellationToken cancellationToken = default(CancellationToken))
{
if(parameters == null)
parameters = new StreamingParameters();
return this.Tokens.SendStreamingRequestAsync(GetMethodType(type), this.GetUrl(type), parameters.Parameters, cancellationToken)
.Done(res => res.GetResponseStreamAsync(), cancellationToken)
.Unwrap()
.Done(stream => EnumerateMessages(stream), cancellationToken);
}
#endif
#endregion
#if !(PCL || WIN_RT || WP)
private IEnumerable<StreamingMessage> AccessStreamingApiImpl(StreamingType type, IEnumerable<KeyValuePair<string, object>> parameters)
{
return EnumerateMessages(
this.Tokens.SendStreamingRequest(GetMethodType(type), this.GetUrl(type), parameters).GetResponseStream()
);
}
private IEnumerable<StreamingMessage> AccessStreamingApi(StreamingType type, Expression<Func<string, object>>[] parameters)
{
return this.AccessStreamingApiImpl(type, InternalUtils.ExpressionsToDictionary(parameters));
}
private IEnumerable<StreamingMessage> AccessStreamingApi(StreamingType type, IDictionary<string, object> parameters)
{
return this.AccessStreamingApiImpl(type, parameters);
}
private IEnumerable<StreamingMessage> AccessStreamingApi(StreamingType type, object parameters)
{
return this.AccessStreamingApiImpl(type, InternalUtils.ResolveObject(parameters));
}
/// <summary>
/// Streams messages for a single user.
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> User(params Expression<Func<string, object>>[] parameters)
{
return this.AccessStreamingApi(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a single user.
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> User(IDictionary<string, object> parameters)
{
return this.AccessStreamingApi(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a single user.
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> User(object parameters)
{
return this.AccessStreamingApi(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a single user.
/// </summary>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <param name="with">Specifies whether to return information for just the authenticating user, or include messages from accounts the user follows.</param>
/// <param name="replies">Specifies whether to return additional @replies.</param>
/// <param name="track">Includes additional Tweets matching the specified keywords. Phrases of keywords are specified by a comma-separated list.</param>
/// <param name="locations">Includes additional Tweets falling within the specified bounding boxes.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> User(bool? stall_warnings = null, string with = null, string replies = null, string track = null, IEnumerable<double> locations = null)
{
var parameters = new Dictionary<string, object>();
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
if (with != null) parameters.Add(nameof(with), with);
if (replies != null) parameters.Add(nameof(replies), replies);
if (track != null) parameters.Add(nameof(track), track);
if (locations != null) parameters.Add(nameof(locations), locations);
return this.AccessStreamingApiImpl(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (required)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Site(params Expression<Func<string, object>>[] parameters)
{
return this.AccessStreamingApi(StreamingType.Site, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (required)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Site(IDictionary<string, object> parameters)
{
return this.AccessStreamingApi(StreamingType.Site, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (required)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Site(object parameters)
{
return this.AccessStreamingApi(StreamingType.Site, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// </summary>
/// <param name="follow">A comma separated list of user IDs, indicating the users to return statuses for in the stream.</param>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <param name="with">Specifies whether to return information for just the users specified in the follow parameter, or include messages from accounts they follow.</param>
/// <param name="replies">Specifies whether to return additional @replies.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Site(IEnumerable<long> follow, bool? stall_warnings = null, string with = null, string replies = null)
{
if (follow == null) throw new ArgumentNullException(nameof(follow));
var parameters = new Dictionary<string, object>();
parameters.Add(nameof(follow), follow);
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
if (with != null) parameters.Add(nameof(with), with);
if (replies != null) parameters.Add(nameof(replies), replies);
return this.AccessStreamingApiImpl(StreamingType.Site, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Filter(params Expression<Func<string, object>>[] parameters)
{
return this.AccessStreamingApi(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Filter(IDictionary<string, object> parameters)
{
return this.AccessStreamingApi(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Filter(object parameters)
{
return this.AccessStreamingApi(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// </summary>
/// <param name="follow">A comma separated list of user IDs, indicating the users to return statuses for in the stream.</param>
/// <param name="track">Keywords to track. Phrases of keywords are specified by a comma-separated list.</param>
/// <param name="locations">Specifies a set of bounding boxes to track.</param>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Filter(IEnumerable<long> follow = null, string track = null, IEnumerable<double> locations = null, bool? stall_warnings = null)
{
if (follow == null && track == null && locations == null)
throw new ArgumentException("At least one predicate parameter (follow, locations, or track) must be specified.");
var parameters = new Dictionary<string, object>();
if (follow != null) parameters.Add(nameof(follow), follow);
if (track != null) parameters.Add(nameof(track), track);
if (locations != null) parameters.Add(nameof(locations), locations);
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
return this.AccessStreamingApiImpl(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Sample(params Expression<Func<string, object>>[] parameters)
{
return this.AccessStreamingApi(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Sample(IDictionary<string, object> parameters)
{
return this.AccessStreamingApi(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Sample(object parameters)
{
return this.AccessStreamingApi(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// </summary>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Sample(bool? stall_warnings = null)
{
var parameters = new Dictionary<string, object>();
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
return this.AccessStreamingApiImpl(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// <para>Available parameters:</para>
/// <para>- <c>int</c> count (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Firehose(params Expression<Func<string, object>>[] parameters)
{
return this.AccessStreamingApi(StreamingType.Firehose, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// <para>Available parameters:</para>
/// <para>- <c>int</c> count (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Firehose(IDictionary<string, object> parameters)
{
return this.AccessStreamingApi(StreamingType.Firehose, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// <para>Available parameters:</para>
/// <para>- <c>int</c> count (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Firehose(object parameters)
{
return this.AccessStreamingApi(StreamingType.Firehose, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// </summary>
/// <param name="count">The number of messages to backfill.</param>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Firehose(int? count = null, bool? stall_warnings = null)
{
var parameters = new Dictionary<string, object>();
if (count != null) parameters.Add(nameof(count), count);
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
return this.AccessStreamingApiImpl(StreamingType.Firehose, parameters);
}
#endif
#if !NET35
private IObservable<StreamingMessage> AccessStreamingApiAsObservableImpl(StreamingType type, IEnumerable<KeyValuePair<string, object>> parameters)
{
return new StreamingObservable(this, type, parameters);
}
private IObservable<StreamingMessage> AccessStreamingApiAsObservable(StreamingType type, Expression<Func<string, object>>[] parameters)
{
return AccessStreamingApiAsObservableImpl(type, InternalUtils.ExpressionsToDictionary(parameters));
}
private IObservable<StreamingMessage> AccessStreamingApiAsObservable(StreamingType type, IDictionary<string, object> parameters)
{
return AccessStreamingApiAsObservableImpl(type, parameters);
}
private IObservable<StreamingMessage> AccessStreamingApiAsObservable(StreamingType type, object parameters)
{
return AccessStreamingApiAsObservableImpl(type, InternalUtils.ResolveObject(parameters));
}
/// <summary>
/// Streams messages for a single user.
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> UserAsObservable(params Expression<Func<string, object>>[] parameters)
{
return AccessStreamingApiAsObservable(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a single user.
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> UserAsObservable(IDictionary<string, object> parameters)
{
return AccessStreamingApiAsObservable(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a single user.
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> UserAsObservable(object parameters)
{
return AccessStreamingApiAsObservable(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a single user.
/// </summary>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <param name="with">Specifies whether to return information for just the authenticating user, or include messages from accounts the user follows.</param>
/// <param name="replies">Specifies whether to return additional @replies.</param>
/// <param name="track">Includes additional Tweets matching the specified keywords. Phrases of keywords are specified by a comma-separated list.</param>
/// <param name="locations">Includes additional Tweets falling within the specified bounding boxes.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> UserAsObservable(bool? stall_warnings = null, string with = null, string replies = null, string track = null, IEnumerable<double> locations = null)
{
var parameters = new Dictionary<string, object>();
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
if (with != null) parameters.Add(nameof(with), with);
if (replies != null) parameters.Add(nameof(replies), replies);
if (track != null) parameters.Add(nameof(track), track);
if (locations != null) parameters.Add(nameof(locations), locations);
return AccessStreamingApiAsObservableImpl(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (required)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SiteAsObservable(params Expression<Func<string, object>>[] parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Site, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (required)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SiteAsObservable(IDictionary<string, object> parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Site, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (required)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SiteAsObservable(object parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Site, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// </summary>
/// <param name="follow">A comma separated list of user IDs, indicating the users to return statuses for in the stream.</param>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <param name="with">Specifies whether to return information for just the users specified in the follow parameter, or include messages from accounts they follow.</param>
/// <param name="replies">Specifies whether to return additional @replies.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SiteAsObservable(IEnumerable<long> follow, bool? stall_warnings = null, string with = null, string replies = null)
{
if (follow == null) throw new ArgumentNullException(nameof(follow));
var parameters = new Dictionary<string, object>();
parameters.Add(nameof(follow), follow);
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
if (with != null) parameters.Add(nameof(with), with);
if (replies != null) parameters.Add(nameof(replies), replies);
return AccessStreamingApiAsObservableImpl(StreamingType.Site, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FilterAsObservable(params Expression<Func<string, object>>[] parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FilterAsObservable(IDictionary<string, object> parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FilterAsObservable(object parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// </summary>
/// <param name="follow">A comma separated list of user IDs, indicating the users to return statuses for in the stream.</param>
/// <param name="track">Keywords to track. Phrases of keywords are specified by a comma-separated list.</param>
/// <param name="locations">Specifies a set of bounding boxes to track.</param>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FilterAsObservable(IEnumerable<long> follow = null, string track = null, IEnumerable<double> locations = null, bool? stall_warnings = null)
{
if (follow == null && track == null && locations == null)
throw new ArgumentException("At least one predicate parameter (follow, locations, or track) must be specified.");
var parameters = new Dictionary<string, object>();
if (follow != null) parameters.Add(nameof(follow), follow);
if (track != null) parameters.Add(nameof(track), track);
if (locations != null) parameters.Add(nameof(locations), locations);
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
return AccessStreamingApiAsObservableImpl(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SampleAsObservable(params Expression<Func<string, object>>[] parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SampleAsObservable(IDictionary<string, object> parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SampleAsObservable(object parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// </summary>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SampleAsObservable(bool? stall_warnings = null)
{
var parameters = new Dictionary<string, object>();
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
return AccessStreamingApiAsObservableImpl(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// <para>Available parameters:</para>
/// <para>- <c>int</c> count (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FirehoseAsObservable(params Expression<Func<string, object>>[] parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Firehose, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// <para>Available parameters:</para>
/// <para>- <c>int</c> count (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FirehoseAsObservable(IDictionary<string, object> parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Firehose, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// <para>Available parameters:</para>
/// <para>- <c>int</c> count (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FirehoseAsObservable(object parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Firehose, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// </summary>
/// <param name="count">The number of messages to backfill.</param>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FirehoseAsObservable(int? count = null, bool? stall_warnings = null)
{
var parameters = new Dictionary<string, object>();
if (count != null) parameters.Add(nameof(count), count);
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
return AccessStreamingApiAsObservableImpl(StreamingType.Firehose, parameters);
}
#endif
}
/// <summary>
/// Represents the parameters for the Twitter Streaming API.
/// </summary>
[Obsolete]
public class StreamingParameters
{
/// <summary>
/// Gets the raw parameters.
/// </summary>
public List<KeyValuePair<string, object>> Parameters { get; }
/// <summary>
/// <para>Initializes a new instance of the <see cref="StreamingParameters"/> class with a specified option.</para>
/// <para>Available parameters: </para>
/// <para>*Note: In filter stream, at least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para><c>bool</c> stall_warnings (optional)" : Specifies whether stall warnings should be delivered.</para>
/// <para><c>string / IEnumerable<long></c> follow (optional*, required in site stream, ignored in user stream)</para>
/// <para><c>string / IEnumerable<string></c> track (optional*)</para>
/// <para><c>string / IEnumerable<string></c> location (optional*)</para>
/// <para><c>string</c> with (optional)</para>
/// </summary>
/// <param name="streamingParameters">The streaming parameters.</param>
public StreamingParameters(params Expression<Func<string, object>>[] streamingParameters)
: this(InternalUtils.ExpressionsToDictionary(streamingParameters)) { }
/// <summary>
/// Initializes a new instance of the <see cref="StreamingParameters"/> class with a specified option.
/// </summary>
/// <param name="streamingParameters">The streaming parameters.</param>
public StreamingParameters(IEnumerable<KeyValuePair<string, object>> streamingParameters)
{
Parameters = streamingParameters.ToList();
}
/// <summary>
/// Initializes a new instance of the <see cref="StreamingParameters"/> class with a specified option.
/// </summary>
/// <param name="streamingParameters">The streaming parameters.</param>
public static StreamingParameters Create<T>(T streamingParameters)
{
return new StreamingParameters(InternalUtils.ResolveObject(streamingParameters));
}
}
}
| |
// 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.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class PreDecrementAssignTests : IncDecAssignTests
{
[Theory]
[MemberData("Int16sAndDecrements")]
[MemberData("NullableInt16sAndDecrements")]
[MemberData("UInt16sAndDecrements")]
[MemberData("NullableUInt16sAndDecrements")]
[MemberData("Int32sAndDecrements")]
[MemberData("NullableInt32sAndDecrements")]
[MemberData("UInt32sAndDecrements")]
[MemberData("NullableUInt32sAndDecrements")]
[MemberData("Int64sAndDecrements")]
[MemberData("NullableInt64sAndDecrements")]
[MemberData("UInt64sAndDecrements")]
[MemberData("NullableUInt64sAndDecrements")]
[MemberData("DecimalsAndDecrements")]
[MemberData("NullableDecimalsAndDecrements")]
[MemberData("SinglesAndDecrements")]
[MemberData("NullableSinglesAndDecrements")]
[MemberData("DoublesAndDecrements")]
[MemberData("NullableDoublesAndDecrements")]
public void ReturnsCorrectValues(Type type, object value, object result)
{
ParameterExpression variable = Expression.Variable(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PreDecrementAssign(variable)
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile()());
}
[Theory]
[MemberData("Int16sAndDecrements")]
[MemberData("NullableInt16sAndDecrements")]
[MemberData("UInt16sAndDecrements")]
[MemberData("NullableUInt16sAndDecrements")]
[MemberData("Int32sAndDecrements")]
[MemberData("NullableInt32sAndDecrements")]
[MemberData("UInt32sAndDecrements")]
[MemberData("NullableUInt32sAndDecrements")]
[MemberData("Int64sAndDecrements")]
[MemberData("NullableInt64sAndDecrements")]
[MemberData("UInt64sAndDecrements")]
[MemberData("NullableUInt64sAndDecrements")]
[MemberData("DecimalsAndDecrements")]
[MemberData("NullableDecimalsAndDecrements")]
[MemberData("SinglesAndDecrements")]
[MemberData("NullableSinglesAndDecrements")]
[MemberData("DoublesAndDecrements")]
[MemberData("NullableDoublesAndDecrements")]
public void AssignsCorrectValues(Type type, object value, object result)
{
ParameterExpression variable = Expression.Variable(type);
LabelTarget target = Expression.Label(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PreDecrementAssign(variable),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(type))
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile()());
}
[Fact]
public void SingleNanToNan()
{
TestPropertyClass<float> instance = new TestPropertyClass<float>();
instance.TestInstance = float.NaN;
Assert.True(float.IsNaN(
Expression.Lambda<Func<float>>(
Expression.PreDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<float>),
"TestInstance"
)
)
).Compile()()
));
Assert.True(float.IsNaN(instance.TestInstance));
}
[Fact]
public void DoubleNanToNan()
{
TestPropertyClass<double> instance = new TestPropertyClass<double>();
instance.TestInstance = double.NaN;
Assert.True(double.IsNaN(
Expression.Lambda<Func<double>>(
Expression.PreDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<double>),
"TestInstance"
)
)
).Compile()()
));
Assert.True(double.IsNaN(instance.TestInstance));
}
[Theory]
[MemberData("DecrementOverflowingValues")]
public void OverflowingValuesThrow(object value)
{
ParameterExpression variable = Expression.Variable(value.GetType());
Action overflow = Expression.Lambda<Action>(
Expression.Block(
typeof(void),
new[] { variable },
Expression.Assign(variable, Expression.Constant(value)),
Expression.PreDecrementAssign(variable)
)
).Compile();
Assert.Throws<OverflowException>(overflow);
}
[Theory]
[MemberData("UnincrementableAndUndecrementableTypes")]
public void InvalidOperandType(Type type)
{
ParameterExpression variable = Expression.Variable(type);
Assert.Throws<InvalidOperationException>(() => Expression.PreDecrementAssign(variable));
}
[Fact]
public void MethodCorrectResult()
{
ParameterExpression variable = Expression.Variable(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PreDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile()());
}
[Fact]
public void MethodCorrectAssign()
{
ParameterExpression variable = Expression.Variable(typeof(string));
LabelTarget target = Expression.Label(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PreDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(string)))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile()());
}
[Fact]
public void IncorrectMethodType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod");
Assert.Throws<InvalidOperationException>(() => Expression.PreDecrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodParameterCount()
{
Expression variable = Expression.Variable(typeof(string));
MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals");
Assert.Throws<ArgumentException>(() => Expression.PreDecrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodReturnType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString");
Assert.Throws<ArgumentException>(() => Expression.PreDecrementAssign(variable, method));
}
[Fact]
public void StaticMemberAccessCorrect()
{
TestPropertyClass<int>.TestStatic = 2;
Assert.Equal(
1,
Expression.Lambda<Func<int>>(
Expression.PreDecrementAssign(
Expression.Property(null, typeof(TestPropertyClass<int>), "TestStatic")
)
).Compile()()
);
Assert.Equal(1, TestPropertyClass<int>.TestStatic);
}
[Fact]
public void InstanceMemberAccessCorrect()
{
TestPropertyClass<int> instance = new TestPropertyClass<int>();
instance.TestInstance = 2;
Assert.Equal(
1,
Expression.Lambda<Func<int>>(
Expression.PreDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<int>),
"TestInstance"
)
)
).Compile()()
);
Assert.Equal(1, instance.TestInstance);
}
[Fact]
public void ArrayAccessCorrect()
{
int[] array = new int[1];
array[0] = 2;
Assert.Equal(
1,
Expression.Lambda<Func<int>>(
Expression.PreDecrementAssign(
Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0))
)
).Compile()()
);
Assert.Equal(1, array[0]);
}
[Fact]
public void CanReduce()
{
ParameterExpression variable = Expression.Variable(typeof(int));
UnaryExpression op = Expression.PreDecrementAssign(variable);
Assert.True(op.CanReduce);
Assert.NotSame(op, op.ReduceAndCheck());
}
[Fact]
public void NullOperand()
{
Assert.Throws<ArgumentNullException>("expression", () => Expression.PreDecrementAssign(null));
}
[Fact]
public void UnwritableOperand()
{
Assert.Throws<ArgumentException>("expression", () => Expression.PreDecrementAssign(Expression.Constant(1)));
}
[Fact]
public void UnreadableOperand()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("expression", () => Expression.PreDecrementAssign(value));
}
[Fact]
public void UpdateSameOperandSameNode()
{
UnaryExpression op = Expression.PreDecrementAssign(Expression.Variable(typeof(int)));
Assert.Same(op, op.Update(op.Operand));
}
[Fact]
public void UpdateDiffOperandDiffNode()
{
UnaryExpression op = Expression.PreDecrementAssign(Expression.Variable(typeof(int)));
Assert.NotSame(op, op.Update(Expression.Variable(typeof(int))));
}
}
}
| |
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 JYaas.API.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 UnityEngine;
using System.Collections;
using Windows.Kinect;
using System.Runtime.InteropServices;
using Microsoft.Kinect.Face;
using System.Collections.Generic;
using System;
public class Kinect2Interface : DepthSensorInterface
{
// change this to false, if you aren't using Kinect-v2 only and want KM to check for available sensors
public static bool sensorAlwaysAvailable = true;
private KinectInterop.FrameSource sensorFlags;
public KinectSensor kinectSensor;
public CoordinateMapper coordMapper;
private BodyFrameReader bodyFrameReader;
private BodyIndexFrameReader bodyIndexFrameReader;
private ColorFrameReader colorFrameReader;
private DepthFrameReader depthFrameReader;
private InfraredFrameReader infraredFrameReader;
private MultiSourceFrameReader multiSourceFrameReader;
private MultiSourceFrame multiSourceFrame;
private BodyFrame msBodyFrame = null;
private BodyIndexFrame msBodyIndexFrame = null;
private ColorFrame msColorFrame = null;
private DepthFrame msDepthFrame = null;
private InfraredFrame msInfraredFrame = null;
private int bodyCount;
private Body[] bodyData;
private bool bFaceTrackingInited = false;
public FaceFrameSource[] faceFrameSources = null;
public FaceFrameReader[] faceFrameReaders = null;
public FaceFrameResult[] faceFrameResults = null;
// private int faceDisplayWidth;
// private int faceDisplayHeight;
private bool isDrawFaceRect = false;
public HighDefinitionFaceFrameSource[] hdFaceFrameSources = null;
public HighDefinitionFaceFrameReader[] hdFaceFrameReaders = null;
public FaceAlignment[] hdFaceAlignments = null;
public FaceModel[] hdFaceModels = null;
private bool bBackgroundRemovalInited = false;
// DLL Imports for speech wrapper functions
[DllImport("Kinect2SpeechWrapper", EntryPoint = "InitSpeechRecognizer")]
private static extern int InitSpeechRecognizerNative([MarshalAs(UnmanagedType.LPWStr)]string sRecoCriteria, bool bUseKinect, bool bAdaptationOff);
[DllImport("Kinect2SpeechWrapper", EntryPoint = "FinishSpeechRecognizer")]
private static extern void FinishSpeechRecognizerNative();
[DllImport("Kinect2SpeechWrapper", EntryPoint = "UpdateSpeechRecognizer")]
private static extern int UpdateSpeechRecognizerNative();
[DllImport("Kinect2SpeechWrapper", EntryPoint = "LoadSpeechGrammar")]
private static extern int LoadSpeechGrammarNative([MarshalAs(UnmanagedType.LPWStr)]string sFileName, short iNewLangCode, bool bDynamic);
[DllImport("Kinect2SpeechWrapper", EntryPoint = "AddGrammarPhrase")]
private static extern int AddGrammarPhraseNative([MarshalAs(UnmanagedType.LPWStr)]string sFromRule, [MarshalAs(UnmanagedType.LPWStr)]string sToRule, [MarshalAs(UnmanagedType.LPWStr)]string sPhrase, bool bClearRule, bool bCommitGrammar);
[DllImport("Kinect2SpeechWrapper", EntryPoint = "SetRequiredConfidence")]
private static extern void SetSpeechConfidenceNative(float fConfidence);
[DllImport("Kinect2SpeechWrapper", EntryPoint = "IsSoundStarted")]
private static extern bool IsSpeechStartedNative();
[DllImport("Kinect2SpeechWrapper", EntryPoint = "IsSoundEnded")]
private static extern bool IsSpeechEndedNative();
[DllImport("Kinect2SpeechWrapper", EntryPoint = "IsPhraseRecognized")]
private static extern bool IsPhraseRecognizedNative();
[DllImport("Kinect2SpeechWrapper", EntryPoint = "GetPhraseConfidence")]
private static extern float GetPhraseConfidenceNative();
[DllImport("Kinect2SpeechWrapper", EntryPoint = "GetRecognizedTag")]
private static extern IntPtr GetRecognizedPhraseTagNative();
[DllImport("Kinect2SpeechWrapper", EntryPoint = "ClearPhraseRecognized")]
private static extern void ClearRecognizedPhraseNative();
public KinectInterop.DepthSensorPlatform GetSensorPlatform()
{
return KinectInterop.DepthSensorPlatform.KinectSDKv2;
}
public bool InitSensorInterface (bool bCopyLibs, ref bool bNeedRestart)
{
bool bOneCopied = false, bAllCopied = true;
string sTargetPath = KinectInterop.GetTargetDllPath(".", KinectInterop.Is64bitArchitecture()) + "/";
if(!bCopyLibs)
{
// check if the native library is there
string sTargetLib = sTargetPath + "KinectUnityAddin.dll";
bNeedRestart = false;
string sZipFileName = !KinectInterop.Is64bitArchitecture() ? "KinectV2UnityAddin.x86.zip" : "KinectV2UnityAddin.x64.zip";
long iTargetSize = KinectInterop.GetUnzippedEntrySize(sZipFileName, "KinectUnityAddin.dll");
System.IO.FileInfo targetFile = new System.IO.FileInfo(sTargetLib);
return targetFile.Exists && targetFile.Length == iTargetSize;
}
if(!KinectInterop.Is64bitArchitecture())
{
Debug.Log("x32-architecture detected.");
//KinectInterop.CopyResourceFile(sTargetPath + "KinectUnityAddin.dll", "KinectUnityAddin.dll", ref bOneCopied, ref bAllCopied);
Dictionary<string, string> dictFilesToUnzip = new Dictionary<string, string>();
dictFilesToUnzip["KinectUnityAddin.dll"] = sTargetPath + "KinectUnityAddin.dll";
dictFilesToUnzip["Kinect20.Face.dll"] = sTargetPath + "Kinect20.Face.dll";
dictFilesToUnzip["KinectFaceUnityAddin.dll"] = sTargetPath + "KinectFaceUnityAddin.dll";
dictFilesToUnzip["Kinect2SpeechWrapper.dll"] = sTargetPath + "Kinect2SpeechWrapper.dll";
dictFilesToUnzip["Kinect20.VisualGestureBuilder.dll"] = sTargetPath + "Kinect20.VisualGestureBuilder.dll";
dictFilesToUnzip["KinectVisualGestureBuilderUnityAddin.dll"] = sTargetPath + "KinectVisualGestureBuilderUnityAddin.dll";
dictFilesToUnzip["vgbtechs/AdaBoostTech.dll"] = sTargetPath + "vgbtechs/AdaBoostTech.dll";
dictFilesToUnzip["vgbtechs/RFRProgressTech.dll"] = sTargetPath + "vgbtechs/RFRProgressTech.dll";
dictFilesToUnzip["msvcp110.dll"] = sTargetPath + "msvcp110.dll";
dictFilesToUnzip["msvcr110.dll"] = sTargetPath + "msvcr110.dll";
KinectInterop.UnzipResourceFiles(dictFilesToUnzip, "KinectV2UnityAddin.x86.zip", ref bOneCopied, ref bAllCopied);
}
else
{
Debug.Log("x64-architecture detected.");
//KinectInterop.CopyResourceFile(sTargetPath + "KinectUnityAddin.dll", "KinectUnityAddin.dll.x64", ref bOneCopied, ref bAllCopied);
Dictionary<string, string> dictFilesToUnzip = new Dictionary<string, string>();
dictFilesToUnzip["KinectUnityAddin.dll"] = sTargetPath + "KinectUnityAddin.dll";
dictFilesToUnzip["Kinect20.Face.dll"] = sTargetPath + "Kinect20.Face.dll";
dictFilesToUnzip["KinectFaceUnityAddin.dll"] = sTargetPath + "KinectFaceUnityAddin.dll";
dictFilesToUnzip["Kinect2SpeechWrapper.dll"] = sTargetPath + "Kinect2SpeechWrapper.dll";
dictFilesToUnzip["Kinect20.VisualGestureBuilder.dll"] = sTargetPath + "Kinect20.VisualGestureBuilder.dll";
dictFilesToUnzip["KinectVisualGestureBuilderUnityAddin.dll"] = sTargetPath + "KinectVisualGestureBuilderUnityAddin.dll";
dictFilesToUnzip["vgbtechs/AdaBoostTech.dll"] = sTargetPath + "vgbtechs/AdaBoostTech.dll";
dictFilesToUnzip["vgbtechs/RFRProgressTech.dll"] = sTargetPath + "vgbtechs/RFRProgressTech.dll";
dictFilesToUnzip["msvcp110.dll"] = sTargetPath + "msvcp110.dll";
dictFilesToUnzip["msvcr110.dll"] = sTargetPath + "msvcr110.dll";
KinectInterop.UnzipResourceFiles(dictFilesToUnzip, "KinectV2UnityAddin.x64.zip", ref bOneCopied, ref bAllCopied);
}
KinectInterop.UnzipResourceDirectory(sTargetPath, "NuiDatabase.zip", sTargetPath + "NuiDatabase");
bNeedRestart = (bOneCopied && bAllCopied);
return true;
}
public void FreeSensorInterface (bool bDeleteLibs)
{
if(bDeleteLibs)
{
KinectInterop.DeleteNativeLib("KinectUnityAddin.dll", true);
KinectInterop.DeleteNativeLib("msvcp110.dll", false);
KinectInterop.DeleteNativeLib("msvcr110.dll", false);
}
}
public bool IsSensorAvailable()
{
KinectSensor sensor = KinectSensor.GetDefault();
if(sensor != null)
{
if(sensorAlwaysAvailable)
{
sensor = null;
return true;
}
if(!sensor.IsOpen)
{
sensor.Open();
}
float fWaitTime = Time.realtimeSinceStartup + 3f;
while(!sensor.IsAvailable && Time.realtimeSinceStartup < fWaitTime)
{
// wait for availability
}
bool bAvailable = sensor.IsAvailable;
if(sensor.IsOpen)
{
sensor.Close();
}
fWaitTime = Time.realtimeSinceStartup + 3f;
while(sensor.IsOpen && Time.realtimeSinceStartup < fWaitTime)
{
// wait for sensor to close
}
sensor = null;
return bAvailable;
}
return false;
}
public int GetSensorsCount()
{
int numSensors = 0;
KinectSensor sensor = KinectSensor.GetDefault();
if(sensor != null)
{
if(!sensor.IsOpen)
{
sensor.Open();
}
float fWaitTime = Time.realtimeSinceStartup + 3f;
while(!sensor.IsAvailable && Time.realtimeSinceStartup < fWaitTime)
{
// wait for availability
}
numSensors = sensor.IsAvailable ? 1 : 0;
if(sensor.IsOpen)
{
sensor.Close();
}
fWaitTime = Time.realtimeSinceStartup + 3f;
while(sensor.IsOpen && Time.realtimeSinceStartup < fWaitTime)
{
// wait for sensor to close
}
}
return numSensors;
}
public KinectInterop.SensorData OpenDefaultSensor (KinectInterop.FrameSource dwFlags, float sensorAngle, bool bUseMultiSource)
{
KinectInterop.SensorData sensorData = new KinectInterop.SensorData();
sensorFlags = dwFlags;
kinectSensor = KinectSensor.GetDefault();
if(kinectSensor == null)
return null;
coordMapper = kinectSensor.CoordinateMapper;
this.bodyCount = kinectSensor.BodyFrameSource.BodyCount;
sensorData.bodyCount = this.bodyCount;
sensorData.jointCount = 25;
sensorData.depthCameraFOV = 60f;
sensorData.colorCameraFOV = 53.8f;
sensorData.depthCameraOffset = -0.02f;
sensorData.faceOverlayOffset = -0.04f;
if((dwFlags & KinectInterop.FrameSource.TypeBody) != 0)
{
if(!bUseMultiSource)
bodyFrameReader = kinectSensor.BodyFrameSource.OpenReader();
bodyData = new Body[sensorData.bodyCount];
}
var frameDesc = kinectSensor.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Rgba);
sensorData.colorImageWidth = frameDesc.Width;
sensorData.colorImageHeight = frameDesc.Height;
if((dwFlags & KinectInterop.FrameSource.TypeColor) != 0)
{
if(!bUseMultiSource)
colorFrameReader = kinectSensor.ColorFrameSource.OpenReader();
sensorData.colorImage = new byte[frameDesc.BytesPerPixel * frameDesc.LengthInPixels];
}
sensorData.depthImageWidth = kinectSensor.DepthFrameSource.FrameDescription.Width;
sensorData.depthImageHeight = kinectSensor.DepthFrameSource.FrameDescription.Height;
if((dwFlags & KinectInterop.FrameSource.TypeDepth) != 0)
{
if(!bUseMultiSource)
depthFrameReader = kinectSensor.DepthFrameSource.OpenReader();
sensorData.depthImage = new ushort[kinectSensor.DepthFrameSource.FrameDescription.LengthInPixels];
}
if((dwFlags & KinectInterop.FrameSource.TypeBodyIndex) != 0)
{
if(!bUseMultiSource)
bodyIndexFrameReader = kinectSensor.BodyIndexFrameSource.OpenReader();
sensorData.bodyIndexImage = new byte[kinectSensor.BodyIndexFrameSource.FrameDescription.LengthInPixels];
}
if((dwFlags & KinectInterop.FrameSource.TypeInfrared) != 0)
{
if(!bUseMultiSource)
infraredFrameReader = kinectSensor.InfraredFrameSource.OpenReader();
sensorData.infraredImage = new ushort[kinectSensor.InfraredFrameSource.FrameDescription.LengthInPixels];
}
//if(!kinectSensor.IsOpen)
{
//Debug.Log("Opening sensor, available: " + kinectSensor.IsAvailable);
kinectSensor.Open();
}
float fWaitTime = Time.realtimeSinceStartup + 3f;
while(!kinectSensor.IsAvailable && Time.realtimeSinceStartup < fWaitTime)
{
// wait for sensor to open
}
Debug.Log("K2-sensor " + (kinectSensor.IsOpen ? "opened" : "closed") +
", available: " + kinectSensor.IsAvailable);
if(bUseMultiSource && dwFlags != KinectInterop.FrameSource.TypeNone && kinectSensor.IsOpen)
{
multiSourceFrameReader = kinectSensor.OpenMultiSourceFrameReader((FrameSourceTypes)((int)dwFlags & 0x3F));
}
return sensorData;
}
public void CloseSensor (KinectInterop.SensorData sensorData)
{
if(coordMapper != null)
{
coordMapper = null;
}
if(bodyFrameReader != null)
{
bodyFrameReader.Dispose();
bodyFrameReader = null;
}
if(bodyIndexFrameReader != null)
{
bodyIndexFrameReader.Dispose();
bodyIndexFrameReader = null;
}
if(colorFrameReader != null)
{
colorFrameReader.Dispose();
colorFrameReader = null;
}
if(depthFrameReader != null)
{
depthFrameReader.Dispose();
depthFrameReader = null;
}
if(infraredFrameReader != null)
{
infraredFrameReader.Dispose();
infraredFrameReader = null;
}
if(multiSourceFrameReader != null)
{
multiSourceFrameReader.Dispose();
multiSourceFrameReader = null;
}
if(kinectSensor != null)
{
//if (kinectSensor.IsOpen)
{
//Debug.Log("Closing sensor, available: " + kinectSensor.IsAvailable);
kinectSensor.Close();
}
float fWaitTime = Time.realtimeSinceStartup + 3f;
while(kinectSensor.IsOpen && Time.realtimeSinceStartup < fWaitTime)
{
// wait for sensor to close
}
Debug.Log("K2-sensor " + (kinectSensor.IsOpen ? "opened" : "closed") +
", available: " + kinectSensor.IsAvailable);
kinectSensor = null;
}
}
public bool UpdateSensorData (KinectInterop.SensorData sensorData)
{
return true;
}
public bool GetMultiSourceFrame (KinectInterop.SensorData sensorData)
{
if(multiSourceFrameReader != null)
{
multiSourceFrame = multiSourceFrameReader.AcquireLatestFrame();
if(multiSourceFrame != null)
{
// try to get all frames at once
msBodyFrame = (sensorFlags & KinectInterop.FrameSource.TypeBody) != 0 ? multiSourceFrame.BodyFrameReference.AcquireFrame() : null;
msBodyIndexFrame = (sensorFlags & KinectInterop.FrameSource.TypeBodyIndex) != 0 ? multiSourceFrame.BodyIndexFrameReference.AcquireFrame() : null;
msColorFrame = (sensorFlags & KinectInterop.FrameSource.TypeColor) != 0 ? multiSourceFrame.ColorFrameReference.AcquireFrame() : null;
msDepthFrame = (sensorFlags & KinectInterop.FrameSource.TypeDepth) != 0 ? multiSourceFrame.DepthFrameReference.AcquireFrame() : null;
msInfraredFrame = (sensorFlags & KinectInterop.FrameSource.TypeInfrared) != 0 ? multiSourceFrame.InfraredFrameReference.AcquireFrame() : null;
bool bAllSet =
((sensorFlags & KinectInterop.FrameSource.TypeBody) == 0 || msBodyFrame != null) &&
((sensorFlags & KinectInterop.FrameSource.TypeBodyIndex) == 0 || msBodyIndexFrame != null) &&
((sensorFlags & KinectInterop.FrameSource.TypeColor) == 0 || msColorFrame != null) &&
((sensorFlags & KinectInterop.FrameSource.TypeDepth) == 0 || msDepthFrame != null) &&
((sensorFlags & KinectInterop.FrameSource.TypeInfrared) == 0 || msInfraredFrame != null);
if(!bAllSet)
{
// release all frames
if(msBodyFrame != null)
{
msBodyFrame.Dispose();
msBodyFrame = null;
}
if(msBodyIndexFrame != null)
{
msBodyIndexFrame.Dispose();
msBodyIndexFrame = null;
}
if(msColorFrame != null)
{
msColorFrame.Dispose();
msColorFrame = null;
}
if(msDepthFrame != null)
{
msDepthFrame.Dispose();
msDepthFrame = null;
}
if(msInfraredFrame != null)
{
msInfraredFrame.Dispose();
msInfraredFrame = null;
}
}
// else
// {
// bool bNeedBody = (sensorFlags & KinectInterop.FrameSource.TypeBody) != 0;
// bool bNeedBodyIndex = (sensorFlags & KinectInterop.FrameSource.TypeBodyIndex) != 0;
// bool bNeedColor = (sensorFlags & KinectInterop.FrameSource.TypeColor) != 0;
// bool bNeedDepth = (sensorFlags & KinectInterop.FrameSource.TypeDepth) != 0;
// bool bNeedInfrared = (sensorFlags & KinectInterop.FrameSource.TypeInfrared) != 0;
//
// bAllSet = true;
// }
}
return (multiSourceFrame != null);
}
return false;
}
public void FreeMultiSourceFrame (KinectInterop.SensorData sensorData)
{
// release all frames
if(msBodyFrame != null)
{
msBodyFrame.Dispose();
msBodyFrame = null;
}
if(msBodyIndexFrame != null)
{
msBodyIndexFrame.Dispose();
msBodyIndexFrame = null;
}
if(msColorFrame != null)
{
msColorFrame.Dispose();
msColorFrame = null;
}
if(msDepthFrame != null)
{
msDepthFrame.Dispose();
msDepthFrame = null;
}
if(msInfraredFrame != null)
{
msInfraredFrame.Dispose();
msInfraredFrame = null;
}
if(multiSourceFrame != null)
{
multiSourceFrame = null;
}
}
public bool PollBodyFrame (KinectInterop.SensorData sensorData, ref KinectInterop.BodyFrameData bodyFrame, ref Matrix4x4 kinectToWorld)
{
bool bNewFrame = false;
if((multiSourceFrameReader != null && multiSourceFrame != null) ||
bodyFrameReader != null)
{
BodyFrame frame = multiSourceFrame != null ? msBodyFrame :
bodyFrameReader.AcquireLatestFrame();
if(frame != null)
{
frame.GetAndRefreshBodyData(bodyData);
bodyFrame.liPreviousTime = bodyFrame.liRelativeTime;
bodyFrame.liRelativeTime = frame.RelativeTime.Ticks;
if(sensorData.hintHeightAngle)
{
// get the floor plane
Windows.Kinect.Vector4 vFloorPlane = frame.FloorClipPlane;
Vector3 floorPlane = new Vector3(vFloorPlane.X, vFloorPlane.Y, vFloorPlane.Z);
sensorData.sensorRotDetected = Quaternion.FromToRotation(floorPlane, Vector3.up);
sensorData.sensorHgtDetected = vFloorPlane.W;
}
frame.Dispose();
frame = null;
for(int i = 0; i < sensorData.bodyCount; i++)
{
Body body = bodyData[i];
if (body == null)
{
bodyFrame.bodyData[i].bIsTracked = 0;
continue;
}
bodyFrame.bodyData[i].bIsTracked = (short)(body.IsTracked ? 1 : 0);
if(body.IsTracked)
{
// transfer body and joints data
bodyFrame.bodyData[i].liTrackingID = (long)body.TrackingId;
// cache the body joints (following the advice of Brian Chasalow)
Dictionary<Windows.Kinect.JointType, Windows.Kinect.Joint> bodyJoints = body.Joints;
// calculate the inter-frame time
float frameTime = 0f;
if(bodyFrame.bTurnAnalisys && bodyFrame.liPreviousTime > 0)
{
frameTime = (float)(bodyFrame.liRelativeTime - bodyFrame.liPreviousTime) / 100000000000;
}
for(int j = 0; j < sensorData.jointCount; j++)
{
Windows.Kinect.Joint joint = bodyJoints[(Windows.Kinect.JointType)j];
KinectInterop.JointData jointData = bodyFrame.bodyData[i].joint[j];
//jointData.jointType = (KinectInterop.JointType)j;
jointData.trackingState = (KinectInterop.TrackingState)joint.TrackingState;
if((int)joint.TrackingState != (int)TrackingState.NotTracked)
{
jointData.kinectPos = new Vector3(joint.Position.X, joint.Position.Y, joint.Position.Z);
jointData.position = kinectToWorld.MultiplyPoint3x4(jointData.kinectPos);
}
jointData.orientation = Quaternion.identity;
// Windows.Kinect.Vector4 vQ = body.JointOrientations[jointData.jointType].Orientation;
// jointData.orientation = new Quaternion(vQ.X, vQ.Y, vQ.Z, vQ.W);
if(j == 0)
{
bodyFrame.bodyData[i].position = jointData.position;
bodyFrame.bodyData[i].orientation = jointData.orientation;
}
bodyFrame.bodyData[i].joint[j] = jointData;
}
if(bodyFrame.bTurnAnalisys && bodyFrame.liPreviousTime > 0)
{
for(int j = 0; j < sensorData.jointCount; j++)
{
KinectInterop.JointData jointData = bodyFrame.bodyData[i].joint[j];
int p = (int)GetParentJoint((KinectInterop.JointType)j);
Vector3 parentPos = bodyFrame.bodyData[i].joint[p].position;
jointData.posRel = jointData.position - parentPos;
jointData.posDrv = frameTime > 0f ? (jointData.position - jointData.posPrev) / frameTime : Vector3.zero;
jointData.posPrev = jointData.position;
bodyFrame.bodyData[i].joint[j] = jointData;
}
}
// tranfer hand states
bodyFrame.bodyData[i].leftHandState = (KinectInterop.HandState)body.HandLeftState;
bodyFrame.bodyData[i].leftHandConfidence = (KinectInterop.TrackingConfidence)body.HandLeftConfidence;
bodyFrame.bodyData[i].rightHandState = (KinectInterop.HandState)body.HandRightState;
bodyFrame.bodyData[i].rightHandConfidence = (KinectInterop.TrackingConfidence)body.HandRightConfidence;
}
}
bNewFrame = true;
}
}
return bNewFrame;
}
public bool PollColorFrame (KinectInterop.SensorData sensorData)
{
bool bNewFrame = false;
if((multiSourceFrameReader != null && multiSourceFrame != null) ||
colorFrameReader != null)
{
ColorFrame colorFrame = multiSourceFrame != null ? msColorFrame :
colorFrameReader.AcquireLatestFrame();
if(colorFrame != null)
{
var pColorData = GCHandle.Alloc(sensorData.colorImage, GCHandleType.Pinned);
colorFrame.CopyConvertedFrameDataToIntPtr(pColorData.AddrOfPinnedObject(), (uint)sensorData.colorImage.Length, ColorImageFormat.Rgba);
pColorData.Free();
sensorData.lastColorFrameTime = colorFrame.RelativeTime.Ticks;
colorFrame.Dispose();
colorFrame = null;
bNewFrame = true;
}
}
return bNewFrame;
}
public bool PollDepthFrame (KinectInterop.SensorData sensorData)
{
bool bNewFrame = false;
if((multiSourceFrameReader != null && multiSourceFrame != null) ||
depthFrameReader != null)
{
DepthFrame depthFrame = multiSourceFrame != null ? msDepthFrame :
depthFrameReader.AcquireLatestFrame();
if(depthFrame != null)
{
var pDepthData = GCHandle.Alloc(sensorData.depthImage, GCHandleType.Pinned);
depthFrame.CopyFrameDataToIntPtr(pDepthData.AddrOfPinnedObject(), (uint)sensorData.depthImage.Length * sizeof(ushort));
pDepthData.Free();
sensorData.lastDepthFrameTime = depthFrame.RelativeTime.Ticks;
depthFrame.Dispose();
depthFrame = null;
bNewFrame = true;
}
if((multiSourceFrameReader != null && multiSourceFrame != null) ||
bodyIndexFrameReader != null)
{
BodyIndexFrame bodyIndexFrame = multiSourceFrame != null ? msBodyIndexFrame :
bodyIndexFrameReader.AcquireLatestFrame();
if(bodyIndexFrame != null)
{
var pBodyIndexData = GCHandle.Alloc(sensorData.bodyIndexImage, GCHandleType.Pinned);
bodyIndexFrame.CopyFrameDataToIntPtr(pBodyIndexData.AddrOfPinnedObject(), (uint)sensorData.bodyIndexImage.Length);
pBodyIndexData.Free();
sensorData.lastBodyIndexFrameTime = bodyIndexFrame.RelativeTime.Ticks;
bodyIndexFrame.Dispose();
bodyIndexFrame = null;
bNewFrame = true;
}
}
}
return bNewFrame;
}
public bool PollInfraredFrame (KinectInterop.SensorData sensorData)
{
bool bNewFrame = false;
if((multiSourceFrameReader != null && multiSourceFrame != null) ||
infraredFrameReader != null)
{
InfraredFrame infraredFrame = multiSourceFrame != null ? msInfraredFrame :
infraredFrameReader.AcquireLatestFrame();
if(infraredFrame != null)
{
var pInfraredData = GCHandle.Alloc(sensorData.infraredImage, GCHandleType.Pinned);
infraredFrame.CopyFrameDataToIntPtr(pInfraredData.AddrOfPinnedObject(), (uint)sensorData.infraredImage.Length * sizeof(ushort));
pInfraredData.Free();
sensorData.lastInfraredFrameTime = infraredFrame.RelativeTime.Ticks;
infraredFrame.Dispose();
infraredFrame = null;
bNewFrame = true;
}
}
return bNewFrame;
}
public void FixJointOrientations(KinectInterop.SensorData sensorData, ref KinectInterop.BodyData bodyData)
{
// no fixes are needed
}
public bool IsBodyTurned(ref KinectInterop.BodyData bodyData)
{
//face = On: Face (357.0/1.0)
//face = Off
//| Head_px <= -0.02
//| | Neck_dx <= 0.08: Face (46.0/1.0)
//| | Neck_dx > 0.08: Back (3.0)
//| Head_px > -0.02
//| | SpineShoulder_px <= -0.02: Face (4.0)
//| | SpineShoulder_px > -0.02: Back (64.0/1.0)
bool bBodyTurned = false;
if(bFaceTrackingInited)
{
bool bFaceOn = IsFaceTracked(bodyData.liTrackingID);
if(bFaceOn)
{
bBodyTurned = false;
}
else
{
// face = Off
if(bodyData.joint[(int)KinectInterop.JointType.Head].posRel.x <= -0.02f)
{
bBodyTurned = (bodyData.joint[(int)KinectInterop.JointType.Neck].posDrv.x > 0.08f);
}
else
{
// Head_px > -0.02
bBodyTurned = (bodyData.joint[(int)KinectInterop.JointType.SpineShoulder].posRel.x > -0.02f);
}
}
}
return bBodyTurned;
}
public Vector2 MapSpacePointToDepthCoords (KinectInterop.SensorData sensorData, Vector3 spacePos)
{
Vector2 vPoint = Vector2.zero;
if(coordMapper != null)
{
CameraSpacePoint camPoint = new CameraSpacePoint();
camPoint.X = spacePos.x;
camPoint.Y = spacePos.y;
camPoint.Z = spacePos.z;
CameraSpacePoint[] camPoints = new CameraSpacePoint[1];
camPoints[0] = camPoint;
DepthSpacePoint[] depthPoints = new DepthSpacePoint[1];
coordMapper.MapCameraPointsToDepthSpace(camPoints, depthPoints);
DepthSpacePoint depthPoint = depthPoints[0];
if(depthPoint.X >= 0 && depthPoint.X < sensorData.depthImageWidth &&
depthPoint.Y >= 0 && depthPoint.Y < sensorData.depthImageHeight)
{
vPoint.x = depthPoint.X;
vPoint.y = depthPoint.Y;
}
}
return vPoint;
}
public Vector3 MapDepthPointToSpaceCoords (KinectInterop.SensorData sensorData, Vector2 depthPos, ushort depthVal)
{
Vector3 vPoint = Vector3.zero;
if(coordMapper != null && depthPos != Vector2.zero)
{
DepthSpacePoint depthPoint = new DepthSpacePoint();
depthPoint.X = depthPos.x;
depthPoint.Y = depthPos.y;
DepthSpacePoint[] depthPoints = new DepthSpacePoint[1];
depthPoints[0] = depthPoint;
ushort[] depthVals = new ushort[1];
depthVals[0] = depthVal;
CameraSpacePoint[] camPoints = new CameraSpacePoint[1];
coordMapper.MapDepthPointsToCameraSpace(depthPoints, depthVals, camPoints);
CameraSpacePoint camPoint = camPoints[0];
vPoint.x = camPoint.X;
vPoint.y = camPoint.Y;
vPoint.z = camPoint.Z;
}
return vPoint;
}
public Vector2 MapDepthPointToColorCoords (KinectInterop.SensorData sensorData, Vector2 depthPos, ushort depthVal)
{
Vector2 vPoint = Vector2.zero;
if(coordMapper != null && depthPos != Vector2.zero)
{
DepthSpacePoint depthPoint = new DepthSpacePoint();
depthPoint.X = depthPos.x;
depthPoint.Y = depthPos.y;
DepthSpacePoint[] depthPoints = new DepthSpacePoint[1];
depthPoints[0] = depthPoint;
ushort[] depthVals = new ushort[1];
depthVals[0] = depthVal;
ColorSpacePoint[] colPoints = new ColorSpacePoint[1];
coordMapper.MapDepthPointsToColorSpace(depthPoints, depthVals, colPoints);
ColorSpacePoint colPoint = colPoints[0];
vPoint.x = colPoint.X;
vPoint.y = colPoint.Y;
}
return vPoint;
}
public bool MapDepthFrameToColorCoords (KinectInterop.SensorData sensorData, ref Vector2[] vColorCoords)
{
if(coordMapper != null && sensorData.colorImage != null && sensorData.depthImage != null)
{
var pDepthData = GCHandle.Alloc(sensorData.depthImage, GCHandleType.Pinned);
var pColorCoordsData = GCHandle.Alloc(vColorCoords, GCHandleType.Pinned);
coordMapper.MapDepthFrameToColorSpaceUsingIntPtr(
pDepthData.AddrOfPinnedObject(),
sensorData.depthImage.Length * sizeof(ushort),
pColorCoordsData.AddrOfPinnedObject(),
(uint)vColorCoords.Length);
pColorCoordsData.Free();
pDepthData.Free();
return true;
}
return false;
}
public bool MapColorFrameToDepthCoords (KinectInterop.SensorData sensorData, ref Vector2[] vDepthCoords)
{
if(coordMapper != null && sensorData.colorImage != null && sensorData.depthImage != null)
{
var pDepthData = GCHandle.Alloc(sensorData.depthImage, GCHandleType.Pinned);
var pDepthCoordsData = GCHandle.Alloc(vDepthCoords, GCHandleType.Pinned);
coordMapper.MapColorFrameToDepthSpaceUsingIntPtr(
pDepthData.AddrOfPinnedObject(),
(uint)sensorData.depthImage.Length * sizeof(ushort),
pDepthCoordsData.AddrOfPinnedObject(),
(uint)vDepthCoords.Length);
pDepthCoordsData.Free();
pDepthData.Free();
return true;
}
return false;
}
// returns the index of the given joint in joint's array or -1 if joint is not applicable
public int GetJointIndex(KinectInterop.JointType joint)
{
return (int)joint;
}
// // returns the joint at given index
// public KinectInterop.JointType GetJointAtIndex(int index)
// {
// return (KinectInterop.JointType)(index);
// }
// returns the parent joint of the given joint
public KinectInterop.JointType GetParentJoint(KinectInterop.JointType joint)
{
switch(joint)
{
case KinectInterop.JointType.SpineBase:
return KinectInterop.JointType.SpineBase;
case KinectInterop.JointType.Neck:
return KinectInterop.JointType.SpineShoulder;
case KinectInterop.JointType.SpineShoulder:
return KinectInterop.JointType.SpineMid;
case KinectInterop.JointType.ShoulderLeft:
case KinectInterop.JointType.ShoulderRight:
return KinectInterop.JointType.SpineShoulder;
case KinectInterop.JointType.HipLeft:
case KinectInterop.JointType.HipRight:
return KinectInterop.JointType.SpineBase;
case KinectInterop.JointType.HandTipLeft:
return KinectInterop.JointType.HandLeft;
case KinectInterop.JointType.ThumbLeft:
return KinectInterop.JointType.WristLeft;
case KinectInterop.JointType.HandTipRight:
return KinectInterop.JointType.HandRight;
case KinectInterop.JointType.ThumbRight:
return KinectInterop.JointType.WristRight;
}
return (KinectInterop.JointType)((int)joint - 1);
}
// returns the next joint in the hierarchy, as to the given joint
public KinectInterop.JointType GetNextJoint(KinectInterop.JointType joint)
{
switch(joint)
{
case KinectInterop.JointType.SpineBase:
return KinectInterop.JointType.SpineMid;
case KinectInterop.JointType.SpineMid:
return KinectInterop.JointType.SpineShoulder;
case KinectInterop.JointType.SpineShoulder:
return KinectInterop.JointType.Neck;
case KinectInterop.JointType.Neck:
return KinectInterop.JointType.Head;
case KinectInterop.JointType.ShoulderLeft:
return KinectInterop.JointType.ElbowLeft;
case KinectInterop.JointType.ElbowLeft:
return KinectInterop.JointType.WristLeft;
case KinectInterop.JointType.WristLeft:
return KinectInterop.JointType.HandLeft;
case KinectInterop.JointType.HandLeft:
return KinectInterop.JointType.HandTipLeft;
case KinectInterop.JointType.ShoulderRight:
return KinectInterop.JointType.ElbowRight;
case KinectInterop.JointType.ElbowRight:
return KinectInterop.JointType.WristRight;
case KinectInterop.JointType.WristRight:
return KinectInterop.JointType.HandRight;
case KinectInterop.JointType.HandRight:
return KinectInterop.JointType.HandTipRight;
case KinectInterop.JointType.HipLeft:
return KinectInterop.JointType.KneeLeft;
case KinectInterop.JointType.KneeLeft:
return KinectInterop.JointType.AnkleLeft;
case KinectInterop.JointType.AnkleLeft:
return KinectInterop.JointType.FootLeft;
case KinectInterop.JointType.HipRight:
return KinectInterop.JointType.KneeRight;
case KinectInterop.JointType.KneeRight:
return KinectInterop.JointType.AnkleRight;
case KinectInterop.JointType.AnkleRight:
return KinectInterop.JointType.FootRight;
}
return joint; // in case of end joint - Head, HandTipLeft, HandTipRight, FootLeft, FootRight
}
public bool IsFaceTrackingAvailable(ref bool bNeedRestart)
{
bool bOneCopied = false, bAllCopied = true;
string sTargetPath = ".";
if(!KinectInterop.Is64bitArchitecture())
{
// 32 bit
sTargetPath = KinectInterop.GetTargetDllPath(".", false) + "/";
Dictionary<string, string> dictFilesToUnzip = new Dictionary<string, string>();
dictFilesToUnzip["Kinect20.Face.dll"] = sTargetPath + "Kinect20.Face.dll";
dictFilesToUnzip["KinectFaceUnityAddin.dll"] = sTargetPath + "KinectFaceUnityAddin.dll";
dictFilesToUnzip["msvcp110.dll"] = sTargetPath + "msvcp110.dll";
dictFilesToUnzip["msvcr110.dll"] = sTargetPath + "msvcr110.dll";
KinectInterop.UnzipResourceFiles(dictFilesToUnzip, "KinectV2UnityAddin.x86.zip", ref bOneCopied, ref bAllCopied);
}
else
{
//Debug.Log("Face - x64-architecture.");
sTargetPath = KinectInterop.GetTargetDllPath(".", true) + "/";
Dictionary<string, string> dictFilesToUnzip = new Dictionary<string, string>();
dictFilesToUnzip["Kinect20.Face.dll"] = sTargetPath + "Kinect20.Face.dll";
dictFilesToUnzip["KinectFaceUnityAddin.dll"] = sTargetPath + "KinectFaceUnityAddin.dll";
dictFilesToUnzip["msvcp110.dll"] = sTargetPath + "msvcp110.dll";
dictFilesToUnzip["msvcr110.dll"] = sTargetPath + "msvcr110.dll";
KinectInterop.UnzipResourceFiles(dictFilesToUnzip, "KinectV2UnityAddin.x64.zip", ref bOneCopied, ref bAllCopied);
}
KinectInterop.UnzipResourceDirectory(sTargetPath, "NuiDatabase.zip", sTargetPath + "NuiDatabase");
bNeedRestart = (bOneCopied && bAllCopied);
return true;
}
public bool InitFaceTracking(bool bUseFaceModel, bool bDrawFaceRect)
{
isDrawFaceRect = bDrawFaceRect;
// // load the native dlls to make sure libraries are loaded (after previous finish-unload)
// KinectInterop.LoadNativeLib("Kinect20.Face.dll");
// KinectInterop.LoadNativeLib("KinectFaceUnityAddin.dll");
// specify the required face frame results
FaceFrameFeatures faceFrameFeatures =
FaceFrameFeatures.BoundingBoxInColorSpace
//| FaceFrameFeatures.BoundingBoxInInfraredSpace
| FaceFrameFeatures.PointsInColorSpace
//| FaceFrameFeatures.PointsInInfraredSpace
| FaceFrameFeatures.RotationOrientation
| FaceFrameFeatures.FaceEngagement
//| FaceFrameFeatures.Glasses
//| FaceFrameFeatures.Happy
//| FaceFrameFeatures.LeftEyeClosed
//| FaceFrameFeatures.RightEyeClosed
| FaceFrameFeatures.LookingAway
//| FaceFrameFeatures.MouthMoved
//| FaceFrameFeatures.MouthOpen
;
// create a face frame source + reader to track each face in the FOV
faceFrameSources = new FaceFrameSource[this.bodyCount];
faceFrameReaders = new FaceFrameReader[this.bodyCount];
if(bUseFaceModel)
{
hdFaceFrameSources = new HighDefinitionFaceFrameSource[this.bodyCount];
hdFaceFrameReaders = new HighDefinitionFaceFrameReader[this.bodyCount];
hdFaceModels = new FaceModel[this.bodyCount];
hdFaceAlignments = new FaceAlignment[this.bodyCount];
}
for (int i = 0; i < bodyCount; i++)
{
// create the face frame source with the required face frame features and an initial tracking Id of 0
faceFrameSources[i] = FaceFrameSource.Create(this.kinectSensor, 0, faceFrameFeatures);
// open the corresponding reader
faceFrameReaders[i] = faceFrameSources[i].OpenReader();
if(bUseFaceModel)
{
///////// HD Face
hdFaceFrameSources[i] = HighDefinitionFaceFrameSource.Create(this.kinectSensor);
hdFaceFrameReaders[i] = hdFaceFrameSources[i].OpenReader();
hdFaceModels[i] = FaceModel.Create();
hdFaceAlignments[i] = FaceAlignment.Create();
}
}
// allocate storage to store face frame results for each face in the FOV
faceFrameResults = new FaceFrameResult[this.bodyCount];
// FrameDescription frameDescription = this.kinectSensor.ColorFrameSource.FrameDescription;
// faceDisplayWidth = frameDescription.Width;
// faceDisplayHeight = frameDescription.Height;
bFaceTrackingInited = true;
return bFaceTrackingInited;
}
public void FinishFaceTracking()
{
if(faceFrameReaders != null)
{
for (int i = 0; i < faceFrameReaders.Length; i++)
{
if (faceFrameReaders[i] != null)
{
faceFrameReaders[i].Dispose();
faceFrameReaders[i] = null;
}
}
}
if(faceFrameSources != null)
{
for (int i = 0; i < faceFrameSources.Length; i++)
{
faceFrameSources[i] = null;
}
}
///////// HD Face
if(hdFaceFrameSources != null)
{
for (int i = 0; i < hdFaceAlignments.Length; i++)
{
hdFaceAlignments[i] = null;
}
for (int i = 0; i < hdFaceModels.Length; i++)
{
if (hdFaceModels[i] != null)
{
hdFaceModels[i].Dispose();
hdFaceModels[i] = null;
}
}
for (int i = 0; i < hdFaceFrameReaders.Length; i++)
{
if (hdFaceFrameReaders[i] != null)
{
hdFaceFrameReaders[i].Dispose();
hdFaceFrameReaders[i] = null;
}
}
for (int i = 0; i < hdFaceFrameSources.Length; i++)
{
//hdFaceFrameSources[i].Dispose(true);
hdFaceFrameSources[i] = null;
}
}
bFaceTrackingInited = false;
// // unload the native dlls to prevent hd-face-wrapper's memory leaks
// KinectInterop.DeleteNativeLib("KinectFaceUnityAddin.dll", true);
// KinectInterop.DeleteNativeLib("Kinect20.Face.dll", true);
}
public bool UpdateFaceTracking()
{
if(bodyData == null || faceFrameSources == null || faceFrameReaders == null)
return false;
for(int i = 0; i < this.bodyCount; i++)
{
if(faceFrameSources[i] != null)
{
if(!faceFrameSources[i].IsTrackingIdValid)
{
faceFrameSources[i].TrackingId = 0;
}
if(bodyData[i] != null && bodyData[i].IsTracked)
{
faceFrameSources[i].TrackingId = bodyData[i].TrackingId;
}
}
if (faceFrameReaders[i] != null)
{
FaceFrame faceFrame = faceFrameReaders[i].AcquireLatestFrame();
if (faceFrame != null)
{
int index = GetFaceSourceIndex(faceFrame.FaceFrameSource);
if(ValidateFaceBox(faceFrame.FaceFrameResult))
{
faceFrameResults[index] = faceFrame.FaceFrameResult;
}
else
{
faceFrameResults[index] = null;
}
faceFrame.Dispose();
faceFrame = null;
}
}
///////// HD Face
if(hdFaceFrameSources != null && hdFaceFrameSources[i] != null)
{
if(!hdFaceFrameSources[i].IsTrackingIdValid)
{
hdFaceFrameSources[i].TrackingId = 0;
}
if(bodyData[i] != null && bodyData[i].IsTracked)
{
hdFaceFrameSources[i].TrackingId = bodyData[i].TrackingId;
}
}
if(hdFaceFrameReaders != null && hdFaceFrameReaders[i] != null)
{
HighDefinitionFaceFrame hdFaceFrame = hdFaceFrameReaders[i].AcquireLatestFrame();
if(hdFaceFrame != null)
{
if(hdFaceFrame.IsFaceTracked && (hdFaceAlignments[i] != null))
{
hdFaceFrame.GetAndRefreshFaceAlignmentResult(hdFaceAlignments[i]);
}
hdFaceFrame.Dispose();
hdFaceFrame = null;
}
}
}
return true;
}
private int GetFaceSourceIndex(FaceFrameSource faceFrameSource)
{
int index = -1;
for (int i = 0; i < this.bodyCount; i++)
{
if (this.faceFrameSources[i] == faceFrameSource)
{
index = i;
break;
}
}
return index;
}
private bool ValidateFaceBox(FaceFrameResult faceResult)
{
bool isFaceValid = faceResult != null;
if (isFaceValid)
{
var faceBox = faceResult.FaceBoundingBoxInColorSpace;
//if (faceBox != null)
{
// check if we have a valid rectangle within the bounds of the screen space
isFaceValid = (faceBox.Right - faceBox.Left) > 0 &&
(faceBox.Bottom - faceBox.Top) > 0; // &&
//faceBox.Right <= this.faceDisplayWidth &&
//faceBox.Bottom <= this.faceDisplayHeight;
}
}
return isFaceValid;
}
public bool IsFaceTrackingActive()
{
return bFaceTrackingInited;
}
public bool IsDrawFaceRect()
{
return isDrawFaceRect;
}
public bool IsFaceTracked(long userId)
{
for (int i = 0; i < this.bodyCount; i++)
{
if(faceFrameSources != null && faceFrameSources[i] != null && faceFrameSources[i].TrackingId == (ulong)userId)
{
if(faceFrameResults != null && faceFrameResults[i] != null)
{
return true;
}
}
}
return false;
}
public bool GetFaceRect(long userId, ref Rect faceRect)
{
for (int i = 0; i < this.bodyCount; i++)
{
if(faceFrameSources != null && faceFrameSources[i] != null && faceFrameSources[i].TrackingId == (ulong)userId)
{
if(faceFrameResults != null && faceFrameResults[i] != null)
{
var faceBox = faceFrameResults[i].FaceBoundingBoxInColorSpace;
//if (faceBox != null)
{
faceRect.x = faceBox.Left;
faceRect.y = faceBox.Top;
faceRect.width = faceBox.Right - faceBox.Left;
faceRect.height = faceBox.Bottom - faceBox.Top;
return true;
}
}
}
}
return false;
}
public void VisualizeFaceTrackerOnColorTex(Texture2D texColor)
{
if(bFaceTrackingInited)
{
for (int i = 0; i < this.bodyCount; i++)
{
if(faceFrameSources != null && faceFrameSources[i] != null && faceFrameSources[i].IsTrackingIdValid)
{
if(faceFrameResults != null && faceFrameResults[i] != null)
{
var faceBox = faceFrameResults[i].FaceBoundingBoxInColorSpace;
//if (faceBox != null)
{
UnityEngine.Color color = UnityEngine.Color.magenta;
Vector2 pt1, pt2;
// bottom
pt1.x = faceBox.Left; pt1.y = faceBox.Top;
pt2.x = faceBox.Right; pt2.y = pt1.y;
DrawLine(texColor, pt1, pt2, color);
// right
pt1.x = pt2.x; pt1.y = pt2.y;
pt2.x = pt1.x; pt2.y = faceBox.Bottom;
DrawLine(texColor, pt1, pt2, color);
// top
pt1.x = pt2.x; pt1.y = pt2.y;
pt2.x = faceBox.Left; pt2.y = pt1.y;
DrawLine(texColor, pt1, pt2, color);
// left
pt1.x = pt2.x; pt1.y = pt2.y;
pt2.x = pt1.x; pt2.y = faceBox.Top;
DrawLine(texColor, pt1, pt2, color);
}
}
}
}
}
}
private void DrawLine(Texture2D a_Texture, Vector2 ptStart, Vector2 ptEnd, UnityEngine.Color a_Color)
{
KinectInterop.DrawLine(a_Texture, (int)ptStart.x, (int)ptStart.y, (int)ptEnd.x, (int)ptEnd.y, a_Color);
}
public bool GetHeadPosition(long userId, ref Vector3 headPos)
{
for (int i = 0; i < this.bodyCount; i++)
{
if(bodyData[i].TrackingId == (ulong)userId && bodyData[i].IsTracked)
{
CameraSpacePoint vHeadPos = bodyData[i].Joints[Windows.Kinect.JointType.Head].Position;
if(vHeadPos.Z > 0f)
{
headPos.x = vHeadPos.X;
headPos.y = vHeadPos.Y;
headPos.z = vHeadPos.Z;
return true;
}
}
}
return false;
}
public bool GetHeadRotation(long userId, ref Quaternion headRot)
{
for (int i = 0; i < this.bodyCount; i++)
{
if(faceFrameSources != null && faceFrameSources[i] != null && faceFrameSources[i].TrackingId == (ulong)userId)
{
if(faceFrameResults != null && faceFrameResults[i] != null)
{
Windows.Kinect.Vector4 vHeadRot = faceFrameResults[i].FaceRotationQuaternion;
if(vHeadRot.W > 0f)
{
headRot = new Quaternion(vHeadRot.X, vHeadRot.Y, vHeadRot.Z, vHeadRot.W);
return true;
}
// else
// {
// Debug.Log(string.Format("Bad rotation: ({0:F2}, {1:F2}, {2:F2}, {3:F2}})", vHeadRot.X, vHeadRot.Y, vHeadRot.Z, vHeadRot.W));
// return false;
// }
}
}
}
return false;
}
public bool GetAnimUnits(long userId, ref Dictionary<KinectInterop.FaceShapeAnimations, float> dictAU)
{
for (int i = 0; i < this.bodyCount; i++)
{
if(hdFaceFrameSources != null && hdFaceFrameSources[i] != null && hdFaceFrameSources[i].TrackingId == (ulong)userId)
{
if(hdFaceAlignments != null && hdFaceAlignments[i] != null)
{
foreach(Microsoft.Kinect.Face.FaceShapeAnimations akey in hdFaceAlignments[i].AnimationUnits.Keys)
{
dictAU[(KinectInterop.FaceShapeAnimations)akey] = hdFaceAlignments[i].AnimationUnits[akey];
}
return true;
}
}
}
return false;
}
public bool GetShapeUnits(long userId, ref Dictionary<KinectInterop.FaceShapeDeformations, float> dictSU)
{
for (int i = 0; i < this.bodyCount; i++)
{
if(hdFaceFrameSources != null && hdFaceFrameSources[i] != null && hdFaceFrameSources[i].TrackingId == (ulong)userId)
{
if(hdFaceModels != null && hdFaceModels[i] != null)
{
foreach(Microsoft.Kinect.Face.FaceShapeDeformations skey in hdFaceModels[i].FaceShapeDeformations.Keys)
{
dictSU[(KinectInterop.FaceShapeDeformations)skey] = hdFaceModels[i].FaceShapeDeformations[skey];
}
return true;
}
}
}
return false;
}
public int GetFaceModelVerticesCount(long userId)
{
for (int i = 0; i < this.bodyCount; i++)
{
if(hdFaceFrameSources != null && hdFaceFrameSources[i] != null && (hdFaceFrameSources[i].TrackingId == (ulong)userId || userId == 0))
{
if(hdFaceModels != null && hdFaceModels[i] != null)
{
var vertices = hdFaceModels[i].CalculateVerticesForAlignment(hdFaceAlignments[i]);
int verticesCount = vertices.Count;
return verticesCount;
}
}
}
return 0;
}
public bool GetFaceModelVertices(long userId, ref Vector3[] avVertices)
{
for (int i = 0; i < this.bodyCount; i++)
{
if(hdFaceFrameSources != null && hdFaceFrameSources[i] != null && (hdFaceFrameSources[i].TrackingId == (ulong)userId || userId == 0))
{
if(hdFaceModels != null && hdFaceModels[i] != null)
{
var vertices = hdFaceModels[i].CalculateVerticesForAlignment(hdFaceAlignments[i]);
int verticesCount = vertices.Count;
if(avVertices.Length == verticesCount)
{
for(int v = 0; v < verticesCount; v++)
{
avVertices[v].x = vertices[v].X;
avVertices[v].y = vertices[v].Y;
avVertices[v].z = vertices[v].Z; // -vertices[v].Z;
}
}
return true;
}
}
}
return false;
}
public int GetFaceModelTrianglesCount()
{
var triangleIndices = FaceModel.TriangleIndices;
int triangleLength = triangleIndices.Count;
return triangleLength;
}
public bool GetFaceModelTriangles(bool bMirrored, ref int[] avTriangles)
{
var triangleIndices = FaceModel.TriangleIndices;
int triangleLength = triangleIndices.Count;
if(avTriangles.Length >= triangleLength)
{
for(int i = 0; i < triangleLength; i += 3)
{
//avTriangles[i] = (int)triangleIndices[i];
avTriangles[i] = (int)triangleIndices[i + 2];
avTriangles[i + 1] = (int)triangleIndices[i + 1];
avTriangles[i + 2] = (int)triangleIndices[i];
}
if(bMirrored)
{
Array.Reverse(avTriangles);
}
return true;
}
return false;
}
public bool IsSpeechRecognitionAvailable(ref bool bNeedRestart)
{
bool bOneCopied = false, bAllCopied = true;
if(!KinectInterop.Is64bitArchitecture())
{
//Debug.Log("Speech - x32-architecture.");
string sTargetPath = KinectInterop.GetTargetDllPath(".", false) + "/";
Dictionary<string, string> dictFilesToUnzip = new Dictionary<string, string>();
dictFilesToUnzip["Kinect2SpeechWrapper.dll"] = sTargetPath + "Kinect2SpeechWrapper.dll";
dictFilesToUnzip["msvcp110.dll"] = sTargetPath + "msvcp110.dll";
dictFilesToUnzip["msvcr110.dll"] = sTargetPath + "msvcr110.dll";
KinectInterop.UnzipResourceFiles(dictFilesToUnzip, "KinectV2UnityAddin.x86.zip", ref bOneCopied, ref bAllCopied);
}
else
{
//Debug.Log("Face - x64-architecture.");
string sTargetPath = KinectInterop.GetTargetDllPath(".", true) + "/";
Dictionary<string, string> dictFilesToUnzip = new Dictionary<string, string>();
dictFilesToUnzip["Kinect2SpeechWrapper.dll"] = sTargetPath + "Kinect2SpeechWrapper.dll";
dictFilesToUnzip["msvcp110.dll"] = sTargetPath + "msvcp110.dll";
dictFilesToUnzip["msvcr110.dll"] = sTargetPath + "msvcr110.dll";
KinectInterop.UnzipResourceFiles(dictFilesToUnzip, "KinectV2UnityAddin.x64.zip", ref bOneCopied, ref bAllCopied);
}
bNeedRestart = (bOneCopied && bAllCopied);
return true;
}
public int InitSpeechRecognition(string sRecoCriteria, bool bUseKinect, bool bAdaptationOff)
{
// if(kinectSensor != null)
// {
// float fWaitTime = Time.realtimeSinceStartup + 5f;
//
// while(!kinectSensor.IsAvailable && Time.realtimeSinceStartup < fWaitTime)
// {
// // wait
// }
// }
return InitSpeechRecognizerNative(sRecoCriteria, bUseKinect, bAdaptationOff);
}
public void FinishSpeechRecognition()
{
FinishSpeechRecognizerNative();
}
public int UpdateSpeechRecognition()
{
return UpdateSpeechRecognizerNative();
}
public int LoadSpeechGrammar(string sFileName, short iLangCode, bool bDynamic)
{
return LoadSpeechGrammarNative(sFileName, iLangCode, bDynamic);
}
public int AddGrammarPhrase(string sFromRule, string sToRule, string sPhrase, bool bClearRulePhrases, bool bCommitGrammar)
{
return AddGrammarPhraseNative(sFromRule, sToRule, sPhrase, bClearRulePhrases, bCommitGrammar);
}
public void SetSpeechConfidence(float fConfidence)
{
SetSpeechConfidenceNative(fConfidence);
}
public bool IsSpeechStarted()
{
return IsSpeechStartedNative();
}
public bool IsSpeechEnded()
{
return IsSpeechEndedNative();
}
public bool IsPhraseRecognized()
{
return IsPhraseRecognizedNative();
}
public float GetPhraseConfidence()
{
return GetPhraseConfidenceNative();
}
public string GetRecognizedPhraseTag()
{
IntPtr pPhraseTag = GetRecognizedPhraseTagNative();
string sPhraseTag = Marshal.PtrToStringUni(pPhraseTag);
return sPhraseTag;
}
public void ClearRecognizedPhrase()
{
ClearRecognizedPhraseNative();
}
public bool IsBackgroundRemovalAvailable(ref bool bNeedRestart)
{
bBackgroundRemovalInited = KinectInterop.IsOpenCvAvailable(ref bNeedRestart);
return bBackgroundRemovalInited;
}
public bool InitBackgroundRemoval(KinectInterop.SensorData sensorData, bool isHiResPrefered)
{
return KinectInterop.InitBackgroundRemoval(sensorData, isHiResPrefered);
}
public void FinishBackgroundRemoval(KinectInterop.SensorData sensorData)
{
KinectInterop.FinishBackgroundRemoval(sensorData);
bBackgroundRemovalInited = false;
}
public bool UpdateBackgroundRemoval(KinectInterop.SensorData sensorData, bool isHiResPrefered, Color32 defaultColor)
{
return KinectInterop.UpdateBackgroundRemoval(sensorData, isHiResPrefered, defaultColor);
}
public bool IsBackgroundRemovalActive()
{
return bBackgroundRemovalInited;
}
public bool IsBRHiResSupported()
{
return true;
}
public Rect GetForegroundFrameRect(KinectInterop.SensorData sensorData, bool isHiResPrefered)
{
return KinectInterop.GetForegroundFrameRect(sensorData, isHiResPrefered);
}
public int GetForegroundFrameLength(KinectInterop.SensorData sensorData, bool isHiResPrefered)
{
return KinectInterop.GetForegroundFrameLength(sensorData, isHiResPrefered);
}
public bool PollForegroundFrame(KinectInterop.SensorData sensorData, bool isHiResPrefered, Color32 defaultColor, ref byte[] foregroundImage)
{
return KinectInterop.PollForegroundFrame(sensorData, isHiResPrefered, defaultColor, ref foregroundImage);
}
}
| |
namespace Snippets5.UpgradeGuides._4to5
{
using System;
using NServiceBus;
using NServiceBus.Persistence;
using Raven.Client.Document;
public class Upgrade
{
public void MessageConventions()
{
#region 4to5MessageConventions
BusConfiguration busConfiguration = new BusConfiguration();
ConventionsBuilder conventions = busConfiguration.Conventions();
conventions.DefiningCommandsAs(t => t.Namespace != null && t.Namespace == "MyNamespace" && t.Namespace.EndsWith("Commands"));
conventions.DefiningEventsAs(t => t.Namespace != null && t.Namespace == "MyNamespace" && t.Namespace.EndsWith("Events"));
conventions.DefiningMessagesAs(t => t.Namespace != null && t.Namespace == "Messages");
conventions.DefiningEncryptedPropertiesAs(p => p.Name.StartsWith("Encrypted"));
conventions.DefiningDataBusPropertiesAs(p => p.Name.EndsWith("DataBus"));
conventions.DefiningExpressMessagesAs(t => t.Name.EndsWith("Express"));
conventions.DefiningTimeToBeReceivedAs(t => t.Name.EndsWith("Expires") ? TimeSpan.FromSeconds(30) : TimeSpan.MaxValue);
#endregion
}
public void CustomConfigOverrides()
{
#region 4to5CustomConfigOverrides
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.AssembliesToScan(AllAssemblies.Except("NotThis.dll"));
busConfiguration.Conventions().DefiningEventsAs(type => type.Name.EndsWith("Event"));
busConfiguration.EndpointName("MyEndpointName");
#endregion
}
public void UseTransport()
{
BusConfiguration busConfiguration = new BusConfiguration();
#region 4to5UseTransport
//Choose one of the following
busConfiguration.UseTransport<MsmqTransport>();
busConfiguration.UseTransport<RabbitMQTransport>();
busConfiguration.UseTransport<SqlServerTransport>();
busConfiguration.UseTransport<AzureStorageQueueTransport>();
busConfiguration.UseTransport<AzureServiceBusTransport>();
#endregion
}
public void InterfaceMessageCreation()
{
IBus Bus = null;
#region 4to5InterfaceMessageCreation
Bus.Publish<MyInterfaceMessage>(o =>
{
o.OrderNumber = 1234;
});
#endregion
IMessageCreator messageCreator = null;
#region 4to5ReflectionInterfaceMessageCreation
//This type would be derived from some other runtime information
Type messageType = typeof(MyInterfaceMessage);
object instance = messageCreator.CreateInstance(messageType);
//use reflection to set properties on the constructed instance
Bus.Publish(instance);
#endregion
}
public interface MyInterfaceMessage
{
int OrderNumber { get; set; }
}
public void CustomRavenConfig()
{
#region 4to5CustomRavenConfig
DocumentStore documentStore = new DocumentStore
{
Url = "http://localhost:8080",
DefaultDatabase = "MyDatabase",
};
documentStore.Initialize();
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.UsePersistence<RavenDBPersistence>()
.SetDefaultDocumentStore(documentStore);
#endregion
}
public void StartupAction()
{
#region 4to5StartupAction
IStartableBus bus = Bus.Create(new BusConfiguration());
MyCustomAction();
bus.Start();
#endregion
}
public void MyCustomAction()
{
}
public void Installers()
{
#region 4to5Installers
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.EnableInstallers();
Bus.Create(busConfiguration); //this will run the installers
#endregion
}
public void AllThePersistence()
{
#pragma warning disable 618
#region 4to5ConfigurePersistence
BusConfiguration busConfiguration = new BusConfiguration();
// Configure to use InMemory for all persistence types
busConfiguration.UsePersistence<InMemoryPersistence>();
// Configure to use InMemory for specific persistence types
busConfiguration.UsePersistence<InMemoryPersistence>()
.For(Storage.Sagas, Storage.Subscriptions);
// Configure to use NHibernate for all persistence types
busConfiguration.UsePersistence<NHibernatePersistence>();
// Configure to use NHibernate for specific persistence types
busConfiguration.UsePersistence<NHibernatePersistence>()
.For(Storage.Sagas, Storage.Subscriptions);
// Configure to use RavenDB for all persistence types
busConfiguration.UsePersistence<RavenDBPersistence>();
// Configure to use RavenDB for specific persistence types
busConfiguration.UsePersistence<RavenDBPersistence>()
.For(Storage.Sagas, Storage.Subscriptions);
#endregion
#pragma warning restore 618
}
#region 4to5BusExtensionMethodForHandler
public class MyHandler : IHandleMessages<MyMessage>
{
IBus bus;
public MyHandler(IBus bus)
{
this.bus = bus;
}
public void Handle(MyMessage message)
{
bus.Reply(new OtherMessage());
}
}
#endregion
public class MyMessage
{
}
public class OtherMessage
{
}
public void RunCustomAction()
{
#region 4to5RunCustomAction
IStartableBus bus = Bus.Create(new BusConfiguration());
MyCustomAction();
bus.Start();
#endregion
}
public void DefineCriticalErrorAction()
{
#region 4to5DefineCriticalErrorAction
BusConfiguration busConfiguration = new BusConfiguration();
// Configuring how NServicebus handles critical errors
busConfiguration.DefineCriticalErrorAction((message, exception) =>
{
string output = string.Format("We got a critical exception: '{0}'\r\n{1}", message, exception);
Console.WriteLine(output);
// Perhaps end the process??
});
#endregion
}
public void FileShareDataBus()
{
string databusPath = null;
#region 4to5FileShareDataBus
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.UseDataBus<FileShareDataBus>()
.BasePath(databusPath);
#endregion
}
public void PurgeOnStartup()
{
#region 4to5PurgeOnStartup
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.PurgeOnStartup(true);
#endregion
}
public void EncryptionServiceSimple()
{
#region 4to5EncryptionServiceSimple
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.RijndaelEncryptionService();
#endregion
}
public void License()
{
#region 4to5License
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.LicensePath("PathToLicense");
//or
busConfiguration.License("YourCustomLicenseText");
#endregion
}
public void TransactionConfig()
{
#region 4to5TransactionConfig
BusConfiguration busConfiguration = new BusConfiguration();
//Enable
busConfiguration.Transactions().Enable();
// Disable
busConfiguration.Transactions().Disable();
#endregion
}
public void StaticConfigureEndpoint()
{
#region 4to5StaticConfigureEndpoint
BusConfiguration busConfiguration = new BusConfiguration();
// SendOnly
Bus.CreateSendOnly(busConfiguration);
// AsVolatile
busConfiguration.Transactions().Disable();
busConfiguration.DisableDurableMessages();
busConfiguration.UsePersistence<InMemoryPersistence>();
// DisableDurableMessages
busConfiguration.DisableDurableMessages();
// EnableDurableMessages
busConfiguration.EnableDurableMessages();
#endregion
}
public void PerformanceMonitoring()
{
#region 4to5PerformanceMonitoring
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.EnableSLAPerformanceCounter();
//or
busConfiguration.EnableSLAPerformanceCounter(TimeSpan.FromMinutes(3));
#endregion
}
public void DoNotCreateQueues()
{
#region 4to5DoNotCreateQueues
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.DoNotCreateQueues();
#endregion
}
public void EndpointName()
{
#region 4to5EndpointName
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.EndpointName("MyEndpoint");
#endregion
}
public void SendOnly()
{
#region 4to5SendOnly
BusConfiguration busConfiguration = new BusConfiguration();
ISendOnlyBus bus = Bus.CreateSendOnly(busConfiguration);
#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.Data.Common;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Threading;
using System.Transactions;
namespace System.Data.SqlClient
{
sealed internal partial class SqlDelegatedTransaction : IPromotableSinglePhaseNotification
{
private static int _objectTypeCount;
private readonly int _objectID = Interlocked.Increment(ref _objectTypeCount);
private const int _globalTransactionsTokenVersionSizeInBytes = 4; // the size of the version in the PromotedDTCToken for Global Transactions
internal int ObjectID
{
get
{
return _objectID;
}
}
// WARNING!!! Multithreaded object!
// Locking strategy: Any potentailly-multithreaded operation must first lock the associated connection, then
// validate this object's active state. Locked activities should ONLY include Sql-transaction state altering activities
// or notifications of same. Updates to the connection's association with the transaction or to the connection pool
// may be initiated here AFTER the connection lock is released, but should NOT fall under this class's locking strategy.
private SqlInternalConnection _connection; // the internal connection that is the root of the transaction
private IsolationLevel _isolationLevel; // the IsolationLevel of the transaction we delegated to the server
private SqlInternalTransaction _internalTransaction; // the SQL Server transaction we're delegating to
private Transaction _atomicTransaction;
private bool _active; // Is the transaction active?
internal SqlDelegatedTransaction(SqlInternalConnection connection, Transaction tx)
{
Debug.Assert(null != connection, "null connection?");
_connection = connection;
_atomicTransaction = tx;
_active = false;
Transactions.IsolationLevel systxIsolationLevel = (Transactions.IsolationLevel)tx.IsolationLevel;
// We need to map the System.Transactions IsolationLevel to the one
// that System.Data uses and communicates to SqlServer. We could
// arguably do that in Initialize when the transaction is delegated,
// however it is better to do this before we actually begin the process
// of delegation, in case System.Transactions adds another isolation
// level we don't know about -- we can throw the exception at a better
// place.
switch (systxIsolationLevel)
{
case Transactions.IsolationLevel.ReadCommitted:
_isolationLevel = IsolationLevel.ReadCommitted;
break;
case Transactions.IsolationLevel.ReadUncommitted:
_isolationLevel = IsolationLevel.ReadUncommitted;
break;
case Transactions.IsolationLevel.RepeatableRead:
_isolationLevel = IsolationLevel.RepeatableRead;
break;
case Transactions.IsolationLevel.Serializable:
_isolationLevel = IsolationLevel.Serializable;
break;
case Transactions.IsolationLevel.Snapshot:
_isolationLevel = IsolationLevel.Snapshot;
break;
default:
throw SQL.UnknownSysTxIsolationLevel(systxIsolationLevel);
}
}
internal Transaction Transaction
{
get { return _atomicTransaction; }
}
public void Initialize()
{
// if we get here, then we know for certain that we're the delegated
// transaction.
SqlInternalConnection connection = _connection;
SqlConnection usersConnection = connection.Connection;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
if (connection.IsEnlistedInTransaction)
{ // defect first
connection.EnlistNull();
}
_internalTransaction = new SqlInternalTransaction(connection, TransactionType.Delegated, null);
connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Begin, null, _isolationLevel, _internalTransaction, true);
// Handle case where ExecuteTran didn't produce a new transaction, but also didn't throw.
if (null == connection.CurrentTransaction)
{
connection.DoomThisConnection();
throw ADP.InternalError(ADP.InternalErrorCode.UnknownTransactionFailure);
}
_active = true;
}
catch (System.OutOfMemoryException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
usersConnection.Abort(e);
throw;
}
}
internal bool IsActive
{
get
{
return _active;
}
}
public byte[] Promote()
{
// Operations that might be affected by multi-threaded use MUST be done inside the lock.
// Don't read values off of the connection outside the lock unless it doesn't really matter
// from an operational standpoint (i.e. logging connection's ObjectID should be fine,
// but the PromotedDTCToken can change over calls. so that must be protected).
SqlInternalConnection connection = GetValidConnection();
Exception promoteException;
byte[] returnValue = null;
SqlConnection usersConnection = connection.Connection;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
lock (connection)
{
try
{
// Now that we've acquired the lock, make sure we still have valid state for this operation.
ValidateActiveOnConnection(connection);
connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Promote, null, IsolationLevel.Unspecified, _internalTransaction, true);
returnValue = _connection.PromotedDTCToken;
// For Global Transactions, we need to set the Transaction Id since we use a Non-MSDTC Promoter type.
if (_connection.IsGlobalTransaction)
{
if (SysTxForGlobalTransactions.SetDistributedTransactionIdentifier == null)
{
throw SQL.UnsupportedSysTxForGlobalTransactions();
}
if (!_connection.IsGlobalTransactionsEnabledForServer)
{
throw SQL.GlobalTransactionsNotEnabled();
}
SysTxForGlobalTransactions.SetDistributedTransactionIdentifier.Invoke(_atomicTransaction, new object[] { this, GetGlobalTxnIdentifierFromToken() });
}
promoteException = null;
}
catch (SqlException e)
{
promoteException = e;
// Doom the connection, to make sure that the transaction is
// eventually rolled back.
// VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
connection.DoomThisConnection();
}
catch (InvalidOperationException e)
{
promoteException = e;
connection.DoomThisConnection();
}
}
}
catch (System.OutOfMemoryException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
usersConnection.Abort(e);
throw;
}
if (promoteException != null)
{
throw SQL.PromotionFailed(promoteException);
}
return returnValue;
}
// Called by transaction to initiate abort sequence
public void Rollback(SinglePhaseEnlistment enlistment)
{
Debug.Assert(null != enlistment, "null enlistment?");
SqlInternalConnection connection = GetValidConnection();
SqlConnection usersConnection = connection.Connection;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
lock (connection)
{
try
{
// Now that we've acquired the lock, make sure we still have valid state for this operation.
ValidateActiveOnConnection(connection);
_active = false; // set to inactive first, doesn't matter how the execute completes, this transaction is done.
_connection = null; // Set prior to ExecuteTransaction call in case this initiates a TransactionEnd event
// If we haven't already rolled back (or aborted) then tell the SQL Server to roll back
if (!_internalTransaction.IsAborted)
{
connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Rollback, null, IsolationLevel.Unspecified, _internalTransaction, true);
}
}
catch (SqlException)
{
// Doom the connection, to make sure that the transaction is
// eventually rolled back.
// VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
connection.DoomThisConnection();
// Unlike SinglePhaseCommit, a rollback is a rollback, regardless
// of how it happens, so SysTx won't throw an exception, and we
// don't want to throw an exception either, because SysTx isn't
// handling it and it may create a fail fast scenario. In the end,
// there is no way for us to communicate to the consumer that this
// failed for more serious reasons than usual.
//
// This is a bit like "should you throw if Close fails", however,
// it only matters when you really need to know. In that case,
// we have the tracing that we're doing to fallback on for the
// investigation.
}
catch (InvalidOperationException)
{
connection.DoomThisConnection();
}
}
// it doesn't matter whether the rollback succeeded or not, we presume
// that the transaction is aborted, because it will be eventually.
connection.CleanupConnectionOnTransactionCompletion(_atomicTransaction);
enlistment.Aborted();
}
catch (System.OutOfMemoryException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
usersConnection.Abort(e);
throw;
}
}
// Called by the transaction to initiate commit sequence
public void SinglePhaseCommit(SinglePhaseEnlistment enlistment)
{
Debug.Assert(null != enlistment, "null enlistment?");
SqlInternalConnection connection = GetValidConnection();
SqlConnection usersConnection = connection.Connection;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
// If the connection is dooomed, we can be certain that the
// transaction will eventually be rolled back, and we shouldn't
// attempt to commit it.
if (connection.IsConnectionDoomed)
{
lock (connection)
{
_active = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done.
_connection = null;
}
enlistment.Aborted(SQL.ConnectionDoomed());
}
else
{
Exception commitException;
lock (connection)
{
try
{
// Now that we've acquired the lock, make sure we still have valid state for this operation.
ValidateActiveOnConnection(connection);
_active = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done.
_connection = null; // Set prior to ExecuteTransaction call in case this initiates a TransactionEnd event
connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Commit, null, IsolationLevel.Unspecified, _internalTransaction, true);
commitException = null;
}
catch (SqlException e)
{
commitException = e;
// Doom the connection, to make sure that the transaction is
// eventually rolled back.
// VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
connection.DoomThisConnection();
}
catch (InvalidOperationException e)
{
commitException = e;
connection.DoomThisConnection();
}
}
if (commitException != null)
{
// connection.ExecuteTransaction failed with exception
if (_internalTransaction.IsCommitted)
{
// Even though we got an exception, the transaction
// was committed by the server.
enlistment.Committed();
}
else if (_internalTransaction.IsAborted)
{
// The transaction was aborted, report that to
// SysTx.
enlistment.Aborted(commitException);
}
else
{
// The transaction is still active, we cannot
// know the state of the transaction.
enlistment.InDoubt(commitException);
}
// We eat the exception. This is called on the SysTx
// thread, not the applications thread. If we don't
// eat the exception an UnhandledException will occur,
// causing the process to FailFast.
}
connection.CleanupConnectionOnTransactionCompletion(_atomicTransaction);
if (commitException == null)
{
// connection.ExecuteTransaction succeeded
enlistment.Committed();
}
}
}
catch (System.OutOfMemoryException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
usersConnection.Abort(e);
throw;
}
}
// Event notification that transaction ended. This comes from the subscription to the Transaction's
// ended event via the internal connection. If it occurs without a prior Rollback or SinglePhaseCommit call,
// it indicates the transaction was ended externally (generally that one of the DTC participants aborted
// the transaction).
internal void TransactionEnded(Transaction transaction)
{
SqlInternalConnection connection = _connection;
if (connection != null)
{
lock (connection)
{
if (_atomicTransaction.Equals(transaction))
{
// No need to validate active on connection, this operation can be called on completed transactions
_active = false;
_connection = null;
}
}
}
}
// Check for connection validity
private SqlInternalConnection GetValidConnection()
{
SqlInternalConnection connection = _connection;
if (null == connection)
{
throw ADP.ObjectDisposed(this);
}
return connection;
}
// Dooms connection and throws and error if not a valid, active, delegated transaction for the given
// connection. Designed to be called AFTER a lock is placed on the connection, otherwise a normal return
// may not be trusted.
private void ValidateActiveOnConnection(SqlInternalConnection connection)
{
bool valid = _active && (connection == _connection) && (connection.DelegatedTransaction == this);
if (!valid)
{
// Invalid indicates something BAAAD happened (Commit after TransactionEnded, for instance)
// Doom anything remotely involved.
if (null != connection)
{
connection.DoomThisConnection();
}
if (connection != _connection && null != _connection)
{
_connection.DoomThisConnection();
}
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner); //TODO: Create a new code
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using rhoruntime;
using rhodes;
namespace rho {
namespace WebViewImpl
{
public class WebView : WebViewBase
{
public WebView(string id) : base(id)
{
}
}
public class WebViewSingleton : WebViewSingletonBase
{
public WebViewSingleton()
{
}
static private MainPage getMainPage()
{
MainPage mainPage = MainPage.getInstance();
return mainPage;
}
public override void getFramework(IMethodResult oResult)
{
MainPage mp = getMainPage();
oResult.set(mp != null ? mp.getWebviewFramework() : "");
}
public override void getFullScreen(IMethodResult oResult)
{
MainPage mp = getMainPage();
oResult.set(mp != null ? mp.isFullscreen() : false);
}
public override void setFullScreen(bool fullScreen, IMethodResult oResult)
{
MainPage mp = getMainPage();
if (mp != null)
mp.fullscreenCommand(fullScreen ? 1 : 0);
}
public override void getKeyboardDisplayRequiresUserAction(IMethodResult oResult)
{
oResult.set(true); }
public override void setKeyboardDisplayRequiresUserAction(bool keyboardDisplayRequiresUserAction, IMethodResult oResult)
{
}
public override void getEnableDragAndDrop(IMethodResult oResult)
{
oResult.set(true); }
public override void setEnableDragAndDrop(bool enableDragAndDrop, IMethodResult oResult)
{
}
public override void getEnableZoom(IMethodResult oResult)
{
// implement this method in C# here
oResult.set(true);
}
public override void getEnableMediaPlaybackWithoutGesture(IMethodResult oResult)
{
oResult.set(false);
}
public override void getEnablePageLoadingIndication(IMethodResult oResult)
{
// implement this method in C# here
oResult.set(false);
}
public override void getEnableWebPlugins(IMethodResult oResult)
{
// implement this method in C# here
oResult.set(true);
}
public override void getNavigationTimeout(IMethodResult oResult)
{
// implement this method in C# here
oResult.set(0);
}
public override void setNavigationTimeout(int navigationTimeout, IMethodResult oResult)
{
// implement this method in C# here
}
public override void getScrollTechnique(IMethodResult oResult)
{
// implement this method in C# here
oResult.set("natural");
}
public override void getFontFamily(IMethodResult oResult)
{
// implement this method in C# here
oResult.set("Arial");
}
public override void getUserAgent(IMethodResult oResult)
{
MainPage mp = getMainPage();
oResult.set(mp != null ? mp.getUserAgent() : "");
}
public override void getViewportEnabled(IMethodResult oResult)
{
// implement this method in C# here
oResult.set(true);
}
public override void getViewportWidth(IMethodResult oResult)
{
MainPage mp = getMainPage();
oResult.set(mp != null ? mp.getScreenWidth() : 0);
}
public override void getCacheSize(IMethodResult oResult)
{
// implement this method in C# here
oResult.set(0);
}
public override void getEnableCache(IMethodResult oResult)
{
// implement this method in C# here
oResult.set(false);
}
public override void getAcceptLanguage(IMethodResult oResult)
{
// implement this method in C# here
oResult.set("en");
}
public override void setAcceptLanguage(string acceptLanguage, IMethodResult oResult)
{
// implement this method in C# here
}
public override void getZoomPage(IMethodResult oResult)
{
// implement this method in C# here
oResult.set(1.0);
}
public override void setZoomPage(double zoomPage, IMethodResult oResult)
{
// implement this method in C# here
}
public override void getTextZoomLevel(IMethodResult oResult)
{
// implement this method in C# here
oResult.set(1.0);
}
public override void setTextZoomLevel(int textZoomLevel, IMethodResult oResult)
{
// implement this method in C# here
}
public override void getActiveTab(IMethodResult oResult)
{
MainPage mp = getMainPage();
oResult.set(mp != null ? mp.tabbarGetCurrent() : 0);
}
public override void refresh(int tabIndex, IMethodResult oResult)
{
MainPage mp = getMainPage();
if (mp != null)
mp.Refresh(tabIndex);
}
public override void navigate(string url, int tabIndex, IMethodResult oResult)
{
MainPage mp = getMainPage();
if (mp != null)
{
//waitForBrowserInitialized(tabIndex);
mp.navigate(CRhoRuntime.getInstance().canonicalizeRhoUrl(url), tabIndex);
}
}
public override void navigateBack(int tabIndex, IMethodResult oResult)
{
MainPage mp = getMainPage();
if (mp != null)
mp.GoBack(tabIndex);
}
public override void currentLocation(int tabIndex, IMethodResult oResult)
{
MainPage mp = getMainPage();
oResult.set(mp != null ? mp.getCurrentURL(tabIndex) : "");
}
public override void currentURL(int tabIndex, IMethodResult oResult)
{
MainPage mp = getMainPage();
oResult.set(mp != null ? mp.getCurrentURL(tabIndex) : "");
}
public override void executeJavascript(string javascriptText, int tabIndex, IMethodResult oResult)
{
MainPage mp = getMainPage();
if (mp != null)
mp.executeScript(javascriptText, tabIndex);
}
public override void active_tab(IMethodResult oResult)
{
getActiveTab(oResult);
}
public override void full_screen_mode(bool enable, IMethodResult oResult)
{
setFullScreen(enable, oResult);
}
public override void setCookie(string url, string cookie, IMethodResult oResult)
{
MainPage mp = getMainPage();
if (mp != null)
mp.setCookie(CRhoRuntime.getInstance().canonicalizeRhoUrl(url), cookie);
}
public override void getCookies(string url, IMethodResult oResult)
{
}
public override void removeCookie(string url, string name, IMethodResult oResult)
{
}
public override void removeAllCookies(IMethodResult oResult)
{
}
public override void save(string format, string path, int tabIndex, IMethodResult oResult)
{
// implement this method in C# here
}
private void waitForBrowserInitialized(int index)
{
while(true)
{
if(getMainPage().isBrowserInitialized(index)) return;
else{
Task task = Task.Delay(TimeSpan.FromSeconds(100));
task.Wait();
}
}
}
}
public class WebViewFactory : WebViewFactoryBase
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using com.calitha.goldparser;
using EpiInfo.Plugin;
//using VariableCollection = Epi.Collections.NamedObjectCollection<Epi.IVariable>;
namespace Epi.Core.EnterInterpreter.Rules
{
public class Rule_Dialog : EnterRule
{
EnterRule Dialog = null;
public Rule_Dialog(Rule_Context pContext, NonterminalToken token) : base(pContext)
{
switch (token.Rule.Lhs.ToString())
{
case "<Simple_Dialog_Statement>":
this.Dialog = new Rule_Simple_Dialog_Statement(pContext, token);
break;
case "<Numeric_Dialog_Implicit_Statement>":
this.Dialog = new Rule_Numeric_Dialog_Implicit_Statement(pContext, token);
break;
case "<TextBox_Dialog_Statement>":
this.Dialog = new Rule_TextBox_Dialog_Statement(pContext, token);
break;
case "<Numeric_Dialog_Explicit_Statement>":
this.Dialog = new Rule_Numeric_Dialog_Explicit_Statement(pContext, token);
break;
case "<Db_Values_Dialog_Statement>":
this.Dialog = new Rule_Db_Values_Dialog_Statement(pContext, token);
break;
case "<YN_Dialog_Statement>":
this.Dialog = new Rule_YN_Dialog_Statement(pContext, token);
break;
case "<Db_Views_Dialog_Statement>":
this.Dialog = new Rule_Db_Views_Dialog_Statement(pContext, token);
break;
case "<Databases_Dialog_Statement>":
this.Dialog = new Rule_Databases_Dialog_Statement(pContext, token);
break;
case "<Db_Variables_Dialog_Statement>":
this.Dialog = new Rule_Db_Variables_Dialog_Statement(pContext, token);
break;
case "<Multiple_Choice_Dialog_Statement>":
this.Dialog = new Rule_Multiple_Choice_Dialog_Statement(pContext, token);
break;
case "<Dialog_Read_Statement>":
this.Dialog = new Rule_Dialog_Read_Statement(pContext, token);
break;
case "<Dialog_Write_Statement>":
this.Dialog = new Rule_Dialog_Write_Statement(pContext, token);
break;
case "<Dialog_Read_Filter_Statement>":
this.Dialog = new Rule_Dialog_Read_Filter_Statement(pContext, token);
break;
case "<Dialog_Write_Filter_Statement>":
this.Dialog = new Rule_Dialog_Write_Filter_Statement(pContext, token);
break;
case "<Dialog_Date_Statement>":
this.Dialog = new Rule_Dialog_Date_Statement(pContext, token);
break;
case "<Dialog_Date_Mask_Statement>":
this.Dialog = new Rule_Dialog_Date_Mask_Statement(pContext, token);
break;
default:
this.Dialog = new Rule_TextBox_Dialog_Statement(pContext, token);
break;
}
}
public override object Execute()
{
return this.Dialog.Execute();
}
public override void ToJavaScript(StringBuilder pJavaScriptBuilder)
{
string DialogType = Dialog.GetType().FullName;
DialogType = DialogType.Substring(DialogType.LastIndexOf('.') + 6);
switch (DialogType)
{
case "Simple_Dialog_Statement":
pJavaScriptBuilder.Append("CCE_ContextOpenSimpleDialogBox('");
pJavaScriptBuilder.Append(((RuleDialogBase)(this.Dialog)).TitleText.ToString());
pJavaScriptBuilder.Append("', '");
pJavaScriptBuilder.Append(((RuleDialogBase)(this.Dialog)).Prompt.ToString().Replace("'","\\'") + "'" );
pJavaScriptBuilder.Append(",id"+ ");");
break;
case "Numeric_Dialog_Explicit_Statement":
case "Dialog_Date_Mask_Statement":
case "TextBox_Dialog_Statement":
case "YN_Dialog_Statement":
pJavaScriptBuilder.Append(GetJavaScriptString("CCE_ContextOpenDialogBox").ToString());
break;
}
}
public StringBuilder GetJavaScriptString(string FunctionName)
{
StringBuilder pJavaScriptBuilder = new StringBuilder();
pJavaScriptBuilder.Append(FunctionName + "('");
pJavaScriptBuilder.Append(((Rules.RuleDialogBase)(this.Dialog)).TitleText.ToString());
pJavaScriptBuilder.Append("', '");
pJavaScriptBuilder.Append(((RuleDialogBase)(this.Dialog)).MaskOpt.ToString());
pJavaScriptBuilder.Append("', '");
pJavaScriptBuilder.Append(((RuleDialogBase)(this.Dialog)).Identifier.ToString().ToLower());
pJavaScriptBuilder.Append("', '");
pJavaScriptBuilder.AppendLine(((RuleDialogBase)(this.Dialog)).Prompt.ToString().Replace("'", "\\'") + "');");
return pJavaScriptBuilder;
}
}
public class Rule_Simple_Dialog_Statement : RuleDialogBase
{
public Rule_Simple_Dialog_Statement(Rule_Context pContext, NonterminalToken token) : base(pContext,token)
{
//<Simple_Dialog_Statement> ::= DIALOG String <TitleOpt>
Prompt = this.GetCommandElement(token.Tokens, 1);
if (token.Tokens.Length > 2)
{
TitleText = this.GetCommandElement(token.Tokens, 2);
}
else
{
TitleText = "";
}
}
public override object Execute()
{
return base.Execute();
}
}
public class Rule_Numeric_Dialog_Implicit_Statement : RuleDialogBase
{
public Rule_Numeric_Dialog_Implicit_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
//<Numeric_Dialog_Implicit_Statement> ::= DIALOG String Identifier <TitleOpt>
Prompt = this.GetCommandElement(token.Tokens, 1);
Identifier = this.GetCommandElement(token.Tokens, 2);
TitleText = this.GetCommandElement(token.Tokens, 3);
}
public override object Execute()
{
this.DialogThenAssign(new Double());
return null;
}
}
public class Rule_TextBox_Dialog_Statement : RuleDialogBase
{
public Rule_TextBox_Dialog_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
//<TextBox_Dialog_Statement> ::= DIALOG String Identifier TEXTINPUT <MaskOpt> <TitleOpt>
Prompt = this.GetCommandElement(token.Tokens, 1);
Identifier = this.GetCommandElement(token.Tokens, 2);
MaskOpt = this.GetCommandElement(token.Tokens, 4);
TitleText = this.GetCommandElement(token.Tokens, 5);
}
public override object Execute()
{
this.DialogThenAssign(string.Empty);
return null;
}
}
public class Rule_Numeric_Dialog_Explicit_Statement : RuleDialogBase
{
public Rule_Numeric_Dialog_Explicit_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
//<Numeric_Dialog_Explicit_Statement> ::= DIALOG String Identifier NUMERIC <MaskOpt> <TitleOpt>
this.Prompt = GetCommandElement(token.Tokens, 1);
this.Identifier = GetCommandElement(token.Tokens, 2);
this.MaskOpt = GetCommandElement(token.Tokens, 4);
this.TitleText = GetCommandElement(token.Tokens, 5);
}
public override object Execute()
{
this.DialogThenAssign(new Double());
return null;
}
}
public class Rule_Db_Values_Dialog_Statement : RuleDialogBase
{
public Rule_Db_Values_Dialog_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
//<Db_Values_Dialog_Statement> ::= DIALOG String Identifier DBVALUES Identifier Identifier <TitleOpt>
Prompt = GetElement(token, 1);
Identifier = GetElement(token, 2);
Modifier = GetElement(token, 3);
TitleText = GetElement(token, 6);
}
public override object Execute()
{
// db values is the listing of all values in one or more databases
List<string> list = new List<string>();
List<EpiInfo.Plugin.IVariable> vars = this.Context.CurrentScope.FindVariables(EpiInfo.Plugin.VariableScope.DataSource);
foreach (EpiInfo.Plugin.IVariable v in vars)
{
list.Add(v.Name);
}
this.DialogThenAssign(list);
return null;
}
}
public class Rule_YN_Dialog_Statement : RuleDialogBase
{
public Rule_YN_Dialog_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
//<YN_Dialog_Statement> ::= DIALOG String Identifier YN <TitleOpt>
this.Prompt = this.GetCommandElement(token.Tokens, 1);
this.Identifier = this.GetCommandElement(token.Tokens, 2);
this.TitleText = this.GetCommandElement(token.Tokens, 4);
}
public override object Execute()
{
this.DialogThenAssign(new Boolean());
return null;
}
}
public class Rule_Db_Views_Dialog_Statement : RuleDialogBase
{
public Rule_Db_Views_Dialog_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
//<Db_Views_Dialog_Statement> ::= DIALOG String Identifier DBVIEWS <titleOpt>
Prompt = GetElement(token, 1);
Identifier = GetElement(token, 2);
Modifier = GetElement(token, 3);
TitleText = GetElement(token, 4);
}
public override object Execute()
{
return null;
/*
Epi.Data.IDbDriver driver = null;
if (this.Context.CurrentRead != null)
{
driver = Epi.Data.DBReadExecute.GetDataDriver(this.Context.CurrentRead.File);
}
else
{
return null;
}
List<string> tableNames = driver.GetTableNames();
List<string> viewNames = new List<string>();
foreach (string name in tableNames)
{
if (name.ToUpper().StartsWith("VIEW"))
{
viewNames.Add(name);
}
}
this.DialogThenAssign(viewNames);
return null;*/
}
}
public class Rule_Databases_Dialog_Statement : RuleDialogBase
{
public Rule_Databases_Dialog_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
//<Databases_Dialog_Statement> ::= DIALOG String Identifier DATABASES <TitleOpt>
Prompt = this.GetCommandElement(token.Tokens, 1);
Identifier = GetElement(token, 2);
Modifier = this.GetCommandElement(token.Tokens, 3);
TitleText = this.GetCommandElement(token.Tokens, 4);
}
public override object Execute()
{
// show the open file dialog and filter on databases
return null;
}
}
public class Rule_Db_Variables_Dialog_Statement : RuleDialogBase
{
public Rule_Db_Variables_Dialog_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
//<Db_Variables_Dialog_Statement> ::= DIALOG String Identifier DBVARIABLES <TitleOpt>
Prompt = GetElement(token, 1);
Identifier = GetElement(token, 2);
Modifier = GetElement(token, 3);
TitleText = GetElement(token, 4);
}
public override object Execute()
{
List<string> list = new List<string>();
List<EpiInfo.Plugin.IVariable> vars = this.Context.CurrentScope.FindVariables(EpiInfo.Plugin.VariableScope.Permanent | EpiInfo.Plugin.VariableScope.Global | EpiInfo.Plugin.VariableScope.Standard);
foreach (EpiInfo.Plugin.IVariable v in vars)
{
list.Add(v.Name);
}
this.DialogThenAssign(list);
return null;
}
}
public class Rule_Multiple_Choice_Dialog_Statement : RuleDialogBase
{
//<Multiple_Choice_Dialog_Statement> ::= DIALOG String Identifier <StringList> <TitleOpt>
public Rule_Multiple_Choice_Dialog_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
this.Prompt = this.GetCommandElement(token.Tokens, 1);
this.Identifier = this.GetCommandElement(token.Tokens, 2);
this.StringList = this.GetCommandElement(token.Tokens, 3);
this.TitleText = this.GetCommandElement(token.Tokens, 4);
}
public override object Execute()
{
List<string> list = new List<string>();
string[] strings = StringList.Split(',');
for (int i = 0; i < strings.Length; i++)
{
strings[i] = strings[i].Trim();
strings[i] = strings[i].Replace("\"", "");
}
list.AddRange(strings);
this.DialogThenAssign(list);
return null;
}
}
public class Rule_Dialog_Read_Statement : RuleDialogBase
{
//<Dialog_Read_Statement> ::= DIALOG String Identifier READ <TitleOpt>
public Rule_Dialog_Read_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
Filter = this.GetCommandElement(token.Tokens, 1);
Identifier = this.GetCommandElement(token.Tokens, 2);
Modifier = this.GetCommandElement(token.Tokens, 3);
TitleText = this.GetCommandElement(token.Tokens, 4);
}
public override object Execute()
{
string obj = Filter;
this.DialogThenAssign(obj);
return null;
}
}
public class Rule_Dialog_Read_Filter_Statement : RuleDialogBase
{
//<Dialog_Read_Filter_Statement> ::= DIALOG String Identifier READ String <TitleOpt>
public Rule_Dialog_Read_Filter_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
Filter = this.GetCommandElement(token.Tokens, 1);
Identifier = this.GetCommandElement(token.Tokens, 2);
Modifier = this.GetCommandElement(token.Tokens, 3);
TitleText = this.GetCommandElement(token.Tokens, 5);
}
public override object Execute()
{
string obj = Filter;
this.DialogThenAssign(obj);
return null;
}
}
public class Rule_Dialog_Write_Statement : RuleDialogBase
{
//<Dialog_Write_Statement> ::= DIALOG String Identifier WRITE <TitleOpt>
public Rule_Dialog_Write_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
Filter = this.GetCommandElement(token.Tokens, 1);
Identifier = this.GetCommandElement(token.Tokens, 2);
Modifier = this.GetCommandElement(token.Tokens, 3);
TitleText = this.GetCommandElement(token.Tokens, 4);
}
public override object Execute()
{
string obj = Filter;
this.DialogThenAssign(obj);
return null;
}
}
public class Rule_Dialog_Write_Filter_Statement : RuleDialogBase
{
//<Dialog_Write_Filter_Statement> ::= DIALOG String Identifier WRITE String <TitleOpt>
public Rule_Dialog_Write_Filter_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
Filter = this.GetCommandElement(token.Tokens, 1);
Identifier = this.GetCommandElement(token.Tokens, 2);
Modifier = this.GetCommandElement(token.Tokens, 3);
TitleText = this.GetCommandElement(token.Tokens, 5);
}
public override object Execute()
{
string obj = Filter;
this.DialogThenAssign(obj);
return null;
}
}
public class Rule_Dialog_Date_Statement : RuleDialogBase
{
public Rule_Dialog_Date_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
//<Dialog_Date_Statement> ::= DIALOG String Identifier DATEFORMAT <TitleOpt>
Prompt = this.GetCommandElement(token.Tokens, 1);
TitleText = this.GetCommandElement(token.Tokens, 4);
}
public override object Execute()
{
this.DialogThenAssign(new DateTime());
return null;
}
}
public class Rule_Dialog_Date_Mask_Statement : RuleDialogBase
{
public Rule_Dialog_Date_Mask_Statement(Rule_Context pContext, NonterminalToken token)
: base(pContext, token)
{
//<Dialog_Date_Mask_Statement> ::= DIALOG String Identifier DATEFORMAT String <TitleOpt>
Prompt = this.GetCommandElement(token.Tokens, 1);
Identifier = this.GetCommandElement(token.Tokens, 2);
MaskOpt = this.GetCommandElement(token.Tokens, 4);
TitleText = this.GetCommandElement(token.Tokens, 5);
}
public override object Execute()
{
this.DialogThenAssign(new DateTime());
return null;
}
}
/// <summary>
/// DIALOG Command base class.
/// </summary>
public class RuleDialogBase : EnterRule
{
protected string mask = "";
protected string titleText = "";
protected string prompt = "";
protected string Filter { get; set; }
public string Identifier { get; set; }
protected string Modifier { get; set; }
protected string StringList { get; set; }
protected string TitleOpt { get; set; }
public string MaskOpt
{
get { return mask; }
set
{
if (!string.IsNullOrEmpty(value) && value.Contains("\""))
{
mask = value.Substring(value.IndexOf("\"") + 1).Trim().TrimEnd('\"');
}
else
{
mask = value;
}
}
}
public string Prompt
{
get { return prompt; }
set
{
if (!string.IsNullOrEmpty(value) && value.Contains("\""))
{
prompt = value.Substring(value.IndexOf("\"") + 1).Trim().TrimEnd('\"');
}
else
{
prompt = value;
}
}
}
public string TitleText
{
get { return titleText; }
set
{
if (!string.IsNullOrEmpty(value) && value.Contains("\""))
{
titleText = value.Substring(value.IndexOf("\"") + 1).Trim().TrimEnd('\"');
}
else
{
titleText = value;
}
}
}
#region Constructors
public RuleDialogBase(Rule_Context pContext, NonterminalToken token)
: base(pContext)
{
}
#endregion Constructors
#region Private Methods
#endregion Private Methods
#region Protected methods
protected bool DialogThenAssign(object obj)
{
MaskOpt = MaskOpt == null ? string.Empty : MaskOpt;
Modifier = Modifier == null ? string.Empty : Modifier;
if (this.Context.EnterCheckCodeInterface.Dialog(Prompt, TitleText, MaskOpt, Modifier, ref obj))
{
Assign.AssignValue(this.Context, Identifier, obj);
return true;
}
return false;
}
protected string GetElement(NonterminalToken token, int index)
{
string returnToken = string.Empty;
if (token.Tokens.Length > index )
{
returnToken = this.GetCommandElement(token.Tokens, index);
}
return returnToken;
}
#endregion Protected methods
#region Public Methods
/// <summary>
/// Executes the DIALOG command
/// </summary>
/// <returns> CommandProcessorResults </returns>
public override object Execute()
{
this.Context.EnterCheckCodeInterface.Dialog(this.Prompt, this.TitleText);
return null;
}
#endregion Public Methods
}
/// <summary>
/// Assign
/// </summary>
public class Assign
{
public static bool AssignValue(Rule_Context pContext, string varName, object value)
{
IVariable var;
string dataValue = string.Empty;
var = (IVariable)pContext.CurrentScope.resolve(varName);
if (var != null)
{
if (var.VariableScope == VariableScope.DataSource)
{
//IVariable fieldVar = new DataSourceVariableRedefined(var.Name, var.DataType);
//fieldVar.PromptText = var.PromptText;
//fieldVar.Expression = value.ToString();
pContext.CurrentScope.undefine(var.Name);
pContext.CurrentScope.define(var);
}
else
{
if (value != null)
{
var.Expression = value.ToString();
}
else
{
var.Expression = "Null";
}
}
}
else
{
if (value != null)
{
pContext.EnterCheckCodeInterface.Assign(varName, value);
}
}
return false;
}
private static EpiInfo.Plugin.DataType GuessDataTypeFromExpression(string expression)
{
double d = 0.0;
DateTime dt;
if (double.TryParse(expression, out d))
{
return DataType.Number;
}
if (System.Text.RegularExpressions.Regex.IsMatch(expression, "([+,-])"))
{
return DataType.Boolean;
}
if (DateTime.TryParse(expression, out dt))
{
return DataType.Date;
}
return DataType.Unknown;
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Studio.Core.CorePublic
File: StrategyInfo.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Studio.Core
{
using System;
using System.ComponentModel;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using Ecng.ComponentModel;
using Ecng.Serialization;
using StockSharp.Algo;
using StockSharp.Algo.Strategies;
using StockSharp.Localization;
public enum StrategyInfoStates
{
[EnumDisplayNameLoc(LocalizedStrings.Str3178Key)]
Stopped,
[EnumDisplayNameLoc(LocalizedStrings.Str3179Key)]
Runned,
}
public enum StrategyInfoTypes
{
[EnumDisplayNameLoc(LocalizedStrings.Str3180Key)]
SourceCode,
[EnumDisplayNameLoc(LocalizedStrings.Str3181Key)]
Diagram,
[EnumDisplayNameLoc(LocalizedStrings.Str3182Key)]
Assembly,
[EnumDisplayNameLoc(LocalizedStrings.Str1221Key)]
Analytics,
[EnumDisplayNameLoc(LocalizedStrings.Str3183Key)]
Terminal,
}
[DisplayNameLoc(LocalizedStrings.StrategyKey)]
[DescriptionLoc(LocalizedStrings.Str3184Key)]
public class StrategyInfo : NotifiableObject
{
public StrategyInfo()
{
_strategies = new SynchronizedList<StrategyContainer>();
_strategies.Added += s => s.ProcessStateChanged += StrategyProcessStateChanged;
_strategies.Removed += s => s.ProcessStateChanged -= StrategyProcessStateChanged;
}
[Identity]
[Field("Id", ReadOnly = true)]
[Browsable(false)]
public long Id { get; set; }
private string _name;
[DisplayNameLoc(LocalizedStrings.NameKey)]
[DescriptionLoc(LocalizedStrings.Str1359Key)]
[CategoryLoc(LocalizedStrings.Str1559Key)]
public string Name
{
get { return _name; }
set
{
_name = value;
NotifyChanged("Name");
}
}
private string _description;
[DisplayNameLoc(LocalizedStrings.DescriptionKey)]
[DescriptionLoc(LocalizedStrings.Str3185Key)]
[CategoryLoc(LocalizedStrings.Str1559Key)]
public string Description
{
get { return _description; }
set
{
_description = value;
NotifyChanged("Description");
}
}
[DisplayNameLoc(LocalizedStrings.StateKey)]
[DescriptionLoc(LocalizedStrings.Str3186Key)]
[CategoryLoc(LocalizedStrings.Str1559Key)]
public StrategyInfoStates State
{
get
{
return Strategies.Any(s => s.ProcessState != ProcessStates.Stopped)
? StrategyInfoStates.Runned
: StrategyInfoStates.Stopped;
}
}
[DisplayNameLoc(LocalizedStrings.TypeKey)]
[DescriptionLoc(LocalizedStrings.Str3187Key)]
[CategoryLoc(LocalizedStrings.Str1559Key)]
[ReadOnly(true)]
public StrategyInfoTypes Type { get; set; }
private string _body;
[Browsable(false)]
public string Body
{
get { return _body; }
set
{
_body = value;
NotifyChanged("Body");
}
}
private Type _strategyType;
[Browsable(false)]
[Ignore]
public Type StrategyType
{
get { return _strategyType; }
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (_strategyType == value)
return;
_strategyType = value;
_strategyTypeName = value.GetTypeName(false);
NotifyChanged("StrategyType");
NotifyChanged("StrategyTypeName");
}
}
private string _strategyTypeName;
[DisplayNameLoc(LocalizedStrings.Str3188Key)]
[DescriptionLoc(LocalizedStrings.Str3189Key)]
[CategoryLoc(LocalizedStrings.Str1559Key)]
[ReadOnly(true)]
public string StrategyTypeName
{
get { return _strategyTypeName; }
set
{
if (StrategyType != null)
throw new InvalidOperationException(LocalizedStrings.Str3190Params.Put(StrategyType.Name));
_strategyTypeName = value;
NotifyChanged("StrategyTypeName");
}
}
private readonly SynchronizedList<StrategyContainer> _strategies;
[Browsable(false)]
[Ignore]
public SynchronizedList<StrategyContainer> Strategies => _strategies;
[DisplayNameLoc(LocalizedStrings.Str2804Key)]
[DescriptionLoc(LocalizedStrings.Str3191Key)]
[CategoryLoc(LocalizedStrings.Str1559Key)]
[ReadOnly(true)]
public string Path { get; set; }
[Browsable(false)]
public byte[] Assembly { get; set; }
[RelationSingle]
[Browsable(false)]
public Session Session { get; set; }
public StrategyInfo Clone()
{
return new StrategyInfo
{
Id = Id,
Name = Name,
Description = Description,
Type = Type,
Body = Body,
//CompiledType = CompiledType,
StrategyType = StrategyType,
Assembly = Assembly,
Path = Path,
};
}
private void StrategyProcessStateChanged(Strategy s)
{
NotifyChanged("State");
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// MemberResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Api.V2010.Account.Queue
{
public class MemberResource : Resource
{
private static Request BuildFetchRequest(FetchMemberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Queues/" + options.PathQueueSid + "/Members/" + options.PathCallSid + ".json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Fetch a specific member from the queue
/// </summary>
/// <param name="options"> Fetch Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Fetch(FetchMemberOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Fetch a specific member from the queue
/// </summary>
/// <param name="options"> Fetch Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> FetchAsync(FetchMemberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Fetch a specific member from the queue
/// </summary>
/// <param name="pathQueueSid"> The SID of the Queue in which to find the members </param>
/// <param name="pathCallSid"> The Call SID of the resource(s) to fetch </param>
/// <param name="pathAccountSid"> The SID of the Account that created the resource(s) to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Fetch(string pathQueueSid,
string pathCallSid,
string pathAccountSid = null,
ITwilioRestClient client = null)
{
var options = new FetchMemberOptions(pathQueueSid, pathCallSid){PathAccountSid = pathAccountSid};
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Fetch a specific member from the queue
/// </summary>
/// <param name="pathQueueSid"> The SID of the Queue in which to find the members </param>
/// <param name="pathCallSid"> The Call SID of the resource(s) to fetch </param>
/// <param name="pathAccountSid"> The SID of the Account that created the resource(s) to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> FetchAsync(string pathQueueSid,
string pathCallSid,
string pathAccountSid = null,
ITwilioRestClient client = null)
{
var options = new FetchMemberOptions(pathQueueSid, pathCallSid){PathAccountSid = pathAccountSid};
return await FetchAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateMemberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Queues/" + options.PathQueueSid + "/Members/" + options.PathCallSid + ".json",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Dequeue a member from a queue and have the member's call begin executing the TwiML document at that URL
/// </summary>
/// <param name="options"> Update Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Update(UpdateMemberOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Dequeue a member from a queue and have the member's call begin executing the TwiML document at that URL
/// </summary>
/// <param name="options"> Update Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> UpdateAsync(UpdateMemberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Dequeue a member from a queue and have the member's call begin executing the TwiML document at that URL
/// </summary>
/// <param name="pathQueueSid"> The SID of the Queue in which to find the members </param>
/// <param name="pathCallSid"> The Call SID of the resource(s) to update </param>
/// <param name="url"> The absolute URL of the Queue resource </param>
/// <param name="pathAccountSid"> The SID of the Account that created the resource(s) to update </param>
/// <param name="method"> How to pass the update request data </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static MemberResource Update(string pathQueueSid,
string pathCallSid,
Uri url,
string pathAccountSid = null,
Twilio.Http.HttpMethod method = null,
ITwilioRestClient client = null)
{
var options = new UpdateMemberOptions(pathQueueSid, pathCallSid, url){PathAccountSid = pathAccountSid, Method = method};
return Update(options, client);
}
#if !NET35
/// <summary>
/// Dequeue a member from a queue and have the member's call begin executing the TwiML document at that URL
/// </summary>
/// <param name="pathQueueSid"> The SID of the Queue in which to find the members </param>
/// <param name="pathCallSid"> The Call SID of the resource(s) to update </param>
/// <param name="url"> The absolute URL of the Queue resource </param>
/// <param name="pathAccountSid"> The SID of the Account that created the resource(s) to update </param>
/// <param name="method"> How to pass the update request data </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<MemberResource> UpdateAsync(string pathQueueSid,
string pathCallSid,
Uri url,
string pathAccountSid = null,
Twilio.Http.HttpMethod method = null,
ITwilioRestClient client = null)
{
var options = new UpdateMemberOptions(pathQueueSid, pathCallSid, url){PathAccountSid = pathAccountSid, Method = method};
return await UpdateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadMemberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Queues/" + options.PathQueueSid + "/Members.json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve the members of the queue
/// </summary>
/// <param name="options"> Read Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static ResourceSet<MemberResource> Read(ReadMemberOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<MemberResource>.FromJson("queue_members", response.Content);
return new ResourceSet<MemberResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve the members of the queue
/// </summary>
/// <param name="options"> Read Member parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<ResourceSet<MemberResource>> ReadAsync(ReadMemberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<MemberResource>.FromJson("queue_members", response.Content);
return new ResourceSet<MemberResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve the members of the queue
/// </summary>
/// <param name="pathQueueSid"> The SID of the Queue in which to find the members </param>
/// <param name="pathAccountSid"> The SID of the Account that created the resource(s) to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Member </returns>
public static ResourceSet<MemberResource> Read(string pathQueueSid,
string pathAccountSid = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadMemberOptions(pathQueueSid){PathAccountSid = pathAccountSid, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve the members of the queue
/// </summary>
/// <param name="pathQueueSid"> The SID of the Queue in which to find the members </param>
/// <param name="pathAccountSid"> The SID of the Account that created the resource(s) to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Member </returns>
public static async System.Threading.Tasks.Task<ResourceSet<MemberResource>> ReadAsync(string pathQueueSid,
string pathAccountSid = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadMemberOptions(pathQueueSid){PathAccountSid = pathAccountSid, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<MemberResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<MemberResource>.FromJson("queue_members", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<MemberResource> NextPage(Page<MemberResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<MemberResource>.FromJson("queue_members", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<MemberResource> PreviousPage(Page<MemberResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<MemberResource>.FromJson("queue_members", response.Content);
}
/// <summary>
/// Converts a JSON string into a MemberResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> MemberResource object represented by the provided JSON </returns>
public static MemberResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<MemberResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The SID of the Call the resource is associated with
/// </summary>
[JsonProperty("call_sid")]
public string CallSid { get; private set; }
/// <summary>
/// The date the member was enqueued
/// </summary>
[JsonProperty("date_enqueued")]
public DateTime? DateEnqueued { get; private set; }
/// <summary>
/// This member's current position in the queue.
/// </summary>
[JsonProperty("position")]
public int? Position { get; private set; }
/// <summary>
/// The URI of the resource, relative to `https://api.twilio.com`
/// </summary>
[JsonProperty("uri")]
public string Uri { get; private set; }
/// <summary>
/// The number of seconds the member has been in the queue.
/// </summary>
[JsonProperty("wait_time")]
public int? WaitTime { get; private set; }
/// <summary>
/// The SID of the Queue the member is in
/// </summary>
[JsonProperty("queue_sid")]
public string QueueSid { get; private set; }
private MemberResource()
{
}
}
}
| |
#region License
/*
* HttpListenerWebSocketContext.cs
*
* The MIT License
*
* Copyright (c) 2012-2013 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Principal;
namespace WebSocketSharp.Net.WebSockets
{
/// <summary>
/// Provides access to the WebSocket connection request objects received by the <see cref="HttpListener"/>.
/// </summary>
/// <remarks>
/// </remarks>
public class HttpListenerWebSocketContext : WebSocketContext
{
#region Private Fields
private HttpListenerContext _context;
private WebSocket _websocket;
private WsStream _stream;
#endregion
#region Internal Constructors
internal HttpListenerWebSocketContext (HttpListenerContext context)
{
_context = context;
_stream = WsStream.CreateServerStream (context);
_websocket = new WebSocket (this);
}
#endregion
#region Internal Properties
internal WsStream Stream {
get {
return _stream;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets the cookies used in the WebSocket opening handshake.
/// </summary>
/// <value>
/// A <see cref="WebSocketSharp.Net.CookieCollection"/> that contains the cookies.
/// </value>
public override CookieCollection CookieCollection {
get {
return _context.Request.Cookies;
}
}
/// <summary>
/// Gets the HTTP headers used in the WebSocket opening handshake.
/// </summary>
/// <value>
/// A <see cref="System.Collections.Specialized.NameValueCollection"/> that contains the HTTP headers.
/// </value>
public override NameValueCollection Headers {
get {
return _context.Request.Headers;
}
}
/// <summary>
/// Gets the value of the Host header field used in the WebSocket opening handshake.
/// </summary>
/// <value>
/// A <see cref="string"/> that contains the value of the Host header field.
/// </value>
public override string Host {
get {
return _context.Request.Headers ["Host"];
}
}
/// <summary>
/// Gets a value indicating whether the client is authenticated.
/// </summary>
/// <value>
/// <c>true</c> if the client is authenticated; otherwise, <c>false</c>.
/// </value>
public override bool IsAuthenticated {
get {
return _context.Request.IsAuthenticated;
}
}
/// <summary>
/// Gets a value indicating whether the client connected from the local computer.
/// </summary>
/// <value>
/// <c>true</c> if the client connected from the local computer; otherwise, <c>false</c>.
/// </value>
public override bool IsLocal {
get {
return _context.Request.IsLocal;
}
}
/// <summary>
/// Gets a value indicating whether the WebSocket connection is secured.
/// </summary>
/// <value>
/// <c>true</c> if the WebSocket connection is secured; otherwise, <c>false</c>.
/// </value>
public override bool IsSecureConnection {
get {
return _context.Request.IsSecureConnection;
}
}
/// <summary>
/// Gets a value indicating whether the request is a WebSocket connection request.
/// </summary>
/// <value>
/// <c>true</c> if the request is a WebSocket connection request; otherwise, <c>false</c>.
/// </value>
public override bool IsWebSocketRequest {
get {
return _context.Request.IsWebSocketRequest;
}
}
/// <summary>
/// Gets the value of the Origin header field used in the WebSocket opening handshake.
/// </summary>
/// <value>
/// A <see cref="string"/> that contains the value of the Origin header field.
/// </value>
public override string Origin {
get {
return _context.Request.Headers ["Origin"];
}
}
/// <summary>
/// Gets the absolute path of the requested WebSocket URI.
/// </summary>
/// <value>
/// A <see cref="string"/> that contains the absolute path of the requested WebSocket URI.
/// </value>
public override string Path {
get {
return RequestUri.GetAbsolutePath ();
}
}
/// <summary>
/// Gets the collection of query string variables used in the WebSocket opening handshake.
/// </summary>
/// <value>
/// A <see cref="NameValueCollection"/> that contains the collection of query string variables.
/// </value>
public override NameValueCollection QueryString {
get {
return _context.Request.QueryString;
}
}
/// <summary>
/// Gets the WebSocket URI requested by the client.
/// </summary>
/// <value>
/// A <see cref="Uri"/> that contains the WebSocket URI.
/// </value>
public override Uri RequestUri {
get {
return _context.Request.RawUrl.ToUri ();
}
}
/// <summary>
/// Gets the value of the Sec-WebSocket-Key header field used in the WebSocket opening handshake.
/// </summary>
/// <remarks>
/// The SecWebSocketKey property provides a part of the information used by the server to prove that it received a valid WebSocket opening handshake.
/// </remarks>
/// <value>
/// A <see cref="string"/> that contains the value of the Sec-WebSocket-Key header field.
/// </value>
public override string SecWebSocketKey {
get {
return _context.Request.Headers ["Sec-WebSocket-Key"];
}
}
/// <summary>
/// Gets the values of the Sec-WebSocket-Protocol header field used in the WebSocket opening handshake.
/// </summary>
/// <remarks>
/// The SecWebSocketProtocols property indicates the subprotocols of the WebSocket connection.
/// </remarks>
/// <value>
/// An IEnumerable<string> that contains the values of the Sec-WebSocket-Protocol header field.
/// </value>
public override IEnumerable<string> SecWebSocketProtocols {
get {
return _context.Request.Headers.GetValues ("Sec-WebSocket-Protocol");
}
}
/// <summary>
/// Gets the value of the Sec-WebSocket-Version header field used in the WebSocket opening handshake.
/// </summary>
/// <remarks>
/// The SecWebSocketVersion property indicates the WebSocket protocol version of the connection.
/// </remarks>
/// <value>
/// A <see cref="string"/> that contains the value of the Sec-WebSocket-Version header field.
/// </value>
public override string SecWebSocketVersion {
get {
return _context.Request.Headers ["Sec-WebSocket-Version"];
}
}
/// <summary>
/// Gets the server endpoint as an IP address and a port number.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that contains the server endpoint.
/// </value>
public override System.Net.IPEndPoint ServerEndPoint {
get {
return _context.Connection.LocalEndPoint;
}
}
/// <summary>
/// Gets the client information (identity, authentication information and security roles).
/// </summary>
/// <value>
/// A <see cref="IPrincipal"/> that contains the client information.
/// </value>
public override IPrincipal User {
get {
return _context.User;
}
}
/// <summary>
/// Gets the client endpoint as an IP address and a port number.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that contains the client endpoint.
/// </value>
public override System.Net.IPEndPoint UserEndPoint {
get {
return _context.Connection.RemoteEndPoint;
}
}
/// <summary>
/// Gets the WebSocket instance used for two-way communication between client and server.
/// </summary>
/// <value>
/// A <see cref="WebSocketSharp.WebSocket"/>.
/// </value>
public override WebSocket WebSocket {
get {
return _websocket;
}
}
#endregion
#region Internal Methods
internal void Close ()
{
_context.Connection.Close (true);
}
#endregion
#region Public Methods
/// <summary>
/// Returns a <see cref="string"/> that represents the current <see cref="HttpListenerWebSocketContext"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the current <see cref="HttpListenerWebSocketContext"/>.
/// </returns>
public override string ToString ()
{
return _context.Request.ToString ();
}
#endregion
}
}
| |
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 RisNotum class.
/// </summary>
[Serializable]
public partial class RisNotumCollection : ActiveList<RisNotum, RisNotumCollection>
{
public RisNotumCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>RisNotumCollection</returns>
public RisNotumCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
RisNotum 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 RIS_Nota table.
/// </summary>
[Serializable]
public partial class RisNotum : ActiveRecord<RisNotum>, IActiveRecord
{
#region .ctors and Default Settings
public RisNotum()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public RisNotum(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public RisNotum(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public RisNotum(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("RIS_Nota", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdNota = new TableSchema.TableColumn(schema);
colvarIdNota.ColumnName = "idNota";
colvarIdNota.DataType = DbType.Int32;
colvarIdNota.MaxLength = 0;
colvarIdNota.AutoIncrement = true;
colvarIdNota.IsNullable = false;
colvarIdNota.IsPrimaryKey = true;
colvarIdNota.IsForeignKey = false;
colvarIdNota.IsReadOnly = false;
colvarIdNota.DefaultSetting = @"";
colvarIdNota.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdNota);
TableSchema.TableColumn colvarIdEstudio = new TableSchema.TableColumn(schema);
colvarIdEstudio.ColumnName = "idEstudio";
colvarIdEstudio.DataType = DbType.Int32;
colvarIdEstudio.MaxLength = 0;
colvarIdEstudio.AutoIncrement = false;
colvarIdEstudio.IsNullable = false;
colvarIdEstudio.IsPrimaryKey = false;
colvarIdEstudio.IsForeignKey = false;
colvarIdEstudio.IsReadOnly = false;
colvarIdEstudio.DefaultSetting = @"";
colvarIdEstudio.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdEstudio);
TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema);
colvarDescripcion.ColumnName = "descripcion";
colvarDescripcion.DataType = DbType.String;
colvarDescripcion.MaxLength = 4000;
colvarDescripcion.AutoIncrement = false;
colvarDescripcion.IsNullable = true;
colvarDescripcion.IsPrimaryKey = false;
colvarDescripcion.IsForeignKey = false;
colvarDescripcion.IsReadOnly = false;
colvarDescripcion.DefaultSetting = @"";
colvarDescripcion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDescripcion);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("RIS_Nota",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdNota")]
[Bindable(true)]
public int IdNota
{
get { return GetColumnValue<int>(Columns.IdNota); }
set { SetColumnValue(Columns.IdNota, value); }
}
[XmlAttribute("IdEstudio")]
[Bindable(true)]
public int IdEstudio
{
get { return GetColumnValue<int>(Columns.IdEstudio); }
set { SetColumnValue(Columns.IdEstudio, value); }
}
[XmlAttribute("Descripcion")]
[Bindable(true)]
public string Descripcion
{
get { return GetColumnValue<string>(Columns.Descripcion); }
set { SetColumnValue(Columns.Descripcion, value); }
}
#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 varIdEstudio,string varDescripcion)
{
RisNotum item = new RisNotum();
item.IdEstudio = varIdEstudio;
item.Descripcion = varDescripcion;
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 varIdNota,int varIdEstudio,string varDescripcion)
{
RisNotum item = new RisNotum();
item.IdNota = varIdNota;
item.IdEstudio = varIdEstudio;
item.Descripcion = varDescripcion;
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 IdNotaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdEstudioColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn DescripcionColumn
{
get { return Schema.Columns[2]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdNota = @"idNota";
public static string IdEstudio = @"idEstudio";
public static string Descripcion = @"descripcion";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections.Generic;
using System.Threading;
namespace Aurora.Framework
{
#region LockFreeQueue from http://www.boyet.com/Articles/LockfreeStack.html. Thanks to Julian M. Bucknall.
internal class SingleLinkNode<T>
{
// Note; the Next member cannot be a property since it participates in
// many CAS operations
public T Item;
public SingleLinkNode<T> Next;
}
public interface IPriorityConverter<P>
{
int PriorityCount { get; }
int Convert(P priority);
}
public class LimitedPriorityQueue<T, P>
{
private readonly IPriorityConverter<P> converter;
private readonly LockFreeQueue<T>[] queueList;
public LimitedPriorityQueue(IPriorityConverter<P> converter)
{
this.converter = converter;
this.queueList = new LockFreeQueue<T>[converter.PriorityCount];
for (int i = 0; i < queueList.Length; i++)
{
queueList[i] = new LockFreeQueue<T>();
}
}
public void Enqueue(T item, P priority)
{
this.queueList[converter.Convert(priority)].Enqueue(item);
}
public bool Dequeue(out T item)
{
foreach (LockFreeQueue<T> q in queueList)
{
if (q.Dequeue(out item))
{
return true;
}
}
item = default(T);
return false;
}
public T Dequeue()
{
T result;
Dequeue(out result);
return result;
}
}
public class LockFreeQueue<T>
{
private SingleLinkNode<T> head;
private SingleLinkNode<T> tail;
public LockFreeQueue()
{
head = new SingleLinkNode<T>();
tail = head;
}
public void Enqueue(T item)
{
SingleLinkNode<T> oldTail = null;
SingleLinkNode<T> oldTailNext;
SingleLinkNode<T> newNode = new SingleLinkNode<T> {Item = item};
bool newNodeWasAdded = false;
while (!newNodeWasAdded)
{
oldTail = tail;
oldTailNext = oldTail.Next;
if (tail == oldTail)
{
if (oldTailNext == null)
newNodeWasAdded = SyncMethods.CAS(ref tail.Next, null, newNode);
else
SyncMethods.CAS(ref tail, oldTail, oldTailNext);
}
}
SyncMethods.CAS(ref tail, oldTail, newNode);
}
public bool Dequeue(out T item)
{
item = default(T);
SingleLinkNode<T> oldHead = null;
bool haveAdvancedHead = false;
while (!haveAdvancedHead)
{
oldHead = head;
SingleLinkNode<T> oldTail = tail;
SingleLinkNode<T> oldHeadNext = oldHead.Next;
if (oldHead == head)
{
if (oldHead == oldTail)
{
if (oldHeadNext == null)
{
return false;
}
SyncMethods.CAS(ref tail, oldTail, oldHeadNext);
}
else
{
item = oldHeadNext.Item;
haveAdvancedHead =
SyncMethods.CAS(ref head, oldHead, oldHeadNext);
}
}
}
return true;
}
public T Dequeue()
{
T result;
Dequeue(out result);
return result;
}
}
public static class SyncMethods
{
public static bool CAS<T>(ref T location, T comparand, T newValue) where T : class
{
return
comparand ==
Interlocked.CompareExchange(ref location, newValue, comparand);
}
}
#endregion
public sealed class LocklessQueue<T>
{
private int count;
private SingleLinkNode head;
private SingleLinkNode tail;
public LocklessQueue()
{
Init();
}
public int Count
{
get { return count; }
}
public void Enqueue(T item)
{
SingleLinkNode oldTail = null;
SingleLinkNode oldTailNext;
SingleLinkNode newNode = new SingleLinkNode {Item = item};
bool newNodeWasAdded = false;
while (!newNodeWasAdded)
{
oldTail = tail;
oldTailNext = oldTail.Next;
if (tail == oldTail)
{
if (oldTailNext == null)
newNodeWasAdded = CAS(ref tail.Next, null, newNode);
else
CAS(ref tail, oldTail, oldTailNext);
}
}
CAS(ref tail, oldTail, newNode);
Interlocked.Increment(ref count);
}
public bool Dequeue(out T item)
{
item = default(T);
SingleLinkNode oldHead = null;
bool haveAdvancedHead = false;
while (!haveAdvancedHead)
{
oldHead = head;
SingleLinkNode oldTail = tail;
SingleLinkNode oldHeadNext = oldHead.Next;
if (oldHead == head)
{
if (oldHead == oldTail)
{
if (oldHeadNext == null)
return false;
CAS(ref tail, oldTail, oldHeadNext);
}
else
{
item = oldHeadNext.Item;
haveAdvancedHead = CAS(ref head, oldHead, oldHeadNext);
}
}
}
Interlocked.Decrement(ref count);
return true;
}
public bool Dequeue(int num, out List<T> items)
{
items = new List<T>(num);
SingleLinkNode oldHead = null;
bool haveAdvancedHead = false;
for (int i = 0; i < num; i++)
{
while (!haveAdvancedHead)
{
oldHead = head;
SingleLinkNode oldTail = tail;
SingleLinkNode oldHeadNext = oldHead.Next;
if (oldHead == head)
{
if (oldHead == oldTail)
{
if (oldHeadNext == null)
return false;
CAS(ref tail, oldTail, oldHeadNext);
}
else
{
items.Add(oldHeadNext.Item);
haveAdvancedHead = CAS(ref head, oldHead, oldHeadNext);
}
}
}
}
Interlocked.Decrement(ref count);
return true;
}
public void Clear()
{
Init();
}
private void Init()
{
count = 0;
head = tail = new SingleLinkNode();
}
private static bool CAS(ref SingleLinkNode location, SingleLinkNode comparand, SingleLinkNode newValue)
{
return
comparand ==
Interlocked.CompareExchange(ref location, newValue, comparand);
}
#region Nested type: SingleLinkNode
private sealed class SingleLinkNode
{
public T Item;
public SingleLinkNode Next;
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EntityProvider.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// <summary>
// The entity provider class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// -------------------------------------------------------------------------------------------
namespace Sitecore.Ecommerce.Data
{
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Linq;
using Diagnostics;
using DomainModel.Configurations;
using DomainModel.Data;
using Globalization;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
/// <summary>
/// The entity provider class.
/// </summary>
/// <typeparam name="T">The container interface.</typeparam>
public class EntityProvider<T> : ProviderBase, IEntityProvider<T> where T : class
{
/// <summary>
/// The configuration provider.
/// </summary>
private readonly IDataMapper dataMapper;
/// <summary>
/// The containers root item id.
/// </summary>
private string settingName;
/// <summary>
/// The default container name.
/// </summary>
private string defaultContainerName;
/// <summary>
/// The container item template Id.
/// </summary>
private string containersItemTemplateId;
/// <summary>
/// Initializes a new instance of the <see cref="EntityProvider<T>"/> class.
/// </summary>
public EntityProvider()
{
this.dataMapper = Context.Entity.Resolve<IDataMapper>();
}
/// <summary>
/// Gets the shop context.
/// </summary>
/// <value>
/// The shop context.
/// </value>
[CanBeNull]
public ShopContext ShopContext
{
get { return Context.Entity.Resolve<ShopContext>(); }
}
/// <summary>
/// Gets the containers root item.
/// </summary>
/// <value>The containers root item.</value>
[CanBeNull]
protected virtual Item ContainersRootItem
{
get
{
EntityHelper entityHelper = Context.Entity.Resolve<EntityHelper>();
string rootItemPath = entityHelper.GetPropertyValueByField<string, BusinessCatalogSettings>(this.BusinessCatalogSettings, this.settingName);
if (string.IsNullOrEmpty(rootItemPath) || !ID.IsID(rootItemPath))
{
Log.Warn("Site container root path is invalid", this);
return default(Item);
}
Assert.IsNotNull(this.Database, "Cannot get current database");
Item rootItem = this.Database.GetItem(rootItemPath);
if (rootItem == null)
{
Log.Warn("Site container root item is null", this);
return default(Item);
}
return rootItem;
}
}
/// <summary>
/// Gets the business catalog settings.
/// </summary>
/// <value>The business catalog settings.</value>
[NotNull]
private BusinessCatalogSettings BusinessCatalogSettings
{
get
{
Assert.IsNotNull(this.ShopContext, "Unable to resolve business settings. Context shop cannot be null.");
Assert.IsNotNull(this.ShopContext.BusinessCatalogSettings, "Business Catalog settings not found.");
return this.ShopContext.BusinessCatalogSettings;
}
}
/// <summary>
/// Gets the business catalog settings.
/// </summary>
/// <value>The business catalog settings.</value>
[NotNull]
private GeneralSettings GeneralSettings
{
get
{
Assert.IsNotNull(this.ShopContext, "Unable to resolve general settings. Context shop cannot be null.");
Assert.IsNotNull(this.ShopContext.GeneralSettings, "General settings not found.");
return this.ShopContext.GeneralSettings;
}
}
/// <summary>
/// Gets the product repository database.
/// </summary>
/// <value>The database.</value>
[NotNull]
private Database Database
{
get
{
Assert.IsNotNull(this.ShopContext, "Unable to resolve database. Context shop cannot be null.");
Assert.IsNotNull(this.ShopContext.Database, "Unable to resolve database.");
return this.ShopContext.Database;
}
}
/// <summary>
/// Initializes the provider.
/// </summary>
/// <param name="name">The friendly name of the provider.</param>
/// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
/// <exception cref="T:System.ArgumentNullException">
/// The name of the provider is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// The name of the provider has a length of zero.
/// </exception>
/// <exception cref="T:System.InvalidOperationException">
/// An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/> on a provider after the provider has already been initialized.
/// </exception>
public override void Initialize(string name, NameValueCollection config)
{
Assert.ArgumentNotNullOrEmpty(name, "name");
Assert.ArgumentNotNull(config, "config");
base.Initialize(name, config);
this.settingName = config["setting name"];
config.Remove("setting name");
this.defaultContainerName = config["default container name"];
config.Remove("default container name");
this.containersItemTemplateId = config["containers item template Id"];
config.Remove("containers item template Id");
}
/// <summary>
/// Gets the default value.
/// </summary>
/// <returns>
/// The default value of container.
/// </returns>
[CanBeNull]
public virtual T GetDefault()
{
EntityHelper entityHelper = Context.Entity.Resolve<EntityHelper>();
IDictionary<string, object> fieldsCollection = entityHelper.GetPropertiesValues(this.GeneralSettings);
string defaultItemId = string.Empty;
if (fieldsCollection.ContainsKey(this.defaultContainerName))
{
defaultItemId = fieldsCollection[this.defaultContainerName] as string;
}
if (!string.IsNullOrEmpty(defaultItemId) && ID.IsID(defaultItemId))
{
Item item = ItemManager.GetItem(defaultItemId, Language.Current, Version.Latest, Sitecore.Context.Database);
if (item != null)
{
return this.dataMapper.GetEntity<T>(item);
}
}
if (Sitecore.Context.Item == null)
{
return this.GetAll().FirstOrDefault();
}
string defaultContainer = Sitecore.Context.Item[this.defaultContainerName];
if (string.IsNullOrEmpty(defaultContainer))
{
return this.GetAll().FirstOrDefault();
}
Assert.IsNotNull(this.ContainersRootItem, "Unable to get default container value. ContainerRootItem cannot be null.");
Item defaultContainerItem = this.ContainersRootItem.Children[new ID(defaultContainer)];
return defaultContainerItem != null
? this.dataMapper.GetEntity<T>(defaultContainerItem)
: this.GetAll().FirstOrDefault();
}
/// <summary>
/// Gets all containers.
/// </summary>
/// <returns>
/// The site containers collection
/// </returns>
[NotNull]
public virtual IEnumerable<T> GetAll()
{
if (this.ContainersRootItem == null)
{
yield break;
}
foreach (Item item in this.ContainersRootItem.Children.Where(i => i.TemplateID.ToString().Equals(this.containersItemTemplateId)))
{
T container = this.dataMapper.GetEntity<T>(item);
yield return container;
}
}
/// <summary>
/// Gets the container by code.
/// </summary>
/// <param name="code">The container code.</param>
/// <returns>
/// The container by code.
/// </returns>
[CanBeNull]
public virtual T Get([NotNull] string code)
{
Assert.ArgumentNotNullOrEmpty(code, "code");
Item item = null;
if (ID.IsID(code) && this.ContainersRootItem != null)
{
item = this.ContainersRootItem.Database.GetItem(code);
}
else if (this.ContainersRootItem != null)
{
item = this.ContainersRootItem.Axes.SelectSingleItem(string.Format("./*[@Code='{0}']", code));
}
if (item == null)
{
return default(T);
}
T container = this.dataMapper.GetEntity<T>(item);
return container;
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// VirtualThumbsticks.cs
//
// Microsoft Advanced Technology Group
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;
#endregion
namespace HoneycombRush
{
/// <summary>
/// Represents virtual thumbsticks which allow touch input.
/// Users can touch the left half of the screen to place the center
/// of the left thumbstick and the right half for the right thumbstick.
/// Users can then drag away from that center to simulate thumbstick input.
///
/// This is a static class with static methods to get the thumbstick properties,
/// for consistency with other XNA input
/// classes like TouchPanel, Gamepad, Keyboard, etc.
/// </summary>
public static class VirtualThumbsticks
{
#region Fields
// the distance in screen pixels that represents a thumbstick value of 1f.
private const float maxThumbstickDistance = 60f;
// the current positions of the physical touches
private static Vector2 leftPosition;
private static Vector2 rightPosition;
// the IDs of the touches we are tracking for the thumbsticks
private static int leftId = -1;
private static int rightId = -1;
/// <summary>
/// Gets the center position of the left thumbstick.
/// </summary>
public static Vector2? LeftThumbstickCenter { get; private set; }
/// <summary>
/// Gets the center position of the right thumbstick.
/// </summary>
public static Vector2? RightThumbstickCenter { get; private set; }
#endregion
/// <summary>
/// Gets the value of the left thumbstick.
/// </summary>
public static Vector2 LeftThumbstick
{
get
{
// if there is no left thumbstick center, return a value of (0, 0)
if (!LeftThumbstickCenter.HasValue)
{
return Vector2.Zero;
}
// calculate the scaled vector from the touch position to the center,
// scaled by the maximum thumbstick distance
Vector2 l = (leftPosition - LeftThumbstickCenter.Value) / maxThumbstickDistance;
// if the length is more than 1, normalize the vector
if (l.LengthSquared() > 1f)
{
l.Normalize();
}
return l;
}
}
/// <summary>
/// Gets the value of the right thumbstick.
/// </summary>
public static Vector2 RightThumbstick
{
get
{
// if there is no left thumbstick center, return a value of (0, 0)
if (!RightThumbstickCenter.HasValue)
{
return Vector2.Zero;
}
// calculate the scaled vector from the touch position to the center,
// scaled by the maximum thumbstick distance
Vector2 r = (rightPosition - RightThumbstickCenter.Value) / maxThumbstickDistance;
// if the length is more than 1, normalize the vector
if (r.LengthSquared() > 1f)
{
r.Normalize();
}
return r;
}
}
/// <summary>
/// Updates the virtual thumbsticks based on current touch state. This must be called every frame.
/// </summary>
public static void Update(InputState input)
{
TouchLocation? leftTouch = null;
TouchLocation? rightTouch = null;
TouchCollection touches = input.TouchState;
// Examine all the touches to convert them to virtual dpad positions. Note that the 'touches'
// collection is the set of all touches at this instant, not a sequence of events. The only
// sequential information we have access to is the previous location for of each touch.
foreach (TouchLocation touch in touches)
{
if (touch.Id == leftId)
{
// This is a motion of a left-stick touch that we're already tracking
leftTouch = touch;
continue;
}
if (touch.Id == rightId)
{
// This is a motion of a right-stick touch that we're already tracking
rightTouch = touch;
continue;
}
// We didn't continue an existing thumbstick gesture; see if we can start a new one.
//
// We'll use the previous touch position if possible, to get as close as possible to where
// the gesture actually began.
TouchLocation earliestTouch;
if (!touch.TryGetPreviousLocation(out earliestTouch))
{
earliestTouch = touch;
}
if (leftId == -1)
{
// if we are not currently tracking a left thumbstick and this touch is on the left
// half of the screen, start tracking this touch as our left stick
if (earliestTouch.Position.X < TouchPanel.DisplayWidth / 2)
{
leftTouch = earliestTouch;
continue;
}
}
if (rightId == -1)
{
// if we are not currently tracking a right thumbstick and this touch is on the right
// half of the screen, start tracking this touch as our right stick
if (earliestTouch.Position.X >= TouchPanel.DisplayWidth / 2)
{
rightTouch = earliestTouch;
continue;
}
}
}
// if we have a left touch
if (leftTouch.HasValue)
{
// if we have no center, this position is our center
if (!LeftThumbstickCenter.HasValue)
{
LeftThumbstickCenter = leftTouch.Value.Position;
}
// save the position of the touch
leftPosition = leftTouch.Value.Position;
// save the ID of the touch
leftId = leftTouch.Value.Id;
}
else
{
// otherwise reset our values to not track any touches
// for the left thumbstick
LeftThumbstickCenter = null;
leftId = -1;
}
// if we have a right touch
if (rightTouch.HasValue)
{
// if we have no center, this position is our center
if (!RightThumbstickCenter.HasValue)
{
RightThumbstickCenter = rightTouch.Value.Position;
}
// save the position of the touch
rightPosition = rightTouch.Value.Position;
// save the ID of the touch
rightId = rightTouch.Value.Id;
}
else
{
// otherwise reset our values to not track any touches
// for the right thumbstick
RightThumbstickCenter = null;
rightId = -1;
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Tools.ToolDialog
// Description: The tool dialog to be used by tools. It get populated by DialogElements once it is created
//
// ********************************************************************************************************
//
// The Original Code is Toolbox.dll for the DotSpatial 4.6/6 ToolManager project
//
// The Initial Developer of this Original Code is Brian Marchionni. Created in Oct, 2008.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DotSpatial.Data;
using DotSpatial.Modeling.Forms.Elements;
using DotSpatial.Modeling.Forms.Parameters;
namespace DotSpatial.Modeling.Forms
{
/// <summary>
/// A generic form that works with the various dialog elements in order to create a fully working process.
/// </summary>
public partial class ToolDialog : Form
{
#region Constants and Fields
private List<DataSetArray> _dataSets = new List<DataSetArray>();
private int _elementHeight = 3;
private readonly Extent _extent;
private readonly List<DialogElement> _listOfDialogElements = new List<DialogElement>();
private ITool _tool;
private readonly IContainer components = null;
#endregion
#region Constructors and Destructors
/// <summary>
/// The constructor for the ToolDialog
/// </summary>
/// <param name="tool">The ITool to create the dialog box for</param>
/// <param name="dataSets">The list of available DataSets available</param>
/// <param name="mapExtent">Creates a new instance of the tool dialog with map extent.</param>
public ToolDialog(ITool tool, List<DataSetArray> dataSets, Extent mapExtent)
{
// Required by the designer
InitializeComponent();
DataSets = dataSets;
_extent = mapExtent;
Initialize(tool);
}
/// <summary>
/// The constructor for the ToolDialog
/// </summary>
/// <param name="tool">The ITool to create the dialog box for</param>
/// <param name="modelElements">A list of all model elements</param>
public ToolDialog(ITool tool, IEnumerable<ModelElement> modelElements)
{
// Required by the designer
InitializeComponent();
// We store all the element names here and extract the datasets
foreach (ModelElement me in modelElements)
{
DataElement de = me as DataElement;
if (de != null)
{
bool addData = true;
foreach (Parameter par in tool.OutputParameters)
{
if (par.ModelName == de.Parameter.ModelName)
{
addData = false;
}
break;
}
if (addData)
{
_dataSets.Add(new DataSetArray(me.Name, de.Parameter.Value as IDataSet));
}
}
}
Initialize(tool);
}
#endregion
#region Public Properties
/// <summary>
/// Returns a list of IDataSet that are available in the ToolDialog excluding any of its own outputs.
/// </summary>
public List<DataSetArray> DataSets
{
get
{
return _dataSets;
}
set
{
_dataSets = value;
}
}
/// <summary>
/// Gets the status of the tool
/// </summary>
public ToolStatus ToolStatus
{
get
{
return _listOfDialogElements.Any(de => de.Status != ToolStatus.Ok) ? ToolStatus.Error : ToolStatus.Ok;
}
}
#endregion
#region Methods
/// <summary>
/// This adds the Elements to the form incrementally lower down
/// </summary>
/// <param name="element">The element to add</param>
private void AddElement(DialogElement element)
{
_listOfDialogElements.Add(element);
panelElementContainer.Controls.Add(element);
element.Clicked += ElementClicked;
element.Location = new Point(5, _elementHeight);
_elementHeight = element.Height + _elementHeight;
}
/// <summary>
/// When one of the DialogElements is clicked this event fires to populate the help
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ElementClicked(object sender, EventArgs e)
{
DialogElement element = sender as DialogElement;
if (element == null)
{
PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage);
}
else if (element.Param == null)
{
PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage);
}
else if (element.Param.HelpText == string.Empty)
{
PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage);
}
else
{
PopulateHelp(element.Param.Name, element.Param.HelpText, element.Param.HelpImage);
}
}
/// <summary>
/// The constructor for the ToolDialog
/// </summary>
/// <param name="tool">The ITool to create the dialog box for</param>
private void Initialize(ITool tool)
{
SuspendLayout();
// Generates the form based on what inputs the ITool has
_tool = tool;
Text = tool.Name;
// Sets up the help link
if (string.IsNullOrEmpty(tool.HelpUrl))
{
helpHyperlink.Visible = false;
}
else
{
helpHyperlink.Links[0].LinkData = tool.HelpUrl;
helpHyperlink.Links.Add(0, helpHyperlink.Text.Length, tool.HelpUrl);
}
// Sets-up the icon for the Dialog
Icon = Images.HammerSmall;
panelToolIcon.BackgroundImage = tool.Icon ?? Images.Hammer;
DialogSpacerElement inputSpacer = new DialogSpacerElement();
inputSpacer.Text = ModelingMessageStrings.Input;
AddElement(inputSpacer);
// Populates the dialog with input elements
PopulateInputElements();
DialogSpacerElement outputSpacer = new DialogSpacerElement();
outputSpacer.Text = ModelingMessageStrings.Output;
AddElement(outputSpacer);
// Populates the dialog with output elements
PopulateOutputElements();
// Populate the help text
PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage);
ResumeLayout();
}
/// <summary>
/// Fires when a parameter is changed
/// </summary>
/// <param name="sender"></param>
private void ParamValueChanged(Parameter sender)
{
_tool.ParameterChanged(sender);
}
/// <summary>
/// This adds a Bitmap to the help section.
/// </summary>
/// <param name="title">The text to appear in the help box.</param>
/// <param name="body">The title to appear in the help box.</param>
/// <param name="image">The bitmap to appear at the bottom of the help box.</param>
private void PopulateHelp(string title, string body, Image image)
{
rtbHelp.Text = string.Empty;
rtbHelp.Size = new Size(0, 0);
// Add the Title
Font fBold = new Font("Tahoma", 14, FontStyle.Bold);
rtbHelp.SelectionFont = fBold;
rtbHelp.SelectionColor = Color.Black;
rtbHelp.SelectedText = title + "\r\n\r\n";
// Add the text body
fBold = new Font("Tahoma", 8, FontStyle.Bold);
rtbHelp.SelectionFont = fBold;
rtbHelp.SelectionColor = Color.Black;
rtbHelp.SelectedText = body;
rtbHelp.Size = new Size(rtbHelp.Width, rtbHelp.GetPositionFromCharIndex(rtbHelp.Text.Length).Y + 30);
// Add the image to the bottom
if (image != null)
{
pnlHelpImage.Visible = true;
if (image.Size.Width > 250)
{
double height = image.Size.Height;
double width = image.Size.Width;
int newHeight = Convert.ToInt32(250 * (height / width));
pnlHelpImage.BackgroundImage = new Bitmap(image, new Size(250, newHeight));
pnlHelpImage.Size = new Size(250, newHeight);
}
else
{
pnlHelpImage.BackgroundImage = image;
pnlHelpImage.Size = image.Size;
}
}
else
{
pnlHelpImage.Visible = false;
pnlHelpImage.BackgroundImage = null;
pnlHelpImage.Size = new Size(0, 0);
}
}
/// <summary>
/// Adds Elements to the dialog based on what input Parameter the ITool contains
/// </summary>
private void PopulateInputElements()
{
// Loops through all the Parameter in the tool and generated their element
foreach (Parameter param in _tool.InputParameters)
{
// We make sure that the input parameter is defined
if (param == null)
{
continue;
}
// We add an event handler that fires if the parameter is changed
param.ValueChanged += ParamValueChanged;
ExtentParam p = param as ExtentParam;
if (p != null && p.DefaultToMapExtent)
{
p.Value = _extent;
}
// Retrieve the dialog element from the parameter and add it to the dialog
AddElement(param.InputDialogElement(DataSets));
}
}
/// <summary>
/// Adds Elements to the dialog based on what output Parameter the ITool contains
/// </summary>
private void PopulateOutputElements()
{
if (_tool.OutputParameters == null)
{
return;
}
// Loops through all the Parameter in the tool and generated their element
foreach (Parameter param in _tool.OutputParameters)
{
// We add an event handler that fires if the parameter is changed
param.ValueChanged += ParamValueChanged;
// Retrieve the dialog element from the parameter and add it to the dialog
AddElement(param.OutputDialogElement(DataSets));
}
}
/// <summary>
/// When the user clicks Cancel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
/// <summary>
/// When the user clicks OK
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOK_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
/// <summary>
/// When the hyperlink is clicked this event fires.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void helpHyperlink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// Determine which link was clicked within the LinkLabel.
helpHyperlink.Links[helpHyperlink.Links.IndexOf(e.Link)].Visited = true;
// Display the appropriate link based on the value of the
// LinkData property of the Link object.
string target = e.Link.LinkData as string;
if (target != null)
Process.Start(target);
}
/// <summary>
/// If the user clicks out side of one of the tool elements
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void otherElement_Click(object sender, EventArgs e)
{
PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage);
}
/// <summary>
/// When the size of the help panel changes this event fires to move stuff around.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelHelp_SizeChanged(object sender, EventArgs e)
{
rtbHelp.Size = new Size(rtbHelp.Width, rtbHelp.GetPositionFromCharIndex(rtbHelp.Text.Length).Y + 30);
}
#endregion
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.ElasticTranscoder.Model
{
/// <summary>
/// <para>Settings for the size, location, and opacity of graphics that you want Elastic Transcoder to overlay over videos that are transcoded
/// using this preset. You can specify settings for up to four watermarks. Watermarks appear in the specified size and location, and with the
/// specified opacity for the duration of the transcoded video.</para> <para>Watermarks can be in .png or .jpg format. If you want to display a
/// watermark that is not rectangular, use the .png format, which supports transparency.</para> <para>When you create a job that uses this
/// preset, you specify the .png or .jpg graphics that you want Elastic Transcoder to include in the transcoded videos. You can specify fewer
/// graphics in the job than you specify watermark settings in the preset, which allows you to use the same preset for up to four watermarks
/// that have different dimensions.</para>
/// </summary>
public class PresetWatermark
{
private string id;
private string maxWidth;
private string maxHeight;
private string sizingPolicy;
private string horizontalAlign;
private string horizontalOffset;
private string verticalAlign;
private string verticalOffset;
private string opacity;
private string target;
/// <summary>
/// A unique identifier for the settings for one watermark. The value of <c>Id</c> can be up to 40 characters long.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 40</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Id
{
get { return this.id; }
set { this.id = value; }
}
/// <summary>
/// Sets the Id property
/// </summary>
/// <param name="id">The value to set for the Id property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public PresetWatermark WithId(string id)
{
this.id = id;
return this;
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this.id != null;
}
/// <summary>
/// The maximum width of the watermark in one of the following formats: <ul> <li>number of pixels (px): The minimum value is 16 pixels, and the
/// maximum value is the value of <c>MaxWidth</c>.</li> <li>integer percentage (%): The range of valid values is 0 to 100. Use the value of
/// <c>Target</c> to specify whether you want Elastic Transcoder to include the black bars that are added by Elastic Transcoder, if any, in the
/// calculation.</li> If you specify the value in pixels, it must be less than or equal to the value of <c>MaxWidth</c>.</ul>
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>(^\d{1,3}([.]\d{0,5})?%$)|(^\d{2,4}?px$)</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string MaxWidth
{
get { return this.maxWidth; }
set { this.maxWidth = value; }
}
/// <summary>
/// Sets the MaxWidth property
/// </summary>
/// <param name="maxWidth">The value to set for the MaxWidth property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public PresetWatermark WithMaxWidth(string maxWidth)
{
this.maxWidth = maxWidth;
return this;
}
// Check to see if MaxWidth property is set
internal bool IsSetMaxWidth()
{
return this.maxWidth != null;
}
/// <summary>
/// The maximum height of the watermark in one of the following formats: <ul> <li>number of pixels (px): The minimum value is 16 pixels, and the
/// maximum value is the value of <c>MaxHeight</c>.</li> <li>integer percentage (%): The range of valid values is 0 to 100. Use the value of
/// <c>Target</c> to specify whether you want Elastic Transcoder to include the black bars that are added by Elastic Transcoder, if any, in the
/// calculation.</li> </ul> If you specify the value in pixels, it must be less than or equal to the value of <c>MaxHeight</c>.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>(^\d{1,3}([.]\d{0,5})?%$)|(^\d{2,4}?px$)</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string MaxHeight
{
get { return this.maxHeight; }
set { this.maxHeight = value; }
}
/// <summary>
/// Sets the MaxHeight property
/// </summary>
/// <param name="maxHeight">The value to set for the MaxHeight property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public PresetWatermark WithMaxHeight(string maxHeight)
{
this.maxHeight = maxHeight;
return this;
}
// Check to see if MaxHeight property is set
internal bool IsSetMaxHeight()
{
return this.maxHeight != null;
}
/// <summary>
/// A value that controls scaling of the watermark: <ul> <li><b>Fit</b>: Elastic Transcoder scales the watermark so it matches the value that
/// you specified in either <c>MaxWidth</c> or <c>MaxHeight</c> without exceeding the other value.</li> <li><b>Stretch</b>: Elastic Transcoder
/// stretches the watermark to match the values that you specified for <c>MaxWidth</c> and <c>MaxHeight</c>. If the relative proportions of the
/// watermark and the values of <c>MaxWidth</c> and <c>MaxHeight</c> are different, the watermark will be distorted.</li>
/// <li><b>ShrinkToFit</b>: Elastic Transcoder scales the watermark down so that its dimensions match the values that you specified for at least
/// one of <c>MaxWidth</c> and <c>MaxHeight</c> without exceeding either value. If you specify this option, Elastic Transcoder does not scale
/// the watermark up.</li></ul>
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>(^Fit$)|(^Stretch$)|(^ShrinkToFit$)</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string SizingPolicy
{
get { return this.sizingPolicy; }
set { this.sizingPolicy = value; }
}
/// <summary>
/// Sets the SizingPolicy property
/// </summary>
/// <param name="sizingPolicy">The value to set for the SizingPolicy property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public PresetWatermark WithSizingPolicy(string sizingPolicy)
{
this.sizingPolicy = sizingPolicy;
return this;
}
// Check to see if SizingPolicy property is set
internal bool IsSetSizingPolicy()
{
return this.sizingPolicy != null;
}
/// <summary>
/// The horizontal position of the watermark unless you specify a non-zero value for <c>HorizontalOffset</c>: <ul> <li><b>Left</b>: The left
/// edge of the watermark is aligned with the left border of the video.</li> <li><b>Right</b>: The right edge of the watermark is aligned with
/// the right border of the video.</li> <li><b>Center</b>: The watermark is centered between the left and right borders.</li></ul>
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>(^Left$)|(^Right$)|(^Center$)</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string HorizontalAlign
{
get { return this.horizontalAlign; }
set { this.horizontalAlign = value; }
}
/// <summary>
/// Sets the HorizontalAlign property
/// </summary>
/// <param name="horizontalAlign">The value to set for the HorizontalAlign property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public PresetWatermark WithHorizontalAlign(string horizontalAlign)
{
this.horizontalAlign = horizontalAlign;
return this;
}
// Check to see if HorizontalAlign property is set
internal bool IsSetHorizontalAlign()
{
return this.horizontalAlign != null;
}
/// <summary>
/// The amount by which you want the horizontal position of the watermark to be offset from the position specified by HorizontalAlign: <ul>
/// <li>number of pixels (px): The minimum value is 0 pixels, and the maximum value is the value of MaxWidth.</li> <li>integer percentage (%):
/// The range of valid values is 0 to 100.</li> </ul>For example, if you specify Left for <c>HorizontalAlign</c> and 5px for
/// <c>HorizontalOffset</c>, the left side of the watermark appears 5 pixels from the left border of the output video. <c>HorizontalOffset</c>
/// is only valid when the value of <c>HorizontalAlign</c> is <c>Left</c> or <c>Right</c>. If you specify an offset that causes the watermark to
/// extend beyond the left or right border and Elastic Transcoder has not added black bars, the watermark is cropped. If Elastic Transcoder has
/// added black bars, the watermark extends into the black bars. If the watermark extends beyond the black bars, it is cropped. Use the value of
/// <c>Target</c> to specify whether you want to include the black bars that are added by Elastic Transcoder, if any, in the offset calculation.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>(^\d{1,3}([.]\d{0,5})?%$)|(^\d{2,4}?px$)</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string HorizontalOffset
{
get { return this.horizontalOffset; }
set { this.horizontalOffset = value; }
}
/// <summary>
/// Sets the HorizontalOffset property
/// </summary>
/// <param name="horizontalOffset">The value to set for the HorizontalOffset property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public PresetWatermark WithHorizontalOffset(string horizontalOffset)
{
this.horizontalOffset = horizontalOffset;
return this;
}
// Check to see if HorizontalOffset property is set
internal bool IsSetHorizontalOffset()
{
return this.horizontalOffset != null;
}
/// <summary>
/// The vertical position of the watermark unless you specify a non-zero value for <c>VerticalOffset</c>: <ul> <li><b>Top</b>: The top edge of
/// the watermark is aligned with the top border of the video.</li> <li><b>Bottom</b>: The bottom edge of the watermark is aligned with the
/// bottom border of the video.</li> <li><b>Center</b>: The watermark is centered between the top and bottom borders.</li></ul>
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>(^Top$)|(^Bottom$)|(^Center$)</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string VerticalAlign
{
get { return this.verticalAlign; }
set { this.verticalAlign = value; }
}
/// <summary>
/// Sets the VerticalAlign property
/// </summary>
/// <param name="verticalAlign">The value to set for the VerticalAlign property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public PresetWatermark WithVerticalAlign(string verticalAlign)
{
this.verticalAlign = verticalAlign;
return this;
}
// Check to see if VerticalAlign property is set
internal bool IsSetVerticalAlign()
{
return this.verticalAlign != null;
}
/// <summary>
/// <c>VerticalOffset</c> The amount by which you want the vertical position of the watermark to be offset from the position specified by
/// VerticalAlign:<ul> <li>number of pixels (px): The minimum value is 0 pixels, and the maximum value is the value of <c>MaxHeight</c>.</li>
/// <li>integer percentage (%): The range of valid values is 0 to 100.</li> </ul> For example, if you specify <c>Top</c> for
/// <c>VerticalAlign</c> and <c>5px</c> for <c>VerticalOffset</c>, the top of the watermark appears 5 pixels from the top border of the output
/// video. <c>VerticalOffset</c> is only valid when the value of VerticalAlign is Top or Bottom. If you specify an offset that causes the
/// watermark to extend beyond the top or bottom border and Elastic Transcoder has not added black bars, the watermark is cropped. If Elastic
/// Transcoder has added black bars, the watermark extends into the black bars. If the watermark extends beyond the black bars, it is cropped.
/// Use the value of <c>Target</c> to specify whether you want Elastic Transcoder to include the black bars that are added by Elastic
/// Transcoder, if any, in the offset calculation.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>(^\d{1,3}([.]\d{0,5})?%$)|(^\d{2,4}?px$)</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string VerticalOffset
{
get { return this.verticalOffset; }
set { this.verticalOffset = value; }
}
/// <summary>
/// Sets the VerticalOffset property
/// </summary>
/// <param name="verticalOffset">The value to set for the VerticalOffset property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public PresetWatermark WithVerticalOffset(string verticalOffset)
{
this.verticalOffset = verticalOffset;
return this;
}
// Check to see if VerticalOffset property is set
internal bool IsSetVerticalOffset()
{
return this.verticalOffset != null;
}
/// <summary>
/// A percentage that indicates how much you want a watermark to obscure the video in the location where it appears. Valid values are 0 (the
/// watermark is invisible) to 100 (the watermark completely obscures the video in the specified location). The datatype of <c>Opacity</c> is
/// float. Elastic Transcoder supports transparent .png graphics. If you use a transparent .png, the transparent portion of the video appears as
/// if you had specified a value of 0 for <c>Opacity</c>. The .jpg file format doesn't support transparency.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>^\d{1,3}([.]\d{0,20})?$</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Opacity
{
get { return this.opacity; }
set { this.opacity = value; }
}
/// <summary>
/// Sets the Opacity property
/// </summary>
/// <param name="opacity">The value to set for the Opacity property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public PresetWatermark WithOpacity(string opacity)
{
this.opacity = opacity;
return this;
}
// Check to see if Opacity property is set
internal bool IsSetOpacity()
{
return this.opacity != null;
}
/// <summary>
/// A value that determines how Elastic Transcoder interprets values that you specified for <c>HorizontalOffset</c>, <c>VerticalOffset</c>,
/// <c>MaxWidth</c>, and <c>MaxHeight</c>: <ul><li><b>Content</b>: <c>HorizontalOffset</c> and <c>VerticalOffset</c> values are calculated based
/// on the borders of the video excluding black bars added by Elastic Transcoder, if any. In addition, <c>MaxWidth</c> and <c>MaxHeight</c>, if
/// specified as a percentage, are calculated based on the borders of the video excluding black bars added by Elastic Transcoder, if any.</li>
/// <li><b>Frame</b>: <c>HorizontalOffset</c> and <c>VerticalOffset</c> values are calculated based on the borders of the video including black
/// bars added by Elastic Transcoder, if any.</li> In addition, <c>MaxWidth</c> and <c>MaxHeight</c>, if specified as a percentage, are
/// calculated based on the borders of the video including black bars added by Elastic Transcoder, if any.</ul>
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>(^Content$)|(^Frame$)</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Target
{
get { return this.target; }
set { this.target = value; }
}
/// <summary>
/// Sets the Target property
/// </summary>
/// <param name="target">The value to set for the Target property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public PresetWatermark WithTarget(string target)
{
this.target = target;
return this;
}
// Check to see if Target property is set
internal bool IsSetTarget()
{
return this.target != null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NPoco;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.Entities;
using Umbraco.Cms.Core.Persistence.Querying;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Infrastructure.Persistence.Dtos;
using Umbraco.Cms.Infrastructure.Persistence.Querying;
using Umbraco.Cms.Infrastructure.Persistence.SqlSyntax;
using Umbraco.Extensions;
using static Umbraco.Cms.Core.Persistence.SqlExtensionsStatics;
namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement
{
/// <summary>
/// Represents the EntityRepository used to query entity objects.
/// </summary>
/// <remarks>
/// <para>Limited to objects that have a corresponding node (in umbracoNode table).</para>
/// <para>Returns <see cref="IEntitySlim"/> objects, i.e. lightweight representation of entities.</para>
/// </remarks>
internal class EntityRepository : RepositoryBase, IEntityRepository
{
public EntityRepository(IScopeAccessor scopeAccessor, AppCaches appCaches)
: base(scopeAccessor, appCaches)
{
}
#region Repository
public IEnumerable<IEntitySlim> GetPagedResultsByQuery(IQuery<IUmbracoEntity> query, Guid objectType, long pageIndex, int pageSize, out long totalRecords,
IQuery<IUmbracoEntity> filter, Ordering ordering)
{
return GetPagedResultsByQuery(query, new[] { objectType }, pageIndex, pageSize, out totalRecords, filter, ordering);
}
// get a page of entities
public IEnumerable<IEntitySlim> GetPagedResultsByQuery(IQuery<IUmbracoEntity> query, Guid[] objectTypes, long pageIndex, int pageSize, out long totalRecords,
IQuery<IUmbracoEntity> filter, Ordering ordering, Action<Sql<ISqlContext>> sqlCustomization = null)
{
var isContent = objectTypes.Any(objectType => objectType == Cms.Core.Constants.ObjectTypes.Document || objectType == Cms.Core.Constants.ObjectTypes.DocumentBlueprint);
var isMedia = objectTypes.Any(objectType => objectType == Cms.Core.Constants.ObjectTypes.Media);
var isMember = objectTypes.Any(objectType => objectType == Cms.Core.Constants.ObjectTypes.Member);
Sql<ISqlContext> sql = GetBaseWhere(isContent, isMedia, isMember, false, s =>
{
sqlCustomization?.Invoke(s);
if (filter != null)
{
foreach (Tuple<string, object[]> filterClause in filter.GetWhereClauses())
{
s.Where(filterClause.Item1, filterClause.Item2);
}
}
}, objectTypes);
ordering = ordering ?? Ordering.ByDefault();
var translator = new SqlTranslator<IUmbracoEntity>(sql, query);
sql = translator.Translate();
sql = AddGroupBy(isContent, isMedia, isMember, sql, ordering.IsEmpty);
if (!ordering.IsEmpty)
{
// apply ordering
ApplyOrdering(ref sql, ordering);
}
// TODO: we should be able to do sql = sql.OrderBy(x => Alias(x.NodeId, "NodeId")); but we can't because the OrderBy extension don't support Alias currently
// no matter what we always must have node id ordered at the end
sql = ordering.Direction == Direction.Ascending ? sql.OrderBy("NodeId") : sql.OrderByDescending("NodeId");
// for content we must query for ContentEntityDto entities to produce the correct culture variant entity names
var pageIndexToFetch = pageIndex + 1;
IEnumerable<BaseDto> dtos;
var page = Database.Page<GenericContentEntityDto>(pageIndexToFetch, pageSize, sql);
dtos = page.Items;
totalRecords = page.TotalItems;
var entities = dtos.Select(BuildEntity).ToArray();
BuildVariants(entities.OfType<DocumentEntitySlim>());
return entities;
}
public IEntitySlim Get(Guid key)
{
var sql = GetBaseWhere(false, false, false, false, key);
var dto = Database.FirstOrDefault<BaseDto>(sql);
return dto == null ? null : BuildEntity(dto);
}
private IEntitySlim GetEntity(Sql<ISqlContext> sql, bool isContent, bool isMedia, bool isMember)
{
// isContent is going to return a 1:M result now with the variants so we need to do different things
if (isContent)
{
var cdtos = Database.Fetch<DocumentEntityDto>(sql);
return cdtos.Count == 0 ? null : BuildVariants(BuildDocumentEntity(cdtos[0]));
}
var dto = isMedia
? Database.FirstOrDefault<MediaEntityDto>(sql)
: Database.FirstOrDefault<BaseDto>(sql);
if (dto == null) return null;
var entity = BuildEntity(dto);
return entity;
}
public IEntitySlim Get(Guid key, Guid objectTypeId)
{
var isContent = objectTypeId == Cms.Core.Constants.ObjectTypes.Document || objectTypeId == Cms.Core.Constants.ObjectTypes.DocumentBlueprint;
var isMedia = objectTypeId == Cms.Core.Constants.ObjectTypes.Media;
var isMember = objectTypeId == Cms.Core.Constants.ObjectTypes.Member;
var sql = GetFullSqlForEntityType(isContent, isMedia, isMember, objectTypeId, key);
return GetEntity(sql, isContent, isMedia, isMember);
}
public IEntitySlim Get(int id)
{
var sql = GetBaseWhere(false, false, false, false, id);
var dto = Database.FirstOrDefault<BaseDto>(sql);
return dto == null ? null : BuildEntity(dto);
}
public IEntitySlim Get(int id, Guid objectTypeId)
{
var isContent = objectTypeId == Cms.Core.Constants.ObjectTypes.Document || objectTypeId == Cms.Core.Constants.ObjectTypes.DocumentBlueprint;
var isMedia = objectTypeId == Cms.Core.Constants.ObjectTypes.Media;
var isMember = objectTypeId == Cms.Core.Constants.ObjectTypes.Member;
var sql = GetFullSqlForEntityType(isContent, isMedia, isMember, objectTypeId, id);
return GetEntity(sql, isContent, isMedia, isMember);
}
public IEnumerable<IEntitySlim> GetAll(Guid objectType, params int[] ids)
{
return ids.Length > 0
? PerformGetAll(objectType, sql => sql.WhereIn<NodeDto>(x => x.NodeId, ids.Distinct()))
: PerformGetAll(objectType);
}
public IEnumerable<IEntitySlim> GetAll(Guid objectType, params Guid[] keys)
{
return keys.Length > 0
? PerformGetAll(objectType, sql => sql.WhereIn<NodeDto>(x => x.UniqueId, keys.Distinct()))
: PerformGetAll(objectType);
}
private IEnumerable<IEntitySlim> GetEntities(Sql<ISqlContext> sql, bool isContent, bool isMedia, bool isMember)
{
// isContent is going to return a 1:M result now with the variants so we need to do different things
if (isContent)
{
var cdtos = Database.Fetch<DocumentEntityDto>(sql);
return cdtos.Count == 0
? Enumerable.Empty<IEntitySlim>()
: BuildVariants(cdtos.Select(BuildDocumentEntity)).ToList();
}
var dtos = isMedia
? (IEnumerable<BaseDto>)Database.Fetch<MediaEntityDto>(sql)
: Database.Fetch<BaseDto>(sql);
var entities = dtos.Select(BuildEntity).ToArray();
return entities;
}
private IEnumerable<IEntitySlim> PerformGetAll(Guid objectType, Action<Sql<ISqlContext>> filter = null)
{
var isContent = objectType == Cms.Core.Constants.ObjectTypes.Document || objectType == Cms.Core.Constants.ObjectTypes.DocumentBlueprint;
var isMedia = objectType == Cms.Core.Constants.ObjectTypes.Media;
var isMember = objectType == Cms.Core.Constants.ObjectTypes.Member;
var sql = GetFullSqlForEntityType(isContent, isMedia, isMember, objectType, filter);
return GetEntities(sql, isContent, isMedia, isMember);
}
public IEnumerable<TreeEntityPath> GetAllPaths(Guid objectType, params int[] ids)
{
return ids.Any()
? PerformGetAllPaths(objectType, sql => sql.WhereIn<NodeDto>(x => x.NodeId, ids.Distinct()))
: PerformGetAllPaths(objectType);
}
public IEnumerable<TreeEntityPath> GetAllPaths(Guid objectType, params Guid[] keys)
{
return keys.Any()
? PerformGetAllPaths(objectType, sql => sql.WhereIn<NodeDto>(x => x.UniqueId, keys.Distinct()))
: PerformGetAllPaths(objectType);
}
private IEnumerable<TreeEntityPath> PerformGetAllPaths(Guid objectType, Action<Sql<ISqlContext>> filter = null)
{
// NodeId is named Id on TreeEntityPath = use an alias
var sql = Sql().Select<NodeDto>(x => Alias(x.NodeId, nameof(TreeEntityPath.Id)), x => x.Path).From<NodeDto>().Where<NodeDto>(x => x.NodeObjectType == objectType);
filter?.Invoke(sql);
return Database.Fetch<TreeEntityPath>(sql);
}
public IEnumerable<IEntitySlim> GetByQuery(IQuery<IUmbracoEntity> query)
{
var sqlClause = GetBase(false, false, false, null);
var translator = new SqlTranslator<IUmbracoEntity>(sqlClause, query);
var sql = translator.Translate();
sql = AddGroupBy(false, false, false, sql, true);
var dtos = Database.Fetch<BaseDto>(sql);
return dtos.Select(BuildEntity).ToList();
}
public IEnumerable<IEntitySlim> GetByQuery(IQuery<IUmbracoEntity> query, Guid objectType)
{
var isContent = objectType == Cms.Core.Constants.ObjectTypes.Document || objectType == Cms.Core.Constants.ObjectTypes.DocumentBlueprint;
var isMedia = objectType == Cms.Core.Constants.ObjectTypes.Media;
var isMember = objectType == Cms.Core.Constants.ObjectTypes.Member;
var sql = GetBaseWhere(isContent, isMedia, isMember, false, null, new[] { objectType });
var translator = new SqlTranslator<IUmbracoEntity>(sql, query);
sql = translator.Translate();
sql = AddGroupBy(isContent, isMedia, isMember, sql, true);
return GetEntities(sql, isContent, isMedia, isMember);
}
public UmbracoObjectTypes GetObjectType(int id)
{
var sql = Sql().Select<NodeDto>(x => x.NodeObjectType).From<NodeDto>().Where<NodeDto>(x => x.NodeId == id);
return ObjectTypes.GetUmbracoObjectType(Database.ExecuteScalar<Guid>(sql));
}
public UmbracoObjectTypes GetObjectType(Guid key)
{
var sql = Sql().Select<NodeDto>(x => x.NodeObjectType).From<NodeDto>().Where<NodeDto>(x => x.UniqueId == key);
return ObjectTypes.GetUmbracoObjectType(Database.ExecuteScalar<Guid>(sql));
}
public bool Exists(Guid key)
{
var sql = Sql().SelectCount().From<NodeDto>().Where<NodeDto>(x => x.UniqueId == key);
return Database.ExecuteScalar<int>(sql) > 0;
}
public bool Exists(int id)
{
var sql = Sql().SelectCount().From<NodeDto>().Where<NodeDto>(x => x.NodeId == id);
return Database.ExecuteScalar<int>(sql) > 0;
}
private DocumentEntitySlim BuildVariants(DocumentEntitySlim entity)
=> BuildVariants(new[] { entity }).First();
private IEnumerable<DocumentEntitySlim> BuildVariants(IEnumerable<DocumentEntitySlim> entities)
{
List<DocumentEntitySlim> v = null;
var entitiesList = entities.ToList();
foreach (var e in entitiesList)
{
if (e.Variations.VariesByCulture())
(v ?? (v = new List<DocumentEntitySlim>())).Add(e);
}
if (v == null) return entitiesList;
// fetch all variant info dtos
var dtos = Database.FetchByGroups<VariantInfoDto, int>(v.Select(x => x.Id), Constants.Sql.MaxParameterCount, GetVariantInfos);
// group by node id (each group contains all languages)
var xdtos = dtos.GroupBy(x => x.NodeId).ToDictionary(x => x.Key, x => x);
foreach (var e in v)
{
// since we're only iterating on entities that vary, we must have something
var edtos = xdtos[e.Id];
e.CultureNames = edtos.Where(x => x.CultureAvailable).ToDictionary(x => x.IsoCode, x => x.Name);
e.PublishedCultures = edtos.Where(x => x.CulturePublished).Select(x => x.IsoCode);
e.EditedCultures = edtos.Where(x => x.CultureAvailable && x.CultureEdited).Select(x => x.IsoCode);
}
return entitiesList;
}
#endregion
#region Sql
protected Sql<ISqlContext> GetVariantInfos(IEnumerable<int> ids)
{
return Sql()
.Select<NodeDto>(x => x.NodeId)
.AndSelect<LanguageDto>(x => x.IsoCode)
.AndSelect<DocumentDto>("doc", x => Alias(x.Published, "DocumentPublished"), x => Alias(x.Edited, "DocumentEdited"))
.AndSelect<DocumentCultureVariationDto>("dcv",
x => Alias(x.Available, "CultureAvailable"), x => Alias(x.Published, "CulturePublished"), x => Alias(x.Edited, "CultureEdited"),
x => Alias(x.Name, "Name"))
// from node x language
.From<NodeDto>()
.CrossJoin<LanguageDto>()
// join to document - always exists - indicates global document published/edited status
.InnerJoin<DocumentDto>("doc")
.On<NodeDto, DocumentDto>((node, doc) => node.NodeId == doc.NodeId, aliasRight: "doc")
// left-join do document variation - matches cultures that are *available* + indicates when *edited*
.LeftJoin<DocumentCultureVariationDto>("dcv")
.On<NodeDto, DocumentCultureVariationDto, LanguageDto>((node, dcv, lang) => node.NodeId == dcv.NodeId && lang.Id == dcv.LanguageId, aliasRight: "dcv")
// for selected nodes
.WhereIn<NodeDto>(x => x.NodeId, ids);
}
// gets the full sql for a given object type and a given unique id
protected Sql<ISqlContext> GetFullSqlForEntityType(bool isContent, bool isMedia, bool isMember, Guid objectType, Guid uniqueId)
{
var sql = GetBaseWhere(isContent, isMedia, isMember, false, objectType, uniqueId);
return AddGroupBy(isContent, isMedia, isMember, sql, true);
}
// gets the full sql for a given object type and a given node id
protected Sql<ISqlContext> GetFullSqlForEntityType(bool isContent, bool isMedia, bool isMember, Guid objectType, int nodeId)
{
var sql = GetBaseWhere(isContent, isMedia, isMember, false, objectType, nodeId);
return AddGroupBy(isContent, isMedia, isMember, sql, true);
}
// gets the full sql for a given object type, with a given filter
protected Sql<ISqlContext> GetFullSqlForEntityType(bool isContent, bool isMedia, bool isMember, Guid objectType, Action<Sql<ISqlContext>> filter)
{
var sql = GetBaseWhere(isContent, isMedia, isMember, false, filter, new[] { objectType });
return AddGroupBy(isContent, isMedia, isMember, sql, true);
}
// gets the base SELECT + FROM [+ filter] sql
// always from the 'current' content version
protected Sql<ISqlContext> GetBase(bool isContent, bool isMedia, bool isMember, Action<Sql<ISqlContext>> filter, bool isCount = false)
{
var sql = Sql();
if (isCount)
{
sql.SelectCount();
}
else
{
sql
.Select<NodeDto>(x => x.NodeId, x => x.Trashed, x => x.ParentId, x => x.UserId, x => x.Level, x => x.Path)
.AndSelect<NodeDto>(x => x.SortOrder, x => x.UniqueId, x => x.Text, x => x.NodeObjectType, x => x.CreateDate)
.Append(", COUNT(child.id) AS children");
if (isContent || isMedia || isMember)
sql
.AndSelect<ContentVersionDto>(x => Alias(x.Id, "versionId"), x=>x.VersionDate)
.AndSelect<ContentTypeDto>(x => x.Alias, x => x.Icon, x => x.Thumbnail, x => x.IsContainer, x => x.Variations);
if (isContent)
{
sql
.AndSelect<DocumentDto>(x => x.Published, x => x.Edited);
}
if (isMedia)
{
sql
.AndSelect<MediaVersionDto>(x => Alias(x.Path, "MediaPath"));
}
}
sql
.From<NodeDto>();
if (isContent || isMedia || isMember)
{
sql
.LeftJoin<ContentVersionDto>().On<NodeDto, ContentVersionDto>((left, right) => left.NodeId == right.NodeId && right.Current)
.LeftJoin<ContentDto>().On<NodeDto, ContentDto>((left, right) => left.NodeId == right.NodeId)
.LeftJoin<ContentTypeDto>().On<ContentDto, ContentTypeDto>((left, right) => left.ContentTypeId == right.NodeId);
}
if (isContent)
{
sql
.LeftJoin<DocumentDto>().On<NodeDto, DocumentDto>((left, right) => left.NodeId == right.NodeId);
}
if (isMedia)
{
sql
.LeftJoin<MediaVersionDto>().On<ContentVersionDto, MediaVersionDto>((left, right) => left.Id == right.Id);
}
//Any LeftJoin statements need to come last
if (isCount == false)
{
sql
.LeftJoin<NodeDto>("child").On<NodeDto, NodeDto>((left, right) => left.NodeId == right.ParentId, aliasRight: "child");
}
filter?.Invoke(sql);
return sql;
}
// gets the base SELECT + FROM [+ filter] + WHERE sql
// for a given object type, with a given filter
protected Sql<ISqlContext> GetBaseWhere(bool isContent, bool isMedia, bool isMember, bool isCount, Action<Sql<ISqlContext>> filter, Guid[] objectTypes)
{
var sql = GetBase(isContent, isMedia, isMember, filter, isCount);
if (objectTypes.Length > 0)
{
sql.WhereIn<NodeDto>(x => x.NodeObjectType, objectTypes);
}
return sql;
}
// gets the base SELECT + FROM + WHERE sql
// for a given node id
protected Sql<ISqlContext> GetBaseWhere(bool isContent, bool isMedia, bool isMember, bool isCount, int id)
{
var sql = GetBase(isContent, isMedia, isMember, null, isCount)
.Where<NodeDto>(x => x.NodeId == id);
return AddGroupBy(isContent, isMedia, isMember, sql, true);
}
// gets the base SELECT + FROM + WHERE sql
// for a given unique id
protected Sql<ISqlContext> GetBaseWhere(bool isContent, bool isMedia, bool isMember, bool isCount, Guid uniqueId)
{
var sql = GetBase(isContent, isMedia, isMember, null, isCount)
.Where<NodeDto>(x => x.UniqueId == uniqueId);
return AddGroupBy(isContent, isMedia, isMember, sql, true);
}
// gets the base SELECT + FROM + WHERE sql
// for a given object type and node id
protected Sql<ISqlContext> GetBaseWhere(bool isContent, bool isMedia, bool isMember, bool isCount, Guid objectType, int nodeId)
{
return GetBase(isContent, isMedia, isMember, null, isCount)
.Where<NodeDto>(x => x.NodeId == nodeId && x.NodeObjectType == objectType);
}
// gets the base SELECT + FROM + WHERE sql
// for a given object type and unique id
protected Sql<ISqlContext> GetBaseWhere(bool isContent, bool isMedia, bool isMember, bool isCount, Guid objectType, Guid uniqueId)
{
return GetBase(isContent, isMedia, isMember, null, isCount)
.Where<NodeDto>(x => x.UniqueId == uniqueId && x.NodeObjectType == objectType);
}
// gets the GROUP BY / ORDER BY sql
// required in order to count children
protected Sql<ISqlContext> AddGroupBy(bool isContent, bool isMedia, bool isMember, Sql<ISqlContext> sql, bool defaultSort)
{
sql
.GroupBy<NodeDto>(x => x.NodeId, x => x.Trashed, x => x.ParentId, x => x.UserId, x => x.Level, x => x.Path)
.AndBy<NodeDto>(x => x.SortOrder, x => x.UniqueId, x => x.Text, x => x.NodeObjectType, x => x.CreateDate);
if (isContent)
{
sql
.AndBy<DocumentDto>(x => x.Published, x => x.Edited);
}
if (isMedia)
{
sql
.AndBy<MediaVersionDto>(x => Alias(x.Path, "MediaPath"));
}
if (isContent || isMedia || isMember)
sql
.AndBy<ContentVersionDto>(x => x.Id, x => x.VersionDate)
.AndBy<ContentTypeDto>(x => x.Alias, x => x.Icon, x => x.Thumbnail, x => x.IsContainer, x => x.Variations);
if (defaultSort)
sql.OrderBy<NodeDto>(x => x.SortOrder);
return sql;
}
private void ApplyOrdering(ref Sql<ISqlContext> sql, Ordering ordering)
{
if (sql == null) throw new ArgumentNullException(nameof(sql));
if (ordering == null) throw new ArgumentNullException(nameof(ordering));
// TODO: although the default ordering string works for name, it wont work for others without a table or an alias of some sort
// As more things are attempted to be sorted we'll prob have to add more expressions here
string orderBy;
switch (ordering.OrderBy.ToUpperInvariant())
{
case "PATH":
orderBy = SqlSyntax.GetQuotedColumn(NodeDto.TableName, "path");
break;
default:
orderBy = ordering.OrderBy;
break;
}
if (ordering.Direction == Direction.Ascending)
sql.OrderBy(orderBy);
else
sql.OrderByDescending(orderBy);
}
#endregion
#region Classes
/// <summary>
/// The DTO used to fetch results for a generic content item which could be either a document, media or a member
/// </summary>
private class GenericContentEntityDto : DocumentEntityDto
{
public string MediaPath { get; set; }
}
/// <summary>
/// The DTO used to fetch results for a document item with its variation info
/// </summary>
private class DocumentEntityDto : BaseDto
{
public ContentVariation Variations { get; set; }
public bool Published { get; set; }
public bool Edited { get; set; }
}
/// <summary>
/// The DTO used to fetch results for a media item with its media path info
/// </summary>
private class MediaEntityDto : BaseDto
{
public string MediaPath { get; set; }
}
/// <summary>
/// The DTO used to fetch results for a member item
/// </summary>
private class MemberEntityDto : BaseDto
{
}
public class VariantInfoDto
{
public int NodeId { get; set; }
public string IsoCode { get; set; }
public string Name { get; set; }
public bool DocumentPublished { get; set; }
public bool DocumentEdited { get; set; }
public bool CultureAvailable { get; set; }
public bool CulturePublished { get; set; }
public bool CultureEdited { get; set; }
}
// ReSharper disable once ClassNeverInstantiated.Local
/// <summary>
/// the DTO corresponding to fields selected by GetBase
/// </summary>
private class BaseDto
{
// ReSharper disable UnusedAutoPropertyAccessor.Local
// ReSharper disable UnusedMember.Local
public int NodeId { get; set; }
public bool Trashed { get; set; }
public int ParentId { get; set; }
public int? UserId { get; set; }
public int Level { get; set; }
public string Path { get; set; }
public int SortOrder { get; set; }
public Guid UniqueId { get; set; }
public string Text { get; set; }
public Guid NodeObjectType { get; set; }
public DateTime CreateDate { get; set; }
public DateTime VersionDate { get; set; }
public int Children { get; set; }
public int VersionId { get; set; }
public string Alias { get; set; }
public string Icon { get; set; }
public string Thumbnail { get; set; }
public bool IsContainer { get; set; }
// ReSharper restore UnusedAutoPropertyAccessor.Local
// ReSharper restore UnusedMember.Local
}
#endregion
#region Factory
private EntitySlim BuildEntity(BaseDto dto)
{
if (dto.NodeObjectType == Cms.Core.Constants.ObjectTypes.Document)
return BuildDocumentEntity(dto);
if (dto.NodeObjectType == Cms.Core.Constants.ObjectTypes.Media)
return BuildMediaEntity(dto);
if (dto.NodeObjectType == Cms.Core.Constants.ObjectTypes.Member)
return BuildMemberEntity(dto);
// EntitySlim does not track changes
var entity = new EntitySlim();
BuildEntity(entity, dto);
return entity;
}
private static void BuildEntity(EntitySlim entity, BaseDto dto)
{
entity.Trashed = dto.Trashed;
entity.CreateDate = dto.CreateDate;
entity.UpdateDate = dto.VersionDate;
entity.CreatorId = dto.UserId ?? Cms.Core.Constants.Security.UnknownUserId;
entity.Id = dto.NodeId;
entity.Key = dto.UniqueId;
entity.Level = dto.Level;
entity.Name = dto.Text;
entity.NodeObjectType = dto.NodeObjectType;
entity.ParentId = dto.ParentId;
entity.Path = dto.Path;
entity.SortOrder = dto.SortOrder;
entity.HasChildren = dto.Children > 0;
entity.IsContainer = dto.IsContainer;
}
private static void BuildContentEntity(ContentEntitySlim entity, BaseDto dto)
{
BuildEntity(entity, dto);
entity.ContentTypeAlias = dto.Alias;
entity.ContentTypeIcon = dto.Icon;
entity.ContentTypeThumbnail = dto.Thumbnail;
}
private MediaEntitySlim BuildMediaEntity(BaseDto dto)
{
// EntitySlim does not track changes
var entity = new MediaEntitySlim();
BuildContentEntity(entity, dto);
// fill in the media info
if (dto is MediaEntityDto mediaEntityDto)
{
entity.MediaPath = mediaEntityDto.MediaPath;
}
else if (dto is GenericContentEntityDto genericContentEntityDto)
{
entity.MediaPath = genericContentEntityDto.MediaPath;
}
return entity;
}
private DocumentEntitySlim BuildDocumentEntity(BaseDto dto)
{
// EntitySlim does not track changes
var entity = new DocumentEntitySlim();
BuildContentEntity(entity, dto);
if (dto is DocumentEntityDto contentDto)
{
// fill in the invariant info
entity.Edited = contentDto.Edited;
entity.Published = contentDto.Published;
entity.Variations = contentDto.Variations;
}
return entity;
}
private MemberEntitySlim BuildMemberEntity(BaseDto dto)
{
// EntitySlim does not track changes
var entity = new MemberEntitySlim();
BuildEntity(entity, dto);
entity.ContentTypeAlias = dto.Alias;
entity.ContentTypeIcon = dto.Icon;
entity.ContentTypeThumbnail = dto.Thumbnail;
return entity;
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Internal.NetworkSenders
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using NLog.Common;
/// <summary>
/// Sends messages over a TCP network connection.
/// </summary>
internal class TcpNetworkSender : NetworkSender
{
private readonly Queue<SocketAsyncEventArgs> _pendingRequests = new Queue<SocketAsyncEventArgs>();
private ISocket _socket;
private Exception _pendingError;
private bool _asyncOperationInProgress;
private AsyncContinuation _closeContinuation;
private AsyncContinuation _flushContinuation;
/// <summary>
/// Initializes a new instance of the <see cref="TcpNetworkSender"/> class.
/// </summary>
/// <param name="url">URL. Must start with tcp://.</param>
/// <param name="addressFamily">The address family.</param>
public TcpNetworkSender(string url, AddressFamily addressFamily)
: base(url)
{
this.AddressFamily = addressFamily;
}
internal AddressFamily AddressFamily { get; set; }
internal int MaxQueueSize { get; set; }
/// <summary>
/// Creates the socket with given parameters.
/// </summary>
/// <param name="addressFamily">The address family.</param>
/// <param name="socketType">Type of the socket.</param>
/// <param name="protocolType">Type of the protocol.</param>
/// <returns>Instance of <see cref="ISocket" /> which represents the socket.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This is a factory method")]
protected internal virtual ISocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
return new SocketProxy(addressFamily, socketType, protocolType);
}
/// <summary>
/// Performs sender-specific initialization.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed in the event handler.")]
protected override void DoInitialize()
{
var args = new MySocketAsyncEventArgs();
args.RemoteEndPoint = this.ParseEndpointAddress(new Uri(this.Address), this.AddressFamily);
args.Completed += this.SocketOperationCompleted;
args.UserToken = null;
this._socket = this.CreateSocket(args.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
this._asyncOperationInProgress = true;
if (!this._socket.ConnectAsync(args))
{
this.SocketOperationCompleted(this._socket, args);
}
}
/// <summary>
/// Closes the socket.
/// </summary>
/// <param name="continuation">The continuation.</param>
protected override void DoClose(AsyncContinuation continuation)
{
lock (this)
{
if (this._asyncOperationInProgress)
{
this._closeContinuation = continuation;
}
else
{
this.CloseSocket(continuation);
}
}
}
/// <summary>
/// Performs sender-specific flush.
/// </summary>
/// <param name="continuation">The continuation.</param>
protected override void DoFlush(AsyncContinuation continuation)
{
lock (this)
{
if (!this._asyncOperationInProgress && this._pendingRequests.Count == 0)
{
continuation(null);
}
else
{
this._flushContinuation = continuation;
}
}
}
/// <summary>
/// Sends the specified text over the connected socket.
/// </summary>
/// <param name="bytes">The bytes to be sent.</param>
/// <param name="offset">Offset in buffer.</param>
/// <param name="length">Number of bytes to send.</param>
/// <param name="asyncContinuation">The async continuation to be invoked after the buffer has been sent.</param>
/// <remarks>To be overridden in inheriting classes.</remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed in the event handler.")]
protected override void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation)
{
var args = new MySocketAsyncEventArgs();
args.SetBuffer(bytes, offset, length);
args.UserToken = asyncContinuation;
args.Completed += this.SocketOperationCompleted;
lock (this)
{
if (this.MaxQueueSize != 0 && this._pendingRequests.Count >= this.MaxQueueSize)
{
var dequeued = this._pendingRequests.Dequeue();
if (dequeued != null)
{
dequeued.Dispose();
}
}
this._pendingRequests.Enqueue(args);
}
this.ProcessNextQueuedItem();
}
private void CloseSocket(AsyncContinuation continuation)
{
try
{
var sock = this._socket;
this._socket = null;
if (sock != null)
{
sock.Close();
}
continuation(null);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
continuation(exception);
}
}
private void SocketOperationCompleted(object sender, SocketAsyncEventArgs e)
{
lock (this)
{
this._asyncOperationInProgress = false;
var asyncContinuation = e.UserToken as AsyncContinuation;
if (e.SocketError != SocketError.Success)
{
this._pendingError = new IOException("Error: " + e.SocketError);
}
e.Dispose();
if (asyncContinuation != null)
{
asyncContinuation(this._pendingError);
}
}
this.ProcessNextQueuedItem();
}
private void ProcessNextQueuedItem()
{
SocketAsyncEventArgs args;
lock (this)
{
if (this._asyncOperationInProgress)
{
return;
}
if (this._pendingError != null)
{
while (this._pendingRequests.Count != 0)
{
args = this._pendingRequests.Dequeue();
var asyncContinuation = (AsyncContinuation)args.UserToken;
args.Dispose();
asyncContinuation(this._pendingError);
}
}
if (this._pendingRequests.Count == 0)
{
var fc = this._flushContinuation;
if (fc != null)
{
this._flushContinuation = null;
fc(this._pendingError);
}
var cc = this._closeContinuation;
if (cc != null)
{
this._closeContinuation = null;
this.CloseSocket(cc);
}
return;
}
args = this._pendingRequests.Dequeue();
this._asyncOperationInProgress = true;
if (!this._socket.SendAsync(args))
{
this.SocketOperationCompleted(this._socket, args);
}
}
}
public override void CheckSocket()
{
if (_socket == null)
{
DoInitialize();
}
}
/// <summary>
/// Facilitates mocking of <see cref="SocketAsyncEventArgs"/> class.
/// </summary>
internal class MySocketAsyncEventArgs : SocketAsyncEventArgs
{
/// <summary>
/// Raises the Completed event.
/// </summary>
public void RaiseCompleted()
{
this.OnCompleted(this);
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Graph.RBAC
{
using Microsoft.Azure;
using Microsoft.Azure.Graph;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ApplicationsOperations.
/// </summary>
public static partial class ApplicationsOperationsExtensions
{
/// <summary>
/// Create a new application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='parameters'>
/// The parameters for creating an application.
/// </param>
public static Application Create(this IApplicationsOperations operations, ApplicationCreateParameters parameters)
{
return operations.CreateAsync(parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Create a new application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='parameters'>
/// The parameters for creating an application.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Application> CreateAsync(this IApplicationsOperations operations, ApplicationCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists applications by filter parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<Application> List(this IApplicationsOperations operations, ODataQuery<Application> odataQuery = default(ODataQuery<Application>))
{
return ((IApplicationsOperations)operations).ListAsync(odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Lists applications by filter parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Application>> ListAsync(this IApplicationsOperations operations, ODataQuery<Application> odataQuery = default(ODataQuery<Application>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete an application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
public static void Delete(this IApplicationsOperations operations, string applicationObjectId)
{
operations.DeleteAsync(applicationObjectId).GetAwaiter().GetResult();
}
/// <summary>
/// Delete an application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IApplicationsOperations operations, string applicationObjectId, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(applicationObjectId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get an application by object ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
public static Application Get(this IApplicationsOperations operations, string applicationObjectId)
{
return operations.GetAsync(applicationObjectId).GetAwaiter().GetResult();
}
/// <summary>
/// Get an application by object ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Application> GetAsync(this IApplicationsOperations operations, string applicationObjectId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(applicationObjectId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Update an existing application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='parameters'>
/// Parameters to update an existing application.
/// </param>
public static void Patch(this IApplicationsOperations operations, string applicationObjectId, ApplicationUpdateParameters parameters)
{
operations.PatchAsync(applicationObjectId, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Update an existing application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='parameters'>
/// Parameters to update an existing application.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PatchAsync(this IApplicationsOperations operations, string applicationObjectId, ApplicationUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PatchWithHttpMessagesAsync(applicationObjectId, parameters, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get the keyCredentials associated with an application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
public static IEnumerable<KeyCredential> ListKeyCredentials(this IApplicationsOperations operations, string applicationObjectId)
{
return operations.ListKeyCredentialsAsync(applicationObjectId).GetAwaiter().GetResult();
}
/// <summary>
/// Get the keyCredentials associated with an application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<KeyCredential>> ListKeyCredentialsAsync(this IApplicationsOperations operations, string applicationObjectId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListKeyCredentialsWithHttpMessagesAsync(applicationObjectId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Update the keyCredentials associated with an application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='parameters'>
/// Parameters to update the keyCredentials of an existing application.
/// </param>
public static void UpdateKeyCredentials(this IApplicationsOperations operations, string applicationObjectId, KeyCredentialsUpdateParameters parameters)
{
operations.UpdateKeyCredentialsAsync(applicationObjectId, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Update the keyCredentials associated with an application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='parameters'>
/// Parameters to update the keyCredentials of an existing application.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateKeyCredentialsAsync(this IApplicationsOperations operations, string applicationObjectId, KeyCredentialsUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateKeyCredentialsWithHttpMessagesAsync(applicationObjectId, parameters, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get the passwordCredentials associated with an application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
public static IEnumerable<PasswordCredential> ListPasswordCredentials(this IApplicationsOperations operations, string applicationObjectId)
{
return operations.ListPasswordCredentialsAsync(applicationObjectId).GetAwaiter().GetResult();
}
/// <summary>
/// Get the passwordCredentials associated with an application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<PasswordCredential>> ListPasswordCredentialsAsync(this IApplicationsOperations operations, string applicationObjectId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListPasswordCredentialsWithHttpMessagesAsync(applicationObjectId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Update passwordCredentials associated with an application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='parameters'>
/// Parameters to update passwordCredentials of an existing application.
/// </param>
public static void UpdatePasswordCredentials(this IApplicationsOperations operations, string applicationObjectId, PasswordCredentialsUpdateParameters parameters)
{
operations.UpdatePasswordCredentialsAsync(applicationObjectId, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Update passwordCredentials associated with an application.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='applicationObjectId'>
/// Application object ID.
/// </param>
/// <param name='parameters'>
/// Parameters to update passwordCredentials of an existing application.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdatePasswordCredentialsAsync(this IApplicationsOperations operations, string applicationObjectId, PasswordCredentialsUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdatePasswordCredentialsWithHttpMessagesAsync(applicationObjectId, parameters, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets a list of applications from the current tenant.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextLink'>
/// Next link for the list operation.
/// </param>
public static IPage<Application> ListNext(this IApplicationsOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of applications from the current tenant.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextLink'>
/// Next link for the list operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Application>> ListNextAsync(this IApplicationsOperations operations, string nextLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// 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.Annotations;
using Microsoft.Data.Edm.Csdl.Internal.Parsing.Ast;
using Microsoft.Data.Edm.Internal;
using Microsoft.Data.Edm.Library;
using Microsoft.Data.Edm.Library.Internal;
using Microsoft.Data.Edm.Validation;
namespace Microsoft.Data.Edm.Csdl.Internal.CsdlSemantics
{
/// <summary>
/// Provides semantics for a CsdlNavigationProperty.
/// </summary>
internal class CsdlSemanticsNavigationProperty : CsdlSemanticsElement, IEdmNavigationProperty, IEdmCheckable
{
private readonly CsdlNavigationProperty navigationProperty;
private readonly CsdlSemanticsEntityTypeDefinition declaringType;
private readonly Cache<CsdlSemanticsNavigationProperty, IEdmTypeReference> typeCache = new Cache<CsdlSemanticsNavigationProperty, IEdmTypeReference>();
private static readonly Func<CsdlSemanticsNavigationProperty, IEdmTypeReference> ComputeTypeFunc = (me) => me.ComputeType();
private readonly Cache<CsdlSemanticsNavigationProperty, IEdmAssociation> associationCache = new Cache<CsdlSemanticsNavigationProperty, IEdmAssociation>();
private static readonly Func<CsdlSemanticsNavigationProperty, IEdmAssociation> ComputeAssociationFunc = (me) => me.ComputeAssociation();
private readonly Cache<CsdlSemanticsNavigationProperty, IEdmAssociationEnd> toCache = new Cache<CsdlSemanticsNavigationProperty, IEdmAssociationEnd>();
private static readonly Func<CsdlSemanticsNavigationProperty, IEdmAssociationEnd> ComputeToFunc = (me) => me.ComputeTo();
private readonly Cache<CsdlSemanticsNavigationProperty, IEdmAssociationEnd> fromCache = new Cache<CsdlSemanticsNavigationProperty, IEdmAssociationEnd>();
private static readonly Func<CsdlSemanticsNavigationProperty, IEdmAssociationEnd> ComputeFromFunc = (me) => me.ComputeFrom();
private readonly Cache<CsdlSemanticsNavigationProperty, IEdmNavigationProperty> partnerCache = new Cache<CsdlSemanticsNavigationProperty, IEdmNavigationProperty>();
private static readonly Func<CsdlSemanticsNavigationProperty, IEdmNavigationProperty> ComputePartnerFunc = (me) => me.ComputePartner();
public CsdlSemanticsNavigationProperty(CsdlSemanticsEntityTypeDefinition declaringType, CsdlNavigationProperty navigationProperty)
: base(navigationProperty)
{
this.declaringType = declaringType;
this.navigationProperty = navigationProperty;
}
public override CsdlSemanticsModel Model
{
get { return this.declaringType.Model; }
}
public override CsdlElement Element
{
get { return this.navigationProperty; }
}
public string Name
{
get { return this.navigationProperty.Name; }
}
public bool IsPrincipal
{
get
{
CsdlSemanticsReferentialConstraint referentialConstraint = this.Association.ReferentialConstraint;
return referentialConstraint != null && referentialConstraint.PrincipalEnd != this.To;
}
}
public EdmOnDeleteAction OnDelete
{
get
{
IEdmAssociationEnd from = this.From;
return from != null ? from.OnDelete : EdmOnDeleteAction.None;
}
}
public IEdmStructuredType DeclaringType
{
get { return this.declaringType; }
}
public IEdmAssociationEnd To
{
get
{
return this.toCache.GetValue(this, ComputeToFunc, null);
}
}
public bool ContainsTarget
{
get { return this.navigationProperty.ContainsTarget; }
}
public IEdmTypeReference Type
{
get { return this.typeCache.GetValue(this, ComputeTypeFunc, null); }
}
public EdmPropertyKind PropertyKind
{
get { return EdmPropertyKind.Navigation; }
}
public IEdmNavigationProperty Partner
{
get { return this.partnerCache.GetValue(this, ComputePartnerFunc, null); }
}
public IEnumerable<EdmError> Errors
{
get
{
List<EdmError> errors = new List<EdmError>();
if (this.Association is UnresolvedAssociation)
{
errors.AddRange(this.Association.Errors());
}
if (this.From is BadCsdlSemanticsNavigationPropertyToEnd)
{
errors.AddRange(this.From.Errors());
}
if (this.To is BadCsdlSemanticsNavigationPropertyToEnd)
{
errors.AddRange(this.To.Errors());
}
return errors;
}
}
public IEdmAssociation Association
{
get
{
return this.associationCache.GetValue(this, ComputeAssociationFunc, null);
}
}
public IEnumerable<IEdmStructuralProperty> DependentProperties
{
get
{
CsdlSemanticsReferentialConstraint referentialConstraint = this.Association.ReferentialConstraint;
return (referentialConstraint != null && referentialConstraint.PrincipalEnd == this.To) ? referentialConstraint.DependentProperties : null;
}
}
private IEdmAssociationEnd From
{
get
{
return this.fromCache.GetValue(this, ComputeFromFunc, null);
}
}
protected override IEnumerable<IEdmVocabularyAnnotation> ComputeInlineVocabularyAnnotations()
{
return this.Model.WrapInlineVocabularyAnnotations(this, this.declaringType.Context);
}
private IEdmAssociation ComputeAssociation()
{
IEdmAssociation association = this.declaringType.Context.FindAssociation(this.navigationProperty.Relationship) ?? new UnresolvedAssociation(this.navigationProperty.Relationship, this.Location);
this.Model.SetAssociationNamespace(this, association.Namespace);
this.Model.SetAssociationName(this, association.Name);
CsdlSemanticsAssociation csdlAssociation = association as CsdlSemanticsAssociation;
CsdlSemanticsAssociationEnd end1 = association.End1 as CsdlSemanticsAssociationEnd;
CsdlSemanticsAssociationEnd end2 = association.End2 as CsdlSemanticsAssociationEnd;
if (csdlAssociation != null && end1 != null && end2 != null)
{
this.Model.SetAssociationAnnotations(
this,
csdlAssociation.DirectValueAnnotations,
(this.navigationProperty.FromRole == end1.Name ? end1 : end2).DirectValueAnnotations,
(this.navigationProperty.FromRole == end1.Name ? end2 : end1).DirectValueAnnotations,
association.ReferentialConstraint != null ? association.ReferentialConstraint.DirectValueAnnotations : Enumerable.Empty<IEdmDirectValueAnnotation>());
}
return association;
}
private IEdmAssociationEnd ComputeFrom()
{
IEdmAssociation association = this.Association;
string fromRole = this.navigationProperty.FromRole;
if (association.End1.Name == fromRole)
{
return association.End1;
}
else if (association.End2.Name == fromRole)
{
return association.End2;
}
else
{
return new BadCsdlSemanticsNavigationPropertyToEnd(
this.Association,
fromRole,
new EdmError[]
{
new EdmError(this.Location, EdmErrorCode.BadNavigationProperty, Microsoft.Data.Edm.Strings.EdmModel_Validator_Semantic_BadNavigationPropertyUndefinedRole(this.Name, fromRole, association.Name))
});
}
}
private IEdmAssociationEnd ComputeTo()
{
string toRole = this.navigationProperty.ToRole;
string fromRole = this.navigationProperty.FromRole;
this.Model.SetAssociationEndName(this, fromRole);
IEdmAssociation association = this.Association;
if (toRole == fromRole)
{
return new BadCsdlSemanticsNavigationPropertyToEnd(association, toRole, new EdmError[] { new EdmError(this.Location, EdmErrorCode.BadNavigationProperty, Microsoft.Data.Edm.Strings.EdmModel_Validator_Semantic_BadNavigationPropertyRolesCannotBeTheSame(this.Name)) });
}
if (association.End1.Name == toRole)
{
return association.End1;
}
else if (association.End2.Name == toRole)
{
return association.End2;
}
else
{
return new BadCsdlSemanticsNavigationPropertyToEnd(
this.Association,
toRole,
new EdmError[]
{
new EdmError(this.Location, EdmErrorCode.BadNavigationProperty, Microsoft.Data.Edm.Strings.EdmModel_Validator_Semantic_BadNavigationPropertyUndefinedRole(this.Name, toRole, association.Name))
});
}
}
private IEdmNavigationProperty ComputePartner()
{
// If multiple navigation properties share an association, pair the first with the first, second with second and so forth.
int propertyIndex = 0;
foreach (IEdmNavigationProperty navigationProperty in this.declaringType.NavigationProperties())
{
if (navigationProperty == this)
{
break;
}
CsdlSemanticsNavigationProperty csdlNavigationProperty = navigationProperty as CsdlSemanticsNavigationProperty;
if (csdlNavigationProperty != null)
{
if (csdlNavigationProperty.Association == this.Association && csdlNavigationProperty.To == this.To)
{
propertyIndex++;
}
}
}
foreach (IEdmNavigationProperty candidate in this.To.EntityType.NavigationProperties())
{
CsdlSemanticsNavigationProperty csdlCandidate = candidate as CsdlSemanticsNavigationProperty;
if (csdlCandidate != null)
{
if (csdlCandidate.Association == this.Association && csdlCandidate.To == this.From)
{
if (propertyIndex == 0)
{
return candidate;
}
else
{
propertyIndex--;
}
}
}
else if (candidate.Partner == this)
{
return candidate;
}
}
return new SilentPartner(this);
}
private IEdmTypeReference ComputeType()
{
switch (this.To.Multiplicity)
{
case EdmMultiplicity.One:
return new EdmEntityTypeReference(this.To.EntityType, false);
case EdmMultiplicity.ZeroOrOne:
return new EdmEntityTypeReference(this.To.EntityType, true);
case EdmMultiplicity.Many:
return new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(this.To.EntityType, false)), false);
default:
// Error is bad by association because the association has to be invalid or non-existent for the error to be produced.
return new BadEntityTypeReference(this.To.EntityType.FullName(), false, new EdmError[] { new EdmError(this.Location, EdmErrorCode.NavigationPropertyTypeInvalidBecauseOfBadAssociation, Edm.Strings.EdmModel_Validator_Semantic_BadNavigationPropertyCouldNotDetermineType(this.To.EntityType.Name)) });
}
}
private class BadCsdlSemanticsNavigationPropertyToEnd : BadAssociationEnd
{
public BadCsdlSemanticsNavigationPropertyToEnd(IEdmAssociation declaringAssociation, string role, IEnumerable<EdmError> errors)
: base(declaringAssociation, role, errors)
{
}
}
/// <summary>
/// Represents a navigation property synthesized for an association end that does not have a corresponding navigation property.
/// </summary>
private class SilentPartner : EdmElement, IEdmNavigationProperty
{
private readonly CsdlSemanticsNavigationProperty partner;
private readonly Cache<SilentPartner, IEdmTypeReference> typeCache = new Cache<SilentPartner, IEdmTypeReference>();
private static readonly Func<SilentPartner, IEdmTypeReference> ComputeTypeFunc = (me) => me.ComputeType();
public SilentPartner(CsdlSemanticsNavigationProperty partner)
{
this.partner = partner;
partner.Model.SetAssociationNamespace(this, partner.Association.Namespace);
partner.Model.SetAssociationName(this, partner.Association.Name);
partner.Model.SetAssociationEndName(this, partner.To.Name);
}
public IEdmNavigationProperty Partner
{
get { return this.partner; }
}
public EdmOnDeleteAction OnDelete
{
get { return this.partner.To.OnDelete; }
}
public bool IsPrincipal
{
get
{
CsdlSemanticsReferentialConstraint constraint = this.partner.Association.ReferentialConstraint;
return constraint != null && constraint.PrincipalEnd == this.partner.To;
}
}
public bool ContainsTarget
{
get { return false; }
}
public IEnumerable<IEdmStructuralProperty> DependentProperties
{
get
{
CsdlSemanticsReferentialConstraint constraint = this.partner.Association.ReferentialConstraint;
return constraint != null && !this.IsPrincipal ? constraint.DependentProperties : null;
}
}
public EdmPropertyKind PropertyKind
{
get { return EdmPropertyKind.Navigation; }
}
public IEdmTypeReference Type
{
get { return this.typeCache.GetValue(this, ComputeTypeFunc, null); }
}
public IEdmStructuredType DeclaringType
{
get { return this.partner.ToEntityType(); }
}
public string Name
{
get { return this.partner.From.Name; }
}
private IEdmTypeReference ComputeType()
{
switch (this.partner.From.Multiplicity)
{
case EdmMultiplicity.One:
return new EdmEntityTypeReference(this.partner.DeclaringEntityType(), false);
case EdmMultiplicity.ZeroOrOne:
return new EdmEntityTypeReference(this.partner.DeclaringEntityType(), true);
case EdmMultiplicity.Many:
return new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(this.partner.DeclaringEntityType(), false)), false);
default:
// Error is bad by association because the association has to be invalid or non-existent for the error to be produced.
return new BadEntityTypeReference(this.partner.DeclaringEntityType().FullName(), false, new EdmError[] { new EdmError(this.partner.To.Location(), EdmErrorCode.NavigationPropertyTypeInvalidBecauseOfBadAssociation, Edm.Strings.EdmModel_Validator_Semantic_BadNavigationPropertyCouldNotDetermineType(this.partner.DeclaringEntityType().Name)) });
}
}
}
}
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
//
// Copyright (C) 2008 Novell (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Calamari.Commands.Support
{
public class OptionSet : KeyedCollection<string, Option>
{
Action<string[]> leftovers;
public OptionSet()
: this(delegate(string f) { return f; })
{
}
public OptionSet(Converter<string, string> localizer)
{
this.localizer = localizer;
}
readonly Converter<string, string> localizer;
public Converter<string, string> MessageLocalizer
{
get { return localizer; }
}
protected override string GetKeyForItem(Option item)
{
if (item == null)
throw new ArgumentNullException("item");
if (item.Names != null && item.Names.Length > 0)
return item.Names[0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException("Option has no names!");
}
[Obsolete("Use KeyedCollection.this[string]")]
protected Option GetOptionForName(string option)
{
if (option == null)
throw new ArgumentNullException("option");
try
{
return base[option];
}
catch (KeyNotFoundException)
{
return null;
}
}
protected override void InsertItem(int index, Option item)
{
base.InsertItem(index, item);
AddImpl(item);
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
var p = Items[index];
// KeyedCollection.RemoveItem() handles the 0th item
for (var i = 1; i < p.Names.Length; ++i)
{
Dictionary.Remove(p.Names[i]);
}
}
protected override void SetItem(int index, Option item)
{
base.SetItem(index, item);
RemoveItem(index);
AddImpl(item);
}
void AddImpl(Option option)
{
if (option == null)
throw new ArgumentNullException("option");
var added = new List<string>(option.Names.Length);
try
{
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (var i = 1; i < option.Names.Length; ++i)
{
Dictionary.Add(option.Names[i], option);
added.Add(option.Names[i]);
}
}
catch (Exception)
{
foreach (var name in added)
Dictionary.Remove(name);
throw;
}
}
public new OptionSet Add(Option option)
{
base.Add(option);
return this;
}
sealed class ActionOption : Option
{
readonly Action<OptionValueCollection> action;
public ActionOption(string prototype, string description, int count, Action<OptionValueCollection> action)
: base(prototype, description, count)
{
if (action == null)
throw new ArgumentNullException("action");
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(c.OptionValues);
}
}
public OptionSet Add(string prototype, Action<string> action)
{
return Add(prototype, null, action);
}
public OptionSet Add(string prototype, string description, Action<string> action)
{
if (action == null)
throw new ArgumentNullException("action");
Option p = new ActionOption(prototype, description, 1,
delegate(OptionValueCollection v) { action(v[0]); });
base.Add(p);
return this;
}
public OptionSet Add(string prototype, OptionAction<string, string> action)
{
return Add(prototype, null, action);
}
public OptionSet Add(string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
throw new ArgumentNullException("action");
Option p = new ActionOption(prototype, description, 2,
delegate(OptionValueCollection v) { action(v[0], v[1]); });
base.Add(p);
return this;
}
sealed class ActionOption<T> : Option
{
readonly Action<T> action;
public ActionOption(string prototype, string description, Action<T> action)
: base(prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException("action");
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(Parse<T>(c.OptionValues[0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option
{
readonly OptionAction<TKey, TValue> action;
public ActionOption(string prototype, string description, OptionAction<TKey, TValue> action)
: base(prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException("action");
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(
Parse<TKey>(c.OptionValues[0], c),
Parse<TValue>(c.OptionValues[1], c));
}
}
public OptionSet Add<T>(string prototype, Action<T> action)
{
return Add(prototype, null, action);
}
public OptionSet Add<T>(string prototype, string description, Action<T> action)
{
return Add(new ActionOption<T>(prototype, description, action));
}
public OptionSet Add<TKey, TValue>(string prototype, OptionAction<TKey, TValue> action)
{
return Add(prototype, null, action);
}
public OptionSet Add<TKey, TValue>(string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add(new ActionOption<TKey, TValue>(prototype, description, action));
}
protected virtual OptionContext CreateOptionContext()
{
return new OptionContext(this);
}
public OptionSet WithExtras(Action<string[]> lo)
{
leftovers = lo;
return this;
}
public List<string> Parse(IEnumerable<string> arguments)
{
var process = true;
var c = CreateOptionContext();
c.OptionIndex = -1;
#pragma warning disable 618
var def = GetOptionForName("<>");
#pragma warning restore 618
var unprocessed =
from argument in arguments
where ++c.OptionIndex >= 0 && (process || def != null)
? process
? argument == "--"
? (process = false)
: !Parse(argument, c)
? def != null
? Unprocessed(null, def, c, argument)
: true
: false
: def != null
? Unprocessed(null, def, c, argument)
: true
: true
select argument;
var r = unprocessed.ToList();
if (c.Option != null)
c.Option.Invoke(c);
if (leftovers != null && r.Count > 0)
{
leftovers(r.ToArray());
}
return r;
}
static bool Unprocessed(ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null)
{
extra.Add(argument);
return false;
}
c.OptionValues.Add(argument);
c.Option = def;
c.Option.Invoke(c);
return false;
}
readonly Regex ValueOption = new Regex(
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
#pragma warning disable 649
bool waitForExit;
#pragma warning restore 649
protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException("argument");
flag = name = sep = value = null;
var m = ValueOption.Match(argument);
if (!m.Success)
{
return false;
}
flag = m.Groups["flag"].Value;
name = m.Groups["name"].Value;
if (m.Groups["sep"].Success && m.Groups["value"].Success)
{
sep = m.Groups["sep"].Value;
value = m.Groups["value"].Value;
}
return true;
}
protected virtual bool Parse(string argument, OptionContext c)
{
if (c.Option != null)
{
ParseValue(argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts(argument, out f, out n, out s, out v))
return false;
var p = this.FirstOrDefault(x => x.Names.Any(y => string.Equals(y, n, StringComparison.InvariantCultureIgnoreCase)));
if (p != null)
{
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType)
{
case OptionValueType.None:
c.OptionValues.Add(n);
c.Option.Invoke(c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue(v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool(argument, n, c))
return true;
// is it a bundled option?
// ReSharper disable once PossiblyMistakenUseOfParamsMethod
if (ParseBundledValue(f, string.Concat(n + s + v), c))
return true;
return false;
}
public bool ShouldWaitForExit
{
get { return waitForExit; }
}
void ParseValue(string option, OptionContext c)
{
if (option != null)
foreach (var o in c.Option.ValueSeparators != null
? option.Split(c.Option.ValueSeparators, StringSplitOptions.None)
: new[] {option})
{
c.OptionValues.Add(o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke(c);
else if (c.OptionValues.Count > c.Option.MaxValueCount)
{
throw new OptionException(localizer(string.Format(
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
bool ParseBool(string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n[n.Length - 1] == '+' || n[n.Length - 1] == '-') &&
Contains((rn = n.Substring(0, n.Length - 1))))
{
p = this[rn];
var v = n[n.Length - 1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add(v);
p.Invoke(c);
return true;
}
return false;
}
bool ParseBundledValue(string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (var i = 0; i < n.Length; ++i)
{
Option p;
var opt = f + n[i];
var rn = n[i].ToString(CultureInfo.InvariantCulture);
if (!Contains(rn))
{
if (i == 0)
return false;
throw new OptionException(string.Format(localizer(
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this[rn];
switch (p.OptionValueType)
{
case OptionValueType.None:
Invoke(c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
{
var v = n.Substring(i + 1);
c.Option = p;
c.OptionName = opt;
ParseValue(v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
static void Invoke(OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add(value);
option.Invoke(c);
}
const int OptionWidth = 29;
public void WriteOptionDescriptions(TextWriter o)
{
foreach (var p in this)
{
var written = 0;
if (!WriteOptionPrototype(o, p, ref written))
continue;
if (written < OptionWidth)
o.Write(new string(' ', OptionWidth - written));
else
{
o.WriteLine();
o.Write(new string(' ', OptionWidth));
}
var lines = GetLines(localizer(GetDescription(p.Description)));
o.WriteLine(lines[0]);
var prefix = new string(' ', OptionWidth);
for (var i = 1; i < lines.Count; ++i)
{
o.Write(prefix);
o.WriteLine(lines[i]);
}
}
}
bool WriteOptionPrototype(TextWriter o, Option p, ref int written)
{
var names = p.Names;
var i = GetNextOptionIndex(names, 0);
if (i == names.Length)
return false;
if (names[i].Length == 1)
{
Write(o, ref written, " -");
Write(o, ref written, names[0]);
}
else
{
Write(o, ref written, " --");
Write(o, ref written, names[0]);
}
for (i = GetNextOptionIndex(names, i + 1);
i < names.Length;
i = GetNextOptionIndex(names, i + 1))
{
Write(o, ref written, ", ");
Write(o, ref written, names[i].Length == 1 ? "-" : "--");
Write(o, ref written, names[i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required)
{
if (p.OptionValueType == OptionValueType.Optional)
{
Write(o, ref written, localizer("["));
}
Write(o, ref written, localizer("=" + GetArgumentName(0, p.MaxValueCount, p.Description)));
var sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators[0]
: " ";
for (var c = 1; c < p.MaxValueCount; ++c)
{
Write(o, ref written, localizer(sep + GetArgumentName(c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional)
{
Write(o, ref written, localizer("]"));
}
}
return true;
}
static int GetNextOptionIndex(string[] names, int i)
{
while (i < names.Length && names[i] == "<>")
{
++i;
}
return i;
}
static void Write(TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write(s);
}
static string GetArgumentName(int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new[] {"{0:", "{"};
else
nameStart = new[] {"{" + index + ":"};
for (var i = 0; i < nameStart.Length; ++i)
{
int start, j = 0;
do
{
start = description.IndexOf(nameStart[i], j, StringComparison.Ordinal);
} while (start >= 0 && j != 0 && description[j++ - 1] == '{');
if (start == -1)
continue;
var end = description.IndexOf("}", start, StringComparison.Ordinal);
if (end == -1)
continue;
return description.Substring(start + nameStart[i].Length, end - start - nameStart[i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
static string GetDescription(string description)
{
if (description == null)
return string.Empty;
var sb = new StringBuilder(description.Length);
var start = -1;
for (var i = 0; i < description.Length; ++i)
{
switch (description[i])
{
case '{':
if (i == start)
{
sb.Append('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0)
{
if ((i + 1) == description.Length || description[i + 1] != '}')
throw new InvalidOperationException("Invalid option description: " + description);
++i;
sb.Append("}");
}
else
{
sb.Append(description.Substring(start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append(description[i]);
break;
}
}
return sb.ToString();
}
static List<string> GetLines(string description)
{
var lines = new List<string>();
if (string.IsNullOrEmpty(description))
{
lines.Add(string.Empty);
return lines;
}
var length = 80 - OptionWidth - 2;
int start = 0, end;
do
{
end = GetLineEnd(start, length, description);
var cont = false;
if (end < description.Length)
{
var c = description[end];
if (c == '-' || (char.IsWhiteSpace(c) && c != '\n'))
++end;
else if (c != '\n')
{
cont = true;
--end;
}
}
lines.Add(description.Substring(start, end - start));
if (cont)
{
lines[lines.Count - 1] += "-";
}
start = end;
if (start < description.Length && description[start] == '\n')
++start;
} while (end < description.Length);
return lines;
}
static int GetLineEnd(int start, int length, string description)
{
var end = Math.Min(start + length, description.Length);
var sep = -1;
for (var i = start; i < end; ++i)
{
switch (description[i])
{
case ' ':
case '\t':
case '\v':
case '-':
case ',':
case '.':
case ';':
sep = i;
break;
case '\n':
return i;
}
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// HttpServerFailure operations.
/// </summary>
public partial class HttpServerFailure : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpServerFailure
{
/// <summary>
/// Initializes a new instance of the HttpServerFailure class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public HttpServerFailure(AutoRestHttpInfrastructureTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHttpInfrastructureTestService
/// </summary>
public AutoRestHttpInfrastructureTestService Client { get; private set; }
/// <summary>
/// Return 501 status code - should be represented in the client as an error
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Error>> Head501WithHttpMessagesAsync(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, "Head501", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/501").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("HEAD");
_httpRequest.RequestUri = new System.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 = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 501 status code - should be represented in the client as an error
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Error>> Get501WithHttpMessagesAsync(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, "Get501", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/501").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.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 = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 505 status code - should be represented in the client as an error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Error>> Post505WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Post505", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/505").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.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 = null;
if(booleanValue != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(booleanValue, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 505 status code - should be represented in the client as an error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Error>> Delete505WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete505", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/505").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.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 = null;
if(booleanValue != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(booleanValue, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2009 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// Summary description for PathConstraintTests.
/// </summary>]
[TestFixture]
public class SamePathTest_Windows : StringConstraintTests
{
[SetUp]
public void SetUp()
{
TheConstraint = new SamePathConstraint( @"C:\folder1\file.tmp" ).IgnoreCase;
ExpectedDescription = @"Path matching ""C:\folder1\file.tmp""";
StringRepresentation = "<samepath \"C:\\folder1\\file.tmp\" ignorecase>";
}
static object[] SuccessData = new object[]
{
@"C:\folder1\file.tmp",
@"C:\Folder1\File.TMP",
@"C:\folder1\.\file.tmp",
@"C:\folder1\folder2\..\file.tmp",
@"C:\FOLDER1\.\folder2\..\File.TMP",
@"C:/folder1/file.tmp"
};
static object[] FailureData = new object[]
{
new TestCaseData( @"C:\folder2\file.tmp", "\"C:\\folder2\\file.tmp\"" ),
new TestCaseData( @"C:\folder1\.\folder2\..\file.temp", "\"C:\\folder1\\.\\folder2\\..\\file.temp\"" )
};
[Test]
public void RootPathEquality()
{
Assert.That("c:\\", Is.SamePath("C:\\junk\\..\\").IgnoreCase);
}
}
[TestFixture]
public class SamePathTest_Linux : StringConstraintTests
{
[SetUp]
public void SetUp()
{
TheConstraint = new SamePathConstraint(@"/folder1/folder2").RespectCase;
ExpectedDescription = @"Path matching ""/folder1/folder2""";
StringRepresentation = @"<samepath ""/folder1/folder2"" respectcase>";
}
static object[] SuccessData = new object[]
{
@"/folder1/folder2",
@"/folder1/folder2/",
@"/folder1/./folder2",
@"/folder1/./folder2/",
@"/folder1/junk/../folder2",
@"/folder1/junk/../folder2/",
@"/folder1/./junk/../folder2",
@"/folder1/./junk/../folder2/",
@"\folder1\folder2",
@"\folder1\folder2\"
};
static object[] FailureData = new object[]
{
new TestCaseData( "folder1/folder2", "\"folder1/folder2\""),
new TestCaseData( "//folder1/folder2", "\"//folder1/folder2\""),
new TestCaseData( @"/junk/folder2", "\"/junk/folder2\"" ),
new TestCaseData( @"/folder1/./junk/../file.temp", "\"/folder1/./junk/../file.temp\"" ),
new TestCaseData( @"/Folder1/FOLDER2", "\"/Folder1/FOLDER2\"" ),
new TestCaseData( @"/FOLDER1/./junk/../FOLDER2", "\"/FOLDER1/./junk/../FOLDER2\"" )
};
[Test]
public void RootPathEquality()
{
Assert.That("/", Is.SamePath("/junk/../"));
}
}
[TestFixture]
public class SubPathTest_Windows : ConstraintTestBase
{
[SetUp]
public void SetUp()
{
TheConstraint = new SubPathConstraint(@"C:\folder1\folder2").IgnoreCase;
ExpectedDescription = @"Subpath of ""C:\folder1\folder2""";
StringRepresentation = @"<subpath ""C:\folder1\folder2"" ignorecase>";
}
static object[] SuccessData = new object[]
{
@"C:\folder1\folder2\folder3",
@"C:\folder1\.\folder2\folder3",
@"C:\folder1\junk\..\folder2\folder3",
@"C:\FOLDER1\.\junk\..\Folder2\temp\..\Folder3",
@"C:/folder1/folder2/folder3",
};
static object[] FailureData = new object[]
{
new TestCaseData(@"C:\folder1\folder3", "\"C:\\folder1\\folder3\""),
new TestCaseData(@"C:\folder1\.\folder2\..\file.temp", "\"C:\\folder1\\.\\folder2\\..\\file.temp\""),
new TestCaseData(@"C:\folder1\folder2", "\"C:\\folder1\\folder2\""),
new TestCaseData(@"C:\Folder1\Folder2", "\"C:\\Folder1\\Folder2\""),
new TestCaseData(@"C:\folder1\.\folder2", "\"C:\\folder1\\.\\folder2\""),
new TestCaseData(@"C:\folder1\junk\..\folder2", "\"C:\\folder1\\junk\\..\\folder2\""),
new TestCaseData(@"C:\FOLDER1\.\junk\..\Folder2", "\"C:\\FOLDER1\\.\\junk\\..\\Folder2\""),
new TestCaseData(@"C:/folder1/folder2", "\"C:/folder1/folder2\"")
};
[Test]
public void SubPathOfRoot()
{
Assert.That("C:\\junk\\file.temp", new SubPathConstraint("C:\\"));
}
}
[TestFixture]
public class SubPathTest_Linux : ConstraintTestBase
{
[SetUp]
public void SetUp()
{
TheConstraint = new SubPathConstraint(@"/folder1/folder2").RespectCase;
ExpectedDescription = @"Subpath of ""/folder1/folder2""";
StringRepresentation = @"<subpath ""/folder1/folder2"" respectcase>";
}
static object[] SuccessData = new object[]
{
@"/folder1/folder2/folder3",
@"/folder1/./folder2/folder3",
@"/folder1/junk/../folder2/folder3",
@"\folder1\folder2\folder3",
};
static object[] FailureData = new object[]
{
new TestCaseData("/Folder1/Folder2", "\"/Folder1/Folder2\""),
new TestCaseData("/FOLDER1/./junk/../Folder2", "\"/FOLDER1/./junk/../Folder2\""),
new TestCaseData("/FOLDER1/./junk/../Folder2/temp/../Folder3", "\"/FOLDER1/./junk/../Folder2/temp/../Folder3\""),
new TestCaseData("/folder1/folder3", "\"/folder1/folder3\""),
new TestCaseData("/folder1/./folder2/../folder3", "\"/folder1/./folder2/../folder3\""),
new TestCaseData("/folder1", "\"/folder1\""),
new TestCaseData("/folder1/folder2", "\"/folder1/folder2\""),
new TestCaseData("/folder1/./folder2", "\"/folder1/./folder2\""),
new TestCaseData("/folder1/junk/../folder2", "\"/folder1/junk/../folder2\""),
new TestCaseData(@"\folder1\folder2", "\"\\folder1\\folder2\"")
};
[Test]
public void SubPathOfRoot()
{
Assert.That("/junk/file.temp", new SubPathConstraint("/"));
}
}
[TestFixture]
public class SamePathOrUnderTest_Windows : StringConstraintTests
{
[SetUp]
public void SetUp()
{
TheConstraint = new SamePathOrUnderConstraint( @"C:\folder1\folder2" ).IgnoreCase;
ExpectedDescription = @"Path under or matching ""C:\folder1\folder2""";
StringRepresentation = @"<samepathorunder ""C:\folder1\folder2"" ignorecase>";
}
static object[] SuccessData = new object[]
{
@"C:\folder1\folder2",
@"C:\Folder1\Folder2",
@"C:\folder1\.\folder2",
@"C:\folder1\junk\..\folder2",
@"C:\FOLDER1\.\junk\..\Folder2",
@"C:/folder1/folder2",
@"C:\folder1\folder2\folder3",
@"C:\folder1\.\folder2\folder3",
@"C:\folder1\junk\..\folder2\folder3",
@"C:\FOLDER1\.\junk\..\Folder2\temp\..\Folder3",
@"C:/folder1/folder2/folder3",
};
static object[] FailureData = new object[]
{
new TestCaseData( @"C:\folder1\folder3", "\"C:\\folder1\\folder3\"" ),
new TestCaseData( @"C:\folder1\.\folder2\..\file.temp", "\"C:\\folder1\\.\\folder2\\..\\file.temp\"" )
};
}
[TestFixture]
public class SamePathOrUnderTest_Linux : StringConstraintTests
{
[SetUp]
public void SetUp()
{
TheConstraint = new SamePathOrUnderConstraint( @"/folder1/folder2" ).RespectCase;
ExpectedDescription = @"Path under or matching ""/folder1/folder2""";
StringRepresentation = @"<samepathorunder ""/folder1/folder2"" respectcase>";
}
static object[] SuccessData = new object[]
{
@"/folder1/folder2",
@"/folder1/./folder2",
@"/folder1/junk/../folder2",
@"\folder1\folder2",
@"/folder1/folder2/folder3",
@"/folder1/./folder2/folder3",
@"/folder1/junk/../folder2/folder3",
@"\folder1\folder2\folder3",
};
static object[] FailureData = new object[]
{
new TestCaseData( "/Folder1/Folder2", "\"/Folder1/Folder2\"" ),
new TestCaseData( "/FOLDER1/./junk/../Folder2", "\"/FOLDER1/./junk/../Folder2\"" ),
new TestCaseData( "/FOLDER1/./junk/../Folder2/temp/../Folder3", "\"/FOLDER1/./junk/../Folder2/temp/../Folder3\"" ),
new TestCaseData( "/folder1/folder3", "\"/folder1/folder3\"" ),
new TestCaseData( "/folder1/./folder2/../folder3", "\"/folder1/./folder2/../folder3\"" ),
new TestCaseData( "/folder1", "\"/folder1\"" )
};
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenMetaverse.Assets;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
/// <summary>
/// Gather uuids for a given entity.
/// </summary>
/// <remarks>
/// This does a deep inspection of the entity to retrieve all the assets it uses (whether as textures, as scripts
/// contained in inventory, as scripts contained in objects contained in another object's inventory, etc. Assets
/// are only retrieved when they are necessary to carry out the inspection (i.e. a serialized object needs to be
/// retrieved to work out which assets it references).
/// </remarks>
public class UuidGatherer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected IAssetService m_assetService;
// /// <summary>
// /// Used as a temporary store of an asset which represents an object. This can be a null if no appropriate
// /// asset was found by the asset service.
// /// </summary>
// private AssetBase m_requestedObjectAsset;
//
// /// <summary>
// /// Signal whether we are currently waiting for the asset service to deliver an asset.
// /// </summary>
// private bool m_waitingForObjectAsset;
public UuidGatherer(IAssetService assetService)
{
m_assetService = assetService;
}
/// <summary>
/// Gather all the asset uuids associated with the asset referenced by a given uuid
/// </summary>
/// <remarks>
/// This includes both those directly associated with
/// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
/// within this object).
/// </remarks>
/// <param name="assetUuid">The uuid of the asset for which to gather referenced assets</param>
/// <param name="assetType">The type of the asset for the uuid given</param>
/// <param name="assetUuids">The assets gathered</param>
public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, AssetType> assetUuids)
{
// avoid infinite loops
if (assetUuids.ContainsKey(assetUuid))
return;
try
{
assetUuids[assetUuid] = assetType;
if (AssetType.Bodypart == assetType || AssetType.Clothing == assetType)
{
GetWearableAssetUuids(assetUuid, assetUuids);
}
else if (AssetType.Gesture == assetType)
{
GetGestureAssetUuids(assetUuid, assetUuids);
}
else if (AssetType.Notecard == assetType)
{
GetTextEmbeddedAssetUuids(assetUuid, assetUuids);
}
else if (AssetType.LSLText == assetType)
{
GetTextEmbeddedAssetUuids(assetUuid, assetUuids);
}
else if (AssetType.Object == assetType)
{
GetSceneObjectAssetUuids(assetUuid, assetUuids);
}
}
catch (Exception)
{
m_log.ErrorFormat(
"[UUID GATHERER]: Failed to gather uuids for asset id {0}, type {1}",
assetUuid, assetType);
throw;
}
}
/// <summary>
/// Gather all the asset uuids associated with a given object.
/// </summary>
/// <remarks>
/// This includes both those directly associated with
/// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
/// within this object).
/// </remarks>
/// <param name="sceneObject">The scene object for which to gather assets</param>
/// <param name="assetUuids">
/// A dictionary which is populated with the asset UUIDs gathered and the type of that asset.
/// For assets where the type is not clear (e.g. UUIDs extracted from LSL and notecards), the type is Unknown.
/// </param>
public void GatherAssetUuids(SceneObjectGroup sceneObject, IDictionary<UUID, AssetType> assetUuids)
{
// m_log.DebugFormat(
// "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID);
SceneObjectPart[] parts = sceneObject.Parts;
for (int i = 0; i < parts.Length; i++)
{
SceneObjectPart part = parts[i];
// m_log.DebugFormat(
// "[ARCHIVER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID);
try
{
Primitive.TextureEntry textureEntry = part.Shape.Textures;
if (textureEntry != null)
{
// Get the prim's default texture. This will be used for faces which don't have their own texture
if (textureEntry.DefaultTexture != null)
assetUuids[textureEntry.DefaultTexture.TextureID] = AssetType.Texture;
if (textureEntry.FaceTextures != null)
{
// Loop through the rest of the texture faces (a non-null face means the face is different from DefaultTexture)
foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures)
{
if (texture != null)
assetUuids[texture.TextureID] = AssetType.Texture;
}
}
}
// If the prim is a sculpt then preserve this information too
if (part.Shape.SculptTexture != UUID.Zero)
assetUuids[part.Shape.SculptTexture] = AssetType.Texture;
TaskInventoryDictionary taskDictionary = (TaskInventoryDictionary)part.TaskInventory.Clone();
// Now analyze this prim's inventory items to preserve all the uuids that they reference
foreach (TaskInventoryItem tii in taskDictionary.Values)
{
// m_log.DebugFormat(
// "[ARCHIVER]: Analysing item {0} asset type {1} in {2} {3}",
// tii.Name, tii.Type, part.Name, part.UUID);
if (!assetUuids.ContainsKey(tii.AssetID))
GatherAssetUuids(tii.AssetID, (AssetType)tii.Type, assetUuids);
}
}
catch (Exception e)
{
m_log.ErrorFormat("[UUID GATHERER]: Failed to get part - {0}", e);
m_log.DebugFormat(
"[UUID GATHERER]: Texture entry length for prim was {0} (min is 46)",
part.Shape.TextureEntry.Length);
}
}
}
// /// <summary>
// /// The callback made when we request the asset for an object from the asset service.
// /// </summary>
// private void AssetReceived(string id, Object sender, AssetBase asset)
// {
// lock (this)
// {
// m_requestedObjectAsset = asset;
// m_waitingForObjectAsset = false;
// Monitor.Pulse(this);
// }
// }
/// <summary>
/// Get an asset synchronously, potentially using an asynchronous callback. If the
/// asynchronous callback is used, we will wait for it to complete.
/// </summary>
/// <param name="uuid"></param>
/// <returns></returns>
protected virtual AssetBase GetAsset(UUID uuid)
{
return m_assetService.Get(uuid.ToString());
// XXX: Switching to do this synchronously where the call was async before but we always waited for it
// to complete anyway!
// m_waitingForObjectAsset = true;
// m_assetCache.Get(uuid.ToString(), this, AssetReceived);
//
// // The asset cache callback can either
// //
// // 1. Complete on the same thread (if the asset is already in the cache) or
// // 2. Come in via a different thread (if we need to go fetch it).
// //
// // The code below handles both these alternatives.
// lock (this)
// {
// if (m_waitingForObjectAsset)
// {
// Monitor.Wait(this);
// m_waitingForObjectAsset = false;
// }
// }
//
// return m_requestedObjectAsset;
}
/// <summary>
/// Record the asset uuids embedded within the given script.
/// </summary>
/// <param name="scriptUuid"></param>
/// <param name="assetUuids">Dictionary in which to record the references</param>
private void GetTextEmbeddedAssetUuids(UUID embeddingAssetId, IDictionary<UUID, AssetType> assetUuids)
{
// m_log.DebugFormat("[ASSET GATHERER]: Getting assets for uuid references in asset {0}", embeddingAssetId);
AssetBase embeddingAsset = GetAsset(embeddingAssetId);
if (null != embeddingAsset)
{
string script = Utils.BytesToString(embeddingAsset.Data);
// m_log.DebugFormat("[ARCHIVER]: Script {0}", script);
MatchCollection uuidMatches = Util.PermissiveUUIDPattern.Matches(script);
// m_log.DebugFormat("[ARCHIVER]: Found {0} matches in text", uuidMatches.Count);
foreach (Match uuidMatch in uuidMatches)
{
UUID uuid = new UUID(uuidMatch.Value);
// m_log.DebugFormat("[ARCHIVER]: Recording {0} in text", uuid);
// Embedded asset references (if not false positives) could be for many types of asset, so we will
// label these as unknown.
assetUuids[uuid] = AssetType.Unknown;
}
}
}
/// <summary>
/// Record the uuids referenced by the given wearable asset
/// </summary>
/// <param name="wearableAssetUuid"></param>
/// <param name="assetUuids">Dictionary in which to record the references</param>
private void GetWearableAssetUuids(UUID wearableAssetUuid, IDictionary<UUID, AssetType> assetUuids)
{
AssetBase assetBase = GetAsset(wearableAssetUuid);
if (null != assetBase)
{
//m_log.Debug(new System.Text.ASCIIEncoding().GetString(bodypartAsset.Data));
AssetWearable wearableAsset = new AssetBodypart(wearableAssetUuid, assetBase.Data);
wearableAsset.Decode();
//m_log.DebugFormat(
// "[ARCHIVER]: Wearable asset {0} references {1} assets", wearableAssetUuid, wearableAsset.Textures.Count);
foreach (UUID uuid in wearableAsset.Textures.Values)
{
assetUuids[uuid] = AssetType.Texture;
}
}
}
/// <summary>
/// Get all the asset uuids associated with a given object. This includes both those directly associated with
/// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
/// within this object).
/// </summary>
/// <param name="sceneObject"></param>
/// <param name="assetUuids"></param>
private void GetSceneObjectAssetUuids(UUID sceneObjectUuid, IDictionary<UUID, AssetType> assetUuids)
{
AssetBase objectAsset = GetAsset(sceneObjectUuid);
if (null != objectAsset)
{
string xml = Utils.BytesToString(objectAsset.Data);
CoalescedSceneObjects coa;
if (CoalescedSceneObjectsSerializer.TryFromXml(xml, out coa))
{
foreach (SceneObjectGroup sog in coa.Objects)
GatherAssetUuids(sog, assetUuids);
}
else
{
SceneObjectGroup sog = SceneObjectSerializer.FromOriginalXmlFormat(xml);
if (null != sog)
GatherAssetUuids(sog, assetUuids);
}
}
}
/// <summary>
/// Get the asset uuid associated with a gesture
/// </summary>
/// <param name="gestureUuid"></param>
/// <param name="assetUuids"></param>
private void GetGestureAssetUuids(UUID gestureUuid, IDictionary<UUID, AssetType> assetUuids)
{
AssetBase assetBase = GetAsset(gestureUuid);
if (null == assetBase)
return;
MemoryStream ms = new MemoryStream(assetBase.Data);
StreamReader sr = new StreamReader(ms);
sr.ReadLine(); // Unknown (Version?)
sr.ReadLine(); // Unknown
sr.ReadLine(); // Unknown
sr.ReadLine(); // Name
sr.ReadLine(); // Comment ?
int count = Convert.ToInt32(sr.ReadLine()); // Item count
for (int i = 0 ; i < count ; i++)
{
string type = sr.ReadLine();
if (type == null)
break;
string name = sr.ReadLine();
if (name == null)
break;
string id = sr.ReadLine();
if (id == null)
break;
string unknown = sr.ReadLine();
if (unknown == null)
break;
// If it can be parsed as a UUID, it is an asset ID
UUID uuid;
if (UUID.TryParse(id, out uuid))
assetUuids[uuid] = AssetType.Animation;
}
}
}
public class HGUuidGatherer : UuidGatherer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_assetServerURL;
public HGUuidGatherer(IAssetService assetService, string assetServerURL)
: base(assetService)
{
m_assetServerURL = assetServerURL;
if (!m_assetServerURL.EndsWith("/") && !m_assetServerURL.EndsWith("="))
m_assetServerURL = m_assetServerURL + "/";
}
protected override AssetBase GetAsset(UUID uuid)
{
if (string.Empty == m_assetServerURL)
return base.GetAsset(uuid);
else
return FetchAsset(uuid);
}
public AssetBase FetchAsset(UUID assetID)
{
// Test if it's already here
AssetBase asset = m_assetService.Get(assetID.ToString());
if (asset == null)
{
// It's not, so fetch it from abroad
asset = m_assetService.Get(m_assetServerURL + assetID.ToString());
if (asset != null)
m_log.DebugFormat("[HGUUIDGatherer]: Copied asset {0} from {1} to local asset server", assetID, m_assetServerURL);
else
m_log.DebugFormat("[HGUUIDGatherer]: Failed to fetch asset {0} from {1}", assetID, m_assetServerURL);
}
//else
// m_log.DebugFormat("[HGUUIDGatherer]: Asset {0} from {1} was already here", assetID, m_assetServerURL);
return asset;
}
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Collections.Specialized;
namespace Owin {
public class Response : IResponse {
#region Constructors
public Response() {
SetValidDefaults();
}
public Response(string bodyText, string status) : this(bodyText) {
Status = status;
}
public Response(string bodyText) : this() {
BodyText = bodyText;
}
public Response(string bodyText, int statusCode) : this() {
BodyText = bodyText;
SetStatus(statusCode);
}
public Response(string bodyText, IDictionary<string, string> headers) : this(0, bodyText, headers) { }
public Response(string bodyText, IDictionary<string, IEnumerable<string>> headers) : this(0, bodyText, headers) { }
public Response(int statusCode, IDictionary<string, string> headers) : this(statusCode, null, headers) { }
public Response(int statusCode, IDictionary<string, IEnumerable<string>> headers) : this(statusCode, null, headers) { }
public Response(int statusCode, string bodyText, IDictionary<string, string> headers) : this() {
if (statusCode != 0) SetStatus(statusCode);
if (bodyText != null) BodyText = bodyText;
if (headers != null) AddHeaders(headers);
}
public Response(int statusCode, string bodyText, IDictionary<string, IEnumerable<string>> headers) : this() {
if (statusCode != 0) SetStatus(statusCode);
if (bodyText != null) BodyText = bodyText;
if (headers != null) AddHeaders(headers);
}
public Response(IResponse response) : this() {
if (response.Status != null)
Status = response.Status;
if (response.Headers != null)
Headers = response.Headers;
foreach (object o in response.GetBody())
AddToBody(o);
}
#endregion
#region Status
public string Status { get; set; }
public int StatusCode {
get { return int.Parse(Status.Substring(0, Status.IndexOf(" "))); }
}
public string StatusMessage {
get { return Status.Substring(Status.IndexOf(" ") + 1); }
}
public Response SetStatus(int statusCode) {
string statusMessage = ((HttpStatusCode)statusCode).ToString();
Status = string.Format("{0} {1}", statusCode, statusMessage);
return this;
}
public Response SetStatus(string status) {
Status = status;
return this;
}
#endregion
#region Body
// Allowed object types: string, byte[], ArraySegment<byte>, FileInfo
public IEnumerable<object> GetBody() {
return Body;
}
public IEnumerable<object> Body { get; set; }
// TODO this needs to update ContentLength!
/// <summary>Set the body to one or many objects, overriding any other values the body may have</summary>
public Response SetBody(params object[] objects) {
if (objects.Length == 1 && objects[0] is IEnumerable<object>)
Body = objects[0] as IEnumerable<object>;
else
Body = objects;
return this;
}
/// <summary>Set the body to one or many objects, adding to any other values the body may have</summary>
public Response AddToBody(params object[] objects) {
IEnumerable<object> stuffToAdd = objects;
if (objects.Length == 1 && objects[0] is IEnumerable<object>)
stuffToAdd = objects[0] as IEnumerable<object>;
List<object> allObjects = new List<object>(Body);
allObjects.AddRange(stuffToAdd);
Body = allObjects;
return this;
}
public string BodyText {
get {
string text = "";
foreach (object bodyPart in Body) {
if (bodyPart is string)
text += bodyPart.ToString();
else
throw new FormatException("Cannot get BodyText unless Body only contains strings. Body contains: " + bodyPart.GetType().Name);
}
return text;
}
set {
Body = new object[] { value };
ContentLength = value.Length;
}
}
// might swap this out with a string builder ...
// it's tough because we should be able to write bytes as well!
public Response Write(string writeToBody) {
BodyText += writeToBody;
return this;
}
public Response Write(string writeToBody, params object[] objects) {
return Write(string.Format(writeToBody, objects));
}
public void Clear() {
BodyText = "";
}
#endregion
#region Headers
public IDictionary<string, IEnumerable<string>> Headers { get; set; }
public Response Redirect(string location) {
return Redirect(302, location);
}
public Response Redirect(int statusCode, string location) {
return SetStatus(statusCode).SetHeader("location", location);
}
/// <summary>Set header with a string, overriding any other values this header may have</summary>
public Response SetHeader(string key, string value) {
Headers[key] = new string[] { value };
return this;
}
/// <summary>Set header, overriding any other values this header may have</summary>
public Response SetHeader(string key, IEnumerable<string> value) {
Headers[key] = value;
return this;
}
/// <summary>Set header with a string, adding to any other values this header may have</summary>
public Response AddHeader(string key, string value) {
if (Headers.ContainsKey(key)) {
List<string> listOfValues = new List<string>(Headers[key]);
listOfValues.Add(value);
SetHeader(key, listOfValues.ToArray());
} else
SetHeader(key, value);
return this;
}
/// <summary>Set header, adding to any other values this header may have</summary>
public Response AddHeader(string key, IEnumerable<string> value) {
if (Headers.ContainsKey(key)) {
List<string> listOfValues = new List<string>(Headers[key]);
listOfValues.AddRange(value);
SetHeader(key, listOfValues.ToArray());
} else
SetHeader(key, value);
return this;
}
/// <summary>Returns the first value of the given header or null if the header does not exist</summary>
public virtual string GetHeader(string key) {
key = key.ToLower(); // <--- instead of doing this everywhere, it would be ideal if the Headers IDictionary could do this by itself!
if (! Headers.ContainsKey(key))
return null;
else {
string value = null;
foreach (string headerValue in Headers[key]) {
value = headerValue;
break;
}
return value;
}
}
public string ContentType {
get { return GetHeader("content-type"); }
set { SetHeader("content-type", value); }
}
public int ContentLength {
get {
string length = GetHeader("content-length");
return (length == null) ? 0 : int.Parse(length);
}
set { SetHeader("content-length", value.ToString()); }
}
#endregion
#region Private
void SetValidDefaults() {
Status = "200 OK";
Headers = new Dictionary<string, IEnumerable<string>>();
Body = new object[] { };
ContentType = "text/html";
}
void AddHeaders(IDictionary<string, string> headers) {
foreach (KeyValuePair<string, string> header in headers)
Headers[header.Key] = new string[] { header.Value };
}
void AddHeaders(IDictionary<string, IEnumerable<string>> headers) {
foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
Headers[header.Key] = header.Value;
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Threading;
using Orleans.AzureUtils;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.Host
{
/// <summary>
/// Wrapper class for an Orleans silo running in the current host process.
/// </summary>
public class AzureSilo
{
/// <summary>
/// Amount of time to pause before retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 5 seconds.
/// </summary>
public TimeSpan StartupRetryPause { get; set; }
/// <summary>
/// Number of times to retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 120 times.
/// </summary>
public int MaxRetries { get; set; }
/// <summary>
/// The name of the configuration key value for locating the DataConnectionString setting from the Azure configuration for this role.
/// Defaults to <c>DataConnectionString</c>
/// </summary>
public string DataConnectionConfigurationSettingName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansSiloEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansSiloEndpoint</c>
/// </summary>
public string SiloEndpointConfigurationKeyName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansProxyEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansProxyEndpoint</c>
/// </summary>
public string ProxyEndpointConfigurationKeyName { get; set; }
private SiloHost host;
private OrleansSiloInstanceManager siloInstanceManager;
private SiloInstanceTableEntry myEntry;
private readonly TraceLogger logger;
private readonly IServiceRuntimeWrapper serviceRuntimeWrapper = new ServiceRuntimeWrapper();
/// <summary>
/// Constructor
/// </summary>
public AzureSilo()
{
DataConnectionConfigurationSettingName = AzureConstants.DataConnectionConfigurationSettingName;
SiloEndpointConfigurationKeyName = AzureConstants.SiloEndpointConfigurationKeyName;
ProxyEndpointConfigurationKeyName = AzureConstants.ProxyEndpointConfigurationKeyName;
StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds
MaxRetries = AzureConstants.MAX_RETRIES; // 120 x 5s = Total: 10 minutes
logger = TraceLogger.GetLogger("OrleansAzureSilo", TraceLogger.LoggerType.Runtime);
}
public static ClusterConfiguration DefaultConfiguration()
{
var config = new ClusterConfiguration();
config.Globals.LivenessType = GlobalConfiguration.LivenessProviderType.AzureTable;
config.Globals.DeploymentId = AzureClient.GetDeploymentId();
config.Globals.DataConnectionString = AzureClient.GetDataConnectionString();
return config;
}
#region Azure RoleEntryPoint methods
/// <summary>
/// Initialize this Orleans silo for execution
/// </summary>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start()
{
return Start(null);
}
/// <summary>
/// Initialize this Orleans silo for execution with the specified Azure deploymentId
/// </summary>
/// <param name="config">If null, Config data will be read from silo config file as normal, otherwise use the specified config data.</param>
/// <param name="deploymentId">Azure DeploymentId this silo is running under</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start(ClusterConfiguration config, string deploymentId = null, string connectionString = null)
{
// Program ident
Trace.TraceInformation("Starting {0} v{1}", this.GetType().FullName, RuntimeVersion.Current);
// Check if deployment id was specified
if (deploymentId == null)
deploymentId = serviceRuntimeWrapper.DeploymentId;
// Read endpoint info for this instance from Azure config
string instanceName = serviceRuntimeWrapper.InstanceName;
// Configure this Orleans silo instance
if (config == null)
{
host = new SiloHost(instanceName);
host.LoadOrleansConfig(); // Load config from file + Initializes logger configurations
}
else
{
host = new SiloHost(instanceName, config); // Use supplied config data + Initializes logger configurations
}
IPEndPoint myEndpoint = serviceRuntimeWrapper.GetIPEndpoint(SiloEndpointConfigurationKeyName);
IPEndPoint proxyEndpoint = serviceRuntimeWrapper.GetIPEndpoint(ProxyEndpointConfigurationKeyName);
host.SetSiloType(Silo.SiloType.Secondary);
int generation = SiloAddress.AllocateNewGeneration();
// Bootstrap this Orleans silo instance
myEntry = new SiloInstanceTableEntry
{
DeploymentId = deploymentId,
Address = myEndpoint.Address.ToString(),
Port = myEndpoint.Port.ToString(CultureInfo.InvariantCulture),
Generation = generation.ToString(CultureInfo.InvariantCulture),
HostName = host.Config.GetOrCreateNodeConfigurationForSilo(host.Name).DNSHostName,
ProxyPort = (proxyEndpoint != null ? proxyEndpoint.Port : 0).ToString(CultureInfo.InvariantCulture),
RoleName = serviceRuntimeWrapper.RoleName,
SiloName = instanceName,
UpdateZone = serviceRuntimeWrapper.UpdateDomain.ToString(CultureInfo.InvariantCulture),
FaultZone = serviceRuntimeWrapper.FaultDomain.ToString(CultureInfo.InvariantCulture),
StartTime = TraceLogger.PrintDate(DateTime.UtcNow),
PartitionKey = deploymentId,
RowKey = myEndpoint.Address + "-" + myEndpoint.Port + "-" + generation
};
if (connectionString == null)
connectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
try
{
siloInstanceManager = OrleansSiloInstanceManager.GetManager(
deploymentId, connectionString).WithTimeout(AzureTableDefaultPolicies.TableCreationTimeout).Result;
}
catch (Exception exc)
{
var error = String.Format("Failed to create OrleansSiloInstanceManager. This means CreateTableIfNotExist for silo instance table has failed with {0}",
TraceLogger.PrintException(exc));
Trace.TraceError(error);
logger.Error(ErrorCode.AzureTable_34, error, exc);
throw new OrleansException(error, exc);
}
// Always use Azure table for membership when running silo in Azure
host.SetSiloLivenessType(GlobalConfiguration.LivenessProviderType.AzureTable);
if (host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.NotSpecified ||
host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain)
{
host.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable);
}
host.SetExpectedClusterSize(serviceRuntimeWrapper.RoleInstanceCount);
siloInstanceManager.RegisterSiloInstance(myEntry);
// Initialise this Orleans silo instance
host.SetDeploymentId(deploymentId, connectionString);
host.SetSiloEndpoint(myEndpoint, generation);
host.SetProxyEndpoint(proxyEndpoint);
host.InitializeOrleansSilo();
logger.Info(ErrorCode.Runtime_Error_100288, "Successfully initialized Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
return StartSilo();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown.
/// </summary>
public void Run()
{
RunImpl();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
public void Run(CancellationToken cancellationToken)
{
RunImpl(cancellationToken);
}
/// <summary>
/// Stop this Orleans silo executing.
/// </summary>
public void Stop()
{
logger.Info(ErrorCode.Runtime_Error_100290, "Stopping {0}", this.GetType().FullName);
serviceRuntimeWrapper.UnsubscribeFromStoppingNotifcation(this, HandleAzureRoleStopping);
host.ShutdownOrleansSilo();
logger.Info(ErrorCode.Runtime_Error_100291, "Orleans silo '{0}' shutdown.", host.Name);
}
#endregion
private bool StartSilo()
{
logger.Info(ErrorCode.Runtime_Error_100292, "Starting Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
bool ok = host.StartOrleansSilo();
if (ok)
logger.Info(ErrorCode.Runtime_Error_100293, "Successfully started Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
else
logger.Error(ErrorCode.Runtime_Error_100285, string.Format("Failed to start Orleans silo '{0}' as a {1} node.", host.Name, host.Type));
return ok;
}
private void HandleAzureRoleStopping(object sender, object e)
{
// Try to perform gracefull shutdown of Silo when we detect Azure role instance is being stopped
logger.Info(ErrorCode.SiloStopping, "HandleAzureRoleStopping - starting to shutdown silo");
host.ShutdownOrleansSilo();
}
/// <summary>
/// Run method helper.
/// </summary>
/// <remarks>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </remarks>
/// <param name="cancellationToken">Optional cancellation token.</param>
private void RunImpl(CancellationToken? cancellationToken = null)
{
logger.Info(ErrorCode.Runtime_Error_100289, "OrleansAzureHost entry point called");
// Hook up to receive notification of Azure role stopping events
serviceRuntimeWrapper.SubscribeForStoppingNotifcation(this, HandleAzureRoleStopping);
if (host.IsStarted)
{
if (cancellationToken.HasValue)
host.WaitForOrleansSiloShutdown(cancellationToken.Value);
else
host.WaitForOrleansSiloShutdown();
}
else
throw new Exception("Silo failed to start correctly - aborting");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using log4net;
using WaterOneFlow.Schema.v1_1;
using WaterOneFlowImpl;
using WaterOneFlowImpl.v1_1;
namespace WaterOneFlow.odws
{
using WaterOneFlow.odm.v1_1;
using SeriesCatalogTableAdapter = WaterOneFlow.odm.v1_1.seriesCatalogDataSetTableAdapters.SeriesCatalogTableAdapter;
namespace v1_1
{
/// <summary>
/// Summary description for ODSeriesCatalog
/// </summary>
public class ODSeriesCatalog
{
private static readonly ILog log = LogManager.GetLogger(typeof(ODSeriesCatalog));
public ODSeriesCatalog()
{
}
/// <summary>
/// get a series catalog for a site.
///
/// </summary>
/// <param name="siteID"></param>
/// <returns></returns>
public static seriesCatalogDataSet GetSeriesCatalogDataSet(int siteID)
{
seriesCatalogDataSet sDS = new seriesCatalogDataSet();
SeriesCatalogTableAdapter seriesTableAdapter =
new SeriesCatalogTableAdapter();
seriesTableAdapter.Connection.ConnectionString = odws.Config.ODDB();
try
{
seriesTableAdapter.FillBySiteID(sDS.SeriesCatalog, siteID);
}
catch (Exception e)
{
log.Fatal("Cannot retrieve information from database: " + e.Message); // + seriesTableAdapter.Connection.DataSource
}
return sDS;
}
public static seriesCatalogType[] dataSet2SeriesCatalog(seriesCatalogDataSet ds, VariablesDataset vds, ControlledVocabularyDataset vocabularyDataset)
{
/* logic
* for each sourceID that is associated with the site
*
*
*/
List<seriesCatalogType> catalogs = new List<seriesCatalogType>();
seriesCatalogType catalog = createSeriesCatalog(ds, vds, vocabularyDataset);
if (catalog != null) catalogs.Add(catalog);
return catalogs.ToArray();
}
private static seriesCatalogType createSeriesCatalog(seriesCatalogDataSet ds, VariablesDataset vds, ControlledVocabularyDataset vocabularyDataset)
{
if (ds.SeriesCatalog.Count > 0)
{
Boolean useOD;
String siteServiceURL;
String siteServiceName;
try
{
useOD = Boolean.Parse(ConfigurationManager.AppSettings["UseODForValues"]);
if (!useOD)
{
siteServiceURL = ConfigurationManager.AppSettings["externalGetValuesService"];
siteServiceName = ConfigurationManager.AppSettings["externalGetValuesName"];
}
else
{
siteServiceURL = "http://localhost/";
siteServiceName = "OD Web Services";
}
}
catch
{
useOD = true; // should be caught earlier
siteServiceURL = "http://locahost/";
siteServiceName = "Fix UseODForValues, externalGetValuesService, externalGetValuesName";
}
seriesCatalogType catalog = CuahsiBuilder.CreateSeriesCatalog(ds.SeriesCatalog.Count,
siteServiceName, // menu name (aka OD name
siteServiceURL // web service location
);
List<seriesCatalogTypeSeries> seriesRecords = new List<seriesCatalogTypeSeries>();
foreach (seriesCatalogDataSet.SeriesCatalogRow row in ds.SeriesCatalog.Rows)
{
seriesCatalogTypeSeries aRecord = row2SeriesCatalogElement(
row, ds, vds, vocabularyDataset);
seriesRecords.Add(aRecord);
}
catalog.series = seriesRecords.ToArray();
return catalog;
}
else
{
seriesCatalogType catalog = CuahsiBuilder.CreateSeriesCatalog(0,
null, // menu name (aka OD name
"http://locahost/" // web service location
);
return catalog;
}
}
public static seriesCatalogTypeSeries row2SeriesCatalogElement(seriesCatalogDataSet.SeriesCatalogRow row, seriesCatalogDataSet ds, VariablesDataset vds, ControlledVocabularyDataset vocabularyDataset)
{
int variableID = row.VariableID;
VariableInfoType variable = ODvariables.GetVariableByID(variableID, vds);
Nullable<W3CDateTime> beginDateTime = null;
if (!row.IsBeginDateTimeNull())
{
TimeSpan timeSpan = row.BeginDateTime.Subtract(row.BeginDateTimeUTC);
beginDateTime = new W3CDateTime(row.BeginDateTime, timeSpan);
}
Nullable<W3CDateTime> endDateTime = null;
if (!row.IsEndDateTimeNull())
{
TimeSpan timeSpan = row.EndDateTime.Subtract(row.EndDateTimeUTC);
endDateTime = new W3CDateTime(row.EndDateTime, timeSpan);
}
Nullable<int> valueCount = null;
if (!row.IsValueCountNull()) valueCount = row.ValueCount;
string qualityControlLevelTerm = null;
int? QualityControlLevelid = null;
if (!row.IsQualityControlLevelIDNull())
{
QualityControlLevelid = row.QualityControlLevelID;
ControlledVocabularyDataset.QualityControlLevelsRow qcRow =
vocabularyDataset.QualityControlLevels.FindByQualityControlLevelID(QualityControlLevelid.Value);
if (qcRow != null )
{
qualityControlLevelTerm = qcRow.Definition;
}
}
int? MethodID = null;
if (!row.IsMethodIDNull()) MethodID = row.MethodID;
int? SourceID = null;
if (!row.IsSourceIDNull()) SourceID = row.SourceID;
Nullable<Boolean> valueCountIsEstimated = false;
/* public static seriesCatalogTypeSeries createSeriesCatalogRecord(
VariableInfoType variable,
string sampleMedium,
Nullable<W3CDateTime> beginDateTime,
Nullable<W3CDateTime> endDateTime,
Nullable<int> valueCount,
Nullable<Boolean> valueCountIsEstimated,
string dataType,
string valueType,
string generalCategory
)
*/
seriesCatalogTypeSeries record = CuahsiBuilder.CreateSeriesRecord(
variable,
variable.sampleMedium.ToString(),
beginDateTime,
endDateTime,
valueCount,
valueCountIsEstimated,
null,
null,
null,
false, // real time
null, // string if real time
row.QualityControlLevelCode,
QualityControlLevelid,
row.MethodDescription,
MethodID, row.Organization,
row.SourceDescription,
SourceID,
row.Citation,
true, // include UTC Time
qualityControlLevelTerm
);
return record;
}
}
}
}
| |
namespace LythumOSL.Reporting.CR
{
partial class FrmReports
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose (bool disposing)
{
if (disposing && (components != null))
{
components.Dispose ();
}
base.Dispose (disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent ()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager (typeof (FrmReports));
this.CrvMain = new CrystalDecisions.Windows.Forms.CrystalReportViewer ();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel ();
this.panel1 = new System.Windows.Forms.Panel ();
this.CmdExport = new System.Windows.Forms.Button ();
this.CmbExportFormat = new System.Windows.Forms.ComboBox ();
this.TxtCopiesCount = new System.Windows.Forms.TextBox ();
this.LblCopiesCount = new System.Windows.Forms.Label ();
this.CmdPrintAll = new System.Windows.Forms.Button ();
this.CmdPrintOne = new System.Windows.Forms.Button ();
this.LbxReports = new System.Windows.Forms.ListBox ();
this.tableLayoutPanel1.SuspendLayout ();
this.panel1.SuspendLayout ();
this.SuspendLayout ();
//
// CrvMain
//
this.CrvMain.ActiveViewIndex = -1;
this.CrvMain.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.CrvMain.DisplayGroupTree = false;
this.CrvMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.CrvMain.Enabled = false;
this.CrvMain.Location = new System.Drawing.Point (258, 3);
this.CrvMain.Name = "CrvMain";
this.CrvMain.SelectionFormula = "";
this.CrvMain.ShowCloseButton = false;
this.CrvMain.ShowGroupTreeButton = false;
this.CrvMain.ShowRefreshButton = false;
this.CrvMain.Size = new System.Drawing.Size (584, 390);
this.CrvMain.TabIndex = 1;
this.CrvMain.ViewTimeSelectionFormula = "";
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 2;
this.tableLayoutPanel1.ColumnStyles.Add (new System.Windows.Forms.ColumnStyle (System.Windows.Forms.SizeType.Percent, 30.17752F));
this.tableLayoutPanel1.ColumnStyles.Add (new System.Windows.Forms.ColumnStyle (System.Windows.Forms.SizeType.Percent, 69.82249F));
this.tableLayoutPanel1.Controls.Add (this.panel1, 0, 1);
this.tableLayoutPanel1.Controls.Add (this.CrvMain, 1, 0);
this.tableLayoutPanel1.Controls.Add (this.LbxReports, 0, 0);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point (0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 2;
this.tableLayoutPanel1.RowStyles.Add (new System.Windows.Forms.RowStyle (System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.RowStyles.Add (new System.Windows.Forms.RowStyle (System.Windows.Forms.SizeType.Absolute, 45F));
this.tableLayoutPanel1.Size = new System.Drawing.Size (845, 441);
this.tableLayoutPanel1.TabIndex = 2;
//
// panel1
//
this.tableLayoutPanel1.SetColumnSpan (this.panel1, 2);
this.panel1.Controls.Add (this.CmdExport);
this.panel1.Controls.Add (this.CmbExportFormat);
this.panel1.Controls.Add (this.TxtCopiesCount);
this.panel1.Controls.Add (this.LblCopiesCount);
this.panel1.Controls.Add (this.CmdPrintAll);
this.panel1.Controls.Add (this.CmdPrintOne);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point (3, 399);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size (839, 39);
this.panel1.TabIndex = 2;
//
// CmdExport
//
this.CmdExport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.CmdExport.Location = new System.Drawing.Point (706, 0);
this.CmdExport.Name = "CmdExport";
this.CmdExport.Size = new System.Drawing.Size (133, 36);
this.CmdExport.TabIndex = 5;
this.CmdExport.Text = "Export selected";
this.CmdExport.UseVisualStyleBackColor = true;
this.CmdExport.Click += new System.EventHandler (this.CmdExport_Click);
//
// CmbExportFormat
//
this.CmbExportFormat.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.CmbExportFormat.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.CmbExportFormat.FormattingEnabled = true;
this.CmbExportFormat.Location = new System.Drawing.Point (560, 3);
this.CmbExportFormat.Name = "CmbExportFormat";
this.CmbExportFormat.Size = new System.Drawing.Size (140, 21);
this.CmbExportFormat.TabIndex = 4;
//
// TxtCopiesCount
//
this.TxtCopiesCount.BackColor = System.Drawing.SystemColors.Window;
this.TxtCopiesCount.HideSelection = false;
this.TxtCopiesCount.Location = new System.Drawing.Point (253, 3);
this.TxtCopiesCount.Name = "TxtCopiesCount";
this.TxtCopiesCount.Size = new System.Drawing.Size (50, 20);
this.TxtCopiesCount.TabIndex = 3;
this.TxtCopiesCount.TextChanged += new System.EventHandler (this.TxtCopiesCount_TextChanged);
this.TxtCopiesCount.Validating += new System.ComponentModel.CancelEventHandler (this.TxtCopiesCount_Validating);
//
// LblCopiesCount
//
this.LblCopiesCount.AutoSize = true;
this.LblCopiesCount.Location = new System.Drawing.Point (309, 3);
this.LblCopiesCount.Name = "LblCopiesCount";
this.LblCopiesCount.Size = new System.Drawing.Size (69, 13);
this.LblCopiesCount.TabIndex = 2;
this.LblCopiesCount.Text = "Copies count";
//
// CmdPrintAll
//
this.CmdPrintAll.Enabled = false;
this.CmdPrintAll.Location = new System.Drawing.Point (127, 0);
this.CmdPrintAll.Name = "CmdPrintAll";
this.CmdPrintAll.Size = new System.Drawing.Size (120, 36);
this.CmdPrintAll.TabIndex = 1;
this.CmdPrintAll.Text = "Print all";
this.CmdPrintAll.UseVisualStyleBackColor = true;
this.CmdPrintAll.Click += new System.EventHandler (this.CmdPrintAll_Click);
//
// CmdPrintOne
//
this.CmdPrintOne.Enabled = false;
this.CmdPrintOne.Location = new System.Drawing.Point (0, 0);
this.CmdPrintOne.Name = "CmdPrintOne";
this.CmdPrintOne.Size = new System.Drawing.Size (120, 36);
this.CmdPrintOne.TabIndex = 0;
this.CmdPrintOne.Text = "Print selected";
this.CmdPrintOne.UseVisualStyleBackColor = true;
this.CmdPrintOne.Click += new System.EventHandler (this.CmdPrintOne_Click);
//
// LbxReports
//
this.LbxReports.Dock = System.Windows.Forms.DockStyle.Fill;
this.LbxReports.FormattingEnabled = true;
this.LbxReports.Location = new System.Drawing.Point (3, 3);
this.LbxReports.Name = "LbxReports";
this.LbxReports.Size = new System.Drawing.Size (249, 381);
this.LbxReports.TabIndex = 3;
this.LbxReports.SelectedIndexChanged += new System.EventHandler (this.LvwList_SelectedIndexChanged);
//
// FrmReports
//
this.AutoScaleDimensions = new System.Drawing.SizeF (6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size (845, 441);
this.Controls.Add (this.tableLayoutPanel1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject ("$this.Icon")));
this.Name = "FrmReports";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "FrmReports";
this.Load += new System.EventHandler (this.FrmReports_Load);
this.Resize += new System.EventHandler (this.FrmReports_Resize);
this.tableLayoutPanel1.ResumeLayout (false);
this.panel1.ResumeLayout (false);
this.panel1.PerformLayout ();
this.ResumeLayout (false);
}
#endregion
internal CrystalDecisions.Windows.Forms.CrystalReportViewer CrvMain;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button CmdPrintAll;
private System.Windows.Forms.Button CmdPrintOne;
private System.Windows.Forms.Label LblCopiesCount;
private System.Windows.Forms.TextBox TxtCopiesCount;
private System.Windows.Forms.Button CmdExport;
private System.Windows.Forms.ComboBox CmbExportFormat;
private System.Windows.Forms.ListBox LbxReports;
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="ComplexPropertyDefinitionBase.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the ComplexPropertyDefinitionBase class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Represents abstract complex property definition.
/// </summary>
internal abstract class ComplexPropertyDefinitionBase : PropertyDefinition
{
/// <summary>
/// Initializes a new instance of the <see cref="ComplexPropertyDefinitionBase"/> class.
/// </summary>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <param name="flags">The flags.</param>
/// <param name="version">The version.</param>
internal ComplexPropertyDefinitionBase(
string xmlElementName,
PropertyDefinitionFlags flags,
ExchangeVersion version)
: base(
xmlElementName,
flags,
version)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ComplexPropertyDefinitionBase"/> class.
/// </summary>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <param name="uri">The URI.</param>
/// <param name="version">The version.</param>
internal ComplexPropertyDefinitionBase(
string xmlElementName,
string uri,
ExchangeVersion version)
: base(
xmlElementName,
uri,
version)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ComplexPropertyDefinitionBase"/> class.
/// </summary>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <param name="uri">The URI.</param>
/// <param name="flags">The flags.</param>
/// <param name="version">The version.</param>
internal ComplexPropertyDefinitionBase(
string xmlElementName,
string uri,
PropertyDefinitionFlags flags,
ExchangeVersion version)
: base(
xmlElementName,
uri,
flags,
version)
{
}
/// <summary>
/// Creates the property instance.
/// </summary>
/// <param name="owner">The owner.</param>
/// <returns>ComplexProperty.</returns>
internal abstract ComplexProperty CreatePropertyInstance(ServiceObject owner);
/// <summary>
/// Internals the load from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="propertyBag">The property bag.</param>
internal virtual void InternalLoadFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag)
{
object complexProperty;
bool justCreated = GetPropertyInstance(propertyBag, out complexProperty);
if (!justCreated && this.HasFlag(PropertyDefinitionFlags.UpdateCollectionItems, propertyBag.Owner.Service.RequestedServerVersion))
{
(complexProperty as ComplexProperty).UpdateFromXml(reader, reader.LocalName);
}
else
{
(complexProperty as ComplexProperty).LoadFromXml(reader, reader.LocalName);
}
propertyBag[this] = complexProperty;
}
/// <summary>
/// Internals the load from json.
/// </summary>
/// <param name="jsonObject">The json object.</param>
/// <param name="service">The service.</param>
/// <param name="propertyBag">The property bag.</param>
internal virtual void InternalLoadFromJson(JsonObject jsonObject, ExchangeService service, PropertyBag propertyBag)
{
object complexProperty;
bool justCreated = GetPropertyInstance(propertyBag, out complexProperty);
(complexProperty as ComplexProperty).LoadFromJson(jsonObject, service);
propertyBag[this] = complexProperty;
}
/// <summary>
/// Internals the load colelction from json.
/// </summary>
/// <param name="jsonCollection">The json collection.</param>
/// <param name="service">The service.</param>
/// <param name="propertyBag">The property bag.</param>
private void InternalLoadCollectionFromJson(object[] jsonCollection, ExchangeService service, PropertyBag propertyBag)
{
object propertyInstance;
bool justCreated = GetPropertyInstance(propertyBag, out propertyInstance);
IJsonCollectionDeserializer complexProperty = propertyInstance as IJsonCollectionDeserializer;
if (complexProperty == null)
{
throw new ServiceJsonDeserializationException();
}
if (!justCreated && this.HasFlag(PropertyDefinitionFlags.UpdateCollectionItems, propertyBag.Owner.Service.RequestedServerVersion))
{
complexProperty.UpdateFromJsonCollection(jsonCollection, service);
}
else
{
complexProperty.CreateFromJsonCollection(jsonCollection, service);
}
propertyBag[this] = complexProperty;
}
/// <summary>
/// Gets the property instance.
/// </summary>
/// <param name="propertyBag">The property bag.</param>
/// <param name="complexProperty">The property instance.</param>
/// <returns>True if the instance is newly created.</returns>
private bool GetPropertyInstance(PropertyBag propertyBag, out object complexProperty)
{
complexProperty = null;
if (!propertyBag.TryGetValue(this, out complexProperty) || !this.HasFlag(PropertyDefinitionFlags.ReuseInstance, propertyBag.Owner.Service.RequestedServerVersion))
{
complexProperty = this.CreatePropertyInstance(propertyBag.Owner);
return true;
}
return false;
}
/// <summary>
/// Loads from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="propertyBag">The property bag.</param>
internal override sealed void LoadPropertyValueFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag)
{
reader.EnsureCurrentNodeIsStartElement(XmlNamespace.Types, this.XmlElementName);
if (!reader.IsEmptyElement || reader.HasAttributes)
{
this.InternalLoadFromXml(reader, propertyBag);
}
reader.ReadEndElementIfNecessary(XmlNamespace.Types, this.XmlElementName);
}
/// <summary>
/// Loads the property value from json.
/// </summary>
/// <param name="value">The JSON value. Can be a JsonObject, string, number, bool, array, or null.</param>
/// <param name="service">The service.</param>
/// <param name="propertyBag">The property bag.</param>
internal override void LoadPropertyValueFromJson(object value, ExchangeService service, PropertyBag propertyBag)
{
JsonObject jsonObject = value as JsonObject;
if (jsonObject != null)
{
this.InternalLoadFromJson(jsonObject, service, propertyBag);
}
else if (value.GetType().IsArray)
{
this.InternalLoadCollectionFromJson(value as object[], service, propertyBag);
}
}
/// <summary>
/// Writes to XML.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="propertyBag">The property bag.</param>
/// <param name="isUpdateOperation">Indicates whether the context is an update operation.</param>
internal override void WritePropertyValueToXml(
EwsServiceXmlWriter writer,
PropertyBag propertyBag,
bool isUpdateOperation)
{
ComplexProperty complexProperty = (ComplexProperty)propertyBag[this];
if (complexProperty != null)
{
complexProperty.WriteToXml(writer, this.XmlElementName);
}
}
/// <summary>
/// Writes the json value.
/// </summary>
/// <param name="jsonObject">The json object.</param>
/// <param name="propertyBag">The property bag.</param>
/// <param name="service">The service.</param>
/// <param name="isUpdateOperation">if set to <c>true</c> [is update operation].</param>
internal override void WriteJsonValue(JsonObject jsonObject, PropertyBag propertyBag, ExchangeService service, bool isUpdateOperation)
{
ComplexProperty complexProperty = (ComplexProperty)propertyBag[this];
if (complexProperty != null)
{
jsonObject.Add(this.XmlElementName, complexProperty.InternalToJson(service));
}
}
}
}
| |
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.Samples.CodeDomTestSuite;
public class PropertiesTest : CodeDomTestTree {
public override TestTypes TestType {
get {
return TestTypes.Subset;
}
}
public override string Name {
get {
return "PropertiesTest";
}
}
public override string Description {
get {
return "Tests properties";
}
}
public override bool ShouldCompile {
get {
return true;
}
}
public override bool ShouldVerify {
get {
return true;
}
}
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
// create a namespace
CodeNamespace ns = new CodeNamespace ("NS");
ns.Imports.Add (new CodeNamespaceImport ("System"));
cu.Namespaces.Add (ns);
// create a class to inherit from, this will be used to test
// overridden properties
CodeTypeDeclaration decl = new CodeTypeDeclaration ();
decl.Name = "BaseClass";
decl.IsClass = true;
ns.Types.Add (decl);
decl.Members.Add (new CodeMemberField (typeof (string), "backing"));
CodeMemberProperty textProp = new CodeMemberProperty ();
textProp.Name = "Text";
textProp.Attributes = MemberAttributes.Public;
textProp.Type = new CodeTypeReference (typeof (string));
textProp.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression ("VooCar")));
textProp.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "backing"),
new CodePropertySetValueReferenceExpression ()));
decl.Members.Add (textProp);
// create a class
CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
class1.Name = "Test";
class1.IsClass = true;
class1.BaseTypes.Add (new CodeTypeReference ("BaseClass"));
ns.Types.Add (class1);
CodeMemberField int1 = new CodeMemberField (typeof (int), "int1");
class1.Members.Add (int1);
CodeMemberField tempString = new CodeMemberField (typeof (string), "tempString");
class1.Members.Add (tempString);
// Property that add 1 on a get
// GENERATE (C#):
// public virtual int prop1 {
// get {
// return (int1 + 1);
// }
// set {
// int1 = value;
// }
// }
AddScenario ("Checkprop1");
CodeMemberProperty prop1 = new CodeMemberProperty ();
prop1.Name = "prop1";
prop1.Type = new CodeTypeReference (typeof (int));
prop1.Attributes = MemberAttributes.Public;
prop1.HasGet = true;
prop1.HasSet = true;
prop1.GetStatements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeFieldReferenceExpression (null, "int1"),
CodeBinaryOperatorType.Add, new CodePrimitiveExpression (1))));
prop1.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "int1"), new CodePropertySetValueReferenceExpression ()));
class1.Members.Add (prop1);
// override Property
AddScenario ("CheckText");
CodeMemberProperty overrideProp = new CodeMemberProperty ();
overrideProp.Name = "Text";
overrideProp.Type = new CodeTypeReference (typeof (string));
overrideProp.Attributes = MemberAttributes.Public | MemberAttributes.Override;
overrideProp.HasGet = true;
overrideProp.HasSet = true;
overrideProp.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "tempString"), new CodePropertySetValueReferenceExpression ()));
overrideProp.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression ("Hello World")));
class1.Members.Add (overrideProp);
// Private Property
// GENERATE (C#):
// private virtual int privProp1 {
// get {
// return (int1 + 1);
// }
// set {
// int1 = value;
// }
// }
CodeMemberProperty privProp1 = new CodeMemberProperty ();
privProp1.Name = "privProp1";
privProp1.Type = new CodeTypeReference (typeof (int));
privProp1.Attributes = MemberAttributes.Private;
privProp1.HasGet = true;
privProp1.HasSet = true;
privProp1.GetStatements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeFieldReferenceExpression (null, "int1"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (1))));
privProp1.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "int1"), new CodePropertySetValueReferenceExpression ()));
class1.Members.Add (privProp1);
// GENERATES (C#):
// protected virtual int protProp1 {
// get {
// return (int1 + 1);
// }
// set {
// int1 = value;
// }
// }
CodeMemberProperty protProp1 = new CodeMemberProperty ();
protProp1.Name = "protProp1";
protProp1.Type = new CodeTypeReference (typeof (int));
protProp1.Attributes = MemberAttributes.Family;
protProp1.HasGet = true;
protProp1.HasSet = true;
protProp1.GetStatements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeFieldReferenceExpression (null, "int1"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (1))));
protProp1.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "int1"), new CodePropertySetValueReferenceExpression ()));
class1.Members.Add (protProp1);
// Internal Property
// GENERATE (C#):
// internal virtual int internalProp {
// get {
// return (int1 + 1);
// }
// set {
// int1 = value;
// }
// }
CodeMemberProperty internalProp = new CodeMemberProperty ();
internalProp.Name = "internalProp";
internalProp.Type = new CodeTypeReference (typeof (int));
internalProp.Attributes = MemberAttributes.Assembly;
internalProp.HasGet = true;
internalProp.HasSet = true;
internalProp.GetStatements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeFieldReferenceExpression (null, "int1"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (1))));
internalProp.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "int1"), new CodePropertySetValueReferenceExpression ()));
class1.Members.Add (internalProp);
// GENERATE (C#):
// public virtual int constStaticProp {
// get {
// return 99;
// }
// }
AddScenario ("CheckconstStaticProp");
CodeMemberProperty constStaticProp = new CodeMemberProperty ();
constStaticProp.Name = "constStaticProp";
constStaticProp.Type = new CodeTypeReference (typeof (int));
constStaticProp.Attributes = MemberAttributes.Public | MemberAttributes.Const;
constStaticProp.HasGet = true;
constStaticProp.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (99)));
class1.Members.Add (constStaticProp);
// 1) this reference
// GENERATE (C#):
// public virtual int thisRef(int value) {
// this.prop1 = value;
// return this.prop1;
// }
AddScenario ("CheckthisRef");
CodeMemberMethod thisRef = new CodeMemberMethod ();
thisRef.Name = "thisRef";
thisRef.ReturnType = new CodeTypeReference (typeof (int));
thisRef.Attributes = MemberAttributes.Public;
CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "value");
thisRef.Parameters.Add (param);
thisRef.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "privProp1"), new CodeArgumentReferenceExpression ("value")));
thisRef.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "privProp1")));
class1.Members.Add (thisRef);
// 1) protected
// GENERATE (C#):
AddScenario ("CheckprotPropMethod");
CodeMemberMethod protPropMethod = new CodeMemberMethod ();
protPropMethod.Name = "protPropMethod";
protPropMethod.ReturnType = new CodeTypeReference (typeof (int));
protPropMethod.Attributes = MemberAttributes.Public;
CodeParameterDeclarationExpression param2 = new CodeParameterDeclarationExpression (typeof (int), "value");
protPropMethod.Parameters.Add (param2);
protPropMethod.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "protProp1"), new CodeArgumentReferenceExpression ("value")));
protPropMethod.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "protProp1")));
class1.Members.Add (protPropMethod);
// 1) internal
// GENERATE (C#):
AddScenario ("CheckinternalPropMethod");
CodeMemberMethod internalPropMethod = new CodeMemberMethod ();
internalPropMethod.Name = "internalPropMethod";
internalPropMethod.ReturnType = new CodeTypeReference (typeof (int));
internalPropMethod.Attributes = MemberAttributes.Public;
CodeParameterDeclarationExpression param3 = new CodeParameterDeclarationExpression (typeof (int), "value");
internalPropMethod.Parameters.Add (param3);
internalPropMethod.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "internalProp"), new CodeArgumentReferenceExpression ("value")));
internalPropMethod.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "internalProp")));
class1.Members.Add (internalPropMethod);
// 2) set value
// GENERATE (C#):
// public virtual int setProp(int value) {
// prop1 = value;
// return int1;
// }
AddScenario ("ChecksetProp");
CodeMemberMethod setProp = new CodeMemberMethod ();
setProp.Name = "setProp";
setProp.ReturnType = new CodeTypeReference (typeof (int));
setProp.Attributes = MemberAttributes.Public;
CodeParameterDeclarationExpression intParam = new CodeParameterDeclarationExpression (typeof (int), "value");
setProp.Parameters.Add (intParam);
setProp.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "prop1"), new CodeArgumentReferenceExpression ("value")));
setProp.Statements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (null, "int1")));
class1.Members.Add (setProp);
}
public override void VerifyAssembly (CodeDomProvider provider, Assembly asm) {
object genObject;
Type genType;
AddScenario ("InstantiateTest", "Find and instantiate Test.");
if (!FindAndInstantiate ("NS.Test", asm, out genObject, out genType))
return;
VerifyScenario ("InstantiateTest");
int i1 = 392;
if (VerifyMethod (genType, genObject, "thisRef", new object[] {i1}, i1 + 1)) {
VerifyScenario ("CheckthisRef");
}
int i3 = -213;
if (VerifyPropertySet (genType, genObject, "prop1", i3) &&
VerifyPropertyGet (genType, genObject, "prop1", i3 + 1)) {
VerifyScenario ("Checkprop1");
}
if (VerifyPropertyGet (genType, genObject, "constStaticProp", 99)) {
VerifyScenario ("CheckconstStaticProp");
}
if (VerifyMethod (genType, genObject, "protPropMethod", new object[] {2317}, 2318)) {
VerifyScenario ("CheckprotPropMethod");
}
if (VerifyMethod (genType, genObject, "internalPropMethod", new object[] {1}, 2)) {
VerifyScenario ("CheckinternalPropMethod");
}
if (VerifyPropertyGet (genType, genObject, "Text", "Hello World")) {
VerifyScenario ("CheckText");
}
if (VerifyMethod (genType, genObject, "setProp", new object[] {1}, 1)) {
VerifyScenario ("ChecksetProp");
}
}
}
| |
using Kazyx.RemoteApi;
using Kazyx.RemoteApi.Camera;
using Kazyx.WPPMM.Utils;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Media;
namespace Kazyx.WPPMM.DataModel
{
public class ApplicationSettings : INotifyPropertyChanged
{
private static ApplicationSettings sSettings = new ApplicationSettings();
private CameraManager.CameraManager manager;
internal List<string> GridTypeSettings = new List<string>()
{
FramingGridTypes.Off,
FramingGridTypes.RuleOfThirds,
FramingGridTypes.Diagonal,
FramingGridTypes.Square,
FramingGridTypes.Crosshairs,
FramingGridTypes.Fibonacci,
FramingGridTypes.GoldenRatio,
};
internal List<string> GridColorSettings = new List<string>()
{
FramingGridColor.White,
FramingGridColor.Black,
FramingGridColor.Red,
FramingGridColor.Green,
FramingGridColor.Blue,
};
internal List<string> FibonacciLineOriginSettings = new List<string>()
{
FibonacciLineOrigins.UpperLeft,
FibonacciLineOrigins.UpperRight,
FibonacciLineOrigins.BottomLeft,
FibonacciLineOrigins.BottomRight,
};
private ApplicationSettings()
{
manager = CameraManager.CameraManager.GetInstance();
IsPostviewTransferEnabled = Preference.IsPostviewTransferEnabled();
IsIntervalShootingEnabled = Preference.IsIntervalShootingEnabled();
IntervalTime = Preference.IntervalTime();
IsShootButtonDisplayed = Preference.IsShootButtonDisplayed();
IsHistogramDisplayed = Preference.IsHistogramDisplayed();
GeotagEnabled = Preference.GeotagEnabled();
GridType = Preference.FramingGridsType() ?? FramingGridTypes.Off;
GridColor = Preference.FramingGridsColor() ?? FramingGridColor.White;
FibonacciLineOrigin = Preference.FibonacciOrigin() ?? FibonacciLineOrigins.UpperLeft;
RequestFocusFrameInfo = Preference.RequestFocusFrameInfo();
PrioritizeOriginalSizeContents = Preference.OriginalSizeContentsPrioritized;
}
public static ApplicationSettings GetInstance()
{
return sSettings;
}
private bool _IsPostviewTransferEnabled = true;
public bool IsPostviewTransferEnabled
{
set
{
if (_IsPostviewTransferEnabled != value)
{
Preference.SetPostviewTransferEnabled(value);
_IsPostviewTransferEnabled = value;
OnPropertyChanged("IsPostviewTransferEnabled");
}
}
get
{
return _IsPostviewTransferEnabled;
}
}
private bool _PrioritizeOriginalSizeContents = false;
public bool PrioritizeOriginalSizeContents
{
set
{
if (_PrioritizeOriginalSizeContents != value)
{
Preference.OriginalSizeContentsPrioritized = value;
_PrioritizeOriginalSizeContents = value;
OnPropertyChanged("PrioritizeOriginalSizeContents");
}
}
get { return _PrioritizeOriginalSizeContents; }
}
private bool _IsIntervalShootingEnabled = false;
public bool IsIntervalShootingEnabled
{
set
{
if (_IsIntervalShootingEnabled != value)
{
Preference.SetIntervalShootingEnabled(value);
_IsIntervalShootingEnabled = value;
OnPropertyChanged("IsIntervalShootingEnabled");
OnPropertyChanged("IntervalTimeVisibility");
// exclusion
if (value)
{
if (manager.Status.IsAvailable("setSelfTimer") && manager.IntervalManager != null)
{
SetSelfTimerOff();
}
}
}
}
get
{
return _IsIntervalShootingEnabled;
}
}
private async void SetSelfTimerOff()
{
try
{
await manager.CameraApi.SetSelfTimerAsync(SelfTimerParam.Off);
}
catch (RemoteApiException e)
{
DebugUtil.Log("Failed to set selftimer off: " + e.code);
}
}
public Visibility IntervalTimeVisibility
{
get { return IsIntervalShootingEnabled ? Visibility.Visible : Visibility.Collapsed; }
}
private int _IntervalTime = 10;
public int IntervalTime
{
set
{
if (_IntervalTime != value)
{
Preference.SetIntervalTime(value);
_IntervalTime = value;
// DebugUtil.Log("IntervalTime changed: " + value);
OnPropertyChanged("IntervalTime");
}
}
get
{
return _IntervalTime;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
// DebugUtil.Log("OnProperty changed: " + name);
if (PropertyChanged != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
try
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
catch (COMException)
{
DebugUtil.Log("Caught COMException: ApplicationSettings");
}
});
}
}
private bool _IsShootButtonDisplayed = true;
public bool IsShootButtonDisplayed
{
set
{
if (_IsShootButtonDisplayed != value)
{
Preference.SetShootButtonDisplayed(value);
_IsShootButtonDisplayed = value;
OnPropertyChanged("ShootButtonVisibility");
DebugUtil.Log("ShootbuttonVisibility updated: " + value.ToString());
}
}
get
{
return _IsShootButtonDisplayed;
}
}
private bool _IsHistogramDisplayed = true;
public bool IsHistogramDisplayed
{
set
{
if (_IsHistogramDisplayed != value)
{
Preference.SetHistogramDisplayed(value);
_IsHistogramDisplayed = value;
OnPropertyChanged("HistogramVisibility");
}
}
get { return _IsHistogramDisplayed; }
}
private bool _GeotagEnabled = false;
public bool GeotagEnabled
{
set
{
if (_GeotagEnabled != value)
{
Preference.SetGeotagEnabled(value);
_GeotagEnabled = value;
OnPropertyChanged("GeotagEnabled");
OnPropertyChanged("GeopositionStatusVisibility");
}
}
get { return _GeotagEnabled; }
}
private bool _RequestFocusFrameInfo = true;
public bool RequestFocusFrameInfo
{
set
{
if (_RequestFocusFrameInfo != value)
{
Preference.SetRequestFocusFrameInfo(value);
_RequestFocusFrameInfo = value;
OnPropertyChanged("RequestFocusFrameInfo");
}
}
get
{
return _RequestFocusFrameInfo;
}
}
private string _GridType = FramingGridTypes.Off;
public string GridType
{
set
{
if (_GridType != value)
{
DebugUtil.Log("GridType updated: " + value);
Preference.SetFramingGridsType(value);
_GridType = value;
OnPropertyChanged("GridType");
}
}
get { return _GridType; }
}
public int GridTypeIndex
{
set
{
GridType = GridTypeSettings[value];
}
get
{
int i = 0;
foreach (string type in GridTypeSettings)
{
if (GridType.Equals(type))
{
return i;
}
i++;
}
return 0;
}
}
private string _GridColor = FramingGridColor.White;
public string GridColor
{
set
{
if (_GridColor != value)
{
Preference.SetFramingGridsColor(value);
_GridColor = value;
OnPropertyChanged("GridColor");
OnPropertyChanged("GridColorBrush");
}
}
get { return _GridColor; }
}
public SolidColorBrush GridColorBrush
{
get
{
Color color;
switch (this.GridColor)
{
case FramingGridColor.White:
color = Color.FromArgb(200, 200, 200, 200);
break;
case FramingGridColor.Black:
color = Color.FromArgb(200, 50, 50, 50);
break;
case FramingGridColor.Red:
color = Color.FromArgb(200, 250, 30, 30);
break;
case FramingGridColor.Green:
color = Color.FromArgb(200, 30, 250, 30);
break;
case FramingGridColor.Blue:
color = Color.FromArgb(200, 30, 30, 250);
break;
default:
color = Color.FromArgb(200, 200, 200, 200);
break;
}
return new SolidColorBrush() { Color = color };
}
}
public int GridColorIndex
{
set
{
GridColor = GridColorSettings[value];
}
get
{
int i = 0;
foreach (string color in GridColorSettings)
{
if (GridColor.Equals(color))
{
return i;
}
i++;
}
return 0;
}
}
private string _FibonacciLineOrigin = FibonacciLineOrigins.UpperLeft;
public string FibonacciLineOrigin
{
get { return _FibonacciLineOrigin; }
set
{
if (value != _FibonacciLineOrigin)
{
Preference.SetFibonacciOrigin(value);
this._FibonacciLineOrigin = value;
OnPropertyChanged("FibonacciLineOrigin");
}
}
}
public int FibonacciOriginIndex
{
set
{
FibonacciLineOrigin = FibonacciLineOriginSettings[value];
}
get
{
int i = 0;
foreach (string f in FibonacciLineOriginSettings)
{
if (FibonacciLineOrigin.Equals(f))
{
return i;
}
i++;
}
return 0;
}
}
public Visibility ShootButtonVisibility
{
get
{
if (_IsShootButtonDisplayed && !ShootButtonTemporaryCollapsed)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
}
private bool _ShootButtonTemporaryCollapsed = false;
public bool ShootButtonTemporaryCollapsed
{
get { return _ShootButtonTemporaryCollapsed; }
set
{
if (value != _ShootButtonTemporaryCollapsed)
{
_ShootButtonTemporaryCollapsed = value;
OnPropertyChanged("ShootButtonVisibility");
}
}
}
public Visibility HistogramVisibility
{
get
{
if (_IsHistogramDisplayed)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
}
public Visibility GeopositionStatusVisibility
{
get
{
if (GeotagEnabled) { return Visibility.Visible; }
else { return Visibility.Collapsed; }
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Windows.Forms
{
/// <summary>
/// Manages opened popups
/// </summary>
public static class RibbonPopupManager
{
#region Subclasses
/// <summary>
/// Specifies reasons why pop-ups can be dismissed
/// </summary>
public enum DismissReason
{
/// <summary>
/// An item has been clicked
/// </summary>
ItemClicked,
/// <summary>
/// The app has been clicked
/// </summary>
AppClicked,
/// <summary>
/// A new popup is showing and will hide sibling's popups
/// </summary>
NewPopup,
/// <summary>
/// The aplication window has been deactivated
/// </summary>
AppFocusChanged,
/// <summary>
/// User has pressed escape on the keyboard
/// </summary>
EscapePressed
}
#endregion
#region Events
public static event EventHandler PopupRegistered;
public static event EventHandler PopupUnRegistered;
#endregion
#region Fields
private static List<RibbonPopup> pops;
#endregion
#region Ctor
static RibbonPopupManager()
{
pops = new List<RibbonPopup>();
}
#endregion
#region Props
/// <summary>
/// Gets the last pop-up of the collection
/// </summary>
internal static RibbonPopup LastPopup
{
get
{
if (pops.Count > 0)
{
return pops[pops.Count - 1];
}
return null;
}
}
internal static int PopupCount
{
get { return pops.Count; }
}
#endregion
#region Methods
/// <summary>
/// Registers a popup existance
/// </summary>
/// <param name="p"></param>
internal static void Register(RibbonPopup p)
{
if (!pops.Contains(p))
{
pops.Add(p);
PopupRegistered(p, EventArgs.Empty);
}
}
/// <summary>
/// Unregisters a popup from existance
/// </summary>
/// <param name="p"></param>
internal static void Unregister(RibbonPopup p)
{
if (pops.Contains(p))
{
pops.Remove(p);
PopupUnRegistered(p, EventArgs.Empty);
}
}
/// <summary>
/// Feeds a click generated on the mouse hook
/// </summary>
/// <param name="e"></param>
internal static bool FeedHookClick(MouseEventArgs e)
{
foreach (RibbonPopup p in pops)
{
if (p.WrappedDropDown.Bounds.Contains(e.Location))
{
return true;
}
}
//If click was in no dropdown, let's go everyone
Dismiss(DismissReason.AppClicked);
return false;
}
/// <summary>
/// Feeds mouse Wheel. If applied on a IScrollableItem it's sended to it
/// </summary>
/// <param name="e"></param>
/// <returns>True if handled. False otherwise</returns>
internal static bool FeedMouseWheel(MouseEventArgs e)
{
RibbonDropDown dd = LastPopup as RibbonDropDown;
if (dd != null)
{
foreach (RibbonItem item in dd.Items)
{
if (dd.RectangleToScreen(item.Bounds).Contains(e.Location))
{
IScrollableRibbonItem sc = item as IScrollableRibbonItem;
if (sc != null)
{
if (e.Delta < 0)
{
sc.ScrollDown();
}
else
{
sc.ScrollUp();
}
return true;
}
}
}
}
//kevin carbis - added scrollbar support to dropdowns so we need to feed the mouse wheel to the
//actual dropdown item if it was not intended for a child item.
if (dd != null)
{
if (e.Delta < 0)
{
dd.ScrollDown();
}
else
{
dd.ScrollUp();
}
return true;
}
return false;
}
/// <summary>
/// Closes all children of specified pop-up
/// </summary>
/// <param name="parent">Pop-up of which children will be closed</param>
/// <param name="reason">Reason for dismissing</param>
public static void DismissChildren(RibbonPopup parent, DismissReason reason)
{
int index = pops.IndexOf(parent);
if (index >= 0)
{
Dismiss(index + 1, reason);
}
}
/// <summary>
/// Closes all currently registered pop-ups
/// </summary>
/// <param name="reason"></param>
public static void Dismiss(DismissReason reason)
{
Dismiss(0, reason);
}
/// <summary>
/// Closes specified pop-up and all its descendants
/// </summary>
/// <param name="startPopup">Pop-up to close (and its descendants)</param>
/// <param name="reason">Reason for closing</param>
public static void Dismiss(RibbonPopup startPopup, DismissReason reason)
{
int index = pops.IndexOf(startPopup);
if (index >= 0)
{
Dismiss(index, reason);
}
}
/// <summary>
/// Closes pop-up of the specified index and all its descendants
/// </summary>
/// <param name="startPopup">Index of the pop-up to close</param>
/// <param name="reason">Reason for closing</param>
private static void Dismiss(int startPopup, DismissReason reason)
{
for (int i = pops.Count - 1; i >= startPopup; i--)
{
pops[i].Close();
}
}
#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,
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.PythonTools.Debugger;
using Microsoft.PythonTools.DkmDebugger.Proxies;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.Breakpoints;
using Microsoft.VisualStudio.Debugger.CallStack;
using Microsoft.VisualStudio.Debugger.Stepping;
namespace Microsoft.PythonTools.DkmDebugger {
internal unsafe class TraceManager : DkmDataItem {
// Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp.
[StructLayout(LayoutKind.Sequential, Pack = 8)]
private struct DebuggerString {
public const int SizeOf = 4;
public int length;
public fixed char data[1];
}
// Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp.
[StructLayout(LayoutKind.Sequential, Pack = 8)]
private struct BreakpointData {
public int maxLineNumber;
public ulong lineNumbers;
public ulong fileNamesOffsets;
public ulong strings;
}
// Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp.
[StructLayout(LayoutKind.Sequential, Pack = 8)]
private struct CurrentSourceLocation {
public int lineNumber;
public ulong fileName;
}
private readonly DkmProcess _process;
private readonly PythonRuntimeInfo _pyrtInfo;
private readonly Dictionary<SourceLocation, List<DkmRuntimeBreakpoint>> _breakpoints = new Dictionary<SourceLocation, List<DkmRuntimeBreakpoint>>();
private readonly ArrayProxy<CliStructProxy<BreakpointData>> _breakpointData;
private readonly ByteProxy _currentBreakpointData, _breakpointDataInUseByTraceFunc;
private readonly CliStructProxy<CurrentSourceLocation> _currentSourceLocation;
private readonly Int32Proxy _stepKind, _steppingStackDepth;
private readonly UInt64Proxy _stepThreadId;
private readonly DkmRuntimeBreakpoint _onBreakpointHitBP, _onStepCompleteBP, _onStepFallThroughBP;
private DkmStepper _stepper;
public TraceManager(DkmProcess process) {
_process = process;
_pyrtInfo = process.GetPythonRuntimeInfo();
_breakpointData = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<ArrayProxy<CliStructProxy<BreakpointData>>>("breakpointData");
_currentBreakpointData = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<ByteProxy>("currentBreakpointData");
_breakpointDataInUseByTraceFunc = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<ByteProxy>("breakpointDataInUseByTraceFunc");
_currentSourceLocation = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<CliStructProxy<CurrentSourceLocation>>("currentSourceLocation");
_stepKind = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<Int32Proxy>("stepKind");
_stepThreadId = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("stepThreadId");
_steppingStackDepth = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<Int32Proxy>("steppingStackDepth");
var onBreakpointHit = _pyrtInfo.DLLs.DebuggerHelper.FindExportName("OnBreakpointHit", true);
_onBreakpointHitBP = DkmRuntimeInstructionBreakpoint.Create(Guids.PythonTraceManagerSourceGuid, null, onBreakpointHit, false, null);
_onBreakpointHitBP.Enable();
var onStepComplete = _pyrtInfo.DLLs.DebuggerHelper.FindExportName("OnStepComplete", true);
_onStepCompleteBP = DkmRuntimeInstructionBreakpoint.Create(Guids.PythonTraceManagerSourceGuid, null, onStepComplete, false, null);
_onStepCompleteBP.Enable();
var onStepFallThrough = _pyrtInfo.DLLs.DebuggerHelper.FindExportName("OnStepFallThrough", true);
_onStepFallThroughBP = DkmRuntimeInstructionBreakpoint.Create(Guids.PythonTraceManagerSourceGuid, null, onStepFallThrough, false, null);
_onStepFallThroughBP.Enable();
WriteBreakpoints();
}
public void OnNativeBreakpointHit(DkmRuntimeBreakpoint nativeBP, DkmThread thread) {
if (nativeBP == _onBreakpointHitBP) {
OnBreakpointHit(thread);
} else if (nativeBP == _onStepCompleteBP) {
OnStepComplete(thread);
} else if (nativeBP == _onStepFallThroughBP) {
OnStepFallThrough(thread);
} else if (nativeBP.SourceId == Guids.PythonStepTargetSourceGuid) {
OnStepTargetBreakpoint(thread);
} else {
Debug.Fail("BreakpointManager notified about a native breakpoint that it didn't create.");
}
}
public void AddBreakpoint(DkmRuntimeBreakpoint bp) {
var loc = bp.GetDataItem<SourceLocation>();
List<DkmRuntimeBreakpoint> bpsAtLoc;
if (!_breakpoints.TryGetValue(loc, out bpsAtLoc)) {
_breakpoints[loc] = bpsAtLoc = new List<DkmRuntimeBreakpoint>();
}
bpsAtLoc.Add(bp);
WriteBreakpoints();
}
public void RemoveBreakpoint(DkmRuntimeBreakpoint bp) {
var loc = bp.GetDataItem<SourceLocation>();
List<DkmRuntimeBreakpoint> bpsAtLoc;
if (!_breakpoints.TryGetValue(loc, out bpsAtLoc)) {
return;
}
if (!bpsAtLoc.Remove(bp)) {
return;
}
if (bpsAtLoc.Count == 0) {
_breakpoints.Remove(loc);
}
WriteBreakpoints();
}
private class StructuralArrayEqualityComparer<T> : EqualityComparer<T[]> {
public override bool Equals(T[] x, T[] y) {
return StructuralComparisons.StructuralEqualityComparer.Equals(x, y);
}
public override int GetHashCode(T[] obj) {
return StructuralComparisons.StructuralEqualityComparer.GetHashCode(obj);
}
}
private void WriteBreakpoints() {
int maxLineNumber = _breakpoints.Keys.Select(loc => loc.LineNumber).DefaultIfEmpty().Max();
var lineNumbersStream = new MemoryStream((maxLineNumber + 1) * sizeof(int));
var lineNumbersWriter = new BinaryWriter(lineNumbersStream);
var stringsStream = new MemoryStream();
var stringsWriter = new BinaryWriter(stringsStream);
var stringOffsets = new Dictionary<string, int>();
stringsWriter.Write((int)0);
foreach (var s in _breakpoints.Keys.Select(loc => loc.FileName).Distinct()) {
stringOffsets[s] = (int)stringsStream.Position;
stringsWriter.Write((int)s.Length);
foreach (char c in s) {
stringsWriter.Write((ushort)c);
}
stringsWriter.Write((ushort)0);
}
var fileNamesOffsetsStream = new MemoryStream();
var fileNamesOffsetsWriter = new BinaryWriter(fileNamesOffsetsStream);
var fileNamesOffsetsIndices = new Dictionary<int[], int>(new StructuralArrayEqualityComparer<int>());
fileNamesOffsetsWriter.Write((int)0);
foreach (var g in _breakpoints.Keys.GroupBy(loc => loc.LineNumber)) {
var lineNumber = g.Key;
var fileNamesOffsets = g.Select(loc => stringOffsets[loc.FileName]).ToArray();
Array.Sort(fileNamesOffsets);
int fileNamesOffsetsIndex;
if (!fileNamesOffsetsIndices.TryGetValue(fileNamesOffsets, out fileNamesOffsetsIndex)) {
fileNamesOffsetsIndex = (int)fileNamesOffsetsStream.Position / sizeof(int);
foreach (int offset in fileNamesOffsets) {
fileNamesOffsetsWriter.Write(offset);
}
fileNamesOffsetsWriter.Write((int)0);
fileNamesOffsetsIndices.Add(fileNamesOffsets, fileNamesOffsetsIndex);
}
lineNumbersStream.Position = lineNumber * sizeof(int);
lineNumbersWriter.Write(fileNamesOffsetsIndex);
}
byte breakpointDataInUseByTraceFunc = _breakpointDataInUseByTraceFunc.Read();
byte currentBreakpointData = (breakpointDataInUseByTraceFunc == 0) ? (byte)1 : (byte)0;
_currentBreakpointData.Write(currentBreakpointData);
var bpDataProxy = _breakpointData[currentBreakpointData];
BreakpointData bpData = bpDataProxy.Read();
if (bpData.lineNumbers != 0) {
_process.FreeVirtualMemory(bpData.lineNumbers, 0, NativeMethods.MEM_RELEASE);
}
if (bpData.fileNamesOffsets != 0) {
_process.FreeVirtualMemory(bpData.fileNamesOffsets, 0, NativeMethods.MEM_RELEASE);
}
if (bpData.strings != 0) {
_process.FreeVirtualMemory(bpData.strings, 0, NativeMethods.MEM_RELEASE);
}
bpData.maxLineNumber = maxLineNumber;
if (lineNumbersStream.Length > 0) {
bpData.lineNumbers = _process.AllocateVirtualMemory(0, (int)lineNumbersStream.Length, NativeMethods.MEM_COMMIT | NativeMethods.MEM_RESERVE, NativeMethods.PAGE_READWRITE);
_process.WriteMemory(bpData.lineNumbers, lineNumbersStream.ToArray());
} else {
bpData.lineNumbers = 0;
}
bpData.fileNamesOffsets = _process.AllocateVirtualMemory(0, (int)fileNamesOffsetsStream.Length, NativeMethods.MEM_COMMIT | NativeMethods.MEM_RESERVE, NativeMethods.PAGE_READWRITE);
_process.WriteMemory(bpData.fileNamesOffsets, fileNamesOffsetsStream.ToArray());
bpData.strings = _process.AllocateVirtualMemory(0, (int)stringsStream.Length, NativeMethods.MEM_COMMIT | NativeMethods.MEM_RESERVE, NativeMethods.PAGE_READWRITE);
_process.WriteMemory(bpData.strings, stringsStream.ToArray());
bpDataProxy.Write(bpData);
}
private void OnBreakpointHit(DkmThread thread) {
CurrentSourceLocation cbp = _currentSourceLocation.Read();
DebuggerString fileNameDS;
_process.ReadMemory(cbp.fileName, DkmReadMemoryFlags.None, &fileNameDS, sizeof(DebuggerString));
char* fileNameBuf = stackalloc char[fileNameDS.length];
ulong dataOffset = (ulong)((byte*)fileNameDS.data - (byte*)&fileNameDS);
_process.ReadMemory(cbp.fileName + dataOffset, DkmReadMemoryFlags.None, fileNameBuf, fileNameDS.length * 2);
string fileName = new string(fileNameBuf, 0, fileNameDS.length);
var loc = new SourceLocation(fileName, cbp.lineNumber);
List<DkmRuntimeBreakpoint> bps;
if (!_breakpoints.TryGetValue(loc, out bps)) {
Debug.Fail("TraceFunc signalled a breakpoint at a location that BreakpointManager does not know about.");
return;
}
foreach (var bp in bps) {
bp.OnHit(thread, false);
}
}
private class StepBeginState : DkmDataItem {
public ulong FrameBase { get; set; }
}
public void BeforeEnableNewStepper(DkmRuntimeInstance runtimeInstance, DkmStepper stepper) {
ulong retAddr, frameBase, vframe;
stepper.Thread.GetCurrentFrameInfo(out retAddr, out frameBase, out vframe);
stepper.SetDataItem(DkmDataCreationDisposition.CreateAlways, new StepBeginState { FrameBase = frameBase });
}
public void Step(DkmStepper stepper, DkmStepArbitrationReason reason) {
var thread = stepper.Thread;
var process = thread.Process;
if (stepper.StepKind == DkmStepKind.StepIntoSpecific) {
throw new NotSupportedException();
} else if (_stepper != null) {
_stepper.CancelStepper(process.GetPythonRuntimeInstance());
_stepper = null;
}
// Check if this was a step out (or step over/in that fell through) from native to Python.
// If so, we consider the step done, since we can report the correct callstack at this point.
if (reason == DkmStepArbitrationReason.TransitionModule) {
var beginState = stepper.GetDataItem<StepBeginState>();
if (beginState != null) {
ulong retAddr, frameBase, vframe;
thread.GetCurrentFrameInfo(out retAddr, out frameBase, out vframe);
if (frameBase >= beginState.FrameBase) {
stepper.OnStepComplete(thread, false);
return;
}
}
}
if (stepper.StepKind == DkmStepKind.Into) {
new LocalComponent.BeginStepInNotification {
ThreadId = thread.UniqueId
}.SendHigher(process);
}
_stepper = stepper;
_stepKind.Write((int)stepper.StepKind + 1);
_stepThreadId.Write((uint)thread.SystemPart.Id);
_steppingStackDepth.Write(0);
}
public void CancelStep(DkmStepper stepper) {
if (_stepper == null) {
return;
} else if (stepper != _stepper) {
Debug.Fail("Trying to cancel a step while no step or another step is in progress.");
throw new InvalidOperationException();
}
StepDone(stepper.Thread);
}
private void OnStepComplete(DkmThread thread) {
if (_stepper != null) {
StepDone(thread).OnStepComplete(thread, false);
}
}
private void OnStepTargetBreakpoint(DkmThread thread) {
if (_stepper == null) {
Debug.Fail("OnStepTargetBreakpoint called but no step operation is in progress.");
throw new InvalidOperationException();
}
if (_stepper.StepKind == DkmStepKind.Into) {
StepDone(thread).OnStepArbitration(DkmStepArbitrationReason.ExitRuntime, _process.GetPythonRuntimeInstance());
} else {
// Just because we hit the return breakpoint doesn't mean that we've actually returned - it could be
// a recursive call. Check stack depth to distinguish this from an actual return.
var beginState = _stepper.GetDataItem<StepBeginState>();
if (beginState != null) {
ulong retAddr, frameBase, vframe;
thread.GetCurrentFrameInfo(out retAddr, out frameBase, out vframe);
if (frameBase > beginState.FrameBase) {
OnStepComplete(thread);
}
}
}
}
private DkmStepper StepDone(DkmThread thread) {
new LocalComponent.StepCompleteNotification().SendHigher(thread.Process);
new LocalStackWalkingComponent.StepCompleteNotification().SendHigher(thread.Process);
var stepper = _stepper;
_stepper = null;
_stepKind.Write(0);
return stepper;
}
private void OnStepFallThrough(DkmThread thread) {
// Step fell through the end of the frame in which it began - time to register the breakpoint for the return address.
new LocalStackWalkingComponent.BeginStepOutNotification {
ThreadId = thread.UniqueId
}.SendHigher(_process);
}
}
}
| |
using UnityEngine;
using UnityEditor;
#if UNITY_2018_1_OR_NEWER
using UnityEditor.Build.Reporting;
#endif
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using V1 = AssetBundleGraph;
using Model = UnityEngine.AssetGraph.DataModel.Version2;
namespace UnityEngine.AssetGraph
{
[CustomNode("Build/Build Player", 90)]
public class PlayerBuilder : Node
{
[SerializeField] private SerializableMultiTargetInt m_buildOptions;
[SerializeField] private SerializableMultiTargetString m_buildLocations;
[SerializeField] private SerializableMultiTargetString m_playerName;
[SerializeField] private SerializableMultiTargetString m_scenes;
[SerializeField] private Vector2 m_scroll;
public override string ActiveStyle
{
get
{
return "node 5 on";
}
}
public override string InactiveStyle
{
get
{
return "node 5";
}
}
public override string Category
{
get
{
return "Build";
}
}
public override Model.NodeOutputSemantics NodeInputType
{
get
{
return Model.NodeOutputSemantics.AssetBundles;
}
}
public override Model.NodeOutputSemantics NodeOutputType
{
get
{
return Model.NodeOutputSemantics.None;
}
}
public override void Initialize(Model.NodeData data)
{
m_buildOptions = new SerializableMultiTargetInt();
m_buildLocations = new SerializableMultiTargetString();
m_playerName = new SerializableMultiTargetString();
m_scenes = new SerializableMultiTargetString();
data.AddDefaultInputPoint();
m_scroll = Vector2.zero;
}
public override Node Clone(Model.NodeData newData)
{
var newNode = new PlayerBuilder();
newNode.m_buildOptions = new SerializableMultiTargetInt(m_buildOptions);
newNode.m_buildLocations = new SerializableMultiTargetString(m_buildLocations);
newNode.m_playerName = new SerializableMultiTargetString(m_playerName);
newNode.m_scenes = new SerializableMultiTargetString(m_scenes);
newNode.m_scroll = m_scroll;
newData.AddDefaultInputPoint();
return newNode;
}
public override void OnInspectorGUI(NodeGUI node, AssetReferenceStreamManager streamManager, NodeGUIEditor editor, Action onValueChanged)
{
EditorGUILayout.HelpBox("Build Player: Build Player.", MessageType.Info);
editor.UpdateNodeName(node);
if (m_buildOptions == null)
{
return;
}
GUILayout.Space(10f);
//Show target configuration tab
editor.DrawPlatformSelector(node);
using (new EditorGUILayout.VerticalScope(GUI.skin.box))
{
var disabledScope = editor.DrawOverrideTargetToggle(node, m_buildOptions.ContainsValueOf(editor.CurrentEditingGroup), (bool enabled) =>
{
using (new RecordUndoScope("Remove Target Build Settings", node, true))
{
if (enabled)
{
m_buildOptions[editor.CurrentEditingGroup] = m_buildOptions.DefaultValue;
m_buildLocations[editor.CurrentEditingGroup] = m_buildLocations.DefaultValue;
m_playerName[editor.CurrentEditingGroup] = m_playerName.DefaultValue;
m_scenes[editor.CurrentEditingGroup] = m_scenes.DefaultValue;
}
else
{
m_buildOptions.Remove(editor.CurrentEditingGroup);
m_buildLocations.Remove(editor.CurrentEditingGroup);
m_playerName.Remove(editor.CurrentEditingGroup);
m_scenes.Remove(editor.CurrentEditingGroup);
}
onValueChanged();
}
});
using (disabledScope)
{
using (var scrollScope = new EditorGUILayout.ScrollViewScope(m_scroll))
{
m_scroll = scrollScope.scrollPosition;
GUILayout.Label("Player Build Location", "BoldLabel");
var newBuildLocation = editor.DrawFolderSelector("", "Select Build Location",
m_buildLocations[editor.CurrentEditingGroup],
Application.dataPath + "/../"
);
if (newBuildLocation.StartsWith(Application.dataPath))
{
throw new NodeException("You can not build player inside Assets directory.",
"Select build location outside Assets directory.",
node.Data);
}
if (newBuildLocation != m_buildLocations[editor.CurrentEditingGroup])
{
using (new RecordUndoScope("Change Build Location", node, true))
{
m_buildLocations[editor.CurrentEditingGroup] = newBuildLocation;
onValueChanged();
}
}
GUILayout.Space(4f);
var newPlayerName = EditorGUILayout.TextField("Player Name", m_playerName[editor.CurrentEditingGroup]);
if (newPlayerName != m_playerName[editor.CurrentEditingGroup])
{
using (new RecordUndoScope("Change Player Name", node, true))
{
m_playerName[editor.CurrentEditingGroup] = newPlayerName;
onValueChanged();
}
}
GUILayout.Space(10f);
GUILayout.Label("Build Options", "BoldLabel");
int buildOptions = m_buildOptions[editor.CurrentEditingGroup];
foreach (var option in Model.Settings.BuildPlayerOptionsSettings)
{
// contains keyword == enabled. if not, disabled.
bool isEnabled = (buildOptions & (int)option.option) != 0;
var result = EditorGUILayout.ToggleLeft(option.description, isEnabled);
if (result != isEnabled)
{
using (new RecordUndoScope("Change Build Option", node, true))
{
buildOptions = (result) ?
((int)option.option | buildOptions) :
(((~(int)option.option)) & buildOptions);
m_buildOptions[editor.CurrentEditingGroup] = buildOptions;
onValueChanged();
}
}
}
var scenesInProject = AssetDatabase.FindAssets("t:Scene");
if (scenesInProject.Length > 0)
{
GUILayout.Space(10f);
GUILayout.Label("Scenes", "BoldLabel");
using (new EditorGUILayout.VerticalScope(GUI.skin.box))
{
var scenesSelected = m_scenes[editor.CurrentEditingGroup].Split(',');
foreach (var sceneGUID in scenesInProject)
{
var path = AssetDatabase.GUIDToAssetPath(sceneGUID);
if (string.IsNullOrEmpty(path))
{
ArrayUtility.Remove(ref scenesSelected, sceneGUID);
m_scenes[editor.CurrentEditingGroup] = string.Join(",", scenesSelected);
onValueChanged();
continue;
}
var type = TypeUtility.GetMainAssetTypeAtPath(path);
if (type != typeof(UnityEditor.SceneAsset))
{
continue;
}
var selected = scenesSelected.Contains(sceneGUID);
var newSelected = EditorGUILayout.ToggleLeft(path, selected);
if (newSelected != selected)
{
using (new RecordUndoScope("Change Scene Selection", node, true))
{
if (newSelected)
{
ArrayUtility.Add(ref scenesSelected, sceneGUID);
}
else
{
ArrayUtility.Remove(ref scenesSelected, sceneGUID);
}
m_scenes[editor.CurrentEditingGroup] = string.Join(",", scenesSelected);
onValueChanged();
}
}
}
}
}
}
}
}
}
public override void Prepare(BuildTarget target,
Model.NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output Output)
{
// BundleBuilder do nothing without incoming connections
if (incoming == null)
{
return;
}
if (string.IsNullOrEmpty(m_buildLocations[target]))
{
throw new NodeException("Build location is empty.", "Set valid build location from inspector.", node);
}
if (string.IsNullOrEmpty(m_playerName[target]))
{
throw new NodeException("Player name is empty.", "Set valid player name from inspector.", node);
}
}
public override void Build(BuildTarget target,
Model.NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output Output,
Action<Model.NodeData, string, float> progressFunc)
{
if (incoming == null)
{
return;
}
if (!Directory.Exists(m_buildLocations[target]))
{
Directory.CreateDirectory(m_buildLocations[target]);
}
var sceneGUIDs = m_scenes[target].Split(',');
string manifestPath = string.Empty;
foreach (var ag in incoming)
{
foreach (var assets in ag.assetGroups.Values)
{
var manifestBundle = assets.Where(a => a.assetType == typeof(AssetBundleManifestReference));
if (manifestBundle.Any())
{
manifestPath = manifestBundle.First().importFrom;
}
}
}
BuildPlayerOptions opt = new BuildPlayerOptions();
opt.options = (BuildOptions)m_buildOptions[target];
opt.locationPathName = m_buildLocations[target] + "/" + m_playerName[target];
opt.assetBundleManifestPath = manifestPath;
opt.scenes = sceneGUIDs.Select(guid => AssetDatabase.GUIDToAssetPath(guid)).Where(path => !string.IsNullOrEmpty(path) && !path.Contains("__DELETED_GUID_Trash")).ToArray();
opt.target = target;
opt.targetGroup = BuildTargetUtility.TargetToGroup(target);
#if UNITY_2018_1_OR_NEWER
var report = BuildPipeline.BuildPlayer(opt);
var summary = report.summary;
switch (summary.result)
{
case BuildResult.Failed:
throw new NodeException(
string.Format("Player build failed. ({0} errors)", summary.totalErrors),
summary.ToString(), node);
case BuildResult.Cancelled:
LogUtility.Logger.Log(LogUtility.kTag, "Player build cancelled.");
break;
case BuildResult.Unknown:
throw new NodeException(
string.Format("Player build ended with Unknown state."),
summary.ToString(), node);
}
#else
var errorMsg = BuildPipeline.BuildPlayer(opt);
if (!string.IsNullOrEmpty(errorMsg))
{
throw new NodeException("Player build failed:" + errorMsg, "See description for detail.", node);
}
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using AzureVmFarmer.Service.Areas.HelpPage.Models;
using AzureVmFarmer.Service.Areas.HelpPage.SampleGeneration;
namespace AzureVmFarmer.Service.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.