context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// Match is the result class for a regex search.
// It returns the location, length, and substring for
// the entire match as well as every captured group.
// Match is also used during the search to keep track of each capture for each group. This is
// done using the "_matches" array. _matches[x] represents an array of the captures for group x.
// This array consists of start and length pairs, and may have empty entries at the end. _matchcount[x]
// stores how many captures a group has. Note that _matchcount[x]*2 is the length of all the valid
// values in _matches. _matchcount[x]*2-2 is the Start of the last capture, and _matchcount[x]*2-1 is the
// Length of the last capture
//
// For example, if group 2 has one capture starting at position 4 with length 6,
// _matchcount[2] == 1
// _matches[2][0] == 4
// _matches[2][1] == 6
//
// Values in the _matches array can also be negative. This happens when using the balanced match
// construct, "(?<start-end>...)". When the "end" group matches, a capture is added for both the "start"
// and "end" groups. The capture added for "start" receives the negative values, and these values point to
// the next capture to be balanced. They do NOT point to the capture that "end" just balanced out. The negative
// values are indices into the _matches array transformed by the formula -3-x. This formula also untransforms.
//
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
namespace System.Text.RegularExpressions
{
/// <summary>
/// Represents the results from a single regular expression match.
/// </summary>
public class Match : Group
{
internal static Match s_empty = new Match(null, 1, String.Empty, 0, 0, 0);
internal GroupCollection _groupcoll;
// input to the match
internal Regex _regex;
internal int _textbeg;
internal int _textpos;
internal int _textend;
internal int _textstart;
// output from the match
internal int[][] _matches;
internal int[] _matchcount;
internal bool _balancing; // whether we've done any balancing with this match. If we
// have done balancing, we'll need to do extra work in Tidy().
/// <summary>
/// Returns an empty Match object.
/// </summary>
public static Match Empty
{
get
{
return s_empty;
}
}
internal Match(Regex regex, int capcount, String text, int begpos, int len, int startpos)
: base(text, new int[2], 0)
{
_regex = regex;
_matchcount = new int[capcount];
_matches = new int[capcount][];
_matches[0] = _caps;
_textbeg = begpos;
_textend = begpos + len;
_textstart = startpos;
_balancing = false;
// No need for an exception here. This is only called internally, so we'll use an Assert instead
System.Diagnostics.Debug.Assert(!(_textbeg < 0 || _textstart < _textbeg || _textend < _textstart || _text.Length < _textend),
"The parameters are out of range.");
}
/*
* Nonpublic set-text method
*/
internal virtual void Reset(Regex regex, String text, int textbeg, int textend, int textstart)
{
_regex = regex;
_text = text;
_textbeg = textbeg;
_textend = textend;
_textstart = textstart;
for (int i = 0; i < _matchcount.Length; i++)
{
_matchcount[i] = 0;
}
_balancing = false;
}
public virtual GroupCollection Groups
{
get
{
if (_groupcoll == null)
_groupcoll = new GroupCollection(this, null);
return _groupcoll;
}
}
/// <summary>
/// Returns a new Match with the results for the next match, starting
/// at the position at which the last match ended (at the character beyond the last
/// matched character).
/// </summary>
public Match NextMatch()
{
if (_regex == null)
return this;
return _regex.Run(false, _length, _text, _textbeg, _textend - _textbeg, _textpos);
}
/// <summary>
/// Returns the expansion of the passed replacement pattern. For
/// example, if the replacement pattern is ?$1$2?, Result returns the concatenation
/// of Group(1).ToString() and Group(2).ToString().
/// </summary>
public virtual String Result(String replacement)
{
RegexReplacement repl;
if (replacement == null)
throw new ArgumentNullException("replacement");
if (_regex == null)
throw new NotSupportedException(SR.NoResultOnFailed);
repl = (RegexReplacement)_regex._replref.Get();
if (repl == null || !repl.Pattern.Equals(replacement))
{
repl = RegexParser.ParseReplacement(replacement, _regex._caps, _regex._capsize, _regex._capnames, _regex._roptions);
_regex._replref.Cache(repl);
}
return repl.Replacement(this);
}
/*
* Used by the replacement code
*/
internal virtual String GroupToStringImpl(int groupnum)
{
int c = _matchcount[groupnum];
if (c == 0)
return String.Empty;
int[] matches = _matches[groupnum];
return _text.Substring(matches[(c - 1) * 2], matches[(c * 2) - 1]);
}
/*
* Used by the replacement code
*/
internal String LastGroupToStringImpl()
{
return GroupToStringImpl(_matchcount.Length - 1);
}
/*
* Convert to a thread-safe object by precomputing cache contents
*/
/// <summary>
/// Returns a Match instance equivalent to the one supplied that is safe to share
/// between multiple threads.
/// </summary>
static internal Match Synchronized(Match inner)
{
if (inner == null)
throw new ArgumentNullException("inner");
int numgroups = inner._matchcount.Length;
// Populate all groups by looking at each one
for (int i = 0; i < numgroups; i++)
{
Group group = inner.Groups[i];
// Depends on the fact that Group.Synchronized just
// operates on and returns the same instance
System.Text.RegularExpressions.Group.Synchronized(group);
}
return inner;
}
/*
* Nonpublic builder: add a capture to the group specified by "cap"
*/
internal virtual void AddMatch(int cap, int start, int len)
{
int capcount;
if (_matches[cap] == null)
_matches[cap] = new int[2];
capcount = _matchcount[cap];
if (capcount * 2 + 2 > _matches[cap].Length)
{
int[] oldmatches = _matches[cap];
int[] newmatches = new int[capcount * 8];
for (int j = 0; j < capcount * 2; j++)
newmatches[j] = oldmatches[j];
_matches[cap] = newmatches;
}
_matches[cap][capcount * 2] = start;
_matches[cap][capcount * 2 + 1] = len;
_matchcount[cap] = capcount + 1;
}
/*
* Nonpublic builder: Add a capture to balance the specified group. This is used by the
balanced match construct. (?<foo-foo2>...)
If there were no such thing as backtracking, this would be as simple as calling RemoveMatch(cap).
However, since we have backtracking, we need to keep track of everything.
*/
internal virtual void BalanceMatch(int cap)
{
int capcount;
int target;
_balancing = true;
// we'll look at the last capture first
capcount = _matchcount[cap];
target = capcount * 2 - 2;
// first see if it is negative, and therefore is a reference to the next available
// capture group for balancing. If it is, we'll reset target to point to that capture.
if (_matches[cap][target] < 0)
target = -3 - _matches[cap][target];
// move back to the previous capture
target -= 2;
// if the previous capture is a reference, just copy that reference to the end. Otherwise, point to it.
if (target >= 0 && _matches[cap][target] < 0)
AddMatch(cap, _matches[cap][target], _matches[cap][target + 1]);
else
AddMatch(cap, -3 - target, -4 - target /* == -3 - (target + 1) */ );
}
/*
* Nonpublic builder: removes a group match by capnum
*/
internal virtual void RemoveMatch(int cap)
{
_matchcount[cap]--;
}
/*
* Nonpublic: tells if a group was matched by capnum
*/
internal virtual bool IsMatched(int cap)
{
return cap < _matchcount.Length && _matchcount[cap] > 0 && _matches[cap][_matchcount[cap] * 2 - 1] != (-3 + 1);
}
/*
* Nonpublic: returns the index of the last specified matched group by capnum
*/
internal virtual int MatchIndex(int cap)
{
int i = _matches[cap][_matchcount[cap] * 2 - 2];
if (i >= 0)
return i;
return _matches[cap][-3 - i];
}
/*
* Nonpublic: returns the length of the last specified matched group by capnum
*/
internal virtual int MatchLength(int cap)
{
int i = _matches[cap][_matchcount[cap] * 2 - 1];
if (i >= 0)
return i;
return _matches[cap][-3 - i];
}
/*
* Nonpublic: tidy the match so that it can be used as an immutable result
*/
internal virtual void Tidy(int textpos)
{
int[] interval;
interval = _matches[0];
_index = interval[0];
_length = interval[1];
_textpos = textpos;
_capcount = _matchcount[0];
if (_balancing)
{
// The idea here is that we want to compact all of our unbalanced captures. To do that we
// use j basically as a count of how many unbalanced captures we have at any given time
// (really j is an index, but j/2 is the count). First we skip past all of the real captures
// until we find a balance captures. Then we check each subsequent entry. If it's a balance
// capture (it's negative), we decrement j. If it's a real capture, we increment j and copy
// it down to the last free position.
for (int cap = 0; cap < _matchcount.Length; cap++)
{
int limit;
int[] matcharray;
limit = _matchcount[cap] * 2;
matcharray = _matches[cap];
int i = 0;
int j;
for (i = 0; i < limit; i++)
{
if (matcharray[i] < 0)
break;
}
for (j = i; i < limit; i++)
{
if (matcharray[i] < 0)
{
// skip negative values
j--;
}
else
{
// but if we find something positive (an actual capture), copy it back to the last
// unbalanced position.
if (i != j)
matcharray[j] = matcharray[i];
j++;
}
}
_matchcount[cap] = j / 2;
}
_balancing = false;
}
}
#if DEBUG
internal bool Debug
{
get
{
if (_regex == null)
return false;
return _regex.Debug;
}
}
internal virtual void Dump()
{
int i, j;
for (i = 0; i < _matchcount.Length; i++)
{
System.Diagnostics.Debug.WriteLine("Capnum " + i.ToString(CultureInfo.InvariantCulture) + ":");
for (j = 0; j < _matchcount[i]; j++)
{
String text = "";
if (_matches[i][j * 2] >= 0)
text = _text.Substring(_matches[i][j * 2], _matches[i][j * 2 + 1]);
System.Diagnostics.Debug.WriteLine(" (" + _matches[i][j * 2].ToString(CultureInfo.InvariantCulture) + "," + _matches[i][j * 2 + 1].ToString(CultureInfo.InvariantCulture) + ") " + text);
}
}
}
#endif
}
/*
* MatchSparse is for handling the case where slots are
* sparsely arranged (e.g., if somebody says use slot 100000)
*/
internal class MatchSparse : Match
{
// the lookup hashtable
new internal Dictionary<Int32, Int32> _caps;
/*
* Nonpublic constructor
*/
internal MatchSparse(Regex regex, Dictionary<Int32, Int32> caps, int capcount,
String text, int begpos, int len, int startpos)
: base(regex, capcount, text, begpos, len, startpos)
{
_caps = caps;
}
public override GroupCollection Groups
{
get
{
if (_groupcoll == null)
_groupcoll = new GroupCollection(this, _caps);
return _groupcoll;
}
}
#if DEBUG
internal override void Dump()
{
if (_caps != null)
{
IEnumerator<Int32> e = _caps.Keys.GetEnumerator();
while (e.MoveNext())
{
System.Diagnostics.Debug.WriteLine("Slot " + e.Current.ToString() + " -> " + _caps[(int)e.Current].ToString());
}
}
base.Dump();
}
#endif
}
}
| |
//
// 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.
//
#if !NETSTANDARD
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections.Generic;
using NLog.Common;
using NLog.LogReceiverService;
using NLog.Config;
using NLog.Targets;
using Xunit;
using NLog.Targets.Wrappers;
using System.Threading;
public class LogReceiverWebServiceTargetTests : NLogTestBase
{
[Fact]
public void LogReceiverWebServiceTargetSingleEventTest()
{
var logger = LogManager.GetLogger("loggerName");
var target = new MyLogReceiverWebServiceTarget();
target.EndpointAddress = "http://notimportant:9999/";
target.Parameters.Add(new MethodCallParameter("message", "${message}"));
target.Parameters.Add(new MethodCallParameter("lvl", "${level}"));
SimpleConfigurator.ConfigureForTargetLogging(target);
logger.Info("message text");
var payload = target.LastPayload;
Assert.Equal(2, payload.LayoutNames.Count);
Assert.Equal("message", payload.LayoutNames[0]);
Assert.Equal("lvl", payload.LayoutNames[1]);
Assert.Equal(3, payload.Strings.Count);
Assert.Single(payload.Events);
Assert.Equal("message text", payload.Strings[payload.Events[0].ValueIndexes[0]]);
Assert.Equal("Info", payload.Strings[payload.Events[0].ValueIndexes[1]]);
Assert.Equal("loggerName", payload.Strings[payload.Events[0].LoggerOrdinal]);
}
[Fact]
public void LogReceiverWebServiceTargetMultipleEventTest()
{
var target = new MyLogReceiverWebServiceTarget();
target.EndpointAddress = "http://notimportant:9999/";
target.Parameters.Add(new MethodCallParameter("message", "${message}"));
target.Parameters.Add(new MethodCallParameter("lvl", "${level}"));
var exceptions = new List<Exception>();
var events = new[]
{
LogEventInfo.Create(LogLevel.Info, "logger1", "message1").WithContinuation(exceptions.Add),
LogEventInfo.Create(LogLevel.Debug, "logger2", "message2").WithContinuation(exceptions.Add),
LogEventInfo.Create(LogLevel.Fatal, "logger1", "message2").WithContinuation(exceptions.Add),
};
var configuration = new LoggingConfiguration();
target.Initialize(configuration);
target.WriteAsyncLogEvents(events);
// with multiple events, we should get string caching
var payload = target.LastPayload;
Assert.Equal(2, payload.LayoutNames.Count);
Assert.Equal("message", payload.LayoutNames[0]);
Assert.Equal("lvl", payload.LayoutNames[1]);
// 7 strings instead of 9 since 'logger1' and 'message2' are being reused
Assert.Equal(7, payload.Strings.Count);
Assert.Equal(3, payload.Events.Length);
Assert.Equal("message1", payload.Strings[payload.Events[0].ValueIndexes[0]]);
Assert.Equal("message2", payload.Strings[payload.Events[1].ValueIndexes[0]]);
Assert.Equal("message2", payload.Strings[payload.Events[2].ValueIndexes[0]]);
Assert.Equal("Info", payload.Strings[payload.Events[0].ValueIndexes[1]]);
Assert.Equal("Debug", payload.Strings[payload.Events[1].ValueIndexes[1]]);
Assert.Equal("Fatal", payload.Strings[payload.Events[2].ValueIndexes[1]]);
Assert.Equal("logger1", payload.Strings[payload.Events[0].LoggerOrdinal]);
Assert.Equal("logger2", payload.Strings[payload.Events[1].LoggerOrdinal]);
Assert.Equal("logger1", payload.Strings[payload.Events[2].LoggerOrdinal]);
Assert.Equal(payload.Events[0].LoggerOrdinal, payload.Events[2].LoggerOrdinal);
}
[Fact]
public void LogReceiverWebServiceTargetMultipleEventWithPerEventPropertiesTest()
{
var target = new MyLogReceiverWebServiceTarget();
target.IncludeEventProperties = true;
target.EndpointAddress = "http://notimportant:9999/";
target.Parameters.Add(new MethodCallParameter("message", "${message}"));
target.Parameters.Add(new MethodCallParameter("lvl", "${level}"));
var exceptions = new List<Exception>();
var events = new[]
{
LogEventInfo.Create(LogLevel.Info, "logger1", "message1").WithContinuation(exceptions.Add),
LogEventInfo.Create(LogLevel.Debug, "logger2", "message2").WithContinuation(exceptions.Add),
LogEventInfo.Create(LogLevel.Fatal, "logger1", "message2").WithContinuation(exceptions.Add),
};
events[0].LogEvent.Properties["prop1"] = "value1";
events[1].LogEvent.Properties["prop1"] = "value2";
events[2].LogEvent.Properties["prop1"] = "value3";
events[0].LogEvent.Properties["prop2"] = "value2a";
var configuration = new LoggingConfiguration();
target.Initialize(configuration);
target.WriteAsyncLogEvents(events);
// with multiple events, we should get string caching
var payload = target.LastPayload;
// 4 layout names - 2 from Parameters, 2 from unique properties in events
Assert.Equal(4, payload.LayoutNames.Count);
Assert.Equal("message", payload.LayoutNames[0]);
Assert.Equal("lvl", payload.LayoutNames[1]);
Assert.Equal("prop1", payload.LayoutNames[2]);
Assert.Equal("prop2", payload.LayoutNames[3]);
Assert.Equal(12, payload.Strings.Count);
Assert.Equal(3, payload.Events.Length);
Assert.Equal("message1", payload.Strings[payload.Events[0].ValueIndexes[0]]);
Assert.Equal("message2", payload.Strings[payload.Events[1].ValueIndexes[0]]);
Assert.Equal("message2", payload.Strings[payload.Events[2].ValueIndexes[0]]);
Assert.Equal("Info", payload.Strings[payload.Events[0].ValueIndexes[1]]);
Assert.Equal("Debug", payload.Strings[payload.Events[1].ValueIndexes[1]]);
Assert.Equal("Fatal", payload.Strings[payload.Events[2].ValueIndexes[1]]);
Assert.Equal("value1", payload.Strings[payload.Events[0].ValueIndexes[2]]);
Assert.Equal("value2", payload.Strings[payload.Events[1].ValueIndexes[2]]);
Assert.Equal("value3", payload.Strings[payload.Events[2].ValueIndexes[2]]);
Assert.Equal("value2a", payload.Strings[payload.Events[0].ValueIndexes[3]]);
Assert.Equal("", payload.Strings[payload.Events[1].ValueIndexes[3]]);
Assert.Equal("", payload.Strings[payload.Events[2].ValueIndexes[3]]);
Assert.Equal("logger1", payload.Strings[payload.Events[0].LoggerOrdinal]);
Assert.Equal("logger2", payload.Strings[payload.Events[1].LoggerOrdinal]);
Assert.Equal("logger1", payload.Strings[payload.Events[2].LoggerOrdinal]);
Assert.Equal(payload.Events[0].LoggerOrdinal, payload.Events[2].LoggerOrdinal);
}
[Fact]
public void NoEmptyEventLists()
{
var configuration = new LoggingConfiguration();
var target = new MyLogReceiverWebServiceTarget();
target.EndpointAddress = "http://notimportant:9999/";
target.Initialize(configuration);
var asyncTarget = new AsyncTargetWrapper(target)
{
Name = "NoEmptyEventLists_wrapper"
};
try
{
asyncTarget.Initialize(configuration);
asyncTarget.WriteAsyncLogEvents(new[] { LogEventInfo.Create(LogLevel.Info, "logger1", "message1").WithContinuation(ex => { }) });
Thread.Sleep(1000);
Assert.Equal(1, target.SendCount);
}
finally
{
asyncTarget.Close();
target.Close();
}
}
public class MyLogReceiverWebServiceTarget : LogReceiverWebServiceTarget
{
public NLogEvents LastPayload;
public int SendCount;
public MyLogReceiverWebServiceTarget() : base()
{
}
public MyLogReceiverWebServiceTarget(string name) : base(name)
{
}
protected internal override bool OnSend(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations)
{
this.LastPayload = events;
++this.SendCount;
foreach (var ac in asyncContinuations)
{
ac.Continuation(null);
}
return false;
}
}
}
}
#endif
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Management;
using Vds = Microsoft.Storage.Vds;
using System.Diagnostics;
namespace WebsitePanel.HyperV.Utils
{
class Program
{
// command line parameters
private const string ns = @"root\virtualization";
private static Wmi wmi = null;
private static string computer = null;
private static string command = null;
private static Dictionary<string, string> Parameters = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
static void Main(string[] args)
{
// display welcome screen
DisplayWelcome();
// parse parameters
if (!ParseParameters(args))
{
DisplayUsage();
return;
}
// connect WMI
wmi = new Wmi(computer, ns);
try
{
// run command
if (String.Equals(command, "MountVHD", StringComparison.CurrentCultureIgnoreCase))
MountVHD();
else if (String.Equals(command, "UnmountVHD", StringComparison.CurrentCultureIgnoreCase))
UnmountVHD();
else
{
Console.WriteLine("Unknown command: " + command);
DisplayUsage();
}
}
catch (Exception ex)
{
Console.WriteLine("\nError: " + ex.Message);
if (ex.InnerException != null)
Console.WriteLine("System message: " + ex.InnerException.Message);
}
}
private static void MountVHD()
{
// check parameters
AssertParameter("path");
string vhdPath = Parameters["path"];
ManagementObject objImgSvc = GetImageManagementService();
Console.WriteLine("Mount VHD: " + vhdPath);
// get method params
ManagementBaseObject inParams = objImgSvc.GetMethodParameters("Mount");
inParams["Path"] = vhdPath;
ManagementBaseObject outParams = (ManagementBaseObject)objImgSvc.InvokeMethod("Mount", inParams, null);
JobResult result = CreateJobResultFromWmiMethodResults(outParams);
// load storage job
if (result.ReturnValue != ReturnCode.JobStarted
|| result.Job.JobState == ConcreteJobState.Exception)
{
throw new Exception("Mount job failed to start with the following message: " + result.Job.ErrorDescription);
}
ManagementObject objJob = wmi.GetWmiObject("msvm_StorageJob", "InstanceID = '{0}'", result.Job.Id);
if (JobCompleted(result.Job))
{
// load output data
ManagementObject objImage = wmi.GetRelatedWmiObject(objJob, "Msvm_MountedStorageImage");
int pathId = Convert.ToInt32(objImage["PathId"]);
int portNumber = Convert.ToInt32(objImage["PortNumber"]);
int targetId = Convert.ToInt32(objImage["TargetId"]);
int lun = Convert.ToInt32(objImage["Lun"]);
string diskAddress = String.Format("Port{0}Path{1}Target{2}Lun{3}", portNumber, pathId, targetId, lun);
// find mounted disk using VDS
Vds.Advanced.AdvancedDisk advancedDisk = null;
Vds.Pack diskPack = null;
// first attempt
System.Threading.Thread.Sleep(3000);
Console.WriteLine("Querying mounted disk...");
FindVdsDisk(diskAddress, out advancedDisk, out diskPack);
// second attempt
if (advancedDisk == null)
{
System.Threading.Thread.Sleep(20000);
Console.WriteLine("Querying mounted disk - second attempt...");
FindVdsDisk(diskAddress, out advancedDisk, out diskPack);
}
if (advancedDisk == null)
throw new Exception("Could not find mounted disk");
List<string> volumes = new List<string>();
Console.WriteLine("Disk flags: " + advancedDisk.Flags);
// clear READONLY
if ((advancedDisk.Flags & Vds.DiskFlags.ReadOnly) == Vds.DiskFlags.ReadOnly)
{
Console.Write("Clearing disk Read-Only flag...");
advancedDisk.ClearFlags(Vds.DiskFlags.ReadOnly);
while ((advancedDisk.Flags & Vds.DiskFlags.ReadOnly) == Vds.DiskFlags.ReadOnly)
{
System.Threading.Thread.Sleep(100);
advancedDisk.Refresh();
}
Console.WriteLine("Done");
}
// bring disk ONLINE
if (advancedDisk.Status == Vds.DiskStatus.Offline)
{
Console.Write("Bringing disk online...");
advancedDisk.Online();
while (advancedDisk.Status == Vds.DiskStatus.Offline)
{
System.Threading.Thread.Sleep(100);
advancedDisk.Refresh();
}
Console.WriteLine("Done");
}
// determine disk index for DiskPart
Wmi cimv2 = new Wmi(computer, "root\\CIMV2");
ManagementObject objDisk = cimv2.GetWmiObject("win32_diskdrive",
"Model='Msft Virtual Disk SCSI Disk Device' and ScsiTargetID={0} and ScsiLogicalUnit={1} and scsiPort={2}",
targetId, lun, portNumber);
if (objDisk != null)
{
Console.WriteLine("DiskPart disk index: " + Convert.ToInt32(objDisk["Index"]));
}
// find volume
diskPack.Refresh();
foreach (Vds.Volume volume in diskPack.Volumes)
{
volumes.Add(volume.DriveLetter.ToString());
}
if (volumes.Count == 0 && objDisk != null)
{
// find volumes using WMI
foreach (ManagementObject objPartition in objDisk.GetRelated("Win32_DiskPartition"))
{
foreach (ManagementObject objVolume in objPartition.GetRelated("Win32_LogicalDisk"))
{
volumes.Add(objVolume["Name"].ToString().TrimEnd(':'));
}
}
}
foreach (string volume in volumes)
{
Console.WriteLine("Volume found: " + volume);
}
//// find disk index
//Wmi win32 = new Wmi(computer, @"root\cimv2");
//System.Threading.Thread.Sleep(1000); // small pause
//ManagementObject objDisk = win32.GetWmiObject("win32_DiskDrive",
// "Model='Msft Virtual Disk SCSI Disk Device' and ScsiTargetID={0} and ScsiLogicalUnit={1} and ScsiPort={2}",
// targetId, lun, portNumber);
//int diskIndex = Convert.ToInt32(objDisk["Index"]);
Console.WriteLine("\nDisk has been mounted.\n");
//Console.WriteLine("Disk index: " + advancedDisk.);
}
}
private static void FindVdsDisk(string diskAddress, out Vds.Advanced.AdvancedDisk advancedDisk, out Vds.Pack diskPack)
{
advancedDisk = null;
diskPack = null;
Vds.ServiceLoader serviceLoader = new Vds.ServiceLoader();
Vds.Service vds = serviceLoader.LoadService(computer);
vds.WaitForServiceReady();
foreach (Vds.Disk disk in vds.UnallocatedDisks)
{
if (disk.DiskAddress == diskAddress)
{
advancedDisk = (Vds.Advanced.AdvancedDisk)disk;
break;
}
}
if (advancedDisk == null)
{
vds.HardwareProvider = false;
vds.SoftwareProvider = true;
foreach (Vds.SoftwareProvider provider in vds.Providers)
foreach (Vds.Pack pack in provider.Packs)
foreach (Vds.Disk disk in pack.Disks)
if (disk.DiskAddress == diskAddress)
{
diskPack = pack;
advancedDisk = (Vds.Advanced.AdvancedDisk)disk;
break;
}
}
}
private static void UnmountVHD()
{
// check parameters
AssertParameter("path");
string vhdPath = Parameters["path"];
Console.WriteLine("Unmount VHD: " + vhdPath);
ManagementObject objImgSvc = GetImageManagementService();
// get method params
ManagementBaseObject inParams = objImgSvc.GetMethodParameters("Unmount");
inParams["Path"] = vhdPath;
ManagementBaseObject outParams = (ManagementBaseObject)objImgSvc.InvokeMethod("Unmount", inParams, null);
ReturnCode result = (ReturnCode)Convert.ToInt32(outParams["ReturnValue"]);
if (result != ReturnCode.OK)
{
throw new Exception("Unmount task failed with the \"" + result + "\" code");
}
Console.WriteLine("\nDisk has been unmounted.");
}
#region Jobs
private static bool JobCompleted(ConcreteJob job)
{
bool jobCompleted = true;
while (job.JobState == ConcreteJobState.Starting ||
job.JobState == ConcreteJobState.Running)
{
System.Threading.Thread.Sleep(200);
job = GetJob(job.Id);
}
if (job.JobState != ConcreteJobState.Completed)
{
jobCompleted = false;
}
return jobCompleted;
}
public static ConcreteJob GetJob(string jobId)
{
ManagementObject objJob = GetJobWmiObject(jobId);
return CreateJobFromWmiObject(objJob);
}
private static ConcreteJob CreateJobFromWmiMethodResults(ManagementBaseObject outParams)
{
ManagementBaseObject objJob = wmi.GetWmiObjectByPath((string)outParams["Job"]);
if (objJob == null || objJob.Properties.Count == 0)
return null;
return CreateJobFromWmiObject(objJob);
}
private static JobResult CreateJobResultFromWmiMethodResults(ManagementBaseObject outParams)
{
JobResult result = new JobResult();
// return value
result.ReturnValue = (ReturnCode)Convert.ToInt32(outParams["ReturnValue"]);
// job
ManagementBaseObject objJob = wmi.GetWmiObjectByPath((string)outParams["Job"]);
if (objJob != null && objJob.Properties.Count > 0)
{
result.Job = CreateJobFromWmiObject(objJob);
}
return result;
}
private static ManagementObject GetJobWmiObject(string id)
{
return wmi.GetWmiObject("CIM_ConcreteJob", "InstanceID = '{0}'", id);
}
private static ConcreteJob CreateJobFromWmiObject(ManagementBaseObject objJob)
{
if (objJob == null || objJob.Properties.Count == 0)
return null;
ConcreteJob job = new ConcreteJob();
job.Id = (string)objJob["InstanceID"];
job.JobState = (ConcreteJobState)Convert.ToInt32(objJob["JobState"]);
job.Caption = (string)objJob["Caption"];
job.Description = (string)objJob["Description"];
job.ElapsedTime = wmi.ToDateTime((string)objJob["ElapsedTime"]);
job.StartTime = wmi.ToDateTime((string)objJob["StartTime"]);
job.ErrorCode = Convert.ToInt32(objJob["ErrorCode"]);
job.ErrorDescription = (string)objJob["ErrorDescription"];
job.PercentComplete = Convert.ToInt32(objJob["PercentComplete"]);
return job;
}
#endregion
#region Managers
private static ManagementObject GetVirtualSystemManagementService()
{
return wmi.GetWmiObject("msvm_VirtualSystemManagementService");
}
private static ManagementObject GetVirtualSwitchManagementService()
{
return wmi.GetWmiObject("msvm_VirtualSwitchManagementService");
}
private static ManagementObject GetImageManagementService()
{
return wmi.GetWmiObject("msvm_ImageManagementService");
}
#endregion
private static void DisplayWelcome()
{
string ver = Assembly.GetExecutingAssembly().GetName().Version.ToString(2);
Console.WriteLine("VmUtils - utility to work with Hyper-V virtual resources. Version " + ver);
Console.WriteLine("Copyright (C) 2011 by Outercurve Foundation. All rights reserved.\n");
}
private static bool ParseParameters(string[] args)
{
if (args == null || args.Length == 0)
return false;
// command
command = args[0];
for (int i = 1; i < args.Length; i++)
{
if (!args[i].StartsWith("-"))
return false; // wrong parameter format
string name = args[i].Substring(1);
if (i == (args.Length - 1))
return false; // no parameter value
string val = args[i + 1];
i++;
// add parameter to the hash
Parameters.Add(name, val);
if (String.Equals(name, "computer", StringComparison.CurrentCultureIgnoreCase))
computer = val;
}
return true;
}
private static void AssertParameter(string name)
{
if (!Parameters.ContainsKey(name))
{
throw new Exception(String.Format("Command \"{0}\" expect \"{1}\" parameter which was not supplied.", command, name));
}
}
private static void DisplayUsage()
{
Console.WriteLine("\nUSAGE:");
Console.WriteLine(" vmutils <command> [-parameter1 value1 -parameter2 value2 ...]\n");
Console.WriteLine("EXAMPLE:");
Console.WriteLine(" vmtuils MountVHD -path \"c:\\templates\\Windows 2008.vhd\" -computer HYPERV01\n");
Console.WriteLine("SUPPORTED COMMANDS:");
Console.WriteLine(" MountVHD - mounts VHD.");
Console.WriteLine(" Parameters:");
Console.WriteLine(" -path - path to VHD file.");
Console.WriteLine(" -computer - (optional) remote computer with Hyper-V role installed.");
Console.WriteLine("");
Console.WriteLine(" UnmountVHD - unmounts VHD.");
Console.WriteLine(" Parameters:");
Console.WriteLine(" -path - path to VHD file.");
Console.WriteLine(" -computer - (optional) remote computer with Hyper-V role installed.");
}
}
}
| |
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace Avalon.Windows.Controls
{
partial class TaskDialog
{
#region Fields
private InlineModalDialog _inlineModalDialog;
#endregion
#region Static - Common
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="header">The header.</param>
/// <returns></returns>
public static TaskDialogResult ShowInline(string header)
{
return ShowInlineCore(null, header, null, string.Empty, TaskDialogButtons.OK, TaskDialogIcon.None, false);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="title">The title.</param>
/// <returns></returns>
public static TaskDialogResult ShowInline(string header, string title)
{
return ShowInlineCore(null, header, null, title, DefaultButton, TaskDialogIcon.None, false);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="header">The header.</param>
/// <returns></returns>
public static TaskDialogResult ShowInline(DependencyObject owner, string header)
{
return ShowInlineCore(owner, header, null, string.Empty, DefaultButton, TaskDialogIcon.None, false);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="title">The title.</param>
/// <param name="standardButtons">The standard buttons.</param>
/// <returns></returns>
public static TaskDialogResult ShowInline(string header, string title, TaskDialogButtons standardButtons)
{
return ShowInlineCore(null, header, null, title, standardButtons, TaskDialogIcon.None, false);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="header">The header.</param>
/// <param name="title">The title.</param>
/// <returns></returns>
public static TaskDialogResult ShowInline(DependencyObject owner, string header, string title)
{
return ShowInlineCore(owner, header, null, title, DefaultButton, TaskDialogIcon.None, false);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="content">The content.</param>
/// <param name="title">The title.</param>
/// <returns></returns>
public static TaskDialogResult ShowInline(string header, string content, string title)
{
return ShowInlineCore(null, header, content, title, DefaultButton, TaskDialogIcon.None, false);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="content">The content.</param>
/// <param name="title">The title.</param>
/// <param name="standardButtons">The standard buttons.</param>
/// <returns></returns>
public static TaskDialogResult ShowInline(string header, string content, string title, TaskDialogButtons standardButtons)
{
return ShowInlineCore(null, header, content, title, standardButtons, TaskDialogIcon.None, false);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="header">The header.</param>
/// <param name="content">The content.</param>
/// <param name="title">The title.</param>
/// <returns></returns>
public static TaskDialogResult ShowInline(DependencyObject owner, string header, string content, string title)
{
return ShowInlineCore(owner, header, content, title, DefaultButton, TaskDialogIcon.None, false);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="content">The content.</param>
/// <param name="title">The title.</param>
/// <param name="standardButtons">The standard buttons.</param>
/// <param name="icon">The icon.</param>
/// <returns></returns>
public static TaskDialogResult ShowInline(string header, string content, string title, TaskDialogButtons standardButtons, TaskDialogIcon icon)
{
return ShowInlineCore(null, header, content, title, standardButtons, icon, false);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="header">The header.</param>
/// <param name="content">The content.</param>
/// <param name="title">The title.</param>
/// <param name="standardButtons">The standard buttons.</param>
/// <returns></returns>
public static TaskDialogResult ShowInline(DependencyObject owner, string header, string content, string title, TaskDialogButtons standardButtons)
{
return ShowInlineCore(owner, header, content, title, standardButtons, TaskDialogIcon.None, false);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="header">The header.</param>
/// <param name="content">The content.</param>
/// <param name="title">The title.</param>
/// <param name="standardButtons">The standard buttons.</param>
/// <param name="icon">The icon.</param>
/// <returns></returns>
public static TaskDialogResult ShowInline(DependencyObject owner, string header, string content, string title, TaskDialogButtons standardButtons, TaskDialogIcon icon)
{
return ShowInlineCore(owner, header, content, title, standardButtons, icon, false);
}
#endregion
#region Static - TaskDialogButtonData
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="content">The content.</param>
/// <param name="title">The title.</param>
/// <param name="standardButtons">The standard buttons.</param>
/// <param name="icon">The icon.</param>
/// <param name="useCommandLinks">if set to <c>true</c>, use <see cref="CommandLink"/>s instead of <see cref="Button"/>s.</param>
/// <param name="buttons">The buttons.</param>
/// <returns></returns>
public static TaskDialogResult ShowInline(string header, string content, string title, TaskDialogButtons standardButtons, TaskDialogIcon icon, bool useCommandLinks, params TaskDialogButtonData[] buttons)
{
return ShowInlineCore(null, header, content, title, standardButtons, icon, useCommandLinks, buttons);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="header">The header.</param>
/// <param name="content">The content.</param>
/// <param name="title">The title.</param>
/// <param name="standardButtons">The standard buttons.</param>
/// <param name="icon">The icon.</param>
/// <param name="useCommandLinks">if set to <c>true</c>, use <see cref="CommandLink"/>s instead of <see cref="Button"/>s.</param>
/// <param name="buttons">The buttons.</param>
/// <returns></returns>
public static TaskDialogResult ShowInline(DependencyObject owner, string header, string content, string title, TaskDialogButtons standardButtons, TaskDialogIcon icon, bool useCommandLinks, params TaskDialogButtonData[] buttons)
{
return ShowInlineCore(owner, header, content, title, standardButtons, icon, useCommandLinks, buttons);
}
#endregion
#region Static - Strings
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="icon">The icon.</param>
/// <param name="defaultButtonIndex">Default index of the button.</param>
/// <param name="buttonContents">The button contents.</param>
/// <returns></returns>
public static int? ShowInline(string header, TaskDialogIcon icon, int defaultButtonIndex, params string[] buttonContents)
{
return ShowInlineCore(null, header, null, string.Empty, icon, false, defaultButtonIndex, buttonContents);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="header">The header.</param>
/// <param name="icon">The icon.</param>
/// <param name="defaultButtonIndex">Default index of the button.</param>
/// <param name="buttonContents">The button contents.</param>
/// <returns></returns>
public static int? ShowInline(DependencyObject owner, string header, TaskDialogIcon icon, int defaultButtonIndex, params string[] buttonContents)
{
return ShowInlineCore(owner, header, null, string.Empty, icon, false, defaultButtonIndex, buttonContents);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="content">The content.</param>
/// <param name="title">The title.</param>
/// <param name="icon">The icon.</param>
/// <param name="useCommandLinks">if set to <c>true</c>, use <see cref="CommandLink" />s instead of <see cref="Button" />s.</param>
/// <param name="defaultButtonIndex">Default index of the button.</param>
/// <param name="buttonContents">The button contents.</param>
/// <returns></returns>
public static int? ShowInline(string header, string content, string title, TaskDialogIcon icon, bool useCommandLinks, int defaultButtonIndex, params string[] buttonContents)
{
return ShowInlineCore(null, header, content, title, icon, useCommandLinks, defaultButtonIndex, buttonContents);
}
/// <summary>
/// Displays a <see cref="TaskDialog"/> using an <see cref="InlineModalDialog" />.
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="header">The header.</param>
/// <param name="content">The content.</param>
/// <param name="title">The title.</param>
/// <param name="icon">The icon.</param>
/// <param name="useCommandLinks">if set to <c>true</c>, use <see cref="CommandLink" />s instead of <see cref="Button" />s.</param>
/// <param name="defaultButtonIndex">Default index of the button.</param>
/// <param name="buttonContents">The button contents.</param>
/// <returns></returns>
public static int? ShowInline(DependencyObject owner, string header, string content, string title, TaskDialogIcon icon, bool useCommandLinks, int defaultButtonIndex, params string[] buttonContents)
{
return ShowInlineCore(owner, header, content, title, icon, useCommandLinks, defaultButtonIndex, buttonContents);
}
#endregion
#region Core Show Methods
private static int? ShowInlineCore(DependencyObject owner, string header, string content, string title, TaskDialogIcon icon, bool useCommandLinks, int defaultButtonIndex, params string[] buttonContents)
{
TaskDialogButtonData[] buttons = buttonContents.Select((s, i) => new TaskDialogButtonData(i, s, null, i == defaultButtonIndex)).ToArray();
TaskDialogResult result = ShowInlineCore(owner, header, content, title, TaskDialogButtons.None, icon, useCommandLinks, buttons);
int? index = null;
if (result.ButtonData != null)
{
index = result.ButtonData.Value;
}
return index;
}
private static TaskDialogResult ShowInlineCore(DependencyObject owner, string header, string content, string title, TaskDialogButtons standardButtons, TaskDialogIcon icon, bool useCommandLinks, params TaskDialogButtonData[] buttons)
{
if (title == null)
{
title = string.Empty;
}
if (content == string.Empty)
{
content = null;
}
var taskDialog = new TaskDialog
{
Title = title,
Header = header,
Content = content,
MainIcon = TaskDialogIconConverter.ConvertFrom(icon)
};
foreach (TaskDialogButtonData buttonData in TaskDialogButtonData.FromStandardButtons(standardButtons))
{
taskDialog.Buttons.Add(buttonData);
}
if (useCommandLinks)
{
foreach (TaskDialogButtonData buttonData in buttons)
{
taskDialog.CommandLinks.Add(buttonData);
}
}
else
{
foreach (TaskDialogButtonData buttonData in buttons)
{
taskDialog.Buttons.Add(buttonData);
}
}
if (owner == null && Application.Current != null)
{
owner = Application.Current.MainWindow;
}
taskDialog.Background = SystemColors.WindowBrush;
taskDialog.ShowInline(owner);
return taskDialog.Result;
}
/// <summary>
/// Shows the task dialog using an <see cref="InlineModalDialog"/>.
/// </summary>
/// <param name="owner"></param>
public void ShowInline(DependencyObject owner)
{
_inlineModalDialog = new InlineModalDialog { Content = this, Owner = owner, Header = Title };
_inlineModalDialog.Show();
}
partial void OnClosed()
{
if (_inlineModalDialog != null)
{
_inlineModalDialog.Close();
_inlineModalDialog = null;
}
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using IndexReader = Lucene.Net.Index.IndexReader;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
namespace Lucene.Net.Search
{
/// <summary>
/// A query that matches all documents.
/// </summary>
[Serializable]
public class MatchAllDocsQuery : Query
{
public MatchAllDocsQuery()
{
}
private class MatchAllScorer : Scorer
{
private void InitBlock(MatchAllDocsQuery enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private MatchAllDocsQuery enclosingInstance;
public MatchAllDocsQuery Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal IndexReader reader;
internal int id;
internal int maxId;
internal float score;
internal MatchAllScorer(MatchAllDocsQuery enclosingInstance, IndexReader reader, Similarity similarity, Weight w):base(similarity)
{
InitBlock(enclosingInstance);
this.reader = reader;
id = - 1;
maxId = reader.MaxDoc() - 1;
score = w.GetValue();
}
public override Explanation Explain(int doc)
{
return null; // not called... see MatchAllDocsWeight.explain()
}
public override int Doc()
{
return id;
}
public override bool Next()
{
while (id < maxId)
{
id++;
if (!reader.IsDeleted(id))
{
return true;
}
}
return false;
}
public override float Score()
{
return score;
}
public override bool SkipTo(int target)
{
id = target - 1;
return Next();
}
}
[Serializable]
private class MatchAllDocsWeight : Weight
{
private void InitBlock(MatchAllDocsQuery enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private MatchAllDocsQuery enclosingInstance;
public MatchAllDocsQuery Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private Similarity similarity;
private float queryWeight;
private float queryNorm;
public MatchAllDocsWeight(MatchAllDocsQuery enclosingInstance, Searcher searcher)
{
InitBlock(enclosingInstance);
this.similarity = searcher.GetSimilarity();
}
public override System.String ToString()
{
return "weight(" + Enclosing_Instance + ")";
}
public virtual Query GetQuery()
{
return Enclosing_Instance;
}
public virtual float GetValue()
{
return queryWeight;
}
public virtual float SumOfSquaredWeights()
{
queryWeight = Enclosing_Instance.GetBoost();
return queryWeight * queryWeight;
}
public virtual void Normalize(float queryNorm)
{
this.queryNorm = queryNorm;
queryWeight *= this.queryNorm;
}
public virtual Scorer Scorer(IndexReader reader)
{
return new MatchAllScorer(enclosingInstance, reader, similarity, this);
}
public virtual Explanation Explain(IndexReader reader, int doc)
{
// explain query weight
Explanation queryExpl = new ComplexExplanation(true, GetValue(), "MatchAllDocsQuery, product of:");
if (Enclosing_Instance.GetBoost() != 1.0f)
{
queryExpl.AddDetail(new Explanation(Enclosing_Instance.GetBoost(), "boost"));
}
queryExpl.AddDetail(new Explanation(queryNorm, "queryNorm"));
return queryExpl;
}
}
protected internal override Weight CreateWeight(Searcher searcher)
{
return new MatchAllDocsWeight(this, searcher);
}
public override void ExtractTerms(System.Collections.Hashtable terms)
{
}
public override System.String ToString(System.String field)
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
buffer.Append("MatchAllDocsQuery");
buffer.Append(ToStringUtils.Boost(GetBoost()));
return buffer.ToString();
}
public override bool Equals(object o)
{
if (!(o is MatchAllDocsQuery))
return false;
MatchAllDocsQuery other = (MatchAllDocsQuery) o;
return this.GetBoost() == other.GetBoost();
}
public override int GetHashCode()
{
return BitConverter.ToInt32(BitConverter.GetBytes(GetBoost()), 0) ^ 0x1AA71190;
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Interfaces;
namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders
{
public class LLRAW : ITerrainLoader
{
public struct HeightmapLookupValue : IComparable<HeightmapLookupValue>
{
public int Index;
public double Value;
public HeightmapLookupValue(int index, double value)
{
Index = index;
Value = value;
}
public int CompareTo(HeightmapLookupValue val)
{
return Value.CompareTo(val.Value);
}
}
/// <summary>Lookup table to speed up terrain exports</summary>
HeightmapLookupValue[] LookupHeightTable;
public LLRAW()
{
LookupHeightTable = new HeightmapLookupValue[256 * 256];
for (int i = 0; i < 256; i++)
{
for (int j = 0; j < 256; j++)
{
LookupHeightTable[i + (j * 256)] = new HeightmapLookupValue(i + (j * 256), ((double)i * ((double)j / 128.0d)));
}
}
Array.Sort<HeightmapLookupValue>(LookupHeightTable);
}
#region ITerrainLoader Members
public ITerrainChannel LoadFile(string filename)
{
FileInfo file = new FileInfo(filename);
FileStream s = file.Open(FileMode.Open, FileAccess.Read);
ITerrainChannel retval = LoadStream(s);
s.Close();
return retval;
}
public ITerrainChannel LoadFile(string filename, int offsetX, int offsetY, int fileWidth, int fileHeight, int sectionWidth, int sectionHeight)
{
TerrainChannel retval = new TerrainChannel(sectionWidth, sectionHeight);
FileInfo file = new FileInfo(filename);
FileStream s = file.Open(FileMode.Open, FileAccess.Read);
BinaryReader bs = new BinaryReader(s);
int currFileYOffset = fileHeight - 1;
// if our region isn't on the first Y section of the areas to be landscaped, then
// advance to our section of the file
while (currFileYOffset > offsetY)
{
// read a whole strip of regions
int heightsToRead = sectionHeight * (fileWidth * sectionWidth);
bs.ReadBytes(heightsToRead * 13); // because there are 13 fun channels
currFileYOffset--;
}
// got to the Y start offset within the file of our region
// so read the file bits associated with our region
int y;
// for each Y within our Y offset
for (y = sectionHeight - 1; y >= 0; y--)
{
int currFileXOffset = 0;
// if our region isn't the first X section of the areas to be landscaped, then
// advance the stream to the X start pos of our section in the file
// i.e. eat X upto where we start
while (currFileXOffset < offsetX)
{
bs.ReadBytes(sectionWidth * 13);
currFileXOffset++;
}
// got to our X offset, so write our regions X line
int x;
for (x = 0; x < sectionWidth; x++)
{
// Read a strip and continue
retval[x, y] = bs.ReadByte() * (bs.ReadByte() / 128.0);
bs.ReadBytes(11);
}
// record that we wrote it
currFileXOffset++;
// if our region isn't the last X section of the areas to be landscaped, then
// advance the stream to the end of this Y column
while (currFileXOffset < fileWidth)
{
// eat the next regions x line
bs.ReadBytes(sectionWidth * 13); //The 13 channels again
currFileXOffset++;
}
}
bs.Close();
s.Close();
return retval;
}
public ITerrainChannel LoadStream(Stream s)
{
TerrainChannel retval = new TerrainChannel();
BinaryReader bs = new BinaryReader(s);
int y;
for (y = 0; y < retval.Height; y++)
{
int x;
for (x = 0; x < retval.Width; x++)
{
retval[x, (retval.Height - 1) - y] = bs.ReadByte() * (bs.ReadByte() / 128.0);
bs.ReadBytes(11); // Advance the stream to next bytes.
}
}
bs.Close();
return retval;
}
public void SaveFile(string filename, ITerrainChannel map)
{
FileInfo file = new FileInfo(filename);
FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write);
SaveStream(s, map);
s.Close();
}
public void SaveStream(Stream s, ITerrainChannel map)
{
BinaryWriter binStream = new BinaryWriter(s);
// Output the calculated raw
for (int y = 0; y < map.Height; y++)
{
for (int x = 0; x < map.Width; x++)
{
double t = map[x, (map.Height - 1) - y];
//if height is less than 0, set it to 0 as
//can't save -ve values in a LLRAW file
if (t < 0d)
{
t = 0d;
}
int index = 0;
// The lookup table is pre-sorted, so we either find an exact match or
// the next closest (smaller) match with a binary search
index = Array.BinarySearch<HeightmapLookupValue>(LookupHeightTable, new HeightmapLookupValue(0, t));
if (index < 0)
index = ~index - 1;
index = LookupHeightTable[index].Index;
byte red = (byte) (index & 0xFF);
byte green = (byte) ((index >> 8) & 0xFF);
const byte blue = 20;
const byte alpha1 = 0;
const byte alpha2 = 0;
const byte alpha3 = 0;
const byte alpha4 = 0;
const byte alpha5 = 255;
const byte alpha6 = 255;
const byte alpha7 = 255;
const byte alpha8 = 255;
byte alpha9 = red;
byte alpha10 = green;
binStream.Write(red);
binStream.Write(green);
binStream.Write(blue);
binStream.Write(alpha1);
binStream.Write(alpha2);
binStream.Write(alpha3);
binStream.Write(alpha4);
binStream.Write(alpha5);
binStream.Write(alpha6);
binStream.Write(alpha7);
binStream.Write(alpha8);
binStream.Write(alpha9);
binStream.Write(alpha10);
}
}
binStream.Close();
}
public string FileExtension
{
get { return ".raw"; }
}
#endregion
public override string ToString()
{
return "LL/SL RAW";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryExclusiveOrTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckByteExclusiveOrTest(bool useInterpreter)
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyByteExclusiveOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckSByteExclusiveOrTest(bool useInterpreter)
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifySByteExclusiveOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUShortExclusiveOrTest(bool useInterpreter)
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUShortExclusiveOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckShortExclusiveOrTest(bool useInterpreter)
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyShortExclusiveOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUIntExclusiveOrTest(bool useInterpreter)
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUIntExclusiveOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIntExclusiveOrTest(bool useInterpreter)
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyIntExclusiveOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckULongExclusiveOrTest(bool useInterpreter)
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyULongExclusiveOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongExclusiveOrTest(bool useInterpreter)
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyLongExclusiveOr(array[i], array[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyByteExclusiveOr(byte a, byte b, bool useInterpreter)
{
Expression<Func<byte>> e =
Expression.Lambda<Func<byte>>(
Expression.ExclusiveOr(
Expression.Constant(a, typeof(byte)),
Expression.Constant(b, typeof(byte))),
Enumerable.Empty<ParameterExpression>());
Func<byte> f = e.Compile(useInterpreter);
Assert.Equal((byte)(a ^ b), f());
}
private static void VerifySByteExclusiveOr(sbyte a, sbyte b, bool useInterpreter)
{
Expression<Func<sbyte>> e =
Expression.Lambda<Func<sbyte>>(
Expression.ExclusiveOr(
Expression.Constant(a, typeof(sbyte)),
Expression.Constant(b, typeof(sbyte))),
Enumerable.Empty<ParameterExpression>());
Func<sbyte> f = e.Compile(useInterpreter);
Assert.Equal((sbyte)(a ^ b), f());
}
private static void VerifyUShortExclusiveOr(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.ExclusiveOr(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
Assert.Equal((ushort)(a ^ b), f());
}
private static void VerifyShortExclusiveOr(short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.ExclusiveOr(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
Assert.Equal((short)(a ^ b), f());
}
private static void VerifyUIntExclusiveOr(uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.ExclusiveOr(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
Assert.Equal(a ^ b, f());
}
private static void VerifyIntExclusiveOr(int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ExclusiveOr(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(a ^ b, f());
}
private static void VerifyULongExclusiveOr(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.ExclusiveOr(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
Assert.Equal(a ^ b, f());
}
private static void VerifyLongExclusiveOr(long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.ExclusiveOr(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
Assert.Equal(a ^ b, f());
}
#endregion
[Fact]
public static void CannotReduce()
{
Expression exp = Expression.ExclusiveOr(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void ThrowsOnLeftNull()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.ExclusiveOr(null, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightNull()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.ExclusiveOr(Expression.Constant(""), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("left", () => Expression.ExclusiveOr(value, Expression.Constant(1)));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("right", () => Expression.ExclusiveOr(Expression.Constant(1), value));
}
[Fact]
public static void ToStringTest()
{
BinaryExpression e = Expression.ExclusiveOr(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a ^ b)", e.ToString());
// NB: Unlike 'Expression.And' and 'Expression.Or', there's no special case for bool and bool? here.
}
}
}
| |
//================================
// Clock
//================================
package WRPClock
{
function BootClock()
{
if(!$WRP::Booted)
return;
Tardis.LoadClock();
Tardis.Tick();
}
function Tardis::LoadClock(%s)
{
deleteVariables("$WRP::Clock::*");
if(isFile("config/server/WorldRP/Clock.cs"))
{
exec("config/server/WorldRP/Clock.cs");
%s.Min = $WRP::Clock::Min;
%s.Hour = $WRP::Clock::Hour;
%s.Day = $WRP::Clock::Day;
%s.Month = $WRP::Clock::Month;
%s.Year = $WRP::Clock::Year;
if(EywaPopulation.Debug) { warn("WorldRP: Clock Loaded From File"); }
return;
}
// Default
%s.Min = "0";
%s.Hour = "1";
%s.Day = "1";
%s.Month = "1";
%s.Year = "1";
%s.AMPM = "AM";
$WRP::Clock::Type = "env";
if(EywaPopulation.Debug) { warn("WorldRP: Clock has started ticking"); }
}
// The GOLDEN GEAR of The Clock
function Tardis::tick(%s)
{
if(!$WRP::Booted)
return;
if(%s.Tick)
cancel(%s.Tick);
// Adjusts the timer accordingly
if($WRP::Clock::Type $= "env")
{
%tickSpeed = $EnvGuiServer::DayLength;
}
else if($WRP::Clock::Type $= "CustomTicker")
{
%tickSpeed = $WRP::Clock::TickSpeed * 1000;
}
%s.Tick = %s.schedule(%tickSpeed, "tick");
%s.Min++;
%s.MinTick();
}
function Tardis::addMonth(%s, %name, %days, %desc)
{
if(!$WRP::Booted)
return;
if(%name $= "" || %days $= "")
if(EywaPopulation.Debug) { warn("WorldRP Debug: Month " @ %name SPC "was not added, incorrect arguements."); }
%s.TotalMonths++;
%NewMonth = %s.TotalMonths;
%s.MonthName[%NewMonth] = %name;
%s.MonthDays[%NewMonth] = %days;
%s.MonthDesc[%NewMonth] = %desc;
}
function Tardis::addHoliday(%s, %HDate, %HName, %HDesc)
{
if(!$WRP::Booted)
return;
if(%HDate $= "" || strstr(%date, "-") !$= "-1" || %HName $= "" || %HDesc $= "")
if(EywaPopulation.Debug) { warn("WorldRP Debug: Holiday " @ %HName SPC "was not added, incorrect arguements."); }
%s.HolidayCount++;
%NewHoliday = %s.HolidayCount;
%s.HolidayDate[%NewHoliday] = %HDate;
%s.HolidayName[%NewHoliday] = %HName;
%s.HolidayDesc[%NewHoliday] = %HDesc;
}
function Tardis::SaveClock(%s)
{
$WRP::Clock::Min = %s.Min;
$WRP::Clock::Hour = %s.Min;
$WRP::Clock::Day = %s.Day;
$WRP::Clock::Month = %s.Month;
$WRP::Clock::Year = %s.Year;
export("$WRP::Clock::*", "config/server/WorldRP/Clock.cs");
deleteVariables("$WRP::Clock::*");
}
function Tardis::CheckClock(%s)
{
if(!$WRP::Booted)
return;
if($WRP::Clock::Type $= "env" || $WRP::Clock::Type $= "CustomTicker")
{
// Hours
if(%s.Min >= 60)
{
%s.Min = "0";
%s.Hour++;
%s.HourTick();
%s.getAMPM();
}
// Days
if(%s.Hour >= 24)
{
%s.Hour = "1";
%s.Day++;
%s.DayTick();
}
// Months
if(%s.Day >= %s.MonthDays[%s.Day])
{
%s.Day = "1";
%s.Month++;
%s.MonthTick();
}
// Years
if(%s.Month >= %s.TotalMonths)
{
%s.month = "1";
%s.year++;
%s.YearTick();
}
}
// else if($WRP::Clock::Type $= "CustomTicker") { }
}
function Tardis::Display(%s,%type)
{
// 24-Hour Clock
if($WRP::Clock::ArmyTime $= "1")
{
if(%s.hour < 10)
{
%hour = "0" @ %s.hour;
}
else
{
%hour = %s.hour;
}
}
// 12-Hour Clock
else if(%s.hour > 12)
{
%hour = (%s.hour - 12) @ "\c6:\c3";
}
else
{
%hour = %s.hour @ "\c6:\c3";
}
// Minute Fix-Up
if(%s.Min < 10 && $WRP::Clock::Type $= "game") { %min = "0" @ %s.Min; } else { %min = %s.Min; }
// Display
if(%type $= "tick")
{
return messageAll('',"\c3" @ %hour @ %min @ " \c6" @ %s.getAMPM());
}
else if(%type $= "color")
{
return "\c3" @ %hour @ %min @ " \c6" @ %s.getAMPM();
}
else
{
return %hour @ %min SPC %s.getAMPM();
}
}
function Tardis::MinTick(%s)
{
if(!$WRP::Booted)
return;
%s.CheckClock();
}
function Tardis::HourTick(%s)
{
if(!$WRP::Booted)
return;
// Save DB
EywaPopulation.savedata();
if(!$WRP::Clock::HourDisplay)
return;
%s.Display("tick");
// Weather/Day
DaySO.getDay();
if(%s.Hour == 2)
{
WeatherSO.getWeather();
}
}
function Tardis::DayTick(%s)
{
// Day Tick
if(%s.isHoliday())
messageAll('',"\c6Today is " @ %s.getHoliday());
}
function Tardis::MonthTick(%s)
{
if(!$WRP::Booted)
return;
// Month Tick
%MonthNum = %s.Month;
messageAll('',"\c6The month is now \c3" @ %s.MonthName[%MonthNum] @ "\c6, " @ %s.MonthDesc[%MonthNum]);
}
function Tardis::YearTick(%s)
{
if(!$WRP::Booted)
return;
// Year Tick
messageAll('',"\c6WOOHOO! Another year gone by! Welcome the new year \c3" @ %s.year @ "\c6!");
}
function Tardis::getSuffix(%s, %num)
{
// Double digit and if the tens place is 1
if(strlen(%num) > 1 && getSubStr(%num, (strlen(%num) - 2), 1) $= "1")
{
return "th";
}
else
{
switch(getSubStr(%num, (strlen(%num) - 1), 1))
{
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
}
function Tardis::getAMPM(%s)
{
// 24-Hour Clock
if($WRP::Clock::ArmyTime)
{
return;
}
else
// AM
if(%s.Hour < 12 && %s.Hour <= 24)
{
%s.AMPM = "AM";
}
// PM
else if(%s.Hour > 12 && %s.Hour <= 24)
{
%s.AMPM = "PM";
}
return %s.AMPM;
}
function Tardis::isHoliday(%s)
{
for(%a=0;%s.HolidayDate[%a] !$= "";%a++)
{
if(%s.HolidayDate[%a] $= %s.Month @ "-" @ %s.Day)
return 1;
}
}
function Tardis::getHoliday(%s,%view)
{
for(%a=0;%s.HolidayDate[%a] !$= "";%a++)
{
if(%s.HolidayDate[%a] $= %s.Month @ "-" @ %s.Day)
{
%HCount++;
if(%HCount > 1) { %divider = "|"; } else { %divider = ""; }
if(%view $= "NamesOnly")
{
%Holidays = "\c3" @ %s.HolidayName[%a] @ %divider @ %Holidays;
}
else
{
%Holidays = "\c3" @ %s.HolidayName[%a] @ "\c6, " @ %s.HolidayDesc[%a] @ %divider @ %Holidays;
}
}
}
return %Holidays;
}
};
WRPRegPackage(WRPClock);
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record.Aggregates
{
using System;
using NPOI.HSSF.Record;
using NPOI.SS.Util;
using NPOI.SS.Formula.PTG;
using NPOI.Util;
/// <summary>
/// The formula record aggregate is used to join toGether the formula record and it's
/// (optional) string record and (optional) Shared Formula Record (template Reads, excel optimization).
/// @author Glen Stampoultzis (glens at apache.org)
/// </summary>
[Serializable]
public class FormulaRecordAggregate: RecordAggregate, CellValueRecordInterface, IComparable, ICloneable
{
public const short sid = -2000;
private FormulaRecord _formulaRecord;
private SharedValueManager _sharedValueManager;
/** caches the calculated result of the formula */
private StringRecord _stringRecord;
[NonSerialized]
private SharedFormulaRecord _sharedFormulaRecord;
/// <summary>
/// Initializes a new instance of the <see cref="FormulaRecordAggregate"/> class.
/// </summary>
/// <param name="formulaRec">The formula rec.</param>
/// <param name="stringRec">The string rec.</param>
/// <param name="svm">The SVM.</param>
public FormulaRecordAggregate(FormulaRecord formulaRec, StringRecord stringRec, SharedValueManager svm)
{
if (svm == null)
{
throw new ArgumentException("sfm must not be null");
}
if (formulaRec.HasCachedResultString)
{
if (stringRec == null)
{
throw new RecordFormatException("Formula record flag is set but String record was not found");
}
_stringRecord = stringRec;
}
else
{
// Usually stringRec is null here (in agreement with what the formula rec says).
// In the case where an extra StringRecord is erroneously present, Excel (2007)
// ignores it (see bug 46213).
_stringRecord = null;
}
_formulaRecord = formulaRec;
_sharedValueManager = svm;
if (formulaRec.IsSharedFormula)
{
CellReference firstCell = formulaRec.Formula.ExpReference;
if (firstCell == null)
{
HandleMissingSharedFormulaRecord(formulaRec);
}
else
{
_sharedFormulaRecord = svm.LinkSharedFormulaRecord(firstCell, this);
}
}
}
/**
* Should be called by any code which is either deleting this formula cell, or changing
* its type. This method gives the aggregate a chance to unlink any shared formula
* that may be involved with this cell formula.
*/
public void NotifyFormulaChanging() {
if (_sharedFormulaRecord != null) {
_sharedValueManager.Unlink(_sharedFormulaRecord);
}
}
public bool IsPartOfArrayFormula
{
get
{
if (_sharedFormulaRecord != null)
{
return false;
}
CellReference expRef = _formulaRecord.Formula.ExpReference;
ArrayRecord arec = expRef == null ? null : _sharedValueManager.GetArrayRecord(expRef.Row, expRef.Col);
return arec != null;
}
}
/// <summary>
/// called by the class that is responsible for writing this sucker.
/// Subclasses should implement this so that their data is passed back in a
/// byte array.
/// </summary>
/// <param name="offset">offset to begin writing at</param>
/// <param name="data">byte array containing instance data.</param>
/// <returns>number of bytes written</returns>
public override int Serialize(int offset, byte [] data)
{
int pos = offset;
pos += _formulaRecord.Serialize(pos, data);
if (_stringRecord != null)
{
pos += _stringRecord.Serialize(pos, data);
}
return pos - offset;
}
/// <summary>
/// Visit each of the atomic BIFF records contained in this {@link RecordAggregate} in the order
/// that they should be written to file. Implementors may or may not return the actual
/// {@link Record}s being used to manage POI's internal implementation. Callers should not
/// assume either way, and therefore only attempt to modify those {@link Record}s after cloning
/// </summary>
/// <param name="rv"></param>
public override void VisitContainedRecords(RecordVisitor rv)
{
rv.VisitRecord(_formulaRecord);
Record sharedFormulaRecord = _sharedValueManager.GetRecordForFirstCell(this);
if (sharedFormulaRecord != null)
{
rv.VisitRecord(sharedFormulaRecord);
}
if (_formulaRecord.HasCachedResultString && _stringRecord != null)
{
rv.VisitRecord(_stringRecord);
}
}
/// <summary>
/// Get the current Serialized size of the record. Should include the sid and recLength (4 bytes).
/// </summary>
/// <value>The size of the record.</value>
public override int RecordSize
{
get
{
int size = _formulaRecord.RecordSize + (_stringRecord == null ? 0 : _stringRecord.RecordSize);
return size;
}
}
/// <summary>
/// return the non static version of the id for this record.
/// </summary>
/// <value>The sid.</value>
public override short Sid
{
get
{
return sid;
}
}
/// <summary>
/// Sometimes the shared formula flag "seems" to be erroneously set (because the corresponding
/// SharedFormulaRecord does not exist). Normally this would leave no way of determining
/// the Ptg tokens for the formula. However as it turns out in these
/// cases, Excel encodes the unshared Ptg tokens in the right place (inside the FormulaRecord).
/// So the the only thing that needs to be done is to ignore the erroneous
/// shared formula flag.
///
/// This method may also be used for setting breakpoints to help diagnose issues regarding the
/// abnormally-set 'shared formula' flags.
/// </summary>
/// <param name="formula">The formula.</param>
private static void HandleMissingSharedFormulaRecord(FormulaRecord formula)
{
// make sure 'unshared' formula is actually available
Ptg firstToken = formula.ParsedExpression[0];
if (firstToken is ExpPtg)
{
throw new RecordFormatException(
"SharedFormulaRecord not found for FormulaRecord with (isSharedFormula=true)");
}
// could log an info message here since this is a fairly unusual occurrence.
formula.IsSharedFormula = false; // no point leaving the flag erroneously set
}
/// <summary>
/// Gets or sets the formula record.
/// </summary>
/// <value>The formula record.</value>
public FormulaRecord FormulaRecord
{
get
{
return _formulaRecord;
}
set { this._formulaRecord = value; }
}
/// <summary>
/// Gets or sets the string record.
/// </summary>
/// <value>The string record.</value>
public StringRecord StringRecord
{
get
{
return _stringRecord;
}
set { this._stringRecord = value; }
}
public short XFIndex
{
get{return _formulaRecord.XFIndex;}
set{_formulaRecord.XFIndex=value;}
}
public int Column
{
get{return _formulaRecord.Column;}
set{_formulaRecord.Column=value;}
}
public int Row
{
get { return _formulaRecord.Row; }
set { _formulaRecord.Row=value; }
}
public int CompareTo(Object o)
{
return _formulaRecord.CompareTo(o);
}
///// <summary>
///// returns whether this cell represents the same cell (NOT VALUE)
///// </summary>
///// <param name="i"> record to Compare</param>
///// <returns>true if the cells are the same cell (positionally), false if not.</returns>
//public bool IsEqual(CellValueRecordInterface i)
//{
// return _formulaRecord.IsEqual(i);
//}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(Object obj)
{
return _formulaRecord.Equals(obj);
}
public override int GetHashCode ()
{
return _formulaRecord.GetHashCode ();
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override String ToString()
{
return _formulaRecord.ToString();
}
/// <summary>
/// Gets the string value.
/// </summary>
/// <value>The string value.</value>
public String StringValue
{
get
{
if (_stringRecord == null) return null;
return _stringRecord.String;
}
}
public void SetCachedDoubleResult(double value)
{
_stringRecord = null;
_formulaRecord.Value = value;
}
/// <summary>
/// Sets the cached string result.
/// </summary>
/// <param name="value">The value.</param>
public void SetCachedStringResult(String value)
{
// Save the string into a String Record, creating one if required
if (_stringRecord == null)
{
_stringRecord = new StringRecord();
}
_stringRecord.String=(value);
if (value.Length < 1)
{
_formulaRecord.SetCachedResultTypeEmptyString();
}
else
{
_formulaRecord.SetCachedResultTypeString();
}
}
/// <summary>
/// Sets the cached boolean result.
/// </summary>
/// <param name="value">if set to <c>true</c> [value].</param>
public void SetCachedBooleanResult(bool value)
{
_stringRecord = null;
_formulaRecord.SetCachedResultBoolean(value);
}
/// <summary>
/// Sets the cached error result.
/// </summary>
/// <param name="errorCode">The error code.</param>
public void SetCachedErrorResult(int errorCode)
{
_stringRecord = null;
_formulaRecord.SetCachedResultErrorCode(errorCode);
}
#region ICloneable Members
public object Clone()
{
return this;
}
#endregion
public Ptg[] FormulaTokens
{
get
{
if (_sharedFormulaRecord != null)
{
return _sharedFormulaRecord.GetFormulaTokens(_formulaRecord);
}
CellReference expRef = _formulaRecord.Formula.ExpReference;
if (expRef != null)
{
ArrayRecord arec = _sharedValueManager.GetArrayRecord(expRef.Row, expRef.Col);
return arec.FormulaTokens;
}
return _formulaRecord.ParsedExpression;
}
}
/**
* Also checks for a related shared formula and unlinks it if found
*/
public void SetParsedExpression(Ptg[] ptgs)
{
NotifyFormulaChanging();
_formulaRecord.ParsedExpression=(ptgs);
}
public void UnlinkSharedFormula()
{
SharedFormulaRecord sfr = _sharedFormulaRecord;
if (sfr == null)
{
throw new InvalidOperationException("Formula not linked to shared formula");
}
Ptg[] ptgs = sfr.GetFormulaTokens(_formulaRecord);
_formulaRecord.SetParsedExpression(ptgs);
//Now its not shared!
_formulaRecord.SetSharedFormula(false);
_sharedFormulaRecord = null;
}
public CellRangeAddress GetArrayFormulaRange()
{
if (_sharedFormulaRecord != null)
{
throw new InvalidOperationException("not an array formula cell.");
}
CellReference expRef = _formulaRecord.Formula.ExpReference;
if (expRef == null)
{
throw new InvalidOperationException("not an array formula cell.");
}
ArrayRecord arec = _sharedValueManager.GetArrayRecord(expRef.Row, expRef.Col);
if (arec == null)
{
throw new InvalidOperationException("ArrayRecord was not found for the locator " + expRef.FormatAsString());
}
CellRangeAddress8Bit a = arec.Range;
return new CellRangeAddress(a.FirstRow, a.LastRow, a.FirstColumn, a.LastColumn);
}
public void SetArrayFormula(CellRangeAddress r, Ptg[] ptgs)
{
ArrayRecord arr = new ArrayRecord(NPOI.SS.Formula.Formula.Create(ptgs), new CellRangeAddress8Bit(r.FirstRow, r.LastRow, r.FirstColumn, r.LastColumn));
_sharedValueManager.AddArrayRecord(arr);
}
/**
* Removes an array formula
* @return the range of the array formula containing the specified cell. Never <code>null</code>
*/
public CellRangeAddress RemoveArrayFormula(int rowIndex, int columnIndex)
{
CellRangeAddress8Bit a = _sharedValueManager.RemoveArrayFormula(rowIndex, columnIndex);
// at this point FormulaRecordAggregate#isPartOfArrayFormula() should return false
_formulaRecord.ParsedExpression = (null);
return new CellRangeAddress(a.FirstRow, a.LastRow, a.FirstColumn, a.LastColumn);
}
}
}
| |
/*
Copyright 2006 - 2010 Intel 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.Xml;
using System.Text;
using OpenSource.UPnP.AV;
using System.Collections;
using System.Runtime.Serialization;
namespace OpenSource.UPnP.AV.CdsMetadata
{
/// <summary>
/// <para>
/// Maps to the CDS/UPNP-AV "upnp:searchClass" element, which
/// describes the types of media that can be returned in a
/// Search request from the container. Search class is always a per container,
/// and no parent-child relationship is assumed.
/// </para>
///
/// <para>
/// This class maps to the "upnp:searchClass" element in
/// the ContentDirectory content hierarchy XML schema.
/// </para>
/// </summary>
[Serializable()]
public class SearchClass : MediaClass
{
/// <summary>
/// Generates a hashcode using the hashcodes of the fields multiplied by prime numbers,
/// then summed together.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return
base.GetHashCode() +
(this.m_IncludeDerived.GetHashCode() * 7);
}
/// <summary>
/// Returns true if the other SearchClass has the same value and attribute values.
/// </summary>
/// <param name="cdsElement">a SearchClass instance; derived classes don't count</param>
/// <returns></returns>
public override bool Equals (object cdsElement)
{
SearchClass other = (SearchClass) cdsElement;
if (this.GetType() == other.GetType())
{
if (this.m_ClassName.Equals(other.m_ClassName))
{
if (this.m_DerivedFrom.Equals(other.m_DerivedFrom))
{
if (this.m_FriendlyName.Equals(other.m_FriendlyName))
{
if (this.m_IncludeDerived.Equals(other.m_IncludeDerived))
{
return true;
}
}
}
}
}
return false;
}
public new static IList GetPossibleAttributes()
{
string[] attributes = {T[_ATTRIB.name], T[_ATTRIB.includeDerived]};
return attributes;
}
public override IList PossibleAttributes
{
get
{
return GetPossibleAttributes();
}
}
public override IList ValidAttributes
{
get
{
ArrayList al = new ArrayList(2);
if (this.m_FriendlyName != "")
{
al.Add(T[_ATTRIB.name]);
}
al.Add(T[_ATTRIB.includeDerived]);
return al;
}
}
/// <summary>
/// Instructs the "xmlWriter" argument to start the "upnp:searchClass" element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
/// <exception cref="InvalidCastException">
/// Thrown when the "data" argument is not a <see cref="ToXmlData"/> object.
/// </exception>
public override void StartElement(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
ToXmlData _d = (ToXmlData) data;
xmlWriter.WriteStartElement(Tags.PropertyAttributes.upnp_searchClass);
if (this.m_AttributeNames == null)
{
this.PrintFriendlyName(_d.DesiredProperties, xmlWriter);
this.PrintIncludeDerived(_d.DesiredProperties, xmlWriter);
}
else
{
foreach (string attribName in this.m_AttributeNames)
{
if (string.Compare(attribName, T[_ATTRIB.name]) == 0)
{
this.PrintFriendlyName(_d.DesiredProperties, xmlWriter);
}
else if (string.Compare(attribName, T[_ATTRIB.includeDerived]) == 0)
{
this.PrintIncludeDerived(_d.DesiredProperties, xmlWriter);
}
}
}
}
private void PrintFriendlyName(ArrayList desiredProperties, XmlTextWriter xmlWriter)
{
if (desiredProperties != null)
{
if ((desiredProperties.Count == 0) || (desiredProperties.Contains(Tags.PropertyAttributes.upnp_searchClassName)))
{
string val = this.FriendlyName;
if ((val != null) && (val != ""))
{
xmlWriter.WriteAttributeString(T[_ATTRIB.name], this.FriendlyName);
}
}
}
}
private void PrintIncludeDerived(ArrayList desiredProperties, XmlTextWriter xmlWriter)
{
if (desiredProperties != null)
{
if ((desiredProperties.Count == 0) || (desiredProperties.Contains(Tags.PropertyAttributes.upnp_searchClassIncludeDerived)))
{
string val = this.IncludeDerived.ToString();
val = val.ToLower();
xmlWriter.WriteAttributeString(T[_ATTRIB.includeDerived], val);
}
}
}
/// <summary>
/// Creates a search class given the class name,
/// base class, optional friendly name, and an indication
/// if objects derived from this specified media class
/// are included when searching for the specified media class.
/// </summary>
/// <param name="className">class name (substring after the last dot "." character in full class name)</param>
/// <param name="derivedFrom">base class (substring before the last dot "." character in full class name)</param>
/// <param name="friendly">optional friendly name</param>
/// <param name="includeDerived">indication if a search request on the container for a particular type includes all derived types</param>
public SearchClass(string className, string derivedFrom, string friendly, bool includeDerived)
: base (className, derivedFrom, friendly)
{
this.m_IncludeDerived = includeDerived;
}
/// <summary>
/// Creates a search class given the full class name,
/// optional friendly name, and an indication
/// if objects derived from this specified media class
/// should be flagged
/// </summary>
/// <param name="fullName">full class name, in "[baseClass].[class name]" format</param>
/// <param name="friendly">optional friendly name</param>
/// <param name="includeDerived">indication if a search request on the container for a particular type includes all derived types</param>
public SearchClass (string fullName, string friendly, bool includeDerived)
: base (fullName, friendly)
{
this.m_IncludeDerived = includeDerived;
}
/// <summary>
/// The element.Name should be upnp:searchClass
/// </summary>
/// <param name="element"></param>
public SearchClass (XmlElement element)
: base (element)
{
XmlAttribute attrib = element.Attributes[T[_ATTRIB.includeDerived]];
this.m_IncludeDerived = MediaObject.IsAttributeValueTrue(attrib, false);
}
/// <summary>
/// Extracts the value of an attribute.
/// Attribute list: name
/// </summary>
/// <param name="attribute">attribute name</param>
/// <returns>returns a comparable value</returns>
public override IComparable ExtractAttribute(string attribute)
{
if (attribute == T[_ATTRIB.name])
{
return this.m_FriendlyName;
}
else if (attribute == T[_ATTRIB.includeDerived])
{
return this.m_IncludeDerived;
}
return null;
}
/// <summary>
/// Indicates that the specfied search class is applicable for all derived classes.
/// </summary>
public bool IncludeDerived
{
get
{
return this.m_IncludeDerived;
}
}
/// <summary>
/// The value for the IncludeDerived property.
/// The variable was at one point internally accessible.
/// </summary>
private readonly bool m_IncludeDerived;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
public struct ValX0 { }
public struct ValY0 { }
public struct ValX1<T> { }
public struct ValY1<T> { }
public struct ValX2<T, U> { }
public struct ValY2<T, U> { }
public struct ValX3<T, U, V> { }
public struct ValY3<T, U, V> { }
public class RefX0 { }
public class RefY0 { }
public class RefX1<T> { }
public class RefY1<T> { }
public class RefX2<T, U> { }
public class RefY2<T, U> { }
public class RefX3<T, U, V> { }
public class RefY3<T, U, V> { }
public interface IGen<T>
{
void _Init(T fld1);
bool InstVerify(System.Type t1);
}
public interface IGenSubInt : IGen<int> { }
public interface IGenSubDouble : IGen<double> { }
public interface IGenSubString : IGen<string> { }
public interface IGenSubObject : IGen<object> { }
public interface IGenSubGuid : IGen<Guid> { }
public interface IGenSubConstructedReference : IGen<RefX1<int>> { }
public interface IGenSubConstructedValue : IGen<ValX1<string>> { }
public interface IGenSub1DIntArray : IGen<int[]> { }
public interface IGenSub2DStringArray : IGen<string[,]> { }
public interface IGenSubJaggedObjectArray : IGen<object[][]> { }
public class GenInt : IGenSubInt
{
int Fld1;
public void _Init(int fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<int>));
}
return result;
}
}
public class GenDouble : IGenSubDouble
{
double Fld1;
public void _Init(double fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<double>));
}
return result;
}
}
public class GenString : IGenSubString
{
string Fld1;
public void _Init(string fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<string>));
}
return result;
}
}
public class GenObject : IGenSubObject
{
object Fld1;
public void _Init(object fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<object>));
}
return result;
}
}
public class GenGuid : IGenSubGuid
{
Guid Fld1;
public void _Init(Guid fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<Guid>));
}
return result;
}
}
public class GenConstructedReference : IGenSubConstructedReference
{
RefX1<int> Fld1;
public void _Init(RefX1<int> fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<RefX1<int>>));
}
return result;
}
}
public class GenConstructedValue : IGenSubConstructedValue
{
ValX1<string> Fld1;
public void _Init(ValX1<string> fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<ValX1<string>>));
}
return result;
}
}
public class Gen1DIntArray : IGenSub1DIntArray
{
int[] Fld1;
public void _Init(int[] fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<int[]>));
}
return result;
}
}
public class Gen2DStringArray : IGenSub2DStringArray
{
string[,] Fld1;
public void _Init(string[,] fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<string[,]>));
}
return result;
}
}
public class GenJaggedObjectArray : IGenSubJaggedObjectArray
{
object[][] Fld1;
public void _Init(object[][] fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<object[][]>));
}
return result;
}
}
public class Test
{
public static int counter = 0;
public static bool result = true;
public static void Eval(bool exp)
{
counter++;
if (!exp)
{
result = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
}
public static int Main()
{
IGen<int> IGenInt = new GenInt();
IGenInt._Init(new int());
Eval(IGenInt.InstVerify(typeof(int)));
IGen<double> IGenDouble = new GenDouble();
IGenDouble._Init(new double());
Eval(IGenDouble.InstVerify(typeof(double)));
IGen<string> IGenString = new GenString();
IGenString._Init("string");
Eval(IGenString.InstVerify(typeof(string)));
IGen<object> IGenObject = new GenObject();
IGenObject._Init(new object());
Eval(IGenObject.InstVerify(typeof(object)));
IGen<Guid> IGenGuid = new GenGuid();
IGenGuid._Init(new Guid());
Eval(IGenGuid.InstVerify(typeof(Guid)));
IGen<RefX1<int>> IGenConstructedReference = new GenConstructedReference();
IGenConstructedReference._Init(new RefX1<int>());
Eval(IGenConstructedReference.InstVerify(typeof(RefX1<int>)));
IGen<ValX1<string>> IGenConstructedValue = new GenConstructedValue();
IGenConstructedValue._Init(new ValX1<string>());
Eval(IGenConstructedValue.InstVerify(typeof(ValX1<string>)));
IGen<int[]> IGen1DIntArray = new Gen1DIntArray();
IGen1DIntArray._Init(new int[1]);
Eval(IGen1DIntArray.InstVerify(typeof(int[])));
IGen<string[,]> IGen2DStringArray = new Gen2DStringArray();
IGen2DStringArray._Init(new string[1, 1]);
Eval(IGen2DStringArray.InstVerify(typeof(string[,])));
IGen<object[][]> IGenJaggedObjectArray = new GenJaggedObjectArray();
IGenJaggedObjectArray._Init(new object[1][]);
Eval(IGenJaggedObjectArray.InstVerify(typeof(object[][])));
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// A type of virtual GPU
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
public partial class VGPU_type : XenObject<VGPU_type>
{
public VGPU_type()
{
}
public VGPU_type(string uuid,
string vendor_name,
string model_name,
long framebuffer_size,
long max_heads,
long max_resolution_x,
long max_resolution_y,
List<XenRef<PGPU>> supported_on_PGPUs,
List<XenRef<PGPU>> enabled_on_PGPUs,
List<XenRef<VGPU>> VGPUs,
List<XenRef<GPU_group>> supported_on_GPU_groups,
List<XenRef<GPU_group>> enabled_on_GPU_groups,
vgpu_type_implementation implementation,
string identifier,
bool experimental)
{
this.uuid = uuid;
this.vendor_name = vendor_name;
this.model_name = model_name;
this.framebuffer_size = framebuffer_size;
this.max_heads = max_heads;
this.max_resolution_x = max_resolution_x;
this.max_resolution_y = max_resolution_y;
this.supported_on_PGPUs = supported_on_PGPUs;
this.enabled_on_PGPUs = enabled_on_PGPUs;
this.VGPUs = VGPUs;
this.supported_on_GPU_groups = supported_on_GPU_groups;
this.enabled_on_GPU_groups = enabled_on_GPU_groups;
this.implementation = implementation;
this.identifier = identifier;
this.experimental = experimental;
}
/// <summary>
/// Creates a new VGPU_type from a Proxy_VGPU_type.
/// </summary>
/// <param name="proxy"></param>
public VGPU_type(Proxy_VGPU_type proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(VGPU_type update)
{
uuid = update.uuid;
vendor_name = update.vendor_name;
model_name = update.model_name;
framebuffer_size = update.framebuffer_size;
max_heads = update.max_heads;
max_resolution_x = update.max_resolution_x;
max_resolution_y = update.max_resolution_y;
supported_on_PGPUs = update.supported_on_PGPUs;
enabled_on_PGPUs = update.enabled_on_PGPUs;
VGPUs = update.VGPUs;
supported_on_GPU_groups = update.supported_on_GPU_groups;
enabled_on_GPU_groups = update.enabled_on_GPU_groups;
implementation = update.implementation;
identifier = update.identifier;
experimental = update.experimental;
}
internal void UpdateFromProxy(Proxy_VGPU_type proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
vendor_name = proxy.vendor_name == null ? null : (string)proxy.vendor_name;
model_name = proxy.model_name == null ? null : (string)proxy.model_name;
framebuffer_size = proxy.framebuffer_size == null ? 0 : long.Parse((string)proxy.framebuffer_size);
max_heads = proxy.max_heads == null ? 0 : long.Parse((string)proxy.max_heads);
max_resolution_x = proxy.max_resolution_x == null ? 0 : long.Parse((string)proxy.max_resolution_x);
max_resolution_y = proxy.max_resolution_y == null ? 0 : long.Parse((string)proxy.max_resolution_y);
supported_on_PGPUs = proxy.supported_on_PGPUs == null ? null : XenRef<PGPU>.Create(proxy.supported_on_PGPUs);
enabled_on_PGPUs = proxy.enabled_on_PGPUs == null ? null : XenRef<PGPU>.Create(proxy.enabled_on_PGPUs);
VGPUs = proxy.VGPUs == null ? null : XenRef<VGPU>.Create(proxy.VGPUs);
supported_on_GPU_groups = proxy.supported_on_GPU_groups == null ? null : XenRef<GPU_group>.Create(proxy.supported_on_GPU_groups);
enabled_on_GPU_groups = proxy.enabled_on_GPU_groups == null ? null : XenRef<GPU_group>.Create(proxy.enabled_on_GPU_groups);
implementation = proxy.implementation == null ? (vgpu_type_implementation) 0 : (vgpu_type_implementation)Helper.EnumParseDefault(typeof(vgpu_type_implementation), (string)proxy.implementation);
identifier = proxy.identifier == null ? null : (string)proxy.identifier;
experimental = (bool)proxy.experimental;
}
public Proxy_VGPU_type ToProxy()
{
Proxy_VGPU_type result_ = new Proxy_VGPU_type();
result_.uuid = (uuid != null) ? uuid : "";
result_.vendor_name = (vendor_name != null) ? vendor_name : "";
result_.model_name = (model_name != null) ? model_name : "";
result_.framebuffer_size = framebuffer_size.ToString();
result_.max_heads = max_heads.ToString();
result_.max_resolution_x = max_resolution_x.ToString();
result_.max_resolution_y = max_resolution_y.ToString();
result_.supported_on_PGPUs = (supported_on_PGPUs != null) ? Helper.RefListToStringArray(supported_on_PGPUs) : new string[] {};
result_.enabled_on_PGPUs = (enabled_on_PGPUs != null) ? Helper.RefListToStringArray(enabled_on_PGPUs) : new string[] {};
result_.VGPUs = (VGPUs != null) ? Helper.RefListToStringArray(VGPUs) : new string[] {};
result_.supported_on_GPU_groups = (supported_on_GPU_groups != null) ? Helper.RefListToStringArray(supported_on_GPU_groups) : new string[] {};
result_.enabled_on_GPU_groups = (enabled_on_GPU_groups != null) ? Helper.RefListToStringArray(enabled_on_GPU_groups) : new string[] {};
result_.implementation = vgpu_type_implementation_helper.ToString(implementation);
result_.identifier = (identifier != null) ? identifier : "";
result_.experimental = experimental;
return result_;
}
/// <summary>
/// Creates a new VGPU_type from a Hashtable.
/// </summary>
/// <param name="table"></param>
public VGPU_type(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
vendor_name = Marshalling.ParseString(table, "vendor_name");
model_name = Marshalling.ParseString(table, "model_name");
framebuffer_size = Marshalling.ParseLong(table, "framebuffer_size");
max_heads = Marshalling.ParseLong(table, "max_heads");
max_resolution_x = Marshalling.ParseLong(table, "max_resolution_x");
max_resolution_y = Marshalling.ParseLong(table, "max_resolution_y");
supported_on_PGPUs = Marshalling.ParseSetRef<PGPU>(table, "supported_on_PGPUs");
enabled_on_PGPUs = Marshalling.ParseSetRef<PGPU>(table, "enabled_on_PGPUs");
VGPUs = Marshalling.ParseSetRef<VGPU>(table, "VGPUs");
supported_on_GPU_groups = Marshalling.ParseSetRef<GPU_group>(table, "supported_on_GPU_groups");
enabled_on_GPU_groups = Marshalling.ParseSetRef<GPU_group>(table, "enabled_on_GPU_groups");
implementation = (vgpu_type_implementation)Helper.EnumParseDefault(typeof(vgpu_type_implementation), Marshalling.ParseString(table, "implementation"));
identifier = Marshalling.ParseString(table, "identifier");
experimental = Marshalling.ParseBool(table, "experimental");
}
public bool DeepEquals(VGPU_type other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._vendor_name, other._vendor_name) &&
Helper.AreEqual2(this._model_name, other._model_name) &&
Helper.AreEqual2(this._framebuffer_size, other._framebuffer_size) &&
Helper.AreEqual2(this._max_heads, other._max_heads) &&
Helper.AreEqual2(this._max_resolution_x, other._max_resolution_x) &&
Helper.AreEqual2(this._max_resolution_y, other._max_resolution_y) &&
Helper.AreEqual2(this._supported_on_PGPUs, other._supported_on_PGPUs) &&
Helper.AreEqual2(this._enabled_on_PGPUs, other._enabled_on_PGPUs) &&
Helper.AreEqual2(this._VGPUs, other._VGPUs) &&
Helper.AreEqual2(this._supported_on_GPU_groups, other._supported_on_GPU_groups) &&
Helper.AreEqual2(this._enabled_on_GPU_groups, other._enabled_on_GPU_groups) &&
Helper.AreEqual2(this._implementation, other._implementation) &&
Helper.AreEqual2(this._identifier, other._identifier) &&
Helper.AreEqual2(this._experimental, other._experimental);
}
public override string SaveChanges(Session session, string opaqueRef, VGPU_type server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static VGPU_type get_record(Session session, string _vgpu_type)
{
return new VGPU_type((Proxy_VGPU_type)session.proxy.vgpu_type_get_record(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse());
}
/// <summary>
/// Get a reference to the VGPU_type instance with the specified UUID.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VGPU_type> get_by_uuid(Session session, string _uuid)
{
return XenRef<VGPU_type>.Create(session.proxy.vgpu_type_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Get the uuid field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_uuid(Session session, string _vgpu_type)
{
return (string)session.proxy.vgpu_type_get_uuid(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse();
}
/// <summary>
/// Get the vendor_name field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_vendor_name(Session session, string _vgpu_type)
{
return (string)session.proxy.vgpu_type_get_vendor_name(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse();
}
/// <summary>
/// Get the model_name field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_model_name(Session session, string _vgpu_type)
{
return (string)session.proxy.vgpu_type_get_model_name(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse();
}
/// <summary>
/// Get the framebuffer_size field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_framebuffer_size(Session session, string _vgpu_type)
{
return long.Parse((string)session.proxy.vgpu_type_get_framebuffer_size(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse());
}
/// <summary>
/// Get the max_heads field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_max_heads(Session session, string _vgpu_type)
{
return long.Parse((string)session.proxy.vgpu_type_get_max_heads(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse());
}
/// <summary>
/// Get the max_resolution_x field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_max_resolution_x(Session session, string _vgpu_type)
{
return long.Parse((string)session.proxy.vgpu_type_get_max_resolution_x(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse());
}
/// <summary>
/// Get the max_resolution_y field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_max_resolution_y(Session session, string _vgpu_type)
{
return long.Parse((string)session.proxy.vgpu_type_get_max_resolution_y(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse());
}
/// <summary>
/// Get the supported_on_PGPUs field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<PGPU>> get_supported_on_PGPUs(Session session, string _vgpu_type)
{
return XenRef<PGPU>.Create(session.proxy.vgpu_type_get_supported_on_pgpus(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse());
}
/// <summary>
/// Get the enabled_on_PGPUs field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<PGPU>> get_enabled_on_PGPUs(Session session, string _vgpu_type)
{
return XenRef<PGPU>.Create(session.proxy.vgpu_type_get_enabled_on_pgpus(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse());
}
/// <summary>
/// Get the VGPUs field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<VGPU>> get_VGPUs(Session session, string _vgpu_type)
{
return XenRef<VGPU>.Create(session.proxy.vgpu_type_get_vgpus(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse());
}
/// <summary>
/// Get the supported_on_GPU_groups field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<GPU_group>> get_supported_on_GPU_groups(Session session, string _vgpu_type)
{
return XenRef<GPU_group>.Create(session.proxy.vgpu_type_get_supported_on_gpu_groups(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse());
}
/// <summary>
/// Get the enabled_on_GPU_groups field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<GPU_group>> get_enabled_on_GPU_groups(Session session, string _vgpu_type)
{
return XenRef<GPU_group>.Create(session.proxy.vgpu_type_get_enabled_on_gpu_groups(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse());
}
/// <summary>
/// Get the implementation field of the given VGPU_type.
/// First published in XenServer Dundee.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static vgpu_type_implementation get_implementation(Session session, string _vgpu_type)
{
return (vgpu_type_implementation)Helper.EnumParseDefault(typeof(vgpu_type_implementation), (string)session.proxy.vgpu_type_get_implementation(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse());
}
/// <summary>
/// Get the identifier field of the given VGPU_type.
/// First published in XenServer Dundee.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_identifier(Session session, string _vgpu_type)
{
return (string)session.proxy.vgpu_type_get_identifier(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse();
}
/// <summary>
/// Get the experimental field of the given VGPU_type.
/// First published in XenServer Dundee.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static bool get_experimental(Session session, string _vgpu_type)
{
return (bool)session.proxy.vgpu_type_get_experimental(session.uuid, (_vgpu_type != null) ? _vgpu_type : "").parse();
}
/// <summary>
/// Return a list of all the VGPU_types known to the system.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VGPU_type>> get_all(Session session)
{
return XenRef<VGPU_type>.Create(session.proxy.vgpu_type_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the VGPU_type Records at once, in a single XML RPC call
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VGPU_type>, VGPU_type> get_all_records(Session session)
{
return XenRef<VGPU_type>.Create<Proxy_VGPU_type>(session.proxy.vgpu_type_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// Name of VGPU vendor
/// </summary>
public virtual string vendor_name
{
get { return _vendor_name; }
set
{
if (!Helper.AreEqual(value, _vendor_name))
{
_vendor_name = value;
Changed = true;
NotifyPropertyChanged("vendor_name");
}
}
}
private string _vendor_name;
/// <summary>
/// Model name associated with the VGPU type
/// </summary>
public virtual string model_name
{
get { return _model_name; }
set
{
if (!Helper.AreEqual(value, _model_name))
{
_model_name = value;
Changed = true;
NotifyPropertyChanged("model_name");
}
}
}
private string _model_name;
/// <summary>
/// Framebuffer size of the VGPU type, in bytes
/// </summary>
public virtual long framebuffer_size
{
get { return _framebuffer_size; }
set
{
if (!Helper.AreEqual(value, _framebuffer_size))
{
_framebuffer_size = value;
Changed = true;
NotifyPropertyChanged("framebuffer_size");
}
}
}
private long _framebuffer_size;
/// <summary>
/// Maximum number of displays supported by the VGPU type
/// </summary>
public virtual long max_heads
{
get { return _max_heads; }
set
{
if (!Helper.AreEqual(value, _max_heads))
{
_max_heads = value;
Changed = true;
NotifyPropertyChanged("max_heads");
}
}
}
private long _max_heads;
/// <summary>
/// Maximum resolution (width) supported by the VGPU type
/// First published in XenServer 6.2 SP1.
/// </summary>
public virtual long max_resolution_x
{
get { return _max_resolution_x; }
set
{
if (!Helper.AreEqual(value, _max_resolution_x))
{
_max_resolution_x = value;
Changed = true;
NotifyPropertyChanged("max_resolution_x");
}
}
}
private long _max_resolution_x;
/// <summary>
/// Maximum resolution (height) supported by the VGPU type
/// First published in XenServer 6.2 SP1.
/// </summary>
public virtual long max_resolution_y
{
get { return _max_resolution_y; }
set
{
if (!Helper.AreEqual(value, _max_resolution_y))
{
_max_resolution_y = value;
Changed = true;
NotifyPropertyChanged("max_resolution_y");
}
}
}
private long _max_resolution_y;
/// <summary>
/// List of PGPUs that support this VGPU type
/// </summary>
public virtual List<XenRef<PGPU>> supported_on_PGPUs
{
get { return _supported_on_PGPUs; }
set
{
if (!Helper.AreEqual(value, _supported_on_PGPUs))
{
_supported_on_PGPUs = value;
Changed = true;
NotifyPropertyChanged("supported_on_PGPUs");
}
}
}
private List<XenRef<PGPU>> _supported_on_PGPUs;
/// <summary>
/// List of PGPUs that have this VGPU type enabled
/// </summary>
public virtual List<XenRef<PGPU>> enabled_on_PGPUs
{
get { return _enabled_on_PGPUs; }
set
{
if (!Helper.AreEqual(value, _enabled_on_PGPUs))
{
_enabled_on_PGPUs = value;
Changed = true;
NotifyPropertyChanged("enabled_on_PGPUs");
}
}
}
private List<XenRef<PGPU>> _enabled_on_PGPUs;
/// <summary>
/// List of VGPUs of this type
/// </summary>
public virtual List<XenRef<VGPU>> VGPUs
{
get { return _VGPUs; }
set
{
if (!Helper.AreEqual(value, _VGPUs))
{
_VGPUs = value;
Changed = true;
NotifyPropertyChanged("VGPUs");
}
}
}
private List<XenRef<VGPU>> _VGPUs;
/// <summary>
/// List of GPU groups in which at least one PGPU supports this VGPU type
/// First published in XenServer 6.2 SP1.
/// </summary>
public virtual List<XenRef<GPU_group>> supported_on_GPU_groups
{
get { return _supported_on_GPU_groups; }
set
{
if (!Helper.AreEqual(value, _supported_on_GPU_groups))
{
_supported_on_GPU_groups = value;
Changed = true;
NotifyPropertyChanged("supported_on_GPU_groups");
}
}
}
private List<XenRef<GPU_group>> _supported_on_GPU_groups;
/// <summary>
/// List of GPU groups in which at least one have this VGPU type enabled
/// First published in XenServer 6.2 SP1.
/// </summary>
public virtual List<XenRef<GPU_group>> enabled_on_GPU_groups
{
get { return _enabled_on_GPU_groups; }
set
{
if (!Helper.AreEqual(value, _enabled_on_GPU_groups))
{
_enabled_on_GPU_groups = value;
Changed = true;
NotifyPropertyChanged("enabled_on_GPU_groups");
}
}
}
private List<XenRef<GPU_group>> _enabled_on_GPU_groups;
/// <summary>
/// The internal implementation of this VGPU type
/// First published in XenServer Dundee.
/// </summary>
public virtual vgpu_type_implementation implementation
{
get { return _implementation; }
set
{
if (!Helper.AreEqual(value, _implementation))
{
_implementation = value;
Changed = true;
NotifyPropertyChanged("implementation");
}
}
}
private vgpu_type_implementation _implementation;
/// <summary>
/// Key used to identify VGPU types and avoid creating duplicates - this field is used internally and not intended for interpretation by API clients
/// First published in XenServer Dundee.
/// </summary>
public virtual string identifier
{
get { return _identifier; }
set
{
if (!Helper.AreEqual(value, _identifier))
{
_identifier = value;
Changed = true;
NotifyPropertyChanged("identifier");
}
}
}
private string _identifier;
/// <summary>
/// Indicates whether VGPUs of this type should be considered experimental
/// First published in XenServer Dundee.
/// </summary>
public virtual bool experimental
{
get { return _experimental; }
set
{
if (!Helper.AreEqual(value, _experimental))
{
_experimental = value;
Changed = true;
NotifyPropertyChanged("experimental");
}
}
}
private bool _experimental;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Threading
{
using System;
using System.Security;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using Microsoft.Win32.SafeHandles;
[System.Runtime.InteropServices.ComVisible(true)]
public delegate void TimerCallback(Object state);
//
// TimerQueue maintains a list of active timers in this AppDomain. We use a single native timer, supplied by the VM,
// to schedule all managed timers in the AppDomain.
//
// Perf assumptions: We assume that timers are created and destroyed frequently, but rarely actually fire.
// There are roughly two types of timer:
//
// - timeouts for operations. These are created and destroyed very frequently, but almost never fire, because
// the whole point is that the timer only fires if something has gone wrong.
//
// - scheduled background tasks. These typically do fire, but they usually have quite long durations.
// So the impact of spending a few extra cycles to fire these is negligible.
//
// Because of this, we want to choose a data structure with very fast insert and delete times, but we can live
// with linear traversal times when firing timers.
//
// The data structure we've chosen is an unordered doubly-linked list of active timers. This gives O(1) insertion
// and removal, and O(N) traversal when finding expired timers.
//
// Note that all instance methods of this class require that the caller hold a lock on TimerQueue.Instance.
//
class TimerQueue
{
#region singleton pattern implementation
// The one-and-only TimerQueue for the AppDomain.
static TimerQueue s_queue = new TimerQueue();
public static TimerQueue Instance
{
get { return s_queue; }
}
private TimerQueue()
{
// empty private constructor to ensure we remain a singleton.
}
#endregion
#region interface to native per-AppDomain timer
//
// We need to keep our notion of time synchronized with the calls to SleepEx that drive
// the underlying native timer. In Win8, SleepEx does not count the time the machine spends
// sleeping/hibernating. Environment.TickCount (GetTickCount) *does* count that time,
// so we will get out of sync with SleepEx if we use that method.
//
// So, on Win8, we use QueryUnbiasedInterruptTime instead; this does not count time spent
// in sleep/hibernate mode.
//
private static int TickCount
{
[SecuritySafeCritical]
get
{
#if !FEATURE_PAL
if (Environment.IsWindows8OrAbove)
{
ulong time100ns;
bool result = Win32Native.QueryUnbiasedInterruptTime(out time100ns);
if (!result)
throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error());
// convert to 100ns to milliseconds, and truncate to 32 bits.
return (int)(uint)(time100ns / 10000);
}
else
#endif
{
return Environment.TickCount;
}
}
}
//
// We use a SafeHandle to ensure that the native timer is destroyed when the AppDomain is unloaded.
//
[SecurityCritical]
class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public AppDomainTimerSafeHandle()
: base(true)
{
}
[SecurityCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected override bool ReleaseHandle()
{
return DeleteAppDomainTimer(handle);
}
}
[SecurityCritical]
AppDomainTimerSafeHandle m_appDomainTimer;
bool m_isAppDomainTimerScheduled;
int m_currentAppDomainTimerStartTicks;
uint m_currentAppDomainTimerDuration;
[SecuritySafeCritical]
private bool EnsureAppDomainTimerFiresBy(uint requestedDuration)
{
//
// The VM's timer implementation does not work well for very long-duration timers.
// See kb 950807.
// So we'll limit our native timer duration to a "small" value.
// This may cause us to attempt to fire timers early, but that's ok -
// we'll just see that none of our timers has actually reached its due time,
// and schedule the native timer again.
//
const uint maxPossibleDuration = 0x0fffffff;
uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration);
if (m_isAppDomainTimerScheduled)
{
uint elapsed = (uint)(TickCount - m_currentAppDomainTimerStartTicks);
if (elapsed >= m_currentAppDomainTimerDuration)
return true; //the timer's about to fire
uint remainingDuration = m_currentAppDomainTimerDuration - elapsed;
if (actualDuration >= remainingDuration)
return true; //the timer will fire earlier than this request
}
// If Pause is underway then do not schedule the timers
// A later update during resume will re-schedule
if(m_pauseTicks != 0)
{
Contract.Assert(!m_isAppDomainTimerScheduled);
Contract.Assert(m_appDomainTimer == null);
return true;
}
if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid)
{
Contract.Assert(!m_isAppDomainTimerScheduled);
m_appDomainTimer = CreateAppDomainTimer(actualDuration);
if (!m_appDomainTimer.IsInvalid)
{
m_isAppDomainTimerScheduled = true;
m_currentAppDomainTimerStartTicks = TickCount;
m_currentAppDomainTimerDuration = actualDuration;
return true;
}
else
{
return false;
}
}
else
{
if (ChangeAppDomainTimer(m_appDomainTimer, actualDuration))
{
m_isAppDomainTimerScheduled = true;
m_currentAppDomainTimerStartTicks = TickCount;
m_currentAppDomainTimerDuration = actualDuration;
return true;
}
else
{
return false;
}
}
}
//
// The VM calls this when the native timer fires.
//
[SecuritySafeCritical]
internal static void AppDomainTimerCallback()
{
Instance.FireNextTimers();
}
[System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime);
[System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime);
[System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
static extern bool DeleteAppDomainTimer(IntPtr handle);
#endregion
#region Firing timers
//
// The list of timers
//
TimerQueueTimer m_timers;
volatile int m_pauseTicks = 0; // Time when Pause was called
[SecurityCritical]
internal void Pause()
{
lock(this)
{
// Delete the native timer so that no timers are fired in the Pause zone
if(m_appDomainTimer != null && !m_appDomainTimer.IsInvalid)
{
m_appDomainTimer.Dispose();
m_appDomainTimer = null;
m_isAppDomainTimerScheduled = false;
m_pauseTicks = TickCount;
}
}
}
[SecurityCritical]
internal void Resume()
{
//
// Update timers to adjust their due-time to accomodate Pause/Resume
//
lock (this)
{
// prevent ThreadAbort while updating state
try { }
finally
{
int pauseTicks = m_pauseTicks;
m_pauseTicks = 0; // Set this to 0 so that now timers can be scheduled
int resumedTicks = TickCount;
int pauseDuration = resumedTicks - pauseTicks;
bool haveTimerToSchedule = false;
uint nextAppDomainTimerDuration = uint.MaxValue;
TimerQueueTimer timer = m_timers;
while (timer != null)
{
Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
Contract.Assert(resumedTicks >= timer.m_startTicks);
uint elapsed; // How much of the timer dueTime has already elapsed
// Timers started before the paused event has to be sufficiently delayed to accomodate
// for the Pause time. However, timers started after the Paused event shouldnt be adjusted.
// E.g. ones created by the app in its Activated event should fire when it was designated.
// The Resumed event which is where this routine is executing is after this Activated and hence
// shouldn't delay this timer
if(timer.m_startTicks <= pauseTicks)
elapsed = (uint)(pauseTicks - timer.m_startTicks);
else
elapsed = (uint)(resumedTicks - timer.m_startTicks);
// Handling the corner cases where a Timer was already due by the time Resume is happening,
// We shouldn't delay those timers.
// Example is a timer started in App's Activated event with a very small duration
timer.m_dueTime = (timer.m_dueTime > elapsed) ? timer.m_dueTime - elapsed : 0;;
timer.m_startTicks = resumedTicks; // re-baseline
if (timer.m_dueTime < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = timer.m_dueTime;
}
timer = timer.m_next;
}
if (haveTimerToSchedule)
{
EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration);
}
}
}
}
//
// Fire any timers that have expired, and update the native timer to schedule the rest of them.
//
private void FireNextTimers()
{
//
// we fire the first timer on this thread; any other timers that might have fired are queued
// to the ThreadPool.
//
TimerQueueTimer timerToFireOnThisThread = null;
lock (this)
{
// prevent ThreadAbort while updating state
try { }
finally
{
//
// since we got here, that means our previous timer has fired.
//
m_isAppDomainTimerScheduled = false;
bool haveTimerToSchedule = false;
uint nextAppDomainTimerDuration = uint.MaxValue;
int nowTicks = TickCount;
//
// Sweep through all timers. The ones that have reached their due time
// will fire. We will calculate the next native timer due time from the
// other timers.
//
TimerQueueTimer timer = m_timers;
while (timer != null)
{
Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
uint elapsed = (uint)(nowTicks - timer.m_startTicks);
if (elapsed >= timer.m_dueTime)
{
//
// Remember the next timer in case we delete this one
//
TimerQueueTimer nextTimer = timer.m_next;
if (timer.m_period != Timeout.UnsignedInfinite)
{
timer.m_startTicks = nowTicks;
timer.m_dueTime = timer.m_period;
//
// This is a repeating timer; schedule it to run again.
//
if (timer.m_dueTime < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = timer.m_dueTime;
}
}
else
{
//
// Not repeating; remove it from the queue
//
DeleteTimer(timer);
}
//
// If this is the first timer, we'll fire it on this thread. Otherwise, queue it
// to the ThreadPool.
//
if (timerToFireOnThisThread == null)
timerToFireOnThisThread = timer;
else
QueueTimerCompletion(timer);
timer = nextTimer;
}
else
{
//
// This timer hasn't fired yet. Just update the next time the native timer fires.
//
uint remaining = timer.m_dueTime - elapsed;
if (remaining < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = remaining;
}
timer = timer.m_next;
}
}
if (haveTimerToSchedule)
EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration);
}
}
//
// Fire the user timer outside of the lock!
//
if (timerToFireOnThisThread != null)
timerToFireOnThisThread.Fire();
}
[SecuritySafeCritical]
private static void QueueTimerCompletion(TimerQueueTimer timer)
{
WaitCallback callback = s_fireQueuedTimerCompletion;
if (callback == null)
s_fireQueuedTimerCompletion = callback = new WaitCallback(FireQueuedTimerCompletion);
// Can use "unsafe" variant because we take care of capturing and restoring
// the ExecutionContext.
ThreadPool.UnsafeQueueUserWorkItem(callback, timer);
}
private static WaitCallback s_fireQueuedTimerCompletion;
private static void FireQueuedTimerCompletion(object state)
{
((TimerQueueTimer)state).Fire();
}
#endregion
#region Queue implementation
public bool UpdateTimer(TimerQueueTimer timer, uint dueTime, uint period)
{
if (timer.m_dueTime == Timeout.UnsignedInfinite)
{
// the timer is not in the list; add it (as the head of the list).
timer.m_next = m_timers;
timer.m_prev = null;
if (timer.m_next != null)
timer.m_next.m_prev = timer;
m_timers = timer;
}
timer.m_dueTime = dueTime;
timer.m_period = (period == 0) ? Timeout.UnsignedInfinite : period;
timer.m_startTicks = TickCount;
return EnsureAppDomainTimerFiresBy(dueTime);
}
public void DeleteTimer(TimerQueueTimer timer)
{
if (timer.m_dueTime != Timeout.UnsignedInfinite)
{
if (timer.m_next != null)
timer.m_next.m_prev = timer.m_prev;
if (timer.m_prev != null)
timer.m_prev.m_next = timer.m_next;
if (m_timers == timer)
m_timers = timer.m_next;
timer.m_dueTime = Timeout.UnsignedInfinite;
timer.m_period = Timeout.UnsignedInfinite;
timer.m_startTicks = 0;
timer.m_prev = null;
timer.m_next = null;
}
}
#endregion
}
//
// A timer in our TimerQueue.
//
sealed class TimerQueueTimer
{
//
// All fields of this class are protected by a lock on TimerQueue.Instance.
//
// The first four fields are maintained by TimerQueue itself.
//
internal TimerQueueTimer m_next;
internal TimerQueueTimer m_prev;
//
// The time, according to TimerQueue.TickCount, when this timer's current interval started.
//
internal int m_startTicks;
//
// Timeout.UnsignedInfinite if we are not going to fire. Otherwise, the offset from m_startTime when we will fire.
//
internal uint m_dueTime;
//
// Timeout.UnsignedInfinite if we are a single-shot timer. Otherwise, the repeat interval.
//
internal uint m_period;
//
// Info about the user's callback
//
readonly TimerCallback m_timerCallback;
readonly Object m_state;
readonly ExecutionContext m_executionContext;
//
// When Timer.Dispose(WaitHandle) is used, we need to signal the wait handle only
// after all pending callbacks are complete. We set m_canceled to prevent any callbacks that
// are already queued from running. We track the number of callbacks currently executing in
// m_callbacksRunning. We set m_notifyWhenNoCallbacksRunning only when m_callbacksRunning
// reaches zero.
//
int m_callbacksRunning;
volatile bool m_canceled;
volatile WaitHandle m_notifyWhenNoCallbacksRunning;
[SecurityCritical]
internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period, ref StackCrawlMark stackMark)
{
m_timerCallback = timerCallback;
m_state = state;
m_dueTime = Timeout.UnsignedInfinite;
m_period = Timeout.UnsignedInfinite;
if (!ExecutionContext.IsFlowSuppressed())
{
m_executionContext = ExecutionContext.Capture(
ref stackMark,
ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
}
//
// After the following statement, the timer may fire. No more manipulation of timer state outside of
// the lock is permitted beyond this point!
//
if (dueTime != Timeout.UnsignedInfinite)
Change(dueTime, period);
}
internal bool Change(uint dueTime, uint period)
{
bool success;
lock (TimerQueue.Instance)
{
if (m_canceled)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic"));
// prevent ThreadAbort while updating state
try { }
finally
{
m_period = period;
if (dueTime == Timeout.UnsignedInfinite)
{
TimerQueue.Instance.DeleteTimer(this);
success = true;
}
else
{
if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer))
FrameworkEventSource.Log.ThreadTransferSendObj(this, 1, string.Empty, true);
success = TimerQueue.Instance.UpdateTimer(this, dueTime, period);
}
}
}
return success;
}
public void Close()
{
lock (TimerQueue.Instance)
{
// prevent ThreadAbort while updating state
try { }
finally
{
if (!m_canceled)
{
m_canceled = true;
TimerQueue.Instance.DeleteTimer(this);
}
}
}
}
public bool Close(WaitHandle toSignal)
{
bool success;
bool shouldSignal = false;
lock (TimerQueue.Instance)
{
// prevent ThreadAbort while updating state
try { }
finally
{
if (m_canceled)
{
success = false;
}
else
{
m_canceled = true;
m_notifyWhenNoCallbacksRunning = toSignal;
TimerQueue.Instance.DeleteTimer(this);
if (m_callbacksRunning == 0)
shouldSignal = true;
success = true;
}
}
}
if (shouldSignal)
SignalNoCallbacksRunning();
return success;
}
internal void Fire()
{
bool canceled = false;
lock (TimerQueue.Instance)
{
// prevent ThreadAbort while updating state
try { }
finally
{
canceled = m_canceled;
if (!canceled)
m_callbacksRunning++;
}
}
if (canceled)
return;
CallCallback();
bool shouldSignal = false;
lock (TimerQueue.Instance)
{
// prevent ThreadAbort while updating state
try { }
finally
{
m_callbacksRunning--;
if (m_canceled && m_callbacksRunning == 0 && m_notifyWhenNoCallbacksRunning != null)
shouldSignal = true;
}
}
if (shouldSignal)
SignalNoCallbacksRunning();
}
[SecuritySafeCritical]
internal void SignalNoCallbacksRunning()
{
Win32Native.SetEvent(m_notifyWhenNoCallbacksRunning.SafeWaitHandle);
}
[SecuritySafeCritical]
internal void CallCallback()
{
if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer))
FrameworkEventSource.Log.ThreadTransferReceiveObj(this, 1, string.Empty);
// call directly if EC flow is suppressed
if (m_executionContext == null)
{
m_timerCallback(m_state);
}
else
{
using (ExecutionContext executionContext =
m_executionContext.IsPreAllocatedDefault ? m_executionContext : m_executionContext.CreateCopy())
{
ContextCallback callback = s_callCallbackInContext;
if (callback == null)
s_callCallbackInContext = callback = new ContextCallback(CallCallbackInContext);
ExecutionContext.Run(
executionContext,
callback,
this, // state
true); // ignoreSyncCtx
}
}
}
[SecurityCritical]
private static ContextCallback s_callCallbackInContext;
[SecurityCritical]
private static void CallCallbackInContext(object state)
{
TimerQueueTimer t = (TimerQueueTimer)state;
t.m_timerCallback(t.m_state);
}
}
//
// TimerHolder serves as an intermediary between Timer and TimerQueueTimer, releasing the TimerQueueTimer
// if the Timer is collected.
// This is necessary because Timer itself cannot use its finalizer for this purpose. If it did,
// then users could control timer lifetimes using GC.SuppressFinalize/ReRegisterForFinalize.
// You might ask, wouldn't that be a good thing? Maybe (though it would be even better to offer this
// via first-class APIs), but Timer has never offered this, and adding it now would be a breaking
// change, because any code that happened to be suppressing finalization of Timer objects would now
// unwittingly be changing the lifetime of those timers.
//
sealed class TimerHolder
{
internal TimerQueueTimer m_timer;
public TimerHolder(TimerQueueTimer timer)
{
m_timer = timer;
}
~TimerHolder()
{
//
// If shutdown has started, another thread may be suspended while holding the timer lock.
// So we can't safely close the timer.
//
// Similarly, we should not close the timer during AD-unload's live-object finalization phase.
// A rude abort may have prevented us from releasing the lock.
//
// Note that in either case, the Timer still won't fire, because ThreadPool threads won't be
// allowed to run in this AppDomain.
//
if (Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload())
return;
m_timer.Close();
}
public void Close()
{
m_timer.Close();
GC.SuppressFinalize(this);
}
public bool Close(WaitHandle notifyObject)
{
bool result = m_timer.Close(notifyObject);
GC.SuppressFinalize(this);
return result;
}
}
[HostProtection(Synchronization=true, ExternalThreading=true)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : MarshalByRefObject, IDisposable
{
private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe;
private TimerHolder m_timer;
[SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
int dueTime,
int period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1 )
throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
TimerSetup(callback,state,(UInt32)dueTime,(UInt32)period,ref stackMark);
}
[SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
TimeSpan dueTime,
TimeSpan period)
{
long dueTm = (long)dueTime.TotalMilliseconds;
if (dueTm < -1)
throw new ArgumentOutOfRangeException(nameof(dueTm),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(dueTm),Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
long periodTm = (long)period.TotalMilliseconds;
if (periodTm < -1)
throw new ArgumentOutOfRangeException(nameof(periodTm),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (periodTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(periodTm),Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
TimerSetup(callback,state,(UInt32)dueTm,(UInt32)periodTm,ref stackMark);
}
[CLSCompliant(false)]
[SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
UInt32 dueTime,
UInt32 period)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
TimerSetup(callback,state,dueTime,period,ref stackMark);
}
[SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
long dueTime,
long period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTime > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(dueTime),Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
if (period > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
TimerSetup(callback,state,(UInt32) dueTime, (UInt32) period,ref stackMark);
}
[SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback)
{
int dueTime = -1; // we want timer to be registered, but not activated. Requires caller to call
int period = -1; // Change after a timer instance is created. This is to avoid the potential
// for a timer to be fired before the returned value is assigned to the variable,
// potentially causing the callback to reference a bogus value (if passing the timer to the callback).
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period, ref stackMark);
}
[SecurityCritical]
private void TimerSetup(TimerCallback callback,
Object state,
UInt32 dueTime,
UInt32 period,
ref StackCrawlMark stackMark)
{
if (callback == null)
throw new ArgumentNullException(nameof(TimerCallback));
Contract.EndContractBlock();
m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, ref stackMark));
}
[SecurityCritical]
internal static void Pause()
{
TimerQueue.Instance.Pause();
}
[SecurityCritical]
internal static void Resume()
{
TimerQueue.Instance.Resume();
}
public bool Change(int dueTime, int period)
{
if (dueTime < -1 )
throw new ArgumentOutOfRangeException(nameof(dueTime),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
}
public bool Change(TimeSpan dueTime, TimeSpan period)
{
return Change((long) dueTime.TotalMilliseconds, (long) period.TotalMilliseconds);
}
[CLSCompliant(false)]
public bool Change(UInt32 dueTime, UInt32 period)
{
return m_timer.m_timer.Change(dueTime, period);
}
public bool Change(long dueTime, long period)
{
if (dueTime < -1 )
throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTime > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
if (period > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
}
public bool Dispose(WaitHandle notifyObject)
{
if (notifyObject==null)
throw new ArgumentNullException(nameof(notifyObject));
Contract.EndContractBlock();
return m_timer.Close(notifyObject);
}
public void Dispose()
{
m_timer.Close();
}
internal void KeepRootedWhileScheduled()
{
GC.SuppressFinalize(m_timer);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Signum.Utilities;
using Signum.Utilities.Reflection;
using Signum.Utilities.ExpressionTrees;
using Signum.Entities;
using Signum.Engine.Maps;
using Signum.Entities.Basics;
using System.Threading;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Signum.Entities.DynamicQuery;
namespace Signum.Engine.DynamicQuery
{
public static class AutocompleteUtils
{
public static List<Lite<Entity>> FindLiteLike(Implementations implementations, string subString, int count)
{
if (implementations.IsByAll)
throw new InvalidOperationException("ImplementedByAll not supported for FindLiteLike");
try
{
using (ExecutionMode.UserInterface())
return FindLiteLike(implementations.Types, subString, count);
}
catch (Exception e)
{
e.Data["implementations"] = implementations.ToString();
throw;
}
}
public static async Task<List<Lite<Entity>>> FindLiteLikeAsync(Implementations implementations, string subString, int count, CancellationToken cancellationToken)
{
if (implementations.IsByAll)
throw new InvalidOperationException("ImplementedByAll not supported for FindLiteLike");
try
{
using (ExecutionMode.UserInterface())
return await FindLiteLikeAsync(implementations.Types, subString, count, cancellationToken);
}
catch (Exception e)
{
e.Data["implementations"] = implementations.ToString();
throw;
}
}
private static bool TryParsePrimaryKey(string value, Type type, out PrimaryKey id)
{
var match = Regex.Match(value, "^id[:]?(.*)", RegexOptions.IgnoreCase);
if (match.Success)
return PrimaryKey.TryParse(match.Groups[1].ToString(), type, out id);
id = default(PrimaryKey);
return false;
}
static List<Lite<Entity>> FindLiteLike(IEnumerable<Type> types, string subString, int count)
{
if (subString == null)
subString = "";
types = types.Where(t => Schema.Current.IsAllowed(t, inUserInterface: true) == null);
List<Lite<Entity>> results = new List<Lite<Entity>>();
foreach (var t in types)
{
if (TryParsePrimaryKey(subString, t, out PrimaryKey id))
{
var lite = giLiteById.GetInvoker(t).Invoke(id);
if (lite != null)
{
results.Add(lite);
if (results.Count >= count)
return results;
}
}
}
foreach (var t in types)
{
if (!TryParsePrimaryKey(subString, t, out PrimaryKey id))
{
var parts = subString.SplitParts();
results.AddRange(giLiteContaining.GetInvoker(t)(parts, count - results.Count));
if (results.Count >= count)
return results;
}
}
return results;
}
private static async Task<List<Lite<Entity>>> FindLiteLikeAsync(IEnumerable<Type> types, string subString, int count, CancellationToken cancellationToken)
{
if (subString == null)
subString = "";
types = types.Where(t => Schema.Current.IsAllowed(t, inUserInterface: true) == null);
List<Lite<Entity>> results = new List<Lite<Entity>>();
foreach (var t in types)
{
if (TryParsePrimaryKey(subString, t, out PrimaryKey id))
{
var lite = await giLiteByIdAsync.GetInvoker(t).Invoke(id, cancellationToken);
if (lite != null)
{
results.Add(lite);
if (results.Count >= count)
return results;
}
}
}
foreach (var t in types)
{
if (!TryParsePrimaryKey(subString, t, out PrimaryKey id))
{
var parts = subString.SplitParts();
var list = await giLiteContainingAsync.GetInvoker(t)(parts, count - results.Count, cancellationToken);
results.AddRange(list);
if (results.Count >= count)
return results;
}
}
return results;
}
static GenericInvoker<Func<PrimaryKey, Lite<Entity>>> giLiteById =
new GenericInvoker<Func<PrimaryKey, Lite<Entity>>>(id => LiteById<TypeEntity>(id));
static Lite<Entity> LiteById<T>(PrimaryKey id)
where T : Entity
{
return Database.Query<T>().Where(a => a.id == id).Select(a => a.ToLite()).SingleOrDefault();
}
static GenericInvoker<Func<PrimaryKey, CancellationToken, Task<Lite<Entity>>>> giLiteByIdAsync =
new GenericInvoker<Func<PrimaryKey, CancellationToken, Task<Lite<Entity>>>>((id, token) => LiteByIdAsync<TypeEntity>(id, token));
static Task<Lite<Entity>> LiteByIdAsync<T>(PrimaryKey id, CancellationToken token)
where T : Entity
{
return Database.Query<T>().Where(a => a.id == id).Select(a => a.ToLite()).SingleOrDefaultAsync(token).ContinueWith(t => (Lite<Entity>)t.Result);
}
static GenericInvoker<Func<string[], int, List<Lite<Entity>>>> giLiteContaining =
new GenericInvoker<Func<string[], int, List<Lite<Entity>>>>((parts, c) => LiteContaining<TypeEntity>(parts, c));
static List<Lite<Entity>> LiteContaining<T>(string[] parts, int count)
where T : Entity
{
return Database.Query<T>()
.Where(a => a.ToString().ContainsAllParts(parts))
.OrderBy(a => a.ToString().Length)
.Select(a => a.ToLite())
.Take(count)
.AsEnumerable()
.Cast<Lite<Entity>>()
.ToList();
}
static GenericInvoker<Func<string[], int, CancellationToken, Task<List<Lite<Entity>>>>> giLiteContainingAsync =
new GenericInvoker<Func<string[], int, CancellationToken, Task<List<Lite<Entity>>>>>((parts, c, token) => LiteContaining<TypeEntity>(parts, c, token));
static async Task<List<Lite<Entity>>> LiteContaining<T>(string[] parts, int count, CancellationToken token)
where T : Entity
{
var list = await Database.Query<T>()
.Where(a => a.ToString().ContainsAllParts(parts))
.OrderBy(a => a.ToString().Length)
.Select(a => a.ToLite())
.Take(count)
.ToListAsync(token);
return list.Cast<Lite<Entity>>().ToList();
}
public static List<Lite<Entity>> FindAllLite(Implementations implementations)
{
if (implementations.IsByAll)
throw new InvalidOperationException("ImplementedByAll is not supported for RetrieveAllLite");
try
{
using (ExecutionMode.UserInterface())
return implementations.Types.SelectMany(type => Database.RetrieveAllLite(type)).ToList();
}
catch (Exception e)
{
e.Data["implementations"] = implementations.ToString();
throw;
}
}
public static async Task<List<Lite<Entity>>> FindAllLiteAsync(Implementations implementations, CancellationToken token)
{
if (implementations.IsByAll)
throw new InvalidOperationException("ImplementedByAll is not supported for RetrieveAllLite");
try
{
using (ExecutionMode.UserInterface())
{
var tasks = implementations.Types.Select(type => Database.RetrieveAllLiteAsync(type, token)).ToList();
var list = await Task.WhenAll(tasks);
return list.SelectMany(li => li).ToList();
}
}
catch (Exception e)
{
e.Data["implementations"] = implementations.ToString();
throw;
}
}
public static List<Lite<T>> Autocomplete<T>(this IQueryable<Lite<T>> query, string subString, int count)
where T : Entity
{
using (ExecutionMode.UserInterface())
{
List<Lite<T>> results = new List<Lite<T>>();
if (TryParsePrimaryKey(subString, typeof(T), out PrimaryKey id))
{
Lite<T>? entity = query.SingleOrDefaultEx(e => e.Id == id);
if (entity != null)
results.Add(entity);
if (results.Count >= count)
return results;
}
var parts = subString.SplitParts();
results.AddRange(query.Where(a => a.ToString()!.ContainsAllParts(parts))
.OrderBy(a => a.ToString()!.Length)
.Take(count - results.Count));
return results;
}
}
public static async Task<List<Lite<T>>> AutocompleteAsync<T>(this IQueryable<Lite<T>> query, string subString, int count, CancellationToken token)
where T : Entity
{
using (ExecutionMode.UserInterface())
{
List<Lite<T>> results = new List<Lite<T>>();
if (TryParsePrimaryKey(subString, typeof(T), out PrimaryKey id))
{
Lite<T> entity = await query.SingleOrDefaultAsync(e => e.Id == id, token);
if (entity != null)
results.Add(entity);
if (results.Count >= count)
return results;
}
var parts = subString.SplitParts();
var list = await query.Where(a => a.ToString()!.ContainsAllParts(parts))
.OrderBy(a => a.ToString()!.Length)
.Take(count - results.Count)
.ToListAsync(token);
results.AddRange(list);
return results;
}
}
public static List<Lite<T>> Autocomplete<T>(this IEnumerable<Lite<T>> collection, string subString, int count)
where T : Entity
{
using (ExecutionMode.UserInterface())
{
List<Lite<T>> results = new List<Lite<T>>();
if (TryParsePrimaryKey(subString, typeof(T), out PrimaryKey id))
{
Lite<T>? entity = collection.SingleOrDefaultEx(e => e.Id == id);
if (entity != null)
results.Add(entity);
if (results.Count >= count)
return results;
}
var parts = subString.SplitParts();
var list = collection.Where(a => a.ToString()!.ContainsAllParts(parts))
.OrderBy(a => a.ToString()!.Length)
.Take(count - results.Count);
results.AddRange(list);
return results;
}
}
public static string[] SplitParts(this string str)
{
if (FilterCondition.ToLowerString())
return str.Trim().ToLower().SplitNoEmpty(' ');
return str.Trim().SplitNoEmpty(' ');
}
[AutoExpressionField]
public static bool ContainsAllParts(this string str, string[] parts) => As.Expression(() =>
FilterCondition.ToLowerString() ?
str.ToLower().ContainsAll(parts) :
str.ContainsAll(parts));
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.Api;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.UI;
using OpenLiveWriter.Interop.Com.Ribbon;
using OpenLiveWriter.Localization;
using OpenLiveWriter.PostEditor.Commands;
using OpenLiveWriter.PostEditor.ContentSources;
using OpenLiveWriter.PostEditor.PostHtmlEditing.Sidebar;
namespace OpenLiveWriter.PostEditor.Video
{
internal class VideoWebPreviewCommand : Command
{
private bool _publishCompleted = false;
public bool PublishCompleted
{
get { return _publishCompleted; }
set
{
if (_publishCompleted != value)
{
_publishCompleted = value;
UpdateInvalidationState(PropertyKeys.Label, InvalidationState.Pending);
UpdateInvalidationState(PropertyKeys.LabelDescription, InvalidationState.Pending);
Invalidate();
}
}
}
internal VideoWebPreviewCommand()
: base(CommandId.VideoWebPreview)
{
}
public override string LabelTitle
{
get
{
return _publishCompleted ? base.LabelTitle : Res.Get(StringId.Plugin_Video_Editor_Cancel);
}
}
public override string TooltipDescription
{
get
{
return _publishCompleted ? base.TooltipDescription : String.Empty;
}
}
// @RIBBON TODO: Other overrides for image/string props.
// Have cancel publish use a placeholder icon for now.
}
internal class VideoEditorControl : AlignmentMarginContentEditor
{
private System.ComponentModel.IContainer components;
private VideoSmartContent _VideoContent;
private ISmartContentEditorSite _contentEditorSite;
public VideoEditorControl(ISmartContentEditorSite contentEditorSite)
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
components = null;
_contentEditorSite = contentEditorSite;
InitializeCommands();
}
private VideoWebPreviewCommand commandVideoWebPreview;
private Command commandVideoWidescreenAspectRatio;
private Command commandVideoStandardAspectRatio;
protected void InitializeCommands()
{
CommandManager cm = ((ICommandManagerHost) _contentEditorSite).CommandManager;
commandVideoWebPreview = new VideoWebPreviewCommand();
commandVideoWebPreview.Execute += VideoWebPreview_Execute;
cm.Add(commandVideoWebPreview);
commandVideoWidescreenAspectRatio = new Command(CommandId.VideoWidescreenAspectRatio);
commandVideoWidescreenAspectRatio.Execute += VideoAspectRatio_Execute;
commandVideoWidescreenAspectRatio.Tag = VideoAspectRatioType.Widescreen;
cm.Add(commandVideoWidescreenAspectRatio);
commandVideoStandardAspectRatio = new Command(CommandId.VideoStandardAspectRatio);
commandVideoStandardAspectRatio.Execute += VideoAspectRatio_Execute;
commandVideoStandardAspectRatio.Tag = VideoAspectRatioType.Standard;
cm.Add(commandVideoStandardAspectRatio);
InitializeAlignmentMarginCommands(((ICommandManagerHost)_contentEditorSite).CommandManager);
cm.Add(new GroupCommand(CommandId.FormatVideoGroup, commandVideoWebPreview));
}
private void VideoWebPreview_Execute(object sender, EventArgs e)
{
if (commandVideoWebPreview.PublishCompleted)
{
ShellHelper.LaunchUrl(_VideoContent.Url ?? String.Empty);
}
else
{
CancelPublish();
}
}
private void CancelPublish()
{
if (((IInternalContent)_VideoContent.SmartContent).ObjectState is IStatusWatcher)
{
((IStatusWatcher)((IInternalContent)_VideoContent.SmartContent).ObjectState).CancelPublish();
}
_VideoContent.Delete();
((ContentSourceSidebarControl)_contentEditorSite).RemoveSelectedContent();
}
private void VideoAspectRatio_Execute(object sender, EventArgs e)
{
Command commandExecuted = (Command)sender;
VideoAspectRatioType newAspectRatioType = (VideoAspectRatioType)commandExecuted.Tag;
if (_VideoContent.AspectRatioType != newAspectRatioType)
{
_VideoContent.AspectRatioType = newAspectRatioType;
OnContentEdited();
}
UpdateAspectRatio();
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
VirtualTransparency.VirtualPaint(this, pevent);
}
protected override void OnSelectedContentChanged()
{
// make connection to settings and elements
_VideoContent = new VideoSmartContent(SelectedContent);
base.OnSelectedContentChanged();
// update the settings UI
InitializeSettingsUI();
// force a layout for dynamic control flow
PerformLayout();
UpdatePadding();
// WinLive 121985: Cannot select the 'Enter Video Caption Here' edit control.
//OnContentEdited();
UpdateAspectRatio();
}
public override bool ContentEnabled
{
set
{
base.ContentEnabled = value;
commandVideoWebPreview.Enabled = value;
commandVideoWidescreenAspectRatio.Enabled = value;
commandVideoStandardAspectRatio.Enabled = value;
if (value == false)
{
commandVideoWidescreenAspectRatio.Latched = false;
commandVideoStandardAspectRatio.Latched = false;
}
}
}
private void UpdateVideoSizeDisplay()
{
_contentEditorSite.UpdateStatusBar(String.Format(CultureInfo.CurrentCulture, Res.Get(StringId.Plugin_Videos_Video_Size), _VideoContent.HtmlSize.Width, _VideoContent.HtmlSize.Height));
}
private void UpdateAspectRatio()
{
// Update the aspect ratio buttons.
commandVideoWidescreenAspectRatio.Latched = _VideoContent.AspectRatioType == VideoAspectRatioType.Widescreen;
commandVideoStandardAspectRatio.Latched = _VideoContent.AspectRatioType == VideoAspectRatioType.Standard;
// The ribbon keeps internal state about if the buttons should be latched or not, so we invalidate the
// state to make sure it calls back into us to get the current values.
commandVideoWidescreenAspectRatio.Invalidate(new[] { PropertyKeys.BooleanValue });
commandVideoStandardAspectRatio.Invalidate(new[] { PropertyKeys.BooleanValue });
}
private void UpdatePadding()
{
// update underlying values
Padding margin = ContentMargin;
bool paddingChanged = _VideoContent.LayoutStyle.TopMargin != Convert.ToInt32(margin.Top) |
_VideoContent.LayoutStyle.LeftMargin != Convert.ToInt32(margin.Left) |
_VideoContent.LayoutStyle.BottomMargin != Convert.ToInt32(margin.Bottom) |
_VideoContent.LayoutStyle.RightMargin != Convert.ToInt32(margin.Right);
_VideoContent.LayoutStyle.TopMargin = Convert.ToInt32(margin.Top);
_VideoContent.LayoutStyle.LeftMargin = Convert.ToInt32(margin.Left);
_VideoContent.LayoutStyle.BottomMargin = Convert.ToInt32(margin.Bottom);
_VideoContent.LayoutStyle.RightMargin = Convert.ToInt32(margin.Right);
// invalidate
if (paddingChanged)
OnContentEdited();
}
private void InitializeSettingsUI()
{
Padding margin = new Padding(_VideoContent.LayoutStyle.LeftMargin,
_VideoContent.LayoutStyle.TopMargin,
_VideoContent.LayoutStyle.RightMargin,
_VideoContent.LayoutStyle.BottomMargin);
SetAlignmentMargin(margin, _VideoContent.LayoutStyle.Alignment);
// video size in status-bar
UpdateVideoSizeDisplay();
IStatusWatcher statusWatcher = ((IInternalContent)_VideoContent.SmartContent).ObjectState as IStatusWatcher;
if (statusWatcher != null && statusWatcher.IsCancelable)
{
commandVideoWebPreview.PublishCompleted = false;
}
else
{
commandVideoWebPreview.PublishCompleted = true;
}
}
protected override void OnMarginChanged(object sender, EventArgs e)
{
UpdatePadding();
base.OnMarginChanged(sender, e);
OnContentEdited();
}
protected override void OnAlignmentChanged(object sender, EventArgs e)
{
_VideoContent.LayoutStyle.Alignment = ContentAlignment;
base.OnAlignmentChanged(sender, e);
OnContentEdited();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Component 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()
{
}
#endregion
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Diagnostics;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics.Joints
{
// Linear constraint (point-to-line)
// d = p2 - p1 = x2 + r2 - x1 - r1
// C = dot(perp, d)
// Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1))
// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2)
// J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)]
//
// Angular constraint
// C = a2 - a1 + a_initial
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
//
// K = J * invM * JT
//
// J = [-a -s1 a s2]
// [0 -1 0 1]
// a = perp
// s1 = cross(d + r1, a) = cross(p2 - x1, a)
// s2 = cross(r2, a) = cross(p2 - x2, a)
// Motor/Limit linear constraint
// C = dot(ax1, d)
// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2)
// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)]
// Block Solver
// We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even
// when the mass has poor distribution (leading to large torques about the joint anchor points).
//
// The Jacobian has 3 rows:
// J = [-uT -s1 uT s2] // linear
// [0 -1 0 1] // angular
// [-vT -a1 vT a2] // limit
//
// u = perp
// v = axis
// s1 = cross(d + r1, u), s2 = cross(r2, u)
// a1 = cross(d + r1, v), a2 = cross(r2, v)
// M * (v2 - v1) = JT * df
// J * v2 = bias
//
// v2 = v1 + invM * JT * df
// J * (v1 + invM * JT * df) = bias
// K * df = bias - J * v1 = -Cdot
// K = J * invM * JT
// Cdot = J * v1 - bias
//
// Now solve for f2.
// df = f2 - f1
// K * (f2 - f1) = -Cdot
// f2 = invK * (-Cdot) + f1
//
// Clamp accumulated limit impulse.
// lower: f2(3) = max(f2(3), 0)
// upper: f2(3) = min(f2(3), 0)
//
// Solve for correct f2(1:2)
// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1
// = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3)
// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2)
// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2)
//
// Now compute impulse to be applied:
// df = f2 - f1
/// <summary>
/// A prismatic joint. This joint provides one degree of freedom: translation
/// along an axis fixed in bodyA. Relative rotation is prevented. You can
/// use a joint limit to restrict the range of motion and a joint motor to
/// drive the motion or to model joint friction.
/// </summary>
public class PrismaticJoint : Joint
{
#region Properties/Fields
/// <summary>
/// The local anchor point on BodyA
/// </summary>
public Vector2 localAnchorA;
/// <summary>
/// The local anchor point on BodyB
/// </summary>
public Vector2 localAnchorB;
public override Vector2 worldAnchorA
{
get { return bodyA.getWorldPoint( localAnchorA ); }
set { localAnchorA = bodyA.getLocalPoint( value ); }
}
public override Vector2 worldAnchorB
{
get { return bodyB.getWorldPoint( localAnchorB ); }
set { localAnchorB = bodyB.getLocalPoint( value ); }
}
/// <summary>
/// Get the current joint translation, usually in meters.
/// </summary>
/// <value></value>
public float jointTranslation
{
get
{
var d = bodyB.getWorldPoint( localAnchorB ) - bodyA.getWorldPoint( localAnchorA );
var axis = bodyA.getWorldVector( localXAxis );
return Vector2.Dot( d, axis );
}
}
/// <summary>
/// Get the current joint translation speed, usually in meters per second.
/// </summary>
/// <value></value>
public float jointSpeed
{
get
{
Transform xf1, xf2;
bodyA.getTransform( out xf1 );
bodyB.getTransform( out xf2 );
var r1 = MathUtils.mul( ref xf1.q, localAnchorA - bodyA.localCenter );
var r2 = MathUtils.mul( ref xf2.q, localAnchorB - bodyB.localCenter );
var p1 = bodyA._sweep.c + r1;
var p2 = bodyB._sweep.c + r2;
var d = p2 - p1;
var axis = bodyA.getWorldVector( localXAxis );
var v1 = bodyA._linearVelocity;
var v2 = bodyB._linearVelocity;
float w1 = bodyA._angularVelocity;
float w2 = bodyB._angularVelocity;
float speed = Vector2.Dot( d, MathUtils.cross( w1, axis ) ) + Vector2.Dot( axis, v2 + MathUtils.cross( w2, r2 ) - v1 - MathUtils.cross( w1, r1 ) );
return speed;
}
}
/// <summary>
/// Is the joint limit enabled?
/// </summary>
/// <value><c>true</c> if [limit enabled]; otherwise, <c>false</c>.</value>
public bool limitEnabled
{
get { return _enableLimit; }
set
{
Debug.Assert( bodyA.fixedRotation == false || bodyB.fixedRotation == false, "Warning: limits does currently not work with fixed rotation" );
if( value != _enableLimit )
{
wakeBodies();
_enableLimit = value;
_impulse.Z = 0;
}
}
}
/// <summary>
/// Get the lower joint limit, usually in meters.
/// </summary>
/// <value></value>
public float lowerLimit
{
get { return _lowerTranslation; }
set
{
if( value != _lowerTranslation )
{
wakeBodies();
_lowerTranslation = value;
_impulse.Z = 0.0f;
}
}
}
/// <summary>
/// Get the upper joint limit, usually in meters.
/// </summary>
/// <value></value>
public float upperLimit
{
get { return _upperTranslation; }
set
{
if( value != _upperTranslation )
{
wakeBodies();
_upperTranslation = value;
_impulse.Z = 0.0f;
}
}
}
/// <summary>
/// Is the joint motor enabled?
/// </summary>
/// <value><c>true</c> if [motor enabled]; otherwise, <c>false</c>.</value>
public bool motorEnabled
{
get { return _enableMotor; }
set
{
wakeBodies();
_enableMotor = value;
}
}
/// <summary>
/// Set the motor speed, usually in meters per second.
/// </summary>
/// <value>The speed.</value>
public float motorSpeed
{
set
{
wakeBodies();
_motorSpeed = value;
}
get { return _motorSpeed; }
}
/// <summary>
/// Set the maximum motor force, usually in N.
/// </summary>
/// <value>The force.</value>
public float maxMotorForce
{
get { return _maxMotorForce; }
set
{
wakeBodies();
_maxMotorForce = value;
}
}
/// <summary>
/// Get the current motor impulse, usually in N.
/// </summary>
/// <value></value>
public float motorImpulse;
/// <summary>
/// The axis at which the joint moves.
/// </summary>
public Vector2 axis
{
get { return _axis1; }
set
{
_axis1 = value;
localXAxis = bodyA.getLocalVector( _axis1 );
Nez.Vector2Ext.normalize( ref localXAxis );
_localYAxisA = MathUtils.cross( 1.0f, localXAxis );
}
}
/// <summary>
/// The axis in local coordinates relative to BodyA
/// </summary>
public Vector2 localXAxis;
/// <summary>
/// The reference angle.
/// </summary>
public float referenceAngle;
Vector2 _localYAxisA;
Vector3 _impulse;
float _lowerTranslation;
float _upperTranslation;
float _maxMotorForce;
float _motorSpeed;
bool _enableLimit;
bool _enableMotor;
private LimitState _limitState;
// Solver temp
int _indexA;
int _indexB;
Vector2 _localCenterA;
private Vector2 _localCenterB;
float _invMassA;
float _invMassB;
float _invIA;
float _invIB;
private Vector2 _axis, _perp;
float _s1, _s2;
float _a1, _a2;
Mat33 _K;
float _motorMass;
Vector2 _axis1;
#endregion
internal PrismaticJoint()
{
jointType = JointType.Prismatic;
}
/// <summary>
/// This requires defining a line of
/// motion using an axis and an anchor point. The definition uses local
/// anchor points and a local axis so that the initial configuration
/// can violate the constraint slightly. The joint translation is zero
/// when the local anchor points coincide in world space. Using local
/// anchors and a local axis helps when saving and loading a game.
/// </summary>
/// <param name="bodyA">The first body.</param>
/// <param name="bodyB">The second body.</param>
/// <param name="anchorA">The first body anchor.</param>
/// <param name="anchorB">The second body anchor.</param>
/// <param name="axis">The axis.</param>
/// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param>
public PrismaticJoint( Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB, Vector2 axis, bool useWorldCoordinates = false )
: base( bodyA, bodyB )
{
initialize( anchorA, anchorB, axis, useWorldCoordinates );
}
public PrismaticJoint( Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis, bool useWorldCoordinates = false )
: base( bodyA, bodyB )
{
initialize( anchor, anchor, axis, useWorldCoordinates );
}
void initialize( Vector2 localAnchorA, Vector2 localAnchorB, Vector2 axis, bool useWorldCoordinates )
{
jointType = JointType.Prismatic;
if( useWorldCoordinates )
{
this.localAnchorA = bodyA.getLocalPoint( localAnchorA );
this.localAnchorB = bodyB.getLocalPoint( localAnchorB );
}
else
{
this.localAnchorA = localAnchorA;
this.localAnchorB = localAnchorB;
}
this.axis = axis; //FPE only: store the orignal value for use in Serialization
referenceAngle = bodyB.rotation - bodyA.rotation;
_limitState = LimitState.Inactive;
}
/// <summary>
/// Set the joint limits, usually in meters.
/// </summary>
/// <param name="lower">The lower limit</param>
/// <param name="upper">The upper limit</param>
public void setLimits( float lower, float upper )
{
if( upper != _upperTranslation || lower != _lowerTranslation )
{
wakeBodies();
_upperTranslation = upper;
_lowerTranslation = lower;
_impulse.Z = 0.0f;
}
}
/// <summary>
/// Gets the motor force.
/// </summary>
/// <param name="invDt">The inverse delta time</param>
public float getMotorForce( float invDt )
{
return invDt * motorImpulse;
}
public override Vector2 getReactionForce( float invDt )
{
return invDt * ( _impulse.X * _perp + ( motorImpulse + _impulse.Z ) * _axis );
}
public override float getReactionTorque( float invDt )
{
return invDt * _impulse.Y;
}
internal override void initVelocityConstraints( ref SolverData data )
{
_indexA = bodyA.islandIndex;
_indexB = bodyB.islandIndex;
_localCenterA = bodyA._sweep.localCenter;
_localCenterB = bodyB._sweep.localCenter;
_invMassA = bodyA._invMass;
_invMassB = bodyB._invMass;
_invIA = bodyA._invI;
_invIB = bodyB._invI;
Vector2 cA = data.positions[_indexA].c;
float aA = data.positions[_indexA].a;
Vector2 vA = data.velocities[_indexA].v;
float wA = data.velocities[_indexA].w;
Vector2 cB = data.positions[_indexB].c;
float aB = data.positions[_indexB].a;
Vector2 vB = data.velocities[_indexB].v;
float wB = data.velocities[_indexB].w;
Rot qA = new Rot( aA ), qB = new Rot( aB );
// Compute the effective masses.
Vector2 rA = MathUtils.mul( qA, localAnchorA - _localCenterA );
Vector2 rB = MathUtils.mul( qB, localAnchorB - _localCenterB );
Vector2 d = ( cB - cA ) + rB - rA;
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
// Compute motor Jacobian and effective mass.
{
_axis = MathUtils.mul( qA, localXAxis );
_a1 = MathUtils.cross( d + rA, _axis );
_a2 = MathUtils.cross( rB, _axis );
_motorMass = mA + mB + iA * _a1 * _a1 + iB * _a2 * _a2;
if( _motorMass > 0.0f )
{
_motorMass = 1.0f / _motorMass;
}
}
// Prismatic constraint.
{
_perp = MathUtils.mul( qA, _localYAxisA );
_s1 = MathUtils.cross( d + rA, _perp );
_s2 = MathUtils.cross( rB, _perp );
float k11 = mA + mB + iA * _s1 * _s1 + iB * _s2 * _s2;
float k12 = iA * _s1 + iB * _s2;
float k13 = iA * _s1 * _a1 + iB * _s2 * _a2;
float k22 = iA + iB;
if( k22 == 0.0f )
{
// For bodies with fixed rotation.
k22 = 1.0f;
}
float k23 = iA * _a1 + iB * _a2;
float k33 = mA + mB + iA * _a1 * _a1 + iB * _a2 * _a2;
_K.ex = new Vector3( k11, k12, k13 );
_K.ey = new Vector3( k12, k22, k23 );
_K.ez = new Vector3( k13, k23, k33 );
}
// Compute motor and limit terms.
if( _enableLimit )
{
float jointTranslation = Vector2.Dot( _axis, d );
if( Math.Abs( _upperTranslation - _lowerTranslation ) < 2.0f * Settings.linearSlop )
{
_limitState = LimitState.Equal;
}
else if( jointTranslation <= _lowerTranslation )
{
if( _limitState != LimitState.AtLower )
{
_limitState = LimitState.AtLower;
_impulse.Z = 0.0f;
}
}
else if( jointTranslation >= _upperTranslation )
{
if( _limitState != LimitState.AtUpper )
{
_limitState = LimitState.AtUpper;
_impulse.Z = 0.0f;
}
}
else
{
_limitState = LimitState.Inactive;
_impulse.Z = 0.0f;
}
}
else
{
_limitState = LimitState.Inactive;
_impulse.Z = 0.0f;
}
if( _enableMotor == false )
{
motorImpulse = 0.0f;
}
if( Settings.enableWarmstarting )
{
// Account for variable time step.
_impulse *= data.step.dtRatio;
motorImpulse *= data.step.dtRatio;
Vector2 P = _impulse.X * _perp + ( motorImpulse + _impulse.Z ) * _axis;
float LA = _impulse.X * _s1 + _impulse.Y + ( motorImpulse + _impulse.Z ) * _a1;
float LB = _impulse.X * _s2 + _impulse.Y + ( motorImpulse + _impulse.Z ) * _a2;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
else
{
_impulse = Vector3.Zero;
motorImpulse = 0.0f;
}
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
data.velocities[_indexB].v = vB;
data.velocities[_indexB].w = wB;
}
internal override void solveVelocityConstraints( ref SolverData data )
{
Vector2 vA = data.velocities[_indexA].v;
float wA = data.velocities[_indexA].w;
Vector2 vB = data.velocities[_indexB].v;
float wB = data.velocities[_indexB].w;
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
// Solve linear motor constraint.
if( _enableMotor && _limitState != LimitState.Equal )
{
float Cdot = Vector2.Dot( _axis, vB - vA ) + _a2 * wB - _a1 * wA;
float impulse = _motorMass * ( _motorSpeed - Cdot );
float oldImpulse = motorImpulse;
float maxImpulse = data.step.dt * _maxMotorForce;
motorImpulse = MathUtils.clamp( motorImpulse + impulse, -maxImpulse, maxImpulse );
impulse = motorImpulse - oldImpulse;
Vector2 P = impulse * _axis;
float LA = impulse * _a1;
float LB = impulse * _a2;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
Vector2 Cdot1 = new Vector2();
Cdot1.X = Vector2.Dot( _perp, vB - vA ) + _s2 * wB - _s1 * wA;
Cdot1.Y = wB - wA;
if( _enableLimit && _limitState != LimitState.Inactive )
{
// Solve prismatic and limit constraint in block form.
float Cdot2;
Cdot2 = Vector2.Dot( _axis, vB - vA ) + _a2 * wB - _a1 * wA;
Vector3 Cdot = new Vector3( Cdot1.X, Cdot1.Y, Cdot2 );
Vector3 f1 = _impulse;
Vector3 df = _K.Solve33( -Cdot );
_impulse += df;
if( _limitState == LimitState.AtLower )
{
_impulse.Z = Math.Max( _impulse.Z, 0.0f );
}
else if( _limitState == LimitState.AtUpper )
{
_impulse.Z = Math.Min( _impulse.Z, 0.0f );
}
// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2)
Vector2 b = -Cdot1 - ( _impulse.Z - f1.Z ) * new Vector2( _K.ez.X, _K.ez.Y );
Vector2 f2r = _K.Solve22( b ) + new Vector2( f1.X, f1.Y );
_impulse.X = f2r.X;
_impulse.Y = f2r.Y;
df = _impulse - f1;
Vector2 P = df.X * _perp + df.Z * _axis;
float LA = df.X * _s1 + df.Y + df.Z * _a1;
float LB = df.X * _s2 + df.Y + df.Z * _a2;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
else
{
// Limit is inactive, just solve the prismatic constraint in block form.
Vector2 df = _K.Solve22( -Cdot1 );
_impulse.X += df.X;
_impulse.Y += df.Y;
Vector2 P = df.X * _perp;
float LA = df.X * _s1 + df.Y;
float LB = df.X * _s2 + df.Y;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
data.velocities[_indexB].v = vB;
data.velocities[_indexB].w = wB;
}
internal override bool solvePositionConstraints( ref SolverData data )
{
Vector2 cA = data.positions[_indexA].c;
float aA = data.positions[_indexA].a;
Vector2 cB = data.positions[_indexB].c;
float aB = data.positions[_indexB].a;
Rot qA = new Rot( aA ), qB = new Rot( aB );
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
// Compute fresh Jacobians
Vector2 rA = MathUtils.mul( qA, localAnchorA - _localCenterA );
Vector2 rB = MathUtils.mul( qB, localAnchorB - _localCenterB );
Vector2 d = cB + rB - cA - rA;
Vector2 axis = MathUtils.mul( qA, localXAxis );
float a1 = MathUtils.cross( d + rA, axis );
float a2 = MathUtils.cross( rB, axis );
Vector2 perp = MathUtils.mul( qA, _localYAxisA );
float s1 = MathUtils.cross( d + rA, perp );
float s2 = MathUtils.cross( rB, perp );
Vector3 impulse;
Vector2 C1 = new Vector2();
C1.X = Vector2.Dot( perp, d );
C1.Y = aB - aA - referenceAngle;
float linearError = Math.Abs( C1.X );
float angularError = Math.Abs( C1.Y );
bool active = false;
float C2 = 0.0f;
if( _enableLimit )
{
float translation = Vector2.Dot( axis, d );
if( Math.Abs( _upperTranslation - _lowerTranslation ) < 2.0f * Settings.linearSlop )
{
// Prevent large angular corrections
C2 = MathUtils.clamp( translation, -Settings.maxLinearCorrection, Settings.maxLinearCorrection );
linearError = Math.Max( linearError, Math.Abs( translation ) );
active = true;
}
else if( translation <= _lowerTranslation )
{
// Prevent large linear corrections and allow some slop.
C2 = MathUtils.clamp( translation - _lowerTranslation + Settings.linearSlop, -Settings.maxLinearCorrection, 0.0f );
linearError = Math.Max( linearError, _lowerTranslation - translation );
active = true;
}
else if( translation >= _upperTranslation )
{
// Prevent large linear corrections and allow some slop.
C2 = MathUtils.clamp( translation - _upperTranslation - Settings.linearSlop, 0.0f, Settings.maxLinearCorrection );
linearError = Math.Max( linearError, translation - _upperTranslation );
active = true;
}
}
if( active )
{
float k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
float k12 = iA * s1 + iB * s2;
float k13 = iA * s1 * a1 + iB * s2 * a2;
float k22 = iA + iB;
if( k22 == 0.0f )
{
// For fixed rotation
k22 = 1.0f;
}
float k23 = iA * a1 + iB * a2;
float k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2;
Mat33 K = new Mat33();
K.ex = new Vector3( k11, k12, k13 );
K.ey = new Vector3( k12, k22, k23 );
K.ez = new Vector3( k13, k23, k33 );
Vector3 C = new Vector3();
C.X = C1.X;
C.Y = C1.Y;
C.Z = C2;
impulse = K.Solve33( -C );
}
else
{
float k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
float k12 = iA * s1 + iB * s2;
float k22 = iA + iB;
if( k22 == 0.0f )
{
k22 = 1.0f;
}
Mat22 K = new Mat22();
K.ex = new Vector2( k11, k12 );
K.ey = new Vector2( k12, k22 );
Vector2 impulse1 = K.Solve( -C1 );
impulse = new Vector3();
impulse.X = impulse1.X;
impulse.Y = impulse1.Y;
impulse.Z = 0.0f;
}
Vector2 P = impulse.X * perp + impulse.Z * axis;
float LA = impulse.X * s1 + impulse.Y + impulse.Z * a1;
float LB = impulse.X * s2 + impulse.Y + impulse.Z * a2;
cA -= mA * P;
aA -= iA * LA;
cB += mB * P;
aB += iB * LB;
data.positions[_indexA].c = cA;
data.positions[_indexA].a = aA;
data.positions[_indexB].c = cB;
data.positions[_indexB].a = aB;
return linearError <= Settings.linearSlop && angularError <= Settings.angularSlop;
}
}
}
| |
/*
* 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 OpenMetaverse;
using log4net;
using Nini.Config;
using System.Reflection;
using OpenSim.Services.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Data;
using OpenSim.Framework;
namespace OpenSim.Services.InventoryService
{
public class HGInventoryService : XInventoryService, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
protected new IXInventoryData m_Database;
public HGInventoryService(IConfigSource config)
: base(config)
{
string dllName = String.Empty;
string connString = String.Empty;
//string realm = "Inventory"; // OSG version doesn't use this
//
// Try reading the [DatabaseService] section, if it exists
//
IConfig dbConfig = config.Configs["DatabaseService"];
if (dbConfig != null)
{
if (dllName == String.Empty)
dllName = dbConfig.GetString("StorageProvider", String.Empty);
if (connString == String.Empty)
connString = dbConfig.GetString("ConnectionString", String.Empty);
}
//
// Try reading the [InventoryService] section, if it exists
//
IConfig authConfig = config.Configs["InventoryService"];
if (authConfig != null)
{
dllName = authConfig.GetString("StorageProvider", dllName);
connString = authConfig.GetString("ConnectionString", connString);
// realm = authConfig.GetString("Realm", realm);
}
//
// We tried, but this doesn't exist. We can't proceed.
//
if (dllName == String.Empty)
throw new Exception("No StorageProvider configured");
m_Database = LoadPlugin<IXInventoryData>(dllName,
new Object[] {connString, String.Empty});
if (m_Database == null)
throw new Exception("Could not find a storage interface in the given module");
m_log.Debug("[HG INVENTORY SERVICE]: Starting...");
}
public override bool CreateUserInventory(UUID principalID)
{
// NOGO
return false;
}
public override List<InventoryFolderBase> GetInventorySkeleton(UUID principalID)
{
// NOGO for this inventory service
return new List<InventoryFolderBase>();
}
public override InventoryFolderBase GetRootFolder(UUID principalID)
{
// Warp! Root folder for travelers
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "folderName"},
new string[] { principalID.ToString(), "My Suitcase" });
if (folders.Length > 0)
return ConvertToOpenSim(folders[0]);
// make one
XInventoryFolder suitcase = CreateFolder(principalID, UUID.Zero, (int)AssetType.Folder, "My Suitcase");
return ConvertToOpenSim(suitcase);
}
//private bool CreateSystemFolders(UUID principalID, XInventoryFolder suitcase)
//{
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.Animation, "Animations");
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.Bodypart, "Body Parts");
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.CallingCard, "Calling Cards");
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.Clothing, "Clothing");
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.Gesture, "Gestures");
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.Landmark, "Landmarks");
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.LostAndFoundFolder, "Lost And Found");
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.Notecard, "Notecards");
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.Object, "Objects");
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.SnapshotFolder, "Photo Album");
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.LSLText, "Scripts");
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.Sound, "Sounds");
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.Texture, "Textures");
// CreateFolder(principalID, suitcase.folderID, (int)AssetType.TrashFolder, "Trash");
// return true;
//}
public override InventoryFolderBase GetFolderForType(UUID principalID, AssetType type)
{
return GetRootFolder(principalID);
}
//
// Use the inherited methods
//
//public InventoryCollection GetFolderContent(UUID principalID, UUID folderID)
//{
//}
//public List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID)
//{
//}
//public override bool AddFolder(InventoryFolderBase folder)
//{
// // Check if it's under the Suitcase folder
// List<InventoryFolderBase> skel = base.GetInventorySkeleton(folder.Owner);
// InventoryFolderBase suitcase = GetRootFolder(folder.Owner);
// List<InventoryFolderBase> suitDescendents = GetDescendents(skel, suitcase.ID);
// foreach (InventoryFolderBase f in suitDescendents)
// if (folder.ParentID == f.ID)
// {
// XInventoryFolder xFolder = ConvertFromOpenSim(folder);
// return m_Database.StoreFolder(xFolder);
// }
// return false;
//}
private List<InventoryFolderBase> GetDescendents(List<InventoryFolderBase> lst, UUID root)
{
List<InventoryFolderBase> direct = lst.FindAll(delegate(InventoryFolderBase f) { return f.ParentID == root; });
if (direct == null)
return new List<InventoryFolderBase>();
List<InventoryFolderBase> indirect = new List<InventoryFolderBase>();
foreach (InventoryFolderBase f in direct)
indirect.AddRange(GetDescendents(lst, f.ID));
direct.AddRange(indirect);
return direct;
}
// Use inherited method
//public bool UpdateFolder(InventoryFolderBase folder)
//{
//}
//public override bool MoveFolder(InventoryFolderBase folder)
//{
// XInventoryFolder[] x = m_Database.GetFolders(
// new string[] { "folderID" },
// new string[] { folder.ID.ToString() });
// if (x.Length == 0)
// return false;
// // Check if it's under the Suitcase folder
// List<InventoryFolderBase> skel = base.GetInventorySkeleton(folder.Owner);
// InventoryFolderBase suitcase = GetRootFolder(folder.Owner);
// List<InventoryFolderBase> suitDescendents = GetDescendents(skel, suitcase.ID);
// foreach (InventoryFolderBase f in suitDescendents)
// if (folder.ParentID == f.ID)
// {
// x[0].parentFolderID = folder.ParentID;
// return m_Database.StoreFolder(x[0]);
// }
// return false;
//}
public override bool DeleteFolders(UUID principalID, List<UUID> folderIDs)
{
// NOGO
return false;
}
public override bool PurgeFolder(InventoryFolderBase folder)
{
// NOGO
return false;
}
// Unfortunately we need to use the inherited method because of how DeRez works.
// The viewer sends the folderID hard-wired in the derez message
//public override bool AddItem(InventoryItemBase item)
//{
// // Check if it's under the Suitcase folder
// List<InventoryFolderBase> skel = base.GetInventorySkeleton(item.Owner);
// InventoryFolderBase suitcase = GetRootFolder(item.Owner);
// List<InventoryFolderBase> suitDescendents = GetDescendents(skel, suitcase.ID);
// foreach (InventoryFolderBase f in suitDescendents)
// if (item.Folder == f.ID)
// return m_Database.StoreItem(ConvertFromOpenSim(item));
// return false;
//}
//public override bool UpdateItem(InventoryItemBase item)
//{
// // Check if it's under the Suitcase folder
// List<InventoryFolderBase> skel = base.GetInventorySkeleton(item.Owner);
// InventoryFolderBase suitcase = GetRootFolder(item.Owner);
// List<InventoryFolderBase> suitDescendents = GetDescendents(skel, suitcase.ID);
// foreach (InventoryFolderBase f in suitDescendents)
// if (item.Folder == f.ID)
// return m_Database.StoreItem(ConvertFromOpenSim(item));
// return false;
//}
//public override bool MoveItems(UUID principalID, List<InventoryItemBase> items)
//{
// // Principal is b0rked. *sigh*
// //
// // Let's assume they all have the same principal
// // Check if it's under the Suitcase folder
// List<InventoryFolderBase> skel = base.GetInventorySkeleton(items[0].Owner);
// InventoryFolderBase suitcase = GetRootFolder(items[0].Owner);
// List<InventoryFolderBase> suitDescendents = GetDescendents(skel, suitcase.ID);
// foreach (InventoryItemBase i in items)
// {
// foreach (InventoryFolderBase f in suitDescendents)
// if (i.Folder == f.ID)
// m_Database.MoveItem(i.ID.ToString(), i.Folder.ToString());
// }
// return true;
//}
// Let these pass. Use inherited methods.
//public bool DeleteItems(UUID principalID, List<UUID> itemIDs)
//{
//}
//public InventoryItemBase GetItem(InventoryItemBase item)
//{
//}
//public InventoryFolderBase GetFolder(InventoryFolderBase folder)
//{
//}
//public List<InventoryItemBase> GetActiveGestures(UUID principalID)
//{
//}
//public int GetAssetPermissions(UUID principalID, UUID assetID)
//{
//}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SystemEx;
using WampSharp.Core.Listener;
using WampSharp.Core.Serialization;
using WampSharp.V2.Core;
using WampSharp.V2.Core.Contracts;
using WampSharp.V2.Realm;
using WampSharp.V2.Rpc;
namespace WampSharp.V2.Client
{
internal class WampCallee<TMessage> :
IWampRpcOperationRegistrationProxy, IWampCallee<TMessage>,
IWampCalleeError<TMessage>
{
private readonly IWampServerProxy mProxy;
private readonly IWampFormatter<TMessage> mFormatter;
private readonly IWampClientConnectionMonitor mMonitor;
private readonly WampRequestIdMapper<RegisterRequest> mPendingRegistrations =
new WampRequestIdMapper<RegisterRequest>();
private readonly ConcurrentDictionary<long, IWampRpcOperation> mRegistrations =
new ConcurrentDictionary<long, IWampRpcOperation>();
private readonly WampRequestIdMapper<UnregisterRequest> mPendingUnregistrations =
new WampRequestIdMapper<UnregisterRequest>();
public WampCallee(IWampServerProxy proxy, IWampFormatter<TMessage> formatter, IWampClientConnectionMonitor monitor)
{
mProxy = proxy;
mFormatter = formatter;
mMonitor = monitor;
monitor.ConnectionBroken += OnConnectionBroken;
monitor.ConnectionError += OnConnectionError;
}
public Task<IAsyncDisposable> Register(IWampRpcOperation operation, RegisterOptions options)
{
RegisterRequest registerRequest =
new RegisterRequest(operation, mFormatter);
long id = mPendingRegistrations.Add(registerRequest);
registerRequest.RequestId = id;
mProxy.Register(id, options, operation.Procedure);
return registerRequest.Task;
}
public void Registered(long requestId, long registrationId)
{
RegisterRequest registerRequest;
if (mPendingRegistrations.TryRemove(requestId, out registerRequest))
{
mRegistrations[registrationId] = registerRequest.Operation;
registerRequest.Complete(new UnregisterDisposable(this, registrationId));
}
}
private class UnregisterDisposable : IAsyncDisposable
{
private readonly WampCallee<TMessage> mCallee;
private readonly long mRegistrationId;
public UnregisterDisposable(WampCallee<TMessage> callee, long registrationId)
{
mCallee = callee;
mRegistrationId = registrationId;
}
public Task DisposeAsync()
{
return mCallee.Unregister(mRegistrationId);
}
}
private Task Unregister(long registrationId)
{
UnregisterRequest unregisterRequest =
new UnregisterRequest(mFormatter);
long requestId = mPendingUnregistrations.Add(unregisterRequest);
unregisterRequest.RequestId = requestId;
mProxy.Unregister(requestId, registrationId);
return unregisterRequest.Task;
}
public void Unregistered(long requestId)
{
UnregisterRequest unregisterRequest;
if (mPendingUnregistrations.TryRemove(requestId, out unregisterRequest))
{
IWampRpcOperation operation;
mRegistrations.TryRemove(requestId, out operation);
unregisterRequest.Complete();
}
}
private IWampRpcOperation TryGetOperation(long registrationId)
{
IWampRpcOperation operation;
if (mRegistrations.TryGetValue(registrationId, out operation))
{
return operation;
}
return null;
}
private IWampRawRpcOperationRouterCallback GetCallback(long requestId)
{
return new ServerProxyCallback(mProxy, requestId);
}
public void Invocation(long requestId, long registrationId, InvocationDetails details)
{
InvocationPattern(requestId, registrationId, details,
(operation, callback, invocationDetails) =>
operation.Invoke(callback,
mFormatter,
invocationDetails));
}
public void Invocation(long requestId, long registrationId, InvocationDetails details, TMessage[] arguments)
{
InvocationPattern(requestId, registrationId, details,
(operation, callback, invocationDetails) =>
operation.Invoke(callback,
mFormatter,
invocationDetails,
arguments));
}
public void Invocation(long requestId, long registrationId, InvocationDetails details, TMessage[] arguments, IDictionary<string, TMessage> argumentsKeywords)
{
InvocationPattern(requestId, registrationId, details,
(operation, callback, invocationDetails) =>
operation.Invoke(callback,
mFormatter,
invocationDetails,
arguments,
argumentsKeywords));
}
private void InvocationPattern(long requestId, long registrationId, InvocationDetails details, Action<IWampRpcOperation, IWampRawRpcOperationRouterCallback, InvocationDetails> invocationAction)
{
IWampRpcOperation operation = TryGetOperation(registrationId);
if (operation != null)
{
IWampRawRpcOperationRouterCallback callback = GetCallback(requestId);
InvocationDetails modifiedDetails = new InvocationDetails(details)
{
Procedure = details.Procedure ?? operation.Procedure
};
invocationAction(operation, callback, modifiedDetails);
}
}
public void RegisterError(long requestId, TMessage details, string error)
{
RegisterRequest registerRequest;
if (mPendingRegistrations.TryRemove(requestId, out registerRequest))
{
registerRequest.Error(details, error);
}
}
public void RegisterError(long requestId, TMessage details, string error, TMessage[] arguments)
{
RegisterRequest registerRequest;
if (mPendingRegistrations.TryRemove(requestId, out registerRequest))
{
registerRequest.Error(details, error, arguments);
}
}
public void RegisterError(long requestId, TMessage details, string error, TMessage[] arguments, TMessage argumentsKeywords)
{
RegisterRequest registerRequest;
if (mPendingRegistrations.TryRemove(requestId, out registerRequest))
{
registerRequest.Error(details, error, arguments, argumentsKeywords);
}
}
public void UnregisterError(long requestId, TMessage details, string error)
{
UnregisterRequest unregisterRequest;
if (mPendingUnregistrations.TryRemove(requestId, out unregisterRequest))
{
unregisterRequest.Error(details, error);
}
}
public void UnregisterError(long requestId, TMessage details, string error, TMessage[] arguments)
{
UnregisterRequest unregisterRequest;
if (mPendingUnregistrations.TryRemove(requestId, out unregisterRequest))
{
unregisterRequest.Error(details, error, arguments);
}
}
public void UnregisterError(long requestId, TMessage details, string error, TMessage[] arguments, TMessage argumentsKeywords)
{
UnregisterRequest unregisterRequest;
if (mPendingUnregistrations.TryRemove(requestId, out unregisterRequest))
{
unregisterRequest.Error(details, error, arguments, argumentsKeywords);
}
}
public void Interrupt(long requestId, TMessage options)
{
throw new NotImplementedException();
}
private class RegisterRequest : WampPendingRequest<TMessage, IAsyncDisposable>
{
private readonly IWampRpcOperation mOperation;
public RegisterRequest(IWampRpcOperation operation, IWampFormatter<TMessage> formatter) :
base(formatter)
{
mOperation = operation;
}
public IWampRpcOperation Operation
{
get
{
return mOperation;
}
}
}
private class UnregisterRequest : WampPendingRequest<TMessage>
{
public UnregisterRequest(IWampFormatter<TMessage> formatter) : base(formatter)
{
}
}
public void OnConnectionError(object sender, WampConnectionErrorEventArgs eventArgs)
{
Exception exception = eventArgs.Exception;
mPendingRegistrations.ConnectionError(exception);
mPendingUnregistrations.ConnectionError(exception);
Cleanup();
}
public void OnConnectionBroken(object sender, WampSessionCloseEventArgs eventArgs)
{
mPendingRegistrations.ConnectionClosed(eventArgs);
mPendingUnregistrations.ConnectionClosed(eventArgs);
Cleanup();
}
private void Cleanup()
{
// TODO: clean up other things?
mRegistrations.Clear();
}
private class ServerProxyCallback : IWampRawRpcOperationRouterCallback
{
private readonly IWampServerProxy mProxy;
private readonly long mRequestId;
public ServerProxyCallback(IWampServerProxy proxy, long requestId)
{
mProxy = proxy;
mRequestId = requestId;
}
public long RequestId
{
get
{
return mRequestId;
}
}
public void Result<TResult>(IWampFormatter<TResult> formatter, YieldOptions options)
{
mProxy.Yield(RequestId, options);
}
public void Result<TResult>(IWampFormatter<TResult> formatter, YieldOptions options, TResult[] arguments)
{
mProxy.Yield(RequestId, options, arguments.Cast<object>().ToArray());
}
public void Result<TResult>(IWampFormatter<TResult> formatter, YieldOptions options, TResult[] arguments, IDictionary<string, TResult> argumentsKeywords)
{
mProxy.Yield(RequestId, options, arguments.Cast<object>().ToArray(), argumentsKeywords.ToDictionary(x => x.Key, x => (object)x.Value));
}
public void Error<TResult>(IWampFormatter<TResult> formatter, TResult details, string error)
{
mProxy.InvocationError(RequestId, details, error);
}
public void Error<TResult>(IWampFormatter<TResult> formatter, TResult details, string error, TResult[] arguments)
{
mProxy.InvocationError(RequestId, details, error, arguments.Cast<object>().ToArray());
}
public void Error<TResult>(IWampFormatter<TResult> formatter, TResult details, string error, TResult[] arguments, TResult argumentsKeywords)
{
mProxy.InvocationError(RequestId, details, error, arguments.Cast<object>().ToArray(), argumentsKeywords);
}
}
}
}
| |
// 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 ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SubnetsOperations operations.
/// </summary>
public partial interface ISubnetsOperations
{
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified subnet by virtual network and resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Subnet>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Subnet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Subnet>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Subnet>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Subnet>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// This RegexNode class is internal to the Regex package.
// It is built into a parsed tree for a regular expression.
// Implementation notes:
//
// Since the node tree is a temporary data structure only used
// during compilation of the regexp to integer codes, it's
// designed for clarity and convenience rather than
// space efficiency.
//
// RegexNodes are built into a tree, linked by the _children list.
// Each node also has a _parent and _ichild member indicating
// its parent and which child # it is in its parent's list.
//
// RegexNodes come in as many types as there are constructs in
// a regular expression, for example, "concatenate", "alternate",
// "one", "rept", "group". There are also node types for basic
// peephole optimizations, e.g., "onerep", "notsetrep", etc.
//
// Because perl 5 allows "lookback" groups that scan backwards,
// each node also gets a "direction". Normally the value of
// boolean _backward = false.
//
// During parsing, top-level nodes are also stacked onto a parse
// stack (a stack of trees). For this purpose we have a _next
// pointer. [Note that to save a few bytes, we could overload the
// _parent pointer instead.]
//
// On the parse stack, each tree has a "role" - basically, the
// nonterminal in the grammar that the parser has currently
// assigned to the tree. That code is stored in _role.
//
// Finally, some of the different kinds of nodes have data.
// Two integers (for the looping constructs) are stored in
// _operands, an object (either a string or a set)
// is stored in _data
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace Flatbox.RegularExpressions
{
internal sealed class RegexNode
{
// RegexNode types
// The following are leaves, and correspond to primitive operations
internal const int Oneloop = RegexCode.Oneloop; // c,n a*
internal const int Notoneloop = RegexCode.Notoneloop; // c,n .*
internal const int Setloop = RegexCode.Setloop; // set,n \d*
internal const int Onelazy = RegexCode.Onelazy; // c,n a*?
internal const int Notonelazy = RegexCode.Notonelazy; // c,n .*?
internal const int Setlazy = RegexCode.Setlazy; // set,n \d*?
internal const int One = RegexCode.One; // char a
internal const int Notone = RegexCode.Notone; // char . [^a]
internal const int Set = RegexCode.Set; // set [a-z] \w \s \d
internal const int Multi = RegexCode.Multi; // string abcdef
internal const int Ref = RegexCode.Ref; // index \1
internal const int Bol = RegexCode.Bol; // ^
internal const int Eol = RegexCode.Eol; // $
internal const int Boundary = RegexCode.Boundary; // \b
internal const int Nonboundary = RegexCode.Nonboundary; // \B
internal const int ECMABoundary = RegexCode.ECMABoundary; // \b
internal const int NonECMABoundary = RegexCode.NonECMABoundary; // \B
internal const int Beginning = RegexCode.Beginning; // \A
internal const int Start = RegexCode.Start; // \G
internal const int EndZ = RegexCode.EndZ; // \Z
internal const int End = RegexCode.End; // \z
// Interior nodes do not correspond to primitive operations, but
// control structures compositing other operations
// Concat and alternate take n children, and can run forward or backwards
internal const int Nothing = 22; // []
internal const int Empty = 23; // ()
internal const int Alternate = 24; // a|b
internal const int Concatenate = 25; // ab
internal const int Loop = 26; // m,x * + ? {,}
internal const int Lazyloop = 27; // m,x *? +? ?? {,}?
internal const int Capture = 28; // n ()
internal const int Group = 29; // (?:)
internal const int Require = 30; // (?=) (?<=)
internal const int Prevent = 31; // (?!) (?<!)
internal const int Greedy = 32; // (?>) (?<)
internal const int Testref = 33; // (?(n) | )
internal const int Testgroup = 34; // (?(...) | )
// RegexNode data members
internal int _type;
internal List<RegexNode> _children;
internal string _str;
internal char _ch;
internal int _m;
internal int _n;
internal readonly RegexOptions _options;
internal RegexNode _next;
internal RegexNode(int type, RegexOptions options)
{
_type = type;
_options = options;
}
internal RegexNode(int type, RegexOptions options, char ch)
{
_type = type;
_options = options;
_ch = ch;
}
internal RegexNode(int type, RegexOptions options, string str)
{
_type = type;
_options = options;
_str = str;
}
internal RegexNode(int type, RegexOptions options, int m)
{
_type = type;
_options = options;
_m = m;
}
internal RegexNode(int type, RegexOptions options, int m, int n)
{
_type = type;
_options = options;
_m = m;
_n = n;
}
internal bool UseOptionR()
{
return (_options & RegexOptions.RightToLeft) != 0;
}
internal RegexNode ReverseLeft()
{
if (UseOptionR() && _type == Concatenate && _children != null)
{
_children.Reverse(0, _children.Count);
}
return this;
}
/// <summary>
/// Pass type as OneLazy or OneLoop
/// </summary>
internal void MakeRep(int type, int min, int max)
{
_type += (type - One);
_m = min;
_n = max;
}
/// <summary>
/// Removes redundant nodes from the subtree, and returns a reduced subtree.
/// </summary>
internal RegexNode Reduce()
{
RegexNode n;
switch (Type())
{
case Alternate:
n = ReduceAlternation();
break;
case Concatenate:
n = ReduceConcatenation();
break;
case Loop:
case Lazyloop:
n = ReduceRep();
break;
case Group:
n = ReduceGroup();
break;
case Set:
case Setloop:
n = ReduceSet();
break;
default:
n = this;
break;
}
return n;
}
/// <summary>
/// Simple optimization. If a concatenation or alternation has only
/// one child strip out the intermediate node. If it has zero children,
/// turn it into an empty.
/// </summary>
internal RegexNode StripEnation(int emptyType)
{
switch (ChildCount())
{
case 0:
return new RegexNode(emptyType, _options);
case 1:
return Child(0);
default:
return this;
}
}
/// <summary>
/// Simple optimization. Once parsed into a tree, non-capturing groups
/// serve no function, so strip them out.
/// </summary>
internal RegexNode ReduceGroup()
{
RegexNode u;
for (u = this; u.Type() == Group;)
u = u.Child(0);
return u;
}
/// <summary>
/// Nested repeaters just get multiplied with each other if they're not
/// too lumpy
/// </summary>
internal RegexNode ReduceRep()
{
RegexNode u;
RegexNode child;
int type;
int min;
int max;
u = this;
type = Type();
min = _m;
max = _n;
for (; ;)
{
if (u.ChildCount() == 0)
break;
child = u.Child(0);
// multiply reps of the same type only
if (child.Type() != type)
{
int childType = child.Type();
if (!(childType >= Oneloop && childType <= Setloop && type == Loop ||
childType >= Onelazy && childType <= Setlazy && type == Lazyloop))
break;
}
// child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})?
// [but things like (a {2,})+ are not too lumpy...]
if (u._m == 0 && child._m > 1 || child._n < child._m * 2)
break;
u = child;
if (u._m > 0)
u._m = min = ((int.MaxValue - 1) / u._m < min) ? int.MaxValue : u._m * min;
if (u._n > 0)
u._n = max = ((int.MaxValue - 1) / u._n < max) ? int.MaxValue : u._n * max;
}
return min == int.MaxValue ? new RegexNode(Nothing, _options) : u;
}
/// <summary>
/// Simple optimization. If a set is a singleton, an inverse singleton,
/// or empty, it's transformed accordingly.
/// </summary>
internal RegexNode ReduceSet()
{
// Extract empty-set, one and not-one case as special
if (RegexCharClass.IsEmpty(_str))
{
_type = Nothing;
_str = null;
}
else if (RegexCharClass.IsSingleton(_str))
{
_ch = RegexCharClass.SingletonChar(_str);
_str = null;
_type += (One - Set);
}
else if (RegexCharClass.IsSingletonInverse(_str))
{
_ch = RegexCharClass.SingletonChar(_str);
_str = null;
_type += (Notone - Set);
}
return this;
}
/// <summary>
/// Basic optimization. Single-letter alternations can be replaced
/// by faster set specifications, and nested alternations with no
/// intervening operators can be flattened:
///
/// a|b|c|def|g|h -> [a-c]|def|[gh]
/// apple|(?:orange|pear)|grape -> apple|orange|pear|grape
/// </summary>
internal RegexNode ReduceAlternation()
{
// Combine adjacent sets/chars
bool wasLastSet;
bool lastNodeCannotMerge;
RegexOptions optionsLast;
RegexOptions optionsAt;
int i;
int j;
RegexNode at;
RegexNode prev;
if (_children == null)
return new RegexNode(Nothing, _options);
wasLastSet = false;
lastNodeCannotMerge = false;
optionsLast = 0;
for (i = 0, j = 0; i < _children.Count; i++, j++)
{
at = _children[i];
if (j < i)
_children[j] = at;
for (; ;)
{
if (at._type == Alternate)
{
for (int k = 0; k < at._children.Count; k++)
at._children[k]._next = this;
_children.InsertRange(i + 1, at._children);
j--;
}
else if (at._type == Set || at._type == One)
{
// Cannot merge sets if L or I options differ, or if either are negated.
optionsAt = at._options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
if (at._type == Set)
{
if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge || !RegexCharClass.IsMergeable(at._str))
{
wasLastSet = true;
lastNodeCannotMerge = !RegexCharClass.IsMergeable(at._str);
optionsLast = optionsAt;
break;
}
}
else if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge)
{
wasLastSet = true;
lastNodeCannotMerge = false;
optionsLast = optionsAt;
break;
}
// The last node was a Set or a One, we're a Set or One and our options are the same.
// Merge the two nodes.
j--;
prev = _children[j];
RegexCharClass prevCharClass;
if (prev._type == One)
{
prevCharClass = new RegexCharClass();
prevCharClass.AddChar(prev._ch);
}
else
{
prevCharClass = RegexCharClass.Parse(prev._str);
}
if (at._type == One)
{
prevCharClass.AddChar(at._ch);
}
else
{
RegexCharClass atCharClass = RegexCharClass.Parse(at._str);
prevCharClass.AddCharClass(atCharClass);
}
prev._type = Set;
prev._str = prevCharClass.ToStringClass();
}
else if (at._type == Nothing)
{
j--;
}
else
{
wasLastSet = false;
lastNodeCannotMerge = false;
}
break;
}
}
if (j < i)
_children.RemoveRange(j, i - j);
return StripEnation(Nothing);
}
/// <summary>
/// Basic optimization. Adjacent strings can be concatenated.
///
/// (?:abc)(?:def) -> abcdef
/// </summary>
internal RegexNode ReduceConcatenation()
{
// Eliminate empties and concat adjacent strings/chars
bool wasLastString;
RegexOptions optionsLast;
RegexOptions optionsAt;
int i;
int j;
if (_children == null)
return new RegexNode(Empty, _options);
wasLastString = false;
optionsLast = 0;
for (i = 0, j = 0; i < _children.Count; i++, j++)
{
RegexNode at;
RegexNode prev;
at = _children[i];
if (j < i)
_children[j] = at;
if (at._type == Concatenate &&
((at._options & RegexOptions.RightToLeft) == (_options & RegexOptions.RightToLeft)))
{
for (int k = 0; k < at._children.Count; k++)
at._children[k]._next = this;
_children.InsertRange(i + 1, at._children);
j--;
}
else if (at._type == Multi ||
at._type == One)
{
// Cannot merge strings if L or I options differ
optionsAt = at._options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
if (!wasLastString || optionsLast != optionsAt)
{
wasLastString = true;
optionsLast = optionsAt;
continue;
}
prev = _children[--j];
if (prev._type == One)
{
prev._type = Multi;
prev._str = Convert.ToString(prev._ch, CultureInfo.InvariantCulture);
}
if ((optionsAt & RegexOptions.RightToLeft) == 0)
{
if (at._type == One)
prev._str += at._ch.ToString();
else
prev._str += at._str;
}
else
{
if (at._type == One)
prev._str = at._ch.ToString() + prev._str;
else
prev._str = at._str + prev._str;
}
}
else if (at._type == Empty)
{
j--;
}
else
{
wasLastString = false;
}
}
if (j < i)
_children.RemoveRange(j, i - j);
return StripEnation(Empty);
}
internal RegexNode MakeQuantifier(bool lazy, int min, int max)
{
RegexNode result;
if (min == 0 && max == 0)
return new RegexNode(Empty, _options);
if (min == 1 && max == 1)
return this;
switch (_type)
{
case One:
case Notone:
case Set:
MakeRep(lazy ? Onelazy : Oneloop, min, max);
return this;
default:
result = new RegexNode(lazy ? Lazyloop : Loop, _options, min, max);
result.AddChild(this);
return result;
}
}
internal void AddChild(RegexNode newChild)
{
RegexNode reducedChild;
if (_children == null)
_children = new List<RegexNode>(4);
reducedChild = newChild.Reduce();
_children.Add(reducedChild);
reducedChild._next = this;
}
internal RegexNode Child(int i)
{
return _children[i];
}
internal int ChildCount()
{
return _children == null ? 0 : _children.Count;
}
internal int Type()
{
return _type;
}
#if DEBUG
internal static readonly string[] TypeStr = new string[] {
"Onerep", "Notonerep", "Setrep",
"Oneloop", "Notoneloop", "Setloop",
"Onelazy", "Notonelazy", "Setlazy",
"One", "Notone", "Set",
"Multi", "Ref",
"Bol", "Eol", "Boundary", "Nonboundary",
"ECMABoundary", "NonECMABoundary",
"Beginning", "Start", "EndZ", "End",
"Nothing", "Empty",
"Alternate", "Concatenate",
"Loop", "Lazyloop",
"Capture", "Group", "Require", "Prevent", "Greedy",
"Testref", "Testgroup"};
internal string Description()
{
StringBuilder ArgSb = new StringBuilder();
ArgSb.Append(TypeStr[_type]);
if ((_options & RegexOptions.ExplicitCapture) != 0)
ArgSb.Append("-C");
if ((_options & RegexOptions.IgnoreCase) != 0)
ArgSb.Append("-I");
if ((_options & RegexOptions.RightToLeft) != 0)
ArgSb.Append("-L");
if ((_options & RegexOptions.Multiline) != 0)
ArgSb.Append("-M");
if ((_options & RegexOptions.Singleline) != 0)
ArgSb.Append("-S");
if ((_options & RegexOptions.IgnorePatternWhitespace) != 0)
ArgSb.Append("-X");
if ((_options & RegexOptions.ECMAScript) != 0)
ArgSb.Append("-E");
switch (_type)
{
case Oneloop:
case Notoneloop:
case Onelazy:
case Notonelazy:
case One:
case Notone:
ArgSb.Append("(Ch = " + RegexCharClass.CharDescription(_ch) + ")");
break;
case Capture:
ArgSb.Append("(index = " + _m.ToString(CultureInfo.InvariantCulture) + ", unindex = " + _n.ToString(CultureInfo.InvariantCulture) + ")");
break;
case Ref:
case Testref:
ArgSb.Append("(index = " + _m.ToString(CultureInfo.InvariantCulture) + ")");
break;
case Multi:
ArgSb.Append("(String = " + _str + ")");
break;
case Set:
case Setloop:
case Setlazy:
ArgSb.Append("(Set = " + RegexCharClass.SetDescription(_str) + ")");
break;
}
switch (_type)
{
case Oneloop:
case Notoneloop:
case Onelazy:
case Notonelazy:
case Setloop:
case Setlazy:
case Loop:
case Lazyloop:
ArgSb.Append("(Min = " + _m.ToString(CultureInfo.InvariantCulture) + ", Max = " + (_n == int.MaxValue ? "inf" : Convert.ToString(_n, CultureInfo.InvariantCulture)) + ")");
break;
}
return ArgSb.ToString();
}
internal const string Space = " ";
internal void Dump()
{
List<int> Stack = new List<int>();
RegexNode CurNode;
int CurChild;
CurNode = this;
CurChild = 0;
Debug.WriteLine(CurNode.Description());
for (; ;)
{
if (CurNode._children != null && CurChild < CurNode._children.Count)
{
Stack.Add(CurChild + 1);
CurNode = CurNode._children[CurChild];
CurChild = 0;
int Depth = Stack.Count;
if (Depth > 32)
Depth = 32;
Debug.WriteLine(Space.Substring(0, Depth) + CurNode.Description());
}
else
{
if (Stack.Count == 0)
break;
CurChild = Stack[Stack.Count - 1];
Stack.RemoveAt(Stack.Count - 1);
CurNode = CurNode._next;
}
}
}
#endif
}
}
| |
// Copyright (c) 2011, Eric Maupin
// 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 Gablarski nor the names of its
// contributors may be used to endorse or promote products
// or services derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
// AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Security;
namespace Gablarski.OpenAL
{
[SuppressUnmanagedCodeSecurity]
public class SourceBuffer
: IDisposable, IEquatable<SourceBuffer>
{
internal SourceBuffer (uint bufferID)
{
this.bufferID = bufferID;
}
public int Frequency
{
get
{
int fs;
alGetBufferi (this.bufferID, ALEnum.AL_FREQUENCY, out fs);
OpenAL.ErrorCheck();
return fs;
}
}
public void Buffer (byte[] data, OpenALAudioFormat format, uint frequency)
{
alBufferData (this.bufferID, format, data, data.Length, frequency);
OpenAL.ErrorCheck ();
}
bool IEquatable<SourceBuffer>.Equals (SourceBuffer other)
{
return other.bufferID == this.bufferID;
}
public override bool Equals (object obj)
{
var b = (obj as SourceBuffer);
if (b == null)
return false;
else
return (this == b);
}
public override int GetHashCode()
{
return this.bufferID.GetHashCode();
}
public static bool operator ==(SourceBuffer buffer1, SourceBuffer buffer2)
{
if (Object.ReferenceEquals (buffer1, null) && Object.ReferenceEquals (buffer2, null))
return true;
else if (Object.ReferenceEquals (buffer1, null))
return false;
else
return (buffer1.bufferID == buffer2.bufferID);
}
public static bool operator !=(SourceBuffer buffer1, SourceBuffer buffer2)
{
return !(buffer1 == buffer2);
}
#region IDisposable Members
private bool disposed;
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
lock (lck)
{
if (this.disposed)
return;
OpenAL.DebugFormat ("Destroying source buffer {0}", this.bufferID);
alDeleteBuffers (1, new[] { this.bufferID });
Buffers.Remove (this.bufferID);
this.disposed = true;
}
}
~SourceBuffer()
{
Dispose (false);
}
#endregion
internal readonly uint bufferID;
public static SourceBuffer Generate ()
{
return Generate (1)[0];
}
public static SourceBuffer[] Generate (int count)
{
OpenAL.DebugFormat ("Generating {0} source buffers", count);
lock (lck)
{
if (Buffers == null)
Buffers = new Dictionary<uint, SourceBuffer> (count);
SourceBuffer[] buffers = new SourceBuffer[count];
uint[] bufferIDs = new uint[count];
alGenBuffers (count, bufferIDs);
OpenAL.ErrorCheck ();
for (int i = 0; i < count; ++i)
{
OpenAL.DebugFormat ("Generated source buffer {0}", bufferIDs[i]);
buffers[i] = new SourceBuffer (bufferIDs[i]);
Buffers.Add (buffers[i].bufferID, buffers[i]);
}
return buffers;
}
}
public static void Clear()
{
lock (lck) {
if (Buffers == null)
return;
foreach (SourceBuffer buffer in Buffers.Values.ToArray())
buffer.Dispose();
Buffers.Clear();
}
}
//public static void Delete (this IEnumerable<SourceBuffer> self)
//{
// uint[] bufferIDs = self.Select (b => b.bufferID).ToArray ();
// alDeleteBuffers (bufferIDs.Length, bufferIDs);
// OpenAL.ErrorCheck ();
//}
#region Imports
[DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void alGetBufferi (uint bufferID, ALEnum property, out int value);
[DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void alGenBuffers (int count, uint[] bufferIDs);
[DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void alBufferData (uint bufferID, OpenALAudioFormat format, byte[] data, int byteSize, uint frequency);
[DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void alDeleteBuffers (int numBuffers, uint[] bufferIDs);
#endregion
private static readonly object lck = new object ();
private static Dictionary<uint, SourceBuffer> Buffers
{
get;
set;
}
internal static SourceBuffer GetBuffer (uint bufferID)
{
lock (lck)
{
return Buffers[bufferID];
}
}
}
}
| |
//
// UUEncoder.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 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;
namespace MimeKit.Encodings {
/// <summary>
/// Incrementally encodes content using the Unix-to-Unix encoding.
/// </summary>
/// <remarks>
/// <para>The UUEncoding is an encoding that predates MIME and was used to encode
/// binary content such as images and other types of multi-media to ensure
/// that the data remained intact when sent via 7bit transports such as SMTP.</para>
/// <para>These days, the UUEncoding has largely been deprecated in favour of
/// the base64 encoding, however, some older mail clients still use it.</para>
/// </remarks>
public class UUEncoder : IMimeEncoder
{
const int MaxInputPerLine = 45;
const int MaxOutputPerLine = ((MaxInputPerLine / 3) * 4) + 2;
readonly byte[] uubuf = new byte[60];
uint saved;
byte nsaved;
byte uulen;
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Encodings.UUEncoder"/> class.
/// </summary>
/// <remarks>
/// Creates a new Unix-to-Unix encoder.
/// </remarks>
public UUEncoder ()
{
}
/// <summary>
/// Clone the <see cref="UUEncoder"/> with its current state.
/// </summary>
/// <remarks>
/// Creates a new <see cref="UUEncoder"/> with exactly the same state as the current encoder.
/// </remarks>
/// <returns>A new <see cref="UUEncoder"/> with identical state.</returns>
public IMimeEncoder Clone ()
{
var encoder = new UUEncoder ();
Buffer.BlockCopy (uubuf, 0, encoder.uubuf, 0, uubuf.Length);
encoder.nsaved = nsaved;
encoder.saved = saved;
encoder.uulen = uulen;
return encoder;
}
/// <summary>
/// Gets the encoding.
/// </summary>
/// <remarks>
/// Gets the encoding that the encoder supports.
/// </remarks>
/// <value>The encoding.</value>
public ContentEncoding Encoding {
get { return ContentEncoding.UUEncode; }
}
/// <summary>
/// Estimates the length of the output.
/// </summary>
/// <remarks>
/// Estimates the number of bytes needed to encode the specified number of input bytes.
/// </remarks>
/// <returns>The estimated output length.</returns>
/// <param name="inputLength">The input length.</param>
public int EstimateOutputLength (int inputLength)
{
return (((inputLength + 2) / MaxInputPerLine) * MaxOutputPerLine) + MaxOutputPerLine + 2;
}
void ValidateArguments (byte[] input, int startIndex, int length, byte[] output)
{
if (input == null)
throw new ArgumentNullException ("input");
if (startIndex < 0 || startIndex > input.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || length > (input.Length - startIndex))
throw new ArgumentOutOfRangeException ("length");
if (output == null)
throw new ArgumentNullException ("output");
if (output.Length < EstimateOutputLength (length))
throw new ArgumentException ("The output buffer is not large enough to contain the encoded input.", "output");
}
static byte Encode (int c)
{
return c != 0 ? (byte) (c + 0x20) : (byte) '`';
}
unsafe int Encode (byte* input, int length, byte[] outbuf, byte* output, byte *uuptr)
{
if (length == 0)
return 0;
byte* inend = input + length;
byte* outptr = output;
byte* inptr = input;
byte* bufptr;
byte b0, b1, b2;
if ((length + uulen) < 45) {
// not enough input to write a full uuencoded line
bufptr = uuptr + ((uulen / 3) * 4);
} else {
bufptr = outptr + 1;
if (uulen > 0) {
// copy the previous call's uubuf to output
int n = (uulen / 3) * 4;
Buffer.BlockCopy (uubuf, 0, outbuf, (int) (bufptr - output), n);
bufptr += n;
}
}
if (nsaved == 2) {
b0 = (byte) ((saved >> 8) & 0xFF);
b1 = (byte) (saved & 0xFF);
b2 = *inptr++;
nsaved = 0;
saved = 0;
// convert 3 input bytes into 4 uuencoded bytes
*bufptr++ = Encode ((b0 >> 2) & 0x3F);
*bufptr++ = Encode (((b0 << 4) | ((b1 >> 4) & 0x0F)) & 0x3F);
*bufptr++ = Encode (((b1 << 2) | ((b2 >> 6) & 0x03)) & 0x3F);
*bufptr++ = Encode (b2 & 0x3F);
uulen += 3;
} else if (nsaved == 1) {
if ((inptr + 2) < inend) {
b0 = (byte) (saved & 0xFF);
b1 = *inptr++;
b2 = *inptr++;
nsaved = 0;
saved = 0;
// convert 3 input bytes into 4 uuencoded bytes
*bufptr++ = Encode ((b0 >> 2) & 0x3F);
*bufptr++ = Encode (((b0 << 4) | ((b1 >> 4) & 0x0F)) & 0x3F);
*bufptr++ = Encode (((b1 << 2) | ((b2 >> 6) & 0x03)) & 0x3F);
*bufptr++ = Encode (b2 & 0x3F);
uulen += 3;
} else {
while (inptr < inend) {
saved = (saved << 8) | *inptr++;
nsaved++;
}
}
}
while (inptr < inend) {
while (uulen < 45 && (inptr + 3) <= inend) {
b0 = *inptr++;
b1 = *inptr++;
b2 = *inptr++;
// convert 3 input bytes into 4 uuencoded bytes
*bufptr++ = Encode ((b0 >> 2) & 0x3F);
*bufptr++ = Encode (((b0 << 4) | ((b1 >> 4) & 0x0F)) & 0x3F);
*bufptr++ = Encode (((b1 << 2) | ((b2 >> 6) & 0x03)) & 0x3F);
*bufptr++ = Encode (b2 & 0x3F);
uulen += 3;
}
if (uulen >= 45) {
// output the uu line length
*outptr = Encode (uulen);
outptr += ((uulen / 3) * 4) + 1;
*outptr++ = (byte) '\n';
uulen = 0;
if ((inptr + 45) <= inend) {
// we have enough input to output another full line
bufptr = outptr + 1;
} else {
bufptr = uuptr;
}
} else {
// not enough input to continue...
for (nsaved = 0, saved = 0; inptr < inend; nsaved++)
saved = (saved << 8) | *inptr++;
}
}
return (int) (outptr - output);
}
/// <summary>
/// Encodes the specified input into the output buffer.
/// </summary>
/// <remarks>
/// <para>Encodes the specified input into the output buffer.</para>
/// <para>The output buffer should be large enough to hold all of the
/// encoded input. For estimating the size needed for the output buffer,
/// see <see cref="EstimateOutputLength"/>.</para>
/// </remarks>
/// <returns>The number of bytes written to the output buffer.</returns>
/// <param name="input">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The length of the input buffer.</param>
/// <param name="output">The output buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="input"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="output"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the <paramref name="input"/> byte array.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="output"/> is not large enough to contain the encoded content.</para>
/// <para>Use the <see cref="EstimateOutputLength"/> method to properly determine the
/// necessary length of the <paramref name="output"/> byte array.</para>
/// </exception>
public int Encode (byte[] input, int startIndex, int length, byte[] output)
{
ValidateArguments (input, startIndex, length, output);
unsafe {
fixed (byte* inptr = input, outptr = output, uuptr = uubuf) {
return Encode (inptr + startIndex, length, output, outptr, uuptr);
}
}
}
unsafe int Flush (byte* input, int length, byte[] outbuf, byte* output, byte* uuptr)
{
byte* outptr = output;
if (length > 0)
outptr += Encode (input, length, outbuf, output, uuptr);
byte* bufptr = uuptr + ((uulen / 3) * 4);
byte uufill = 0;
if (nsaved > 0) {
while (nsaved < 3) {
saved <<= 8;
uufill++;
nsaved++;
}
if (nsaved == 3) {
// convert 3 input bytes into 4 uuencoded bytes
byte b0, b1, b2;
b0 = (byte) ((saved >> 16) & 0xFF);
b1 = (byte) ((saved >> 8) & 0xFF);
b2 = (byte) (saved & 0xFF);
*bufptr++ = Encode ((b0 >> 2) & 0x3F);
*bufptr++ = Encode (((b0 << 4) | ((b1 >> 4) & 0x0F)) & 0x3F);
*bufptr++ = Encode (((b1 << 2) | ((b2 >> 6) & 0x03)) & 0x3F);
*bufptr++ = Encode (b2 & 0x3F);
uulen += 3;
nsaved = 0;
saved = 0;
}
}
if (uulen > 0) {
int n = (uulen / 3) * 4;
*outptr++ = Encode ((uulen - uufill) & 0xFF);
Buffer.BlockCopy (uubuf, 0, outbuf, (int) (outptr - output), n);
outptr += n;
*outptr++ = (byte) '\n';
uulen = 0;
}
*outptr++ = Encode (uulen & 0xFF);
*outptr++ = (byte) '\n';
Reset ();
return (int) (outptr - output);
}
/// <summary>
/// Encodes the specified input into the output buffer, flushing any internal buffer state as well.
/// </summary>
/// <remarks>
/// <para>Encodes the specified input into the output buffer, flusing any internal state as well.</para>
/// <para>The output buffer should be large enough to hold all of the
/// encoded input. For estimating the size needed for the output buffer,
/// see <see cref="EstimateOutputLength"/>.</para>
/// </remarks>
/// <returns>The number of bytes written to the output buffer.</returns>
/// <param name="input">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The length of the input buffer.</param>
/// <param name="output">The output buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="input"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="output"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the <paramref name="input"/> byte array.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="output"/> is not large enough to contain the encoded content.</para>
/// <para>Use the <see cref="EstimateOutputLength"/> method to properly determine the
/// necessary length of the <paramref name="output"/> byte array.</para>
/// </exception>
public int Flush (byte[] input, int startIndex, int length, byte[] output)
{
ValidateArguments (input, startIndex, length, output);
unsafe {
fixed (byte* inptr = input, outptr = output, uuptr = uubuf) {
return Flush (inptr + startIndex, length, output, outptr, uuptr);
}
}
}
/// <summary>
/// Resets the encoder.
/// </summary>
/// <remarks>
/// Resets the state of the encoder.
/// </remarks>
public void Reset ()
{
nsaved = 0;
saved = 0;
uulen = 0;
}
}
}
| |
/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using ZXing.Common;
namespace ZXing.PDF417.Internal
{
/// <summary>
/// A Bounding Box helper class
/// </summary>
/// <author>Guenther Grau</author>
public sealed class BoundingBox
{
private readonly BitMatrix image;
public ResultPoint TopLeft { get; private set; }
public ResultPoint TopRight { get; private set; }
public ResultPoint BottomLeft { get; private set; }
public ResultPoint BottomRight { get; private set; }
public int MinX { get; private set; }
public int MaxX { get; private set; }
public int MinY { get; private set; }
public int MaxY { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="ZXing.PDF417.Internal.BoundingBox"/> class.
/// returns null if the corner points don't match up correctly
/// </summary>
/// <param name="image">The image.</param>
/// <param name="topLeft">The top left.</param>
/// <param name="bottomLeft">The bottom left.</param>
/// <param name="topRight">The top right.</param>
/// <param name="bottomRight">The bottom right.</param>
/// <returns></returns>
public static BoundingBox Create(BitMatrix image,
ResultPoint topLeft,
ResultPoint bottomLeft,
ResultPoint topRight,
ResultPoint bottomRight)
{
if ((topLeft == null && topRight == null) ||
(bottomLeft == null && bottomRight == null) ||
(topLeft != null && bottomLeft == null) ||
(topRight != null && bottomRight == null))
{
return null;
}
return new BoundingBox(image, topLeft, bottomLeft,topRight, bottomRight);
}
/// <summary>
/// Creates the specified box.
/// </summary>
/// <param name="box">The box.</param>
/// <returns></returns>
public static BoundingBox Create(BoundingBox box)
{
return new BoundingBox(box.image, box.TopLeft, box.BottomLeft, box.TopRight, box.BottomRight);
}
/// <summary>
/// Initializes a new instance of the <see cref="ZXing.PDF417.Internal.BoundingBox"/> class.
/// Will throw an exception if the corner points don't match up correctly
/// </summary>
/// <param name="image">Image.</param>
/// <param name="topLeft">Top left.</param>
/// <param name="topRight">Top right.</param>
/// <param name="bottomLeft">Bottom left.</param>
/// <param name="bottomRight">Bottom right.</param>
private BoundingBox(BitMatrix image,
ResultPoint topLeft,
ResultPoint bottomLeft,
ResultPoint topRight,
ResultPoint bottomRight)
{
this.image = image;
this.TopLeft = topLeft;
this.TopRight = topRight;
this.BottomLeft = bottomLeft;
this.BottomRight = bottomRight;
calculateMinMaxValues();
}
/// <summary>
/// Merge two Bounding Boxes, getting the left corners of left, and the right corners of right
/// (Images should be the same)
/// </summary>
/// <param name="leftBox">Left.</param>
/// <param name="rightBox">Right.</param>
internal static BoundingBox merge(BoundingBox leftBox, BoundingBox rightBox)
{
if (leftBox == null)
return rightBox;
if (rightBox == null)
return leftBox;
return new BoundingBox(leftBox.image, leftBox.TopLeft, leftBox.BottomLeft, rightBox.TopRight, rightBox.BottomRight);
}
/// <summary>
/// Adds the missing rows.
/// </summary>
/// <returns>The missing rows.</returns>
/// <param name="missingStartRows">Missing start rows.</param>
/// <param name="missingEndRows">Missing end rows.</param>
/// <param name="isLeft">If set to <c>true</c> is left.</param>
public BoundingBox addMissingRows(int missingStartRows, int missingEndRows, bool isLeft)
{
ResultPoint newTopLeft = TopLeft;
ResultPoint newBottomLeft = BottomLeft;
ResultPoint newTopRight = TopRight;
ResultPoint newBottomRight = BottomRight;
if (missingStartRows > 0)
{
ResultPoint top = isLeft ? TopLeft : TopRight;
int newMinY = (int) top.Y - missingStartRows;
if (newMinY < 0)
{
newMinY = 0;
}
ResultPoint newTop = new ResultPoint(top.X, newMinY);
if (isLeft)
{
newTopLeft = newTop;
}
else
{
newTopRight = newTop;
}
}
if (missingEndRows > 0)
{
ResultPoint bottom = isLeft ? BottomLeft : BottomRight;
int newMaxY = (int) bottom.Y + missingEndRows;
if (newMaxY >= image.Height)
{
newMaxY = image.Height - 1;
}
ResultPoint newBottom = new ResultPoint(bottom.X, newMaxY);
if (isLeft)
{
newBottomLeft = newBottom;
}
else
{
newBottomRight = newBottom;
}
}
calculateMinMaxValues();
return new BoundingBox(image, newTopLeft, newBottomLeft, newTopRight, newBottomRight);
}
/// <summary>
/// Calculates the minimum and maximum X & Y values based on the corner points.
/// </summary>
private void calculateMinMaxValues()
{
// Constructor ensures that either Left or Right is not null
if (TopLeft == null)
{
TopLeft = new ResultPoint(0, TopRight.Y);
BottomLeft = new ResultPoint(0, BottomRight.Y);
}
else if (TopRight == null)
{
TopRight = new ResultPoint(image.Width - 1, TopLeft.Y);
BottomRight = new ResultPoint(image.Width - 1, TopLeft.Y);
}
MinX = (int) Math.Min(TopLeft.X, BottomLeft.X);
MaxX = (int) Math.Max(TopRight.X, BottomRight.X);
MinY = (int) Math.Min(TopLeft.Y, TopRight.Y);
MaxY = (int) Math.Max(BottomLeft.Y, BottomRight.Y);
}
/// <summary>
/// If we adjust the width, set a new right corner coordinate and recalculate
/// </summary>
/// <param name="bottomRight">Bottom right.</param>
internal void SetBottomRight(ResultPoint bottomRight)
{
this.BottomRight = bottomRight;
calculateMinMaxValues();
}
/*
/// <summary>
/// If we adjust the width, set a new right corner coordinate and recalculate
/// </summary>
/// <param name="topRight">Top right.</param>
internal void SetTopRight(ResultPoint topRight)
{
this.TopRight = topRight;
calculateMinMaxValues();
}
*/
}
}
| |
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 PushSystem.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using AxiomCoders.PdfTemplateEditor.Common;
using System.Xml;
namespace AxiomCoders.PdfTemplateEditor.EditorStuff
{
/// <summary>
/// This is font class used in editor. It should be used instead of regular Font everywhere in application
/// </summary>
public class EditorFont: SaveLoadMechanism
{
private Font font;
/// <summary>
/// number used for referencing on what is saved and loaded
/// </summary>
private int saveID;
/// <summary>
/// Number used for saving and loading
/// </summary>
public int SaveID
{
get { return saveID; }
set { saveID = value; }
}
/// <summary>
/// font object
/// </summary>
public Font Font
{
get { return font; }
set { font = value; }
}
/// <summary>
/// Constructor from regular font
/// </summary>
/// <param name="font"></param>
public EditorFont(Font font): this()
{
this.font = font;
}
private static int lastSaveId = 1;
/// <summary>
/// Default Constructor
/// </summary>
public EditorFont()
{
this.saveID = lastSaveId;
lastSaveId++;
}
#region SaveLoadMechanism Members
/// <summary>
/// Save font. It will create this
/// <font Name="something" StemV="20" Width="[234 34]"><EmbeddedFont>dasjdlkajsdljxlkjsaldjasldjxflj</embeddedFont></font>
/// </summary>
/// <param name="doc"></param>
/// <param name="element"></param>
public void Save(System.Xml.XmlDocument doc, System.Xml.XmlElement element)
{
// save font
XmlElement el = doc.CreateElement("Font");
XmlAttribute attr = doc.CreateAttribute("Name");
attr.Value = this.Font.Name;
el.SetAttributeNode(attr);
attr = doc.CreateAttribute("SaveID");
attr.Value = this.SaveID.ToString();
el.SetAttributeNode(attr);
// save metrics
attr = doc.CreateAttribute("EmHeight");
attr.Value = this.Font.FontFamily.GetEmHeight(this.Font.Style).ToString();
el.SetAttributeNode(attr);
attr = doc.CreateAttribute("Ascent");
attr.Value = this.Font.FontFamily.GetCellAscent(this.font.Style).ToString();
el.SetAttributeNode(attr);
attr = doc.CreateAttribute("Descent");
attr.Value = this.Font.FontFamily.GetCellDescent(this.font.Style).ToString();
el.SetAttributeNode(attr);
attr = doc.CreateAttribute("Bold");
attr.Value = this.Font.Bold ? "1" : "0";
el.SetAttributeNode(attr);
attr = doc.CreateAttribute("Italic");
attr.Value = this.Font.Italic ? "1" : "0";
el.SetAttributeNode(attr);
// Get font metrics to save some properties of font
FontMetrics metrics = new FontMetrics(this.Font);
attr = doc.CreateAttribute("EmbeddingLicense");
attr.Value = ((int)metrics.EmbeddingLicense).ToString();
el.SetAttributeNode(attr);
attr = doc.CreateAttribute("ItalicAngle");
attr.Value = metrics.ItalicAngle.ToString();
el.SetAttributeNode(attr);
attr = doc.CreateAttribute("BBoxLeft"); attr.Value = metrics.FontBBox.Left.ToString(); el.SetAttributeNode(attr);
attr = doc.CreateAttribute("BBoxRight"); attr.Value = metrics.FontBBox.Right.ToString(); el.SetAttributeNode(attr);
attr = doc.CreateAttribute("BBoxTop"); attr.Value = metrics.FontBBox.Top.ToString(); el.SetAttributeNode(attr);
attr = doc.CreateAttribute("BBoxBottom"); attr.Value = metrics.FontBBox.Bottom.ToString(); el.SetAttributeNode(attr);
attr = doc.CreateAttribute("StemV");
attr.Value = metrics.StemV.ToString();
el.SetAttributeNode(attr);
attr = doc.CreateAttribute("Flags");
attr.Value = metrics.Flags.ToString();
el.SetAttributeNode(attr);
attr = doc.CreateAttribute("FirstChar"); attr.Value = metrics.FirstChar.ToString(); el.SetAttributeNode(attr);
attr = doc.CreateAttribute("LastChar"); attr.Value = metrics.LastChar.ToString(); el.SetAttributeNode(attr);
// make glyph widths
string glyphwidth = "[ ";
for (int i = metrics.FirstChar; i <= metrics.LastChar; i++)
{
int gw = metrics.GetGlyphWidth(this.font, i);
glyphwidth += gw.ToString() + " ";
}
glyphwidth += " ]";
attr = doc.CreateAttribute("Widths"); attr.Value = glyphwidth; el.SetAttributeNode(attr);
// embedd font if not std font
if (!this.IsStandardFont)
{
byte[] fontBuffer = FontMetrics.GetFontData(this.Font);
attr = doc.CreateAttribute("EmbeddedDecodedFontLength"); attr.Value = fontBuffer.Length.ToString(); el.SetAttributeNode(attr);
XmlText textValue = doc.CreateTextNode("EmdeddedFont");
textValue.Value = Convert.ToBase64String(fontBuffer);
attr = doc.CreateAttribute("EmbeddedFontLength"); attr.Value = textValue.Value.Length.ToString(); el.SetAttributeNode(attr);
el.AppendChild(textValue);
}
element.AppendChild(el);
}
/// <summary>
/// Return true if this is standard font like Arial
/// </summary>
public bool IsStandardFont
{
get
{
if (this.Font.Name.ToLower() == "arial")
{
return true;
}
if (this.Font.Name.ToLower() == "courier")
{
return true;
}
if (this.Font.Name.ToLower() == "helvetica")
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// Load font object
/// </summary>
/// <param name="node"></param>
public void Load(System.Xml.XmlNode node)
{
UnitsManager unitMng = new UnitsManager();
this.saveID = Convert.ToInt32(node.Attributes["SaveID"].Value);
int italic = System.Convert.ToInt32(node.Attributes["Italic"].Value);
int bold = System.Convert.ToInt32(node.Attributes["Bold"].Value);
FontStyle style = FontStyle.Regular;
if (italic == 1)
{
style = FontStyle.Italic;
}
if (bold == 1)
{
style |= FontStyle.Bold;
}
this.Font = new Font(node.Attributes["Name"].Value, 12.0f, style);
}
#endregion
}
}
| |
#pragma warning disable 162,108,618
using Casanova.Prelude;
using System.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Game {public class World : MonoBehaviour{
public static int frame;
void Update () { Update(Time.deltaTime, this);
frame++; }
public bool JustEntered = true;
public void Start()
{
Boids = (
(Enumerable.Range(0,(1) + ((10) - (0))).ToList<System.Int32>()).Select(__ContextSymbol0 => new { ___b00 = __ContextSymbol0 })
.Select(__ContextSymbol1 => new Boid(new UnityEngine.Vector3(UnityEngine.Random.Range(-10,10),UnityEngine.Random.Range(-10,10),0f)))
.ToList<Boid>()).ToList<Boid>();
BoidBoss = new BoidLeader(new UnityEngine.Vector3(0f,10f,0f));
}
public BoidLeader __BoidBoss;
public BoidLeader BoidBoss{ get { return __BoidBoss; }
set{ __BoidBoss = value;
if(!value.JustEntered) __BoidBoss = value;
else{ value.JustEntered = false;
}
}
}
public List<Boid> Boids;
System.DateTime init_time = System.DateTime.Now;
public void Update(float dt, World world) {
var t = System.DateTime.Now;
BoidBoss.Update(dt, world);
for(int x0 = 0; x0 < Boids.Count; x0++) {
Boids[x0].Update(dt, world);
}
}
}
public class Boid{
public int frame;
public bool JustEntered = true;
private UnityEngine.Vector3 pos;
public int ID;
public Boid(UnityEngine.Vector3 pos)
{JustEntered = false;
frame = World.frame;
Velocity = Vector3.zero;
UnityBoid = UnityBoid.Instantiate(pos);
Separation = Vector3.zero;
Seek = Vector3.zero;
MaxVelocity = 4f;
Cohesion = Vector3.zero;
}
public UnityEngine.Vector3 Cohesion;
public System.Single MaxVelocity;
public UnityEngine.Vector3 Position{ get { return UnityBoid.Position; }
set{UnityBoid.Position = value; }
}
public UnityEngine.Vector3 Seek;
public UnityEngine.Vector3 Separation;
public UnityBoid UnityBoid;
public UnityEngine.Vector3 Velocity;
public System.Boolean enabled{ get { return UnityBoid.enabled; }
set{UnityBoid.enabled = value; }
}
public UnityEngine.GameObject gameObject{ get { return UnityBoid.gameObject; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnityBoid.hideFlags; }
set{UnityBoid.hideFlags = value; }
}
public System.Boolean isActiveAndEnabled{ get { return UnityBoid.isActiveAndEnabled; }
}
public System.String name{ get { return UnityBoid.name; }
set{UnityBoid.name = value; }
}
public System.String tag{ get { return UnityBoid.tag; }
set{UnityBoid.tag = value; }
}
public UnityEngine.Transform transform{ get { return UnityBoid.transform; }
}
public System.Boolean useGUILayout{ get { return UnityBoid.useGUILayout; }
set{UnityBoid.useGUILayout = value; }
}
public System.Single ___max_dist10;
public List<UnityEngine.Vector3> ___positions10;
public List<UnityEngine.Vector3> ___positions11;
public UnityEngine.Vector3 ___position_total10;
public System.Int32 ___neighbours10;
public UnityEngine.Vector3 ___average10;
public UnityEngine.Vector3 ___desired10;
public UnityEngine.Vector3 ___desired11;
public UnityEngine.Vector3 ___steer10;
public System.Single ___max_dist21;
public List<UnityEngine.Vector3> ___list_neighbours20;
public List<UnityEngine.Vector3> ___list_neighbours21;
public UnityEngine.Vector3 ___list_position_neighbours20;
public UnityEngine.Vector3 ___average21;
public UnityEngine.Vector3 ___p20;
public void Update(float dt, World world) {
frame = World.frame;
this.Rule0(dt, world);
this.Rule1(dt, world);
this.Rule2(dt, world);
}
int s0=-1;
public void Rule0(float dt, World world){
switch (s0)
{
case -1:
Position = ((Position) + (((Velocity) * (dt))));
s0 = -1;
return;
default: return;}}
int s1=-1;
public void Rule1(float dt, World world){
switch (s1)
{
case -1:
___max_dist10 = 5f;
___positions10 = (
(world.Boids).Select(__ContextSymbol2 => new { ___boid10 = __ContextSymbol2 })
.Where(__ContextSymbol3 => ((!(((__ContextSymbol3.___boid10) == (this)))) && (((___max_dist10) > (UnityEngine.Vector3.Distance(this.Position,__ContextSymbol3.___boid10.Position))))))
.Select(__ContextSymbol4 => __ContextSymbol4.___boid10.Position)
.ToList<UnityEngine.Vector3>()).ToList<UnityEngine.Vector3>();
___positions11 = new Cons<UnityEngine.Vector3>(world.BoidBoss.Position, (___positions10)).ToList<UnityEngine.Vector3>();
___position_total10 = (
(___positions11).Select(__ContextSymbol5 => new { ___boid11 = __ContextSymbol5 })
.Select(__ContextSymbol6 => __ContextSymbol6.___boid11)
.Aggregate(default(UnityEngine.Vector3), (acc, __x) => acc + __x));
___neighbours10 = ___positions11.Count;
___average10 = new UnityEngine.Vector3((___position_total10.x) / (___neighbours10),(___position_total10.y) / (___neighbours10),0f);
___desired10 = ((___average10) - (Position));
___desired11 = ((___desired10.normalized) * (4f));
___steer10 = ((___desired11) - (Velocity));
Velocity = ((Velocity) + (((((___steer10.normalized) * (3f))) * (dt))));
s1 = -1;
return;
default: return;}}
int s2=-1;
public void Rule2(float dt, World world){
switch (s2)
{
case -1:
___max_dist21 = 5f;
___list_neighbours20 = (
(world.Boids).Select(__ContextSymbol8 => new { ___boid22 = __ContextSymbol8 })
.Where(__ContextSymbol9 => ((!(((__ContextSymbol9.___boid22) == (this)))) && (((___max_dist21) > (UnityEngine.Vector3.Distance(Position,__ContextSymbol9.___boid22.Position))))))
.Select(__ContextSymbol10 => __ContextSymbol10.___boid22.Position)
.ToList<UnityEngine.Vector3>()).ToList<UnityEngine.Vector3>();
if(((___max_dist21) > (UnityEngine.Vector3.Distance(world.BoidBoss.Position,Position))))
{
___list_neighbours21 = new Cons<UnityEngine.Vector3>(world.BoidBoss.Position, (___list_neighbours20)).ToList<UnityEngine.Vector3>(); }else
{
___list_neighbours21 = ___list_neighbours20; }
___list_position_neighbours20 = (
(___list_neighbours21).Select(__ContextSymbol11 => new { ___boid23 = __ContextSymbol11 })
.Select(__ContextSymbol12 => __ContextSymbol12.___boid23)
.Aggregate(default(UnityEngine.Vector3), (acc, __x) => acc + __x));
___average21 = new UnityEngine.Vector3((___list_position_neighbours20.x) / (___list_neighbours21.Count),(___list_position_neighbours20.y) / (___list_neighbours21.Count),0f);
___p20 = ((Position) - (___average21));
Velocity = ((Velocity) + (((((___p20.normalized) * (5f))) * (dt))));
s2 = -1;
return;
default: return;}}
}
public class BoidLeader{
public int frame;
public bool JustEntered = true;
private UnityEngine.Vector3 position;
public int ID;
public BoidLeader(UnityEngine.Vector3 position)
{JustEntered = false;
frame = World.frame;
UnityBoidLeader = UnityBoidLeader.Instantiate(position);
Start = true;
MaxVelocity = 6f;
Camera = UnityCamera.Find();
}
public UnityEngine.Vector3 Backward{ get { return UnityBoidLeader.Backward; }
}
public UnityCamera Camera;
public UnityEngine.Vector3 Down{ get { return UnityBoidLeader.Down; }
}
public UnityEngine.Vector3 Forward{ get { return UnityBoidLeader.Forward; }
}
public UnityEngine.Vector3 Left{ get { return UnityBoidLeader.Left; }
}
public System.Single MaxVelocity;
public UnityEngine.Vector3 Position{ get { return UnityBoidLeader.Position; }
set{UnityBoidLeader.Position = value; }
}
public UnityEngine.Vector3 Right{ get { return UnityBoidLeader.Right; }
}
public UnityEngine.Quaternion Rotation{ get { return UnityBoidLeader.Rotation; }
set{UnityBoidLeader.Rotation = value; }
}
public System.Boolean Start;
public UnityBoidLeader UnityBoidLeader;
public UnityEngine.Vector3 Up{ get { return UnityBoidLeader.Up; }
}
public System.Boolean enabled{ get { return UnityBoidLeader.enabled; }
set{UnityBoidLeader.enabled = value; }
}
public UnityEngine.GameObject gameObject{ get { return UnityBoidLeader.gameObject; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnityBoidLeader.hideFlags; }
set{UnityBoidLeader.hideFlags = value; }
}
public System.Boolean isActiveAndEnabled{ get { return UnityBoidLeader.isActiveAndEnabled; }
}
public System.String name{ get { return UnityBoidLeader.name; }
set{UnityBoidLeader.name = value; }
}
public System.String tag{ get { return UnityBoidLeader.tag; }
set{UnityBoidLeader.tag = value; }
}
public UnityEngine.Transform transform{ get { return UnityBoidLeader.transform; }
}
public System.Boolean useGUILayout{ get { return UnityBoidLeader.useGUILayout; }
set{UnityBoidLeader.useGUILayout = value; }
}
public void Update(float dt, World world) {
frame = World.frame;
this.Rule0(dt, world);
this.Rule1(dt, world);
this.Rule2(dt, world);
this.Rule3(dt, world);
this.Rule4(dt, world);
}
int s0=-1;
public void Rule0(float dt, World world){
switch (s0)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.S)))
{
s0 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Down) * (dt))) * (MaxVelocity))));
s0 = -1;
return;
default: return;}}
int s1=-1;
public void Rule1(float dt, World world){
switch (s1)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.W)))
{
s1 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Up) * (dt))) * (MaxVelocity))));
s1 = -1;
return;
default: return;}}
int s2=-1;
public void Rule2(float dt, World world){
switch (s2)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.D)))
{
s2 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Right) * (dt))) * (MaxVelocity))));
s2 = -1;
return;
default: return;}}
int s3=-1;
public void Rule3(float dt, World world){
switch (s3)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.A)))
{
s3 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Left) * (dt))) * (MaxVelocity))));
s3 = -1;
return;
default: return;}}
int s4=-1;
public void Rule4(float dt, World world){
switch (s4)
{
case -1:
if(!(Start))
{
s4 = -1;
return; }else
{
goto case 0; }
case 0:
Camera.Position = ((Position) + (new UnityEngine.Vector3(0f,1f,-20f)));
Start = false;
s4 = -1;
return;
default: return;}}
}
}
| |
// 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 0.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsHead
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestHeadTestService : ServiceClient<AutoRestHeadTestService>, IAutoRestHeadTestService, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// The management credentials for Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// The retry timeout for Long Running Operations.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
public virtual IHttpSuccessOperations HttpSuccess { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
public AutoRestHeadTestService() : base()
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
/// <param name='handlers'>
/// Optional. The set of delegating handlers to insert in the http
/// client pipeline.
/// </param>
public AutoRestHeadTestService(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The set of delegating handlers to insert in the http
/// client pipeline.
/// </param>
public AutoRestHeadTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The set of delegating handlers to insert in the http
/// client pipeline.
/// </param>
public AutoRestHeadTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. The management credentials for Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The set of delegating handlers to insert in the http
/// client pipeline.
/// </param>
public AutoRestHeadTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. The management credentials for Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The set of delegating handlers to insert in the http
/// client pipeline.
/// </param>
public AutoRestHeadTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.HttpSuccess = new HttpSuccessOperations(this);
this.BaseUri = new Uri("http://localhost");
this.AcceptLanguage = "en-US";
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings = new JsonSerializerSettings{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Client.Params.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Org.Apache.Http.Client.Params
{
/// <summary>
/// <para>Parameter names for the HttpClient module. This does not include parameters for informational units HttpAuth, HttpCookie, or HttpConn.</para><para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/params/ClientPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/ClientPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IClientPNamesConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Defines the class name of the default org.apache.http.conn.ClientConnectionManager </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// CONNECTION_MANAGER_FACTORY_CLASS_NAME
/// </java-name>
[Dot42.DexImport("CONNECTION_MANAGER_FACTORY_CLASS_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string CONNECTION_MANAGER_FACTORY_CLASS_NAME = "http.connection-manager.factory-class-name";
/// <summary>
/// <para>Defines the factory to create a default org.apache.http.conn.ClientConnectionManager. </para><para>This parameters expects a value of type org.apache.http.conn.ClientConnectionManagerFactory. </para>
/// </summary>
/// <java-name>
/// CONNECTION_MANAGER_FACTORY
/// </java-name>
[Dot42.DexImport("CONNECTION_MANAGER_FACTORY", "Ljava/lang/String;", AccessFlags = 25)]
public const string CONNECTION_MANAGER_FACTORY = "http.connection-manager.factory-object";
/// <summary>
/// <para>Defines whether redirects should be handled automatically </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// HANDLE_REDIRECTS
/// </java-name>
[Dot42.DexImport("HANDLE_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)]
public const string HANDLE_REDIRECTS = "http.protocol.handle-redirects";
/// <summary>
/// <para>Defines whether relative redirects should be rejected. </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// REJECT_RELATIVE_REDIRECT
/// </java-name>
[Dot42.DexImport("REJECT_RELATIVE_REDIRECT", "Ljava/lang/String;", AccessFlags = 25)]
public const string REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect";
/// <summary>
/// <para>Defines the maximum number of redirects to be followed. The limit on number of redirects is intended to prevent infinite loops. </para><para>This parameter expects a value of type Integer. </para>
/// </summary>
/// <java-name>
/// MAX_REDIRECTS
/// </java-name>
[Dot42.DexImport("MAX_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_REDIRECTS = "http.protocol.max-redirects";
/// <summary>
/// <para>Defines whether circular redirects (redirects to the same location) should be allowed. The HTTP spec is not sufficiently clear whether circular redirects are permitted, therefore optionally they can be enabled </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// ALLOW_CIRCULAR_REDIRECTS
/// </java-name>
[Dot42.DexImport("ALLOW_CIRCULAR_REDIRECTS", "Ljava/lang/String;", AccessFlags = 25)]
public const string ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects";
/// <summary>
/// <para>Defines whether authentication should be handled automatically. </para><para>This parameter expects a value of type Boolean. </para>
/// </summary>
/// <java-name>
/// HANDLE_AUTHENTICATION
/// </java-name>
[Dot42.DexImport("HANDLE_AUTHENTICATION", "Ljava/lang/String;", AccessFlags = 25)]
public const string HANDLE_AUTHENTICATION = "http.protocol.handle-authentication";
/// <summary>
/// <para>Defines the name of the cookie specification to be used for HTTP state management. </para><para>This parameter expects a value of type String. </para>
/// </summary>
/// <java-name>
/// COOKIE_POLICY
/// </java-name>
[Dot42.DexImport("COOKIE_POLICY", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE_POLICY = "http.protocol.cookie-policy";
/// <summary>
/// <para>Defines the virtual host name. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para>
/// </summary>
/// <java-name>
/// VIRTUAL_HOST
/// </java-name>
[Dot42.DexImport("VIRTUAL_HOST", "Ljava/lang/String;", AccessFlags = 25)]
public const string VIRTUAL_HOST = "http.virtual-host";
/// <summary>
/// <para>Defines the request headers to be sent per default with each request. </para><para>This parameter expects a value of type java.util.Collection. The collection is expected to contain org.apache.http.Headers. </para>
/// </summary>
/// <java-name>
/// DEFAULT_HEADERS
/// </java-name>
[Dot42.DexImport("DEFAULT_HEADERS", "Ljava/lang/String;", AccessFlags = 25)]
public const string DEFAULT_HEADERS = "http.default-headers";
/// <summary>
/// <para>Defines the default host. The default value will be used if the target host is not explicitly specified in the request URI. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para>
/// </summary>
/// <java-name>
/// DEFAULT_HOST
/// </java-name>
[Dot42.DexImport("DEFAULT_HOST", "Ljava/lang/String;", AccessFlags = 25)]
public const string DEFAULT_HOST = "http.default-host";
}
/// <summary>
/// <para>Parameter names for the HttpClient module. This does not include parameters for informational units HttpAuth, HttpCookie, or HttpConn.</para><para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/params/ClientPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/ClientPNames", AccessFlags = 1537)]
public partial interface IClientPNames
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>An adaptor for accessing HTTP client parameters in HttpParams.</para><para><para></para><para></para><title>Revision:</title><para>659595 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/params/HttpClientParams
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/HttpClientParams", AccessFlags = 33)]
public partial class HttpClientParams
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal HttpClientParams() /* MethodBuilder.Create */
{
}
/// <java-name>
/// isRedirecting
/// </java-name>
[Dot42.DexImport("isRedirecting", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)]
public static bool IsRedirecting(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// setRedirecting
/// </java-name>
[Dot42.DexImport("setRedirecting", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)]
public static void SetRedirecting(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */
{
}
/// <java-name>
/// isAuthenticating
/// </java-name>
[Dot42.DexImport("isAuthenticating", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)]
public static bool IsAuthenticating(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// setAuthenticating
/// </java-name>
[Dot42.DexImport("setAuthenticating", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)]
public static void SetAuthenticating(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getCookiePolicy
/// </java-name>
[Dot42.DexImport("getCookiePolicy", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)]
public static string GetCookiePolicy(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// setCookiePolicy
/// </java-name>
[Dot42.DexImport("setCookiePolicy", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)]
public static void SetCookiePolicy(global::Org.Apache.Http.Params.IHttpParams @params, string cookiePolicy) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Collected parameter names for the HttpClient module. This interface combines the parameter definitions of the HttpClient module and all dependency modules or informational units. It does not define additional parameter names, but references other interfaces defining parameter names. <br></br> This interface is meant as a navigation aid for developers. When referring to parameter names, you should use the interfaces in which the respective constants are actually defined.</para><para><para></para><title>Revision:</title><para>576078 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/params/AllClientPNames
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/AllClientPNames", AccessFlags = 1537)]
public partial interface IAllClientPNames : global::Org.Apache.Http.Params.ICoreConnectionPNames, global::Org.Apache.Http.Params.ICoreProtocolPNames, global::Org.Apache.Http.Client.Params.IClientPNames, global::Org.Apache.Http.Auth.Params.IAuthPNames, global::Org.Apache.Http.Cookie.Params.ICookieSpecPNames, global::Org.Apache.Http.Conn.Params.IConnConnectionPNames, global::Org.Apache.Http.Conn.Params.IConnManagerPNames, global::Org.Apache.Http.Conn.Params.IConnRoutePNames
/* scope: __dot42__ */
{
}
/// <java-name>
/// org/apache/http/client/params/CookiePolicy
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/CookiePolicy", AccessFlags = 49)]
public sealed partial class CookiePolicy
/* scope: __dot42__ */
{
/// <summary>
/// <para>The policy that provides high degree of compatibilty with common cookie management of popular HTTP agents. </para>
/// </summary>
/// <java-name>
/// BROWSER_COMPATIBILITY
/// </java-name>
[Dot42.DexImport("BROWSER_COMPATIBILITY", "Ljava/lang/String;", AccessFlags = 25)]
public const string BROWSER_COMPATIBILITY = "compatibility";
/// <summary>
/// <para>The Netscape cookie draft compliant policy. </para>
/// </summary>
/// <java-name>
/// NETSCAPE
/// </java-name>
[Dot42.DexImport("NETSCAPE", "Ljava/lang/String;", AccessFlags = 25)]
public const string NETSCAPE = "netscape";
/// <summary>
/// <para>The RFC 2109 compliant policy. </para>
/// </summary>
/// <java-name>
/// RFC_2109
/// </java-name>
[Dot42.DexImport("RFC_2109", "Ljava/lang/String;", AccessFlags = 25)]
public const string RFC_2109 = "rfc2109";
/// <summary>
/// <para>The RFC 2965 compliant policy. </para>
/// </summary>
/// <java-name>
/// RFC_2965
/// </java-name>
[Dot42.DexImport("RFC_2965", "Ljava/lang/String;", AccessFlags = 25)]
public const string RFC_2965 = "rfc2965";
/// <summary>
/// <para>The default 'best match' policy. </para>
/// </summary>
/// <java-name>
/// BEST_MATCH
/// </java-name>
[Dot42.DexImport("BEST_MATCH", "Ljava/lang/String;", AccessFlags = 25)]
public const string BEST_MATCH = "best-match";
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal CookiePolicy() /* MethodBuilder.Create */
{
}
}
/// <java-name>
/// org/apache/http/client/params/AuthPolicy
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/AuthPolicy", AccessFlags = 49)]
public sealed partial class AuthPolicy
/* scope: __dot42__ */
{
/// <summary>
/// <para>The NTLM scheme is a proprietary Microsoft Windows Authentication protocol (considered to be the most secure among currently supported authentication schemes). </para>
/// </summary>
/// <java-name>
/// NTLM
/// </java-name>
[Dot42.DexImport("NTLM", "Ljava/lang/String;", AccessFlags = 25)]
public const string NTLM = "NTLM";
/// <summary>
/// <para>Digest authentication scheme as defined in RFC2617. </para>
/// </summary>
/// <java-name>
/// DIGEST
/// </java-name>
[Dot42.DexImport("DIGEST", "Ljava/lang/String;", AccessFlags = 25)]
public const string DIGEST = "Digest";
/// <summary>
/// <para>Basic authentication scheme as defined in RFC2617 (considered inherently insecure, but most widely supported) </para>
/// </summary>
/// <java-name>
/// BASIC
/// </java-name>
[Dot42.DexImport("BASIC", "Ljava/lang/String;", AccessFlags = 25)]
public const string BASIC = "Basic";
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal AuthPolicy() /* MethodBuilder.Create */
{
}
}
/// <java-name>
/// org/apache/http/client/params/ClientParamBean
/// </java-name>
[Dot42.DexImport("org/apache/http/client/params/ClientParamBean", AccessFlags = 33)]
public partial class ClientParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)]
public ClientParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setConnectionManagerFactoryClassName
/// </java-name>
[Dot42.DexImport("setConnectionManagerFactoryClassName", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetConnectionManagerFactoryClassName(string factory) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setConnectionManagerFactory
/// </java-name>
[Dot42.DexImport("setConnectionManagerFactory", "(Lorg/apache/http/conn/ClientConnectionManagerFactory;)V", AccessFlags = 1)]
public virtual void SetConnectionManagerFactory(global::Org.Apache.Http.Conn.IClientConnectionManagerFactory factory) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setHandleRedirects
/// </java-name>
[Dot42.DexImport("setHandleRedirects", "(Z)V", AccessFlags = 1)]
public virtual void SetHandleRedirects(bool handle) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setRejectRelativeRedirect
/// </java-name>
[Dot42.DexImport("setRejectRelativeRedirect", "(Z)V", AccessFlags = 1)]
public virtual void SetRejectRelativeRedirect(bool reject) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setMaxRedirects
/// </java-name>
[Dot42.DexImport("setMaxRedirects", "(I)V", AccessFlags = 1)]
public virtual void SetMaxRedirects(int maxRedirects) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setAllowCircularRedirects
/// </java-name>
[Dot42.DexImport("setAllowCircularRedirects", "(Z)V", AccessFlags = 1)]
public virtual void SetAllowCircularRedirects(bool allow) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setHandleAuthentication
/// </java-name>
[Dot42.DexImport("setHandleAuthentication", "(Z)V", AccessFlags = 1)]
public virtual void SetHandleAuthentication(bool handle) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setCookiePolicy
/// </java-name>
[Dot42.DexImport("setCookiePolicy", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetCookiePolicy(string policy) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setVirtualHost
/// </java-name>
[Dot42.DexImport("setVirtualHost", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)]
public virtual void SetVirtualHost(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setDefaultHeaders
/// </java-name>
[Dot42.DexImport("setDefaultHeaders", "(Ljava/util/Collection;)V", AccessFlags = 1, Signature = "(Ljava/util/Collection<Lorg/apache/http/Header;>;)V")]
public virtual void SetDefaultHeaders(global::Java.Util.ICollection<global::Org.Apache.Http.IHeader> headers) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setDefaultHost
/// </java-name>
[Dot42.DexImport("setDefaultHost", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)]
public virtual void SetDefaultHost(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ClientParamBean() /* TypeBuilder.AddDefaultConstructor */
{
}
}
}
| |
// This file is part of SNMP#NET
//
// SNMP#NET is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SNMP#NET is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SNMP#NET. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Text;
namespace SnmpSharpNet
{
/// <summary>
/// SMI Object Identifier type implementation.
/// </summary>
[Serializable]
public class Oid: AsnType, ICloneable, IComparable, IEnumerable<UInt32>
{
/// <summary>Internal buffer</summary>
protected UInt32[] _data;
#region Constructors
/// <summary> Creates a default empty object identifier.
/// </summary>
public Oid()
{
_asnType = SnmpConstants.SMI_OBJECTID;
_data = null;
}
/// <summary>Constructor. Initialize ObjectId value to the unsigned integer array</summary>
/// <param name="data">Integer array representing objectId</param>
public Oid(UInt32[] data)
:this()
{
Set(data);
}
/// <summary>Constructor. Initialize ObjectId value to integer array</summary>
/// <param name="data">Integer array representing objectId</param>
public Oid(int[] data)
:this()
{
Set(data);
}
/// <summary>Constructor. Duplicate objectId value from argument.</summary>
/// <param name="second">objectId whose value is used to initilize this class value</param>
public Oid(Oid second)
:this()
{
Set(second);
}
/// <summary>Constructor. Initialize objectId value from string argument.</summary>
/// <param name="value">String value representing objectId</param>
public Oid(System.String value)
: this()
{
Set(value);
}
#endregion Constructors
#region Set members
/// <summary>
/// Set Oid value from integer array. If integer array is null or length == 0, internal buffer is set to null.
/// </summary>
/// <param name="value">Integer array</param>
/// <exception cref="ArgumentNullException">Parameter is null</exception>
/// <exception cref="ArgumentOutOfRangeException">Parameter contains less then 2 integer values</exception>
/// <exception cref="OverflowException">Paramater contains a value that is less then zero. This is an invalid instance value</exception>
public virtual void Set(int[] value)
{
if (value == null)
_data = null;
else
{
// Verify all values are greater then or equal 0
foreach (int i in value)
{
if (i < 0)
throw new OverflowException("OID instance value cannot be less then zero.");
}
_data = new UInt32[value.Length];
for (int i = 0; i < value.Length; i++)
{
_data[i] = (UInt32)value[i];
}
}
}
/// <summary>
/// Set Oid value from integer array. If integer array is null or length == 0, internal buffer is set to null.
/// </summary>
/// <param name="value">Integer array</param>
/// <exception cref="ArgumentNullException">Parameter is null</exception>
/// <exception cref="ArgumentOutOfRangeException">Parameter contains less then 2 integer values</exception>
public virtual void Set(UInt32[] value)
{
if (value == null)
_data = null;
else
{
_data = new UInt32[value.Length];
Array.Copy(value, 0, _data, 0, value.Length);
}
}
/// <summary>
/// Set class value from another Oid class.
/// </summary>
/// <param name="value">Oid class</param>
/// <exception cref="ArgumentNullException">Thrown when parameter is null</exception>
public void Set(Oid value)
{
if (value == null)
throw new ArgumentNullException("value");
Set(value.GetData());
}
/// <summary> Sets the object to the passed dotted decimal
/// object identifier string.
/// </summary>
/// <param name="value">The dotted decimal object identifier.
/// </param>
public void Set(System.String value)
{
if (value == null || value.Length == 0)
{
_data = null;
}
else
{
_data = Parse(value);
}
}
#endregion Set members
/// <summary> Gets the number of object identifiers
/// in the object.
/// </summary>
/// <returns> Returns the number of object identifiers
/// </returns>
virtual public int Length
{
get
{
if (_data == null)
return 0;
return _data.Length;
}
}
/// <summary> Add an array of identifiers to the current object.</summary>
/// <param name="ids">The array Int32 identifiers to append to the object</param>
/// <exception cref="OverflowException">Thrown when one of the instance IDs to add are less then zero</exception>
public virtual void Add(int[] ids)
{
if (ids == null || ids.Length == 0)
{
return;
}
if (_data != null)
{
if (ids != null && ids.Length != 0)
{
UInt32[] tmp = new UInt32[_data.Length + ids.Length];
Array.Copy(_data, 0, tmp, 0, _data.Length);
for (int i = 0; i < ids.Length; i++)
{
if (ids[i] < 0)
{
throw new OverflowException("Instance value cannot be less then zero.");
}
tmp[_data.Length + i] = (UInt32)ids[i];
}
_data = tmp;
}
}
else
{
_data = new UInt32[ids.Length];
for (int i = 0; i < ids.Length; i++)
{
if (ids[i] < 0)
{
throw new OverflowException("Instance value cannot be less then zero.");
}
_data[i] = (UInt32)ids[i];
}
}
}
/// <summary> Add UInt32 identifiers to the current object.</summary>
/// <param name="ids">The array of identifiers to append</param>
/// <exception cref="OverflowException">Thrown when one of the instance IDs to add are less then zero</exception>
public virtual void Add(UInt32[] ids)
{
if (ids == null || ids.Length == 0)
{
return;
}
if (_data != null)
{
if (ids != null && ids.Length != 0)
{
UInt32[] tmp = new UInt32[_data.Length + ids.Length];
Array.Copy(_data, 0, tmp, 0, _data.Length);
Array.Copy(ids, 0, tmp, _data.Length, ids.Length);
_data = tmp;
}
}
else
{
_data = new UInt32[ids.Length];
Array.Copy(ids, _data, ids.Length);
}
}
/// <summary>Add a single UInt32 id to the end of the object</summary>
/// <param name="id">Id to add to the oid</param>
public virtual void Add(UInt32 id)
{
if (_data != null)
{
UInt32[] tmp = new UInt32[_data.Length + 1];
Array.Copy(_data, 0, tmp, 0, _data.Length);
tmp[_data.Length] = id;
_data = tmp;
}
else
{
_data = new UInt32[1];
_data[0] = id;
}
}
/// <summary>Add a single Int32 id to the end of the object</summary>
/// <param name="id">Id to add to the oid</param>
/// <exception cref="OverflowException">Thrown when id value is less then zero</exception>
public virtual void Add(int id)
{
if (id < 0)
{
throw new OverflowException("Instance id is less then zero.");
}
if (_data != null)
{
UInt32[] tmp = new UInt32[_data.Length + 1];
Array.Copy(_data, 0, tmp, 0, _data.Length);
tmp[_data.Length] = (UInt32)id;
_data = tmp;
}
else
{
_data = new UInt32[1];
_data[0] = (UInt32)id;
}
}
/// <summary> Converts the passed string to an object identifier
/// and appends them to the current object.
/// </summary>
/// <param name="strOids">The dotted decimal identifiers to Append
/// </param>
public virtual void Add(string strOids)
{
UInt32[] oids = Parse(strOids);
Add(oids);
}
/// <summary> Appends the passed Oid object to
/// self.
/// </summary>
/// <param name="second">The object to Append to self
/// </param>
public virtual void Add(Oid second)
{
Add(second.GetData());
}
#region Comparison methods
/// <summary>Compare Oid value with array of UInt32 integers</summary>
/// <param name="ids">Array of integers</param>
/// <returns>-1 if class is less then, 0 if the same or 1 if greater then the integer array value</returns>
public virtual int Compare(UInt32[] ids)
{
if (ids == null && _data == null)
return 0;
else if (ids != null && _data == null)
return 1;
else if (ids == null && _data != null)
return -1;
return Compare(ids, _data.Length > ids.Length ? ids.Length : _data.Length);
}
/// <summary>Compare class value with the contents of the array. Compare up to dist number of Oid values
/// to determine equality.</summary>
/// <param name="ids">Unsigned integer array to Compare with</param>
/// <param name="dist">Number of oid instance values to compare</param>
/// <returns>0 if equal, -1 if less then and 1 if greater then.</returns>
public virtual int Compare(UInt32[] ids, int dist)
{
if (_data == null)
{
if (ids == null)
return 0;
return -1;
}
if (ids == null)
{
return 1;
}
if (ids.Length < dist || _data.Length < dist)
{
if (_data.Length < ids.Length || _data.Length == ids.Length)
{
return -1;
}
return 1;
}
for (int cnt = 0; cnt < dist; cnt++)
{
if (_data[cnt] < ids[cnt])
{
return -1;
}
else if (_data[cnt] > ids[cnt])
{
return 1;
}
}
// If we made it all the way through, the Oids are the same
return 0;
}
/// <summary>
/// Exact comparison of two Oid values
/// </summary>
/// <param name="oid">Oid to compare against</param>
/// <returns>1 if class is greater then argument, -1 if class value is less then argument, 0 if the same</returns>
public int CompareExact(Oid oid)
{
return CompareExact(oid.GetData());
}
/// <summary>
/// Exact comparison of two Oid values
/// </summary>
/// <remarks>
/// This method is required for cases when exact comparison is required and not lexographical comparison.
///
/// This method will compare the lengths first and, if not the same, make a comparison determination based
/// on it before looking into the data.
/// </remarks>
/// <param name="ids">Array of unsigned integers to compare against</param>
/// <returns>1 if class is greater then argument, -1 if class value is less then argument, 0 if the same</returns>
public int CompareExact(UInt32[] ids)
{
int cmpVal = Compare(ids);
if (cmpVal == 0)
{
if (ids == null)
{
if (_data == null)
return 0;
return 1;
}
if (_data == null)
return -1;
if (_data.Length != ids.Length)
{
if (_data.Length > ids.Length)
return 1;
else if (_data.Length < ids.Length)
return -1;
}
}
return cmpVal;
/*
for (int i = 0; i < _data.Length; i++)
{
if (_data[i] != ids[i])
{
if (_data[i] > ids[i])
return 1;
else if (_data[i] < ids[i])
return -1;
}
}
return 0;
*/
}
/// <summary>Compare objectId values</summary>
/// <param name="cmp">ObjectId to Compare with</param>
/// <returns>0 if equal, -1 if less then and 1 if greater then.</returns>
public virtual int Compare(Oid cmp)
{
if (((Object)cmp) == null)
return 1;
if (cmp.GetData() == null && _data == null)
return 0;
else if (cmp.GetData() != null && _data == null)
return 1;
else if (cmp.GetData() == null && _data != null)
return -1;
return Compare(cmp.GetData());
}
/// <summary> Test for equality. Returns true if 'o' is an instance of an Oid and is equal to self.</summary>
/// <param name="obj">The object to be tested for equality.</param>
/// <returns> True if the object is an Oid and is equal to self. False otherwise.</returns>
public override bool Equals(System.Object obj)
{
if (obj == null)
{
return false;
}
if (obj is Oid)
{
return (CompareExact(((Oid)obj)._data) == 0);
}
else if (obj is System.String)
{
return (CompareExact(Parse((System.String)obj)) == 0);
}
else if (obj is UInt32[])
{
return (CompareExact((UInt32[])obj) == 0);
}
return false;
}
/// <summary>Compares the passed object identifier against self
/// to determine if self is the root of the passed object.
/// If the passed object is in the same root tree as self
/// then a true value is returned. Otherwise a false value
/// is returned from the object.
/// </summary>
/// <param name="leaf">The object to be tested
/// </param>
/// <returns> True if leaf is in the tree.
/// </returns>
public virtual bool IsRootOf(Oid leaf)
{
return (Compare(leaf._data, _data == null ? 0 : _data.Length) == 0);
}
/// <summary>
/// IComparable interface implementation. Internally uses <see cref="Oid.CompareExact(Oid)"/> method to perform comparisons.
/// </summary>
/// <param name="obj"></param>
/// <returns>1 if class is greater then argument, -1 if class value is less then argument, 0 if the same</returns>
public int CompareTo(object obj)
{
if (obj == null)
return 1;
if( obj is Oid )
return CompareExact((Oid)obj);
return 1;
}
#endregion Comparison methods
/// <summary>
/// Return internal integer array. This is required by static members of the class and other methods in
/// this library so internal attribute is applied to it.
/// </summary>
/// <returns>Internal unsigned integer array buffer.</returns>
protected UInt32[] GetData()
{
return _data;
}
/// <summary>
/// Reset class value to null
/// </summary>
public void Reset()
{
if (_data != null)
{
_data = null;
}
}
/// <summary>
/// Is Oid a null value or Oid equivalent (0.0)
/// </summary>
public bool IsNull
{
get
{
if (Length == 0)
return true;
if (Length == 2 && _data[0] == 0 && _data[1] == 0)
return true;
return false;
}
}
/// <summary>
/// Convert the Oid class to a integer array. Internal class data buffer is *copied* and not passed to the caller.
/// </summary>
/// <returns>Unsigned integer array representing the Oid class IDs</returns>
public UInt32[] ToArray()
{
if (_data == null || _data.Length == 0)
return null;
UInt32[] tmp = new UInt32[_data.Length];
Array.Copy(_data, 0, tmp, 0, _data.Length);
return tmp;
}
/// <summary>
/// Access individual Oid values.
/// </summary>
/// <param name="index">Index of the Oid value to access (0 based)</param>
/// <returns>Oid instance at index value</returns>
/// <exception cref="OverflowException">Requested instance is outside the bounds of the Oid array</exception>
public UInt32 this[int index]
{
get
{
if (_data == null || index < 0 || index >= _data.Length)
throw new OverflowException("Requested instance is outside the bounds of the Oid array");
return _data[index];
}
}
/// <summary>
/// Return child components of the leaf OID.
/// </summary>
/// <param name="root">Root Oid</param>
/// <param name="leaf">Leaf Oid</param>
/// <returns>Returns int array of child OIDs, if there was an error or no child IDs are present, returns null.</returns>
public static UInt32[] GetChildIdentifiers(Oid root, Oid leaf)
{
UInt32[] tmp;
if (((Object)leaf) == null || leaf.IsNull)
{
return null;
}
else if ((((Object)root) == null || root.IsNull) && ((Object)leaf) != null)
{
tmp = new UInt32[leaf.Length];
Array.Copy(leaf.GetData(), tmp, leaf.Length);
return tmp;
}
if (!root.IsRootOf(leaf))
{
// Has to be a child OID
return null;
}
if (leaf.Length <= root.Length)
{
return null; // There are not child ids if this oid is longer
}
int leafLen = leaf.Length - root.Length;
tmp = new UInt32[leafLen];
Array.Copy(leaf.GetData(), root.Length, tmp, 0, leafLen);
return tmp;
}
/// <summary>
/// Return a string formatted as OID value of the passed integer array
/// </summary>
/// <param name="vals">Array of integers</param>
/// <returns>String formatted OID</returns>
public static string ToString(int[] vals)
{
string r = "";
if (vals == null)
return r;
for (int i = 0; i < vals.Length; i++)
{
r += vals[i].ToString(CultureInfo.CurrentCulture);
if (i != (vals.Length - 1))
{
r += ".";
}
}
return r;
}
/// <summary>
/// Return a string formatted as OID value of the passed integer array starting at array item startpos.
/// </summary>
/// <param name="vals">Array of integers</param>
/// <param name="startpos">Start position in the array. 0 based.</param>
/// <returns>String formatted OID</returns>
/// <exception cref="IndexOutOfRangeException">Thrown when start position is outside of the bounds of the available data.</exception>
public static string ToString(int[] vals, int startpos)
{
string r = "";
if (vals == null)
return r;
if (startpos < 0 || startpos >= vals.Length)
{
throw new IndexOutOfRangeException("Requested value is out of range");
}
for (int i = startpos; i < vals.Length; i++)
{
r += vals[i].ToString();
if (i != (vals.Length - 1))
{
r += ".";
}
}
return r;
}
#region Operators
/// <summary>
/// Add Oid class value and oid values in the integer array into a new class instance.
/// </summary>
/// <param name="oid">Oid class</param>
/// <param name="ids">Unsigned integer array to add to the Oid</param>
/// <returns>New Oid class with the two values added together</returns>
public static Oid operator +(Oid oid, UInt32[] ids)
{
if (((Object)oid) == null && ((Object)ids) == null)
return null;
if (((Object)ids) == null)
return (Oid)oid.Clone();
Oid newoid = new Oid(oid);
newoid.Add(ids);
return newoid;
}
/// <summary>
/// Add Oid class value and oid represented as a string into a new Oid class instance
/// </summary>
/// <param name="oid">Oid class</param>
/// <param name="strOids">string value representing an Oid</param>
/// <returns>New Oid class with the new oid value.</returns>
public static Oid operator +(Oid oid, string strOids)
{
if (((Object)oid) == null && (strOids == null || strOids.Length == 0))
return null;
if (strOids == null || strOids.Length == 0)
return (Oid)oid.Clone();
Oid newoid = new Oid(oid);
newoid.Add(strOids);
return newoid;
}
/// <summary>
/// Add two Oid values and return the new class
/// </summary>
/// <param name="oid1">First Oid</param>
/// <param name="oid2">Second Oid</param>
/// <returns>New class with two Oid values added.</returns>
public static Oid operator +(Oid oid1, Oid oid2)
{
if (((Object)oid1) == null && ((Object)oid2) == null )
return null;
if ((Object)oid2 == null || oid2.IsNull)
return (Oid)oid1.Clone();
if ((Object)oid1 == null)
return (Oid)oid2.Clone();
Oid newoid = new Oid(oid1);
newoid.Add(oid2);
return newoid;
}
/// <summary>
/// Add integer id to the Oid class
/// </summary>
/// <param name="oid1">Oid class to add id to</param>
/// <param name="id">Id value to add to the oid</param>
/// <returns>New Oid class with id added to the Oid class.</returns>
public static Oid operator +(Oid oid1, UInt32 id)
{
if (((Object)oid1) == null)
return null;
Oid newoid = new Oid(oid1);
newoid.Add(id);
return newoid;
}
/// <summary>
/// Operator allowing explicit conversion from Oid class to integer array int[]
/// </summary>
/// <param name="oid">Oid to present as integer array int[]</param>
/// <returns>Integer array representing the Oid class value</returns>
public static explicit operator UInt32[](Oid oid)
{
return oid.ToArray();
}
/// <summary>
/// Comparison of two Oid class values.
/// </summary>
/// <param name="oid1">First Oid class</param>
/// <param name="oid2">Second Oid class</param>
/// <returns>true if class values are same, otherwise false</returns>
public static bool operator ==(Oid oid1, Oid oid2)
{
// I'm casting the oid values to Object to avoid recursive calls to this operator override.
if ( ((Object)oid1) == null && ((Object)oid2) == null)
{
return true;
}
else if (((Object)oid1) == null || ((Object)oid2) == null)
{
return false;
}
return oid1.Equals(oid2);
}
/// <summary>
/// Negative comparison of two Oid class values.
/// </summary>
/// <param name="oid1">First Oid class</param>
/// <param name="oid2">Second Oid class</param>
/// <returns>true if class values are not the same, otherwise false</returns>
public static bool operator !=(Oid oid1, Oid oid2)
{
if (((Object)oid1) == null && ((Object)oid2) == null)
{
return false;
}
else if (((Object)oid1) == null || ((Object)oid2) == null)
{
return true;
}
return !oid1.Equals(oid2);
}
/// <summary>
/// Greater then operator.
/// </summary>
/// <remarks>Compare first oid with second and if first OID is greater return true</remarks>
/// <param name="oid1">First oid</param>
/// <param name="oid2">Second oid</param>
/// <returns>True if first oid is greater then second, otherwise false</returns>
public static bool operator >(Oid oid1, Oid oid2)
{
if (((Object)oid1) == null && ((Object)oid2) == null)
{
return false;
}
else if (((Object)oid1) == null)
{
return false;
}
else if (((Object)oid2) == null )
{
return true;
}
if (oid1.Compare(oid2) > 0)
return true;
return false;
}
/// <summary>
/// Less then operator.
/// </summary>
/// <remarks>Compare first oid with second and if first OID is less return true</remarks>
/// <param name="oid1">First oid</param>
/// <param name="oid2">Second oid</param>
/// <returns>True if first oid is less then second, otherwise false</returns>
public static bool operator <(Oid oid1, Oid oid2)
{
if (((Object)oid1) == null && ((Object)oid2) == null)
{
return false;
}
else if (((Object)oid1) == null)
{
return true;
}
else if (((Object)oid2) == null)
{
return false;
}
if (oid1.Compare(oid2) < 0)
return true;
return false;
}
#endregion Operators
/// <summary> Converts the object identifier to a dotted decimal
/// string representation.
/// </summary>
/// <returns> Returns the dotted decimal object id string.
/// </returns>
public override System.String ToString()
{
StringBuilder buf = new StringBuilder();
if (_data == null)
{
buf.Append("0.0");
}
else
{
for (int x = 0; x < _data.Length; x++)
{
if (x > 0)
{
buf.Append('.');
}
buf.Append(_data[x].ToString());
}
}
return buf.ToString();
}
/// <summary>Hash value for OID value
/// </summary>
/// <returns> The hash code for the object.
/// </returns>
public override int GetHashCode()
{
int hash = 0;
if (_data == null)
{
return hash;
}
for (int i = 0; i < _data.Length; i++)
{
hash = hash ^ (_data[i] > Int32.MaxValue ? Int32.MaxValue : (int)_data[i]);
}
return hash;
}
/// <summary>Duplicate current object.</summary>
/// <returns> Returns a new Oid copy of self cast as Object.</returns>
public override Object Clone()
{
return new Oid(this);
}
#region Encode & Decode
/// <summary>
/// Encodes ASN.1 object identifier and append it to the end of the passed buffer.
/// </summary>
/// <param name="buffer">
/// Buffer to append the encoded information to.
/// </param>
public override void encode(MutableByte buffer)
{
MutableByte tmpBuffer = new MutableByte();
UInt32[] values = _data;
if (values == null || values.Length < 2)
{
values = new UInt32[2];
values[0] = values[1] = 0;
}
// verify that it is a valid object id!
if (values[0] < 0 || values[0] > 2)
throw new SnmpException("Invalid Object Identifier");
if (values[1] < 0 || values[1] > 40)
throw new SnmpException("Invalid Object Identifier");
// add the first oid!
tmpBuffer.Append((byte)(values[0] * 40 + values[1]));
// encode remaining instance values
for (int i = 2; i < values.Length; i++)
{
tmpBuffer.Append(encodeInstance(values[i]));
}
// build value header
BuildHeader(buffer, Type, tmpBuffer.Length);
// Append encoded value to the result buffer
buffer.Append(tmpBuffer);
}
/// <summary>
/// Encode single OID instance value
/// </summary>
/// <param name="number">Instance value</param>
/// <returns>Encoded instance value</returns>
protected byte[] encodeInstance(UInt32 number)
{
MutableByte result = new MutableByte();
if (number <= 127)
{
result.Set((byte)(number));
}
else
{
UInt32 val = number;
MutableByte tmp = new MutableByte();
while (val != 0)
{
byte[] b = BitConverter.GetBytes(val);
byte bval = b[0];
if ((bval & 0x80) != 0)
{
bval = (byte)(bval & ~HIGH_BIT); // clear high bit
}
val >>= 7; // shift original value by 7 bits
tmp.Append(bval);
}
// now we need to reverse the bytes for the final encoding
for (int i = tmp.Length - 1; i >= 0; i--)
{
if (i > 0)
result.Append((byte)(tmp[i] | HIGH_BIT));
else
result.Append(tmp[i]);
}
}
return result;
}
/// <summary>Decode BER encoded Oid value.</summary>
/// <param name="buffer">BER encoded buffer</param>
/// <param name="offset">The offset location to begin decoding</param>
/// <returns>Buffer position after the decoded value</returns>
public override int decode(byte[] buffer, int offset)
{
int headerLength;
byte asnType = ParseHeader(buffer, ref offset, out headerLength);
if (asnType != Type)
throw new SnmpException("Invalid ASN.1 type.");
// check for sufficient data
if ((buffer.Length - offset) < headerLength)
throw new OverflowException("Buffer underflow error");
if (headerLength == 0)
{
_data = null;
return offset;
}
List<UInt32> list = new List<UInt32>();
// decode the first byte
--headerLength;
UInt32 oid = Convert.ToUInt32(buffer[offset++]);
list.Add(oid / 40);
list.Add(oid % 40);
//
// decode the rest of the identifiers
//
while (headerLength > 0)
{
UInt32 result = 0;
// this is where we decode individual values
{
if ((buffer[offset] & HIGH_BIT) == 0)
{
// short encoding
result = (UInt32)buffer[offset];
offset += 1;
--headerLength;
}
else
{
// long encoding
MutableByte tmp = new MutableByte();
bool completed = false;
do
{
tmp.Append((byte)(buffer[offset] & ~HIGH_BIT));
if ((buffer[offset] & HIGH_BIT) == 0)
completed = true;
offset += 1; // advance offset
--headerLength; // take out the processed byte from the header length
} while (!completed);
// convert byte array to integer
for (int i = 0; i < tmp.Length; i++)
{
result <<= 7;
result |= tmp[i];
}
}
}
list.Add(result);
}
_data = list.ToArray();
if (_data.Length == 2 && _data[0] == 0 && _data[1] == 0)
_data = null;
return offset;
}
#endregion Encode & Decode
/// <summary>Parse string formatted oid value into an array of integers</summary>
/// <param name="oidStr">string formatted oid</param>
/// <returns>Integer array representing the oid or null if invalid object id was passed</returns>
private static UInt32[] Parse(System.String oidStr)
{
if (oidStr == null || oidStr.Length <= 0)
{
return null;
}
// verify correct values are the only ones present in the string
foreach (char c in oidStr.ToCharArray())
{
if (!char.IsNumber(c) && c != '.')
{
return null;
}
}
// check if oid starts with a '.' and remove it if it does
if (oidStr[0] == '.')
{
oidStr = oidStr.Remove(0, 1);
}
// split string into an array
string[] splitString = oidStr.Split(new char[] { '.' }, StringSplitOptions.None);
// if we didn't find any entries, return null
if (splitString.Length < 0)
return null;
List<UInt32> result = new List<UInt32>();
foreach (string s in splitString)
{
result.Add(Convert.ToUInt32(s));
}
return result.ToArray();
}
/// <summary>
/// Returns an enumerator that iterates through the Oid integer collection
/// </summary>
/// <returns>An IEnumerator object that can be used to iterate through the collection.</returns>
public IEnumerator<UInt32> GetEnumerator()
{
if( _data != null )
return ((IEnumerable<UInt32>)_data).GetEnumerator();
return null;
}
/// <summary>
/// Returns an enumerator that iterates through the Oid integer collection
/// </summary>
/// <returns>An IEnumerator object that can be used to iterate through the collection.</returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
if (_data != null)
return _data.GetEnumerator();
return null;
}
/// <summary>
/// Return instance of Oid class set to null value {0,0}
/// </summary>
/// <returns>Oid class instance set to null Oid value</returns>
public static Oid NullOid()
{
return new Oid(new UInt32[] { 0, 0 });
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Simulation;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nwc.XmlRpc;
using Nini.Config;
namespace OpenSim.Services.Connectors.Hypergrid
{
public class UserAgentServiceConnector : SimulationServiceConnector, IUserAgentService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURLHost;
private string m_ServerURL;
private GridRegion m_Gatekeeper;
public UserAgentServiceConnector(string url) : this(url, true)
{
}
public UserAgentServiceConnector(string url, bool dnsLookup)
{
m_ServerURL = m_ServerURLHost = url;
if (dnsLookup)
{
// Doing this here, because XML-RPC or mono have some strong ideas about
// caching DNS translations.
try
{
Uri m_Uri = new Uri(m_ServerURL);
IPAddress ip = Util.GetHostFromDNS(m_Uri.Host);
m_ServerURL = m_ServerURL.Replace(m_Uri.Host, ip.ToString());
if (!m_ServerURL.EndsWith("/"))
m_ServerURL += "/";
}
catch (Exception e)
{
m_log.DebugFormat("[USER AGENT CONNECTOR]: Malformed Uri {0}: {1}", url, e.Message);
}
}
//m_log.DebugFormat("[USER AGENT CONNECTOR]: new connector to {0} ({1})", url, m_ServerURL);
}
public UserAgentServiceConnector(IConfigSource config)
{
IConfig serviceConfig = config.Configs["UserAgentService"];
if (serviceConfig == null)
{
m_log.Error("[USER AGENT CONNECTOR]: UserAgentService missing from ini");
throw new Exception("UserAgent connector init error");
}
string serviceURI = serviceConfig.GetString("UserAgentServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[USER AGENT CONNECTOR]: No Server URI named in section UserAgentService");
throw new Exception("UserAgent connector init error");
}
m_ServerURL = m_ServerURLHost = serviceURI;
if (!m_ServerURL.EndsWith("/"))
m_ServerURL += "/";
//m_log.DebugFormat("[USER AGENT CONNECTOR]: new connector to {0}", m_ServerURL);
}
protected override string AgentPath()
{
return "homeagent/";
}
// The Login service calls this interface with fromLogin=true
// Sims call it with fromLogin=false
// Either way, this is verified by the handler
public bool LoginAgentToGrid(GridRegion source, AgentCircuitData aCircuit, GridRegion gatekeeper, GridRegion destination, bool fromLogin, out string reason)
{
reason = String.Empty;
if (destination == null)
{
reason = "Destination is null";
m_log.Debug("[USER AGENT CONNECTOR]: Given destination is null");
return false;
}
GridRegion home = new GridRegion();
home.ServerURI = m_ServerURL;
home.RegionID = destination.RegionID;
home.RegionLocX = destination.RegionLocX;
home.RegionLocY = destination.RegionLocY;
m_Gatekeeper = gatekeeper;
Console.WriteLine(" >>> LoginAgentToGrid <<< " + home.ServerURI);
uint flags = fromLogin ? (uint)TeleportFlags.ViaLogin : (uint)TeleportFlags.ViaHome;
return CreateAgent(source, home, aCircuit, flags, out reason);
}
// The simulators call this interface
public bool LoginAgentToGrid(GridRegion source, AgentCircuitData aCircuit, GridRegion gatekeeper, GridRegion destination, out string reason)
{
return LoginAgentToGrid(source, aCircuit, gatekeeper, destination, false, out reason);
}
protected override void PackData(OSDMap args, GridRegion source, AgentCircuitData aCircuit, GridRegion destination, uint flags)
{
base.PackData(args, source, aCircuit, destination, flags);
args["gatekeeper_serveruri"] = OSD.FromString(m_Gatekeeper.ServerURI);
args["gatekeeper_host"] = OSD.FromString(m_Gatekeeper.ExternalHostName);
args["gatekeeper_port"] = OSD.FromString(m_Gatekeeper.HttpPort.ToString());
args["destination_serveruri"] = OSD.FromString(destination.ServerURI);
}
public void SetClientToken(UUID sessionID, string token)
{
// no-op
}
private Hashtable CallServer(string methodName, Hashtable hash)
{
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest(methodName, paramList);
// Send and get reply
XmlRpcResponse response = null;
try
{
response = request.Send(m_ServerURL, 10000);
}
catch (Exception e)
{
m_log.DebugFormat("[USER AGENT CONNECTOR]: {0} call to {1} failed: {2}", methodName, m_ServerURLHost, e.Message);
throw;
}
if (response.IsFault)
{
throw new Exception(string.Format("[USER AGENT CONNECTOR]: {0} call to {1} returned an error: {2}", methodName, m_ServerURLHost, response.FaultString));
}
hash = (Hashtable)response.Value;
if (hash == null)
{
throw new Exception(string.Format("[USER AGENT CONNECTOR]: {0} call to {1} returned null", methodName, m_ServerURLHost));
}
return hash;
}
public GridRegion GetHomeRegion(UUID userID, out Vector3 position, out Vector3 lookAt)
{
position = Vector3.UnitY; lookAt = Vector3.UnitY;
Hashtable hash = new Hashtable();
hash["userID"] = userID.ToString();
hash = CallServer("get_home_region", hash);
bool success;
if (!Boolean.TryParse((string)hash["result"], out success) || !success)
return null;
GridRegion region = new GridRegion();
UUID.TryParse((string)hash["uuid"], out region.RegionID);
//m_log.Debug(">> HERE, uuid: " + region.RegionID);
int n = 0;
if (hash["x"] != null)
{
Int32.TryParse((string)hash["x"], out n);
region.RegionLocX = n;
//m_log.Debug(">> HERE, x: " + region.RegionLocX);
}
if (hash["y"] != null)
{
Int32.TryParse((string)hash["y"], out n);
region.RegionLocY = n;
//m_log.Debug(">> HERE, y: " + region.RegionLocY);
}
if (hash["size_x"] != null)
{
Int32.TryParse((string)hash["size_x"], out n);
region.RegionSizeX = n;
//m_log.Debug(">> HERE, x: " + region.RegionLocX);
}
if (hash["size_y"] != null)
{
Int32.TryParse((string)hash["size_y"], out n);
region.RegionSizeY = n;
//m_log.Debug(">> HERE, y: " + region.RegionLocY);
}
if (hash["region_name"] != null)
{
region.RegionName = (string)hash["region_name"];
//m_log.Debug(">> HERE, name: " + region.RegionName);
}
if (hash["hostname"] != null)
region.ExternalHostName = (string)hash["hostname"];
if (hash["http_port"] != null)
{
uint p = 0;
UInt32.TryParse((string)hash["http_port"], out p);
region.HttpPort = p;
}
if (hash.ContainsKey("server_uri") && hash["server_uri"] != null)
region.ServerURI = (string)hash["server_uri"];
if (hash["internal_port"] != null)
{
int p = 0;
Int32.TryParse((string)hash["internal_port"], out p);
region.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), p);
}
if (hash["position"] != null)
Vector3.TryParse((string)hash["position"], out position);
if (hash["lookAt"] != null)
Vector3.TryParse((string)hash["lookAt"], out lookAt);
// Successful return
return region;
}
public bool IsAgentComingHome(UUID sessionID, string thisGridExternalName)
{
Hashtable hash = new Hashtable();
hash["sessionID"] = sessionID.ToString();
hash["externalName"] = thisGridExternalName;
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("agent_is_coming_home", paramList);
string reason = string.Empty;
return GetBoolResponse(request, out reason);
}
public bool VerifyAgent(UUID sessionID, string token)
{
Hashtable hash = new Hashtable();
hash["sessionID"] = sessionID.ToString();
hash["token"] = token;
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("verify_agent", paramList);
string reason = string.Empty;
return GetBoolResponse(request, out reason);
}
public bool VerifyClient(UUID sessionID, string token)
{
Hashtable hash = new Hashtable();
hash["sessionID"] = sessionID.ToString();
hash["token"] = token;
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("verify_client", paramList);
string reason = string.Empty;
return GetBoolResponse(request, out reason);
}
public void LogoutAgent(UUID userID, UUID sessionID)
{
Hashtable hash = new Hashtable();
hash["sessionID"] = sessionID.ToString();
hash["userID"] = userID.ToString();
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("logout_agent", paramList);
string reason = string.Empty;
GetBoolResponse(request, out reason);
}
[Obsolete]
public List<UUID> StatusNotification(List<string> friends, UUID userID, bool online)
{
Hashtable hash = new Hashtable();
hash["userID"] = userID.ToString();
hash["online"] = online.ToString();
int i = 0;
foreach (string s in friends)
{
hash["friend_" + i.ToString()] = s;
i++;
}
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("status_notification", paramList);
// string reason = string.Empty;
// Send and get reply
List<UUID> friendsOnline = new List<UUID>();
XmlRpcResponse response = null;
try
{
response = request.Send(m_ServerURL, 6000);
}
catch
{
m_log.DebugFormat("[USER AGENT CONNECTOR]: Unable to contact remote server {0} for StatusNotification", m_ServerURLHost);
// reason = "Exception: " + e.Message;
return friendsOnline;
}
if (response.IsFault)
{
m_log.ErrorFormat("[USER AGENT CONNECTOR]: remote call to {0} for StatusNotification returned an error: {1}", m_ServerURLHost, response.FaultString);
// reason = "XMLRPC Fault";
return friendsOnline;
}
hash = (Hashtable)response.Value;
//foreach (Object o in hash)
// m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
try
{
if (hash == null)
{
m_log.ErrorFormat("[USER AGENT CONNECTOR]: GetOnlineFriends Got null response from {0}! THIS IS BAAAAD", m_ServerURLHost);
// reason = "Internal error 1";
return friendsOnline;
}
// Here is the actual response
foreach (object key in hash.Keys)
{
if (key is string && ((string)key).StartsWith("friend_") && hash[key] != null)
{
UUID uuid;
if (UUID.TryParse(hash[key].ToString(), out uuid))
friendsOnline.Add(uuid);
}
}
}
catch
{
m_log.ErrorFormat("[USER AGENT CONNECTOR]: Got exception on GetOnlineFriends response.");
// reason = "Exception: " + e.Message;
}
return friendsOnline;
}
[Obsolete]
public List<UUID> GetOnlineFriends(UUID userID, List<string> friends)
{
Hashtable hash = new Hashtable();
hash["userID"] = userID.ToString();
int i = 0;
foreach (string s in friends)
{
hash["friend_" + i.ToString()] = s;
i++;
}
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("get_online_friends", paramList);
// string reason = string.Empty;
// Send and get reply
List<UUID> online = new List<UUID>();
XmlRpcResponse response = null;
try
{
response = request.Send(m_ServerURL, 10000);
}
catch
{
m_log.DebugFormat("[USER AGENT CONNECTOR]: Unable to contact remote server {0} for GetOnlineFriends", m_ServerURLHost);
// reason = "Exception: " + e.Message;
return online;
}
if (response.IsFault)
{
m_log.ErrorFormat("[USER AGENT CONNECTOR]: remote call to {0} for GetOnlineFriends returned an error: {1}", m_ServerURLHost, response.FaultString);
// reason = "XMLRPC Fault";
return online;
}
hash = (Hashtable)response.Value;
//foreach (Object o in hash)
// m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
try
{
if (hash == null)
{
m_log.ErrorFormat("[USER AGENT CONNECTOR]: GetOnlineFriends Got null response from {0}! THIS IS BAAAAD", m_ServerURLHost);
// reason = "Internal error 1";
return online;
}
// Here is the actual response
foreach (object key in hash.Keys)
{
if (key is string && ((string)key).StartsWith("friend_") && hash[key] != null)
{
UUID uuid;
if (UUID.TryParse(hash[key].ToString(), out uuid))
online.Add(uuid);
}
}
}
catch
{
m_log.ErrorFormat("[USER AGENT CONNECTOR]: Got exception on GetOnlineFriends response.");
// reason = "Exception: " + e.Message;
}
return online;
}
public Dictionary<string,object> GetUserInfo (UUID userID)
{
Hashtable hash = new Hashtable();
hash["userID"] = userID.ToString();
hash = CallServer("get_user_info", hash);
Dictionary<string, object> info = new Dictionary<string, object>();
foreach (object key in hash.Keys)
{
if (hash[key] != null)
{
info.Add(key.ToString(), hash[key]);
}
}
return info;
}
public Dictionary<string, object> GetServerURLs(UUID userID)
{
Hashtable hash = new Hashtable();
hash["userID"] = userID.ToString();
hash = CallServer("get_server_urls", hash);
Dictionary<string, object> serverURLs = new Dictionary<string, object>();
foreach (object key in hash.Keys)
{
if (key is string && ((string)key).StartsWith("SRV_") && hash[key] != null)
{
string serverType = key.ToString().Substring(4); // remove "SRV_"
serverURLs.Add(serverType, hash[key].ToString());
}
}
return serverURLs;
}
public string LocateUser(UUID userID)
{
Hashtable hash = new Hashtable();
hash["userID"] = userID.ToString();
hash = CallServer("locate_user", hash);
string url = string.Empty;
// Here's the actual response
if (hash.ContainsKey("URL"))
url = hash["URL"].ToString();
return url;
}
public string GetUUI(UUID userID, UUID targetUserID)
{
Hashtable hash = new Hashtable();
hash["userID"] = userID.ToString();
hash["targetUserID"] = targetUserID.ToString();
hash = CallServer("get_uui", hash);
string uui = string.Empty;
// Here's the actual response
if (hash.ContainsKey("UUI"))
uui = hash["UUI"].ToString();
return uui;
}
public UUID GetUUID(String first, String last)
{
Hashtable hash = new Hashtable();
hash["first"] = first;
hash["last"] = last;
hash = CallServer("get_uuid", hash);
if (!hash.ContainsKey("UUID"))
{
throw new Exception(string.Format("[USER AGENT CONNECTOR]: get_uuid call to {0} didn't return a UUID", m_ServerURLHost));
}
UUID uuid;
if (!UUID.TryParse(hash["UUID"].ToString(), out uuid))
{
throw new Exception(string.Format("[USER AGENT CONNECTOR]: get_uuid call to {0} returned an invalid UUID: {1}", m_ServerURLHost, hash["UUID"].ToString()));
}
return uuid;
}
private bool GetBoolResponse(XmlRpcRequest request, out string reason)
{
//m_log.Debug("[USER AGENT CONNECTOR]: GetBoolResponse from/to " + m_ServerURLHost);
XmlRpcResponse response = null;
try
{
response = request.Send(m_ServerURL, 10000);
}
catch (Exception e)
{
m_log.DebugFormat("[USER AGENT CONNECTOR]: Unable to contact remote server {0} for GetBoolResponse", m_ServerURLHost);
reason = "Exception: " + e.Message;
return false;
}
if (response.IsFault)
{
m_log.ErrorFormat("[USER AGENT CONNECTOR]: remote call to {0} for GetBoolResponse returned an error: {1}", m_ServerURLHost, response.FaultString);
reason = "XMLRPC Fault";
return false;
}
Hashtable hash = (Hashtable)response.Value;
//foreach (Object o in hash)
// m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
try
{
if (hash == null)
{
m_log.ErrorFormat("[USER AGENT CONNECTOR]: Got null response from {0}! THIS IS BAAAAD", m_ServerURLHost);
reason = "Internal error 1";
return false;
}
bool success = false;
reason = string.Empty;
if (hash.ContainsKey("result"))
Boolean.TryParse((string)hash["result"], out success);
else
{
reason = "Internal error 2";
m_log.WarnFormat("[USER AGENT CONNECTOR]: response from {0} does not have expected key 'result'", m_ServerURLHost);
}
return success;
}
catch (Exception e)
{
m_log.ErrorFormat("[USER AGENT CONNECTOR]: Got exception on GetBoolResponse response.");
if (hash.ContainsKey("result") && hash["result"] != null)
m_log.ErrorFormat("Reply was ", (string)hash["result"]);
reason = "Exception: " + e.Message;
return false;
}
}
}
}
| |
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Voxalia.Shared;
using Voxalia.ClientGame.UISystem;
using Voxalia.ClientGame.NetworkSystem.PacketsIn;
using Voxalia.ClientGame.NetworkSystem.PacketsOut;
using BEPUutilities;
using BEPUphysics;
using BEPUphysics.BroadPhaseEntries.MobileCollidables;
using BEPUphysics.BroadPhaseEntries;
using BEPUphysics.BroadPhaseSystems;
using BEPUphysics.OtherSpaceStages;
using BEPUphysics.UpdateableSystems;
using BEPUphysics.NarrowPhaseSystems.Pairs;
using BEPUphysics.PositionUpdating;
using BEPUphysics.NarrowPhaseSystems;
using BEPUphysics.Constraints;
using BEPUphysics.Constraints.SingleEntity;
using Voxalia.ClientGame.GraphicsSystems;
using Voxalia.ClientGame.GraphicsSystems.LightingSystem;
using Voxalia.ClientGame.WorldSystem;
using Voxalia.ClientGame.OtherSystems;
using Voxalia.Shared.Collision;
using BEPUphysics.Character;
using FreneticScript;
using Voxalia.ClientGame.ClientMainSystem;
using Voxalia.ClientGame.JointSystem;
using FreneticScript.TagHandlers;
using FreneticScript.TagHandlers.Objects;
namespace Voxalia.ClientGame.EntitySystem
{
public abstract class CharacterEntity : PhysicsEntity, EntityAnimated
{
public CharacterEntity(Region tregion)
: base(tregion, true, true)
{
}
public virtual void Solidify()
{
CGroup = CollisionUtil.Character;
if (Body != null)
{
Body.CollisionInformation.CollisionRules.Group = CGroup;
}
}
public virtual void Desolidify()
{
CGroup = CollisionUtil.NonSolid;
if (Body != null)
{
Body.CollisionInformation.CollisionRules.Group = CGroup;
}
}
public bool IsTyping = false;
public bool Upward = false;
public bool Click = false;
public bool AltClick = false;
public bool Downward = false;
public bool Use = false;
// TODO: This block -> HumanoidEntity?
public SingleAnimation hAnim;
public SingleAnimation tAnim;
public SingleAnimation lAnim;
public double aHTime;
public double aTTime;
public double aLTime;
public bool IsFlying = false;
public float PreFlyMass = 0;
public bool HasFuel = false;
public Stance DesiredStance = Stance.Standing;
public void SetAnimation(string anim, byte mode)
{
if (mode == 0)
{
hAnim = TheClient.Animations.GetAnimation(anim, TheClient.Files);
aHTime = 0;
}
else if (mode == 1)
{
tAnim = TheClient.Animations.GetAnimation(anim, TheClient.Files);
aTTime = 0;
}
else
{
lAnim = TheClient.Animations.GetAnimation(anim, TheClient.Files);
aLTime = 0;
}
}
public Location Direction = new Location(0, 0, 0);
public double SoundTimeout = 0;
public void PlayRelevantSounds()
{
if (SoundTimeout > 0)
{
SoundTimeout -= TheRegion.Delta;
return;
}
Location vel = GetVelocity();
if (vel.LengthSquared() < 0.2)
{
return;
}
Material mat = TheRegion.GetBlockMaterial(GetPosition() + new Location(0, 0, -0.05f));
MaterialSound sound = mat.Sound();
if (sound == MaterialSound.NONE)
{
return;
}
double velLen = vel.Length();
new DefaultSoundPacketIn() { TheClient = TheClient }.PlayDefaultBlockSound(GetPosition(), sound, 1f, 0.14f * (float)velLen);
TheClient.Particles.Steps(GetPosition(), mat, GetVelocity(), (float)velLen);
SoundTimeout = (Utilities.UtilRandom.NextDouble() * 0.2 + 1.0) / velLen;
}
public float XMove = 0;
public float YMove = 0;
public float SprintOrWalk = 0f;
public List<JointVehicleMotor> DrivingMotors = new List<JointVehicleMotor>();
public List<JointVehicleMotor> SteeringMotors = new List<JointVehicleMotor>();
public void MoveVehicle()
{
foreach (JointVehicleMotor motor in DrivingMotors)
{
motor.Motor.Settings.VelocityMotor.GoalVelocity = YMove * 100; // TODO: Sprint/Walk mods?
}
foreach (JointVehicleMotor motor in SteeringMotors)
{
motor.Motor.Settings.Servo.Goal = MathHelper.Pi * -0.2f * XMove;
}
}
public CharacterController CBody;
public float mod_scale = 1;
public CharacterController GenCharCon()
{
// TODO: Better variable control! (Server should command every detail!)
CharacterController cb = new CharacterController(GetPosition().ToBVector(), CBHHeight * 2f * mod_scale, CBHHeight * 1.1f * mod_scale,
CBHHeight * 1f * mod_scale, CBRadius * mod_scale, CBMargin, Mass, CBMaxTractionSlope, CBMaxSupportSlope, CBStandSpeed, CBCrouchSpeed, CBProneSpeed,
CBTractionForce * Mass, CBSlideSpeed, CBSlideForce * Mass, CBAirSpeed, CBAirForce * Mass, CBJumpSpeed, CBSlideJumpSpeed, CBGlueForce * Mass);
cb.StanceManager.DesiredStance = Stance.Standing;
cb.ViewDirection = new Vector3(1f, 0f, 0f);
cb.Down = new Vector3(0f, 0f, -1f);
cb.Tag = this;
BEPUphysics.Entities.Prefabs.Cylinder tb = cb.Body;
tb.Tag = this;
tb.AngularDamping = 1.0f;
tb.CollisionInformation.CollisionRules.Group = CGroup;
cb.StepManager.MaximumStepHeight = CBStepHeight;
cb.StepManager.MinimumDownStepHeight = CBDownStepHeight;
return cb;
}
public override void SpawnBody()
{
if (CBody != null)
{
DestroyBody();
}
CBody = GenCharCon();
Body = CBody.Body;
Shape = CBody.Body.CollisionInformation.Shape;
TheRegion.PhysicsWorld.Add(CBody);
Jetpack = new JetpackMotionConstraint(this);
TheRegion.PhysicsWorld.Add(Jetpack);
}
public float CBHHeight = 1.3f;
public float CBProneSpeed = 1f;
public float CBMargin = 0.01f;
public float CBStepHeight = 0.6f;
public float CBDownStepHeight = 0.6f;
public float CBRadius = 0.3f;
public float CBMaxTractionSlope = 1.0f;
public float CBMaxSupportSlope = 1.3f;
public float CBStandSpeed = 5.0f;
public float CBCrouchSpeed = 2.5f;
public float CBSlideSpeed = 3f;
public float CBAirSpeed = 1f;
public float CBTractionForce = 100f;
public float CBSlideForce = 70f;
public float CBAirForce = 50f;
public float CBJumpSpeed = 8f;
public float CBSlideJumpSpeed = 3.5f;
public float CBGlueForce = 500f;
public override void DestroyBody()
{
if (CBody == null)
{
return;
}
if (Jetpack != null)
{
TheRegion.PhysicsWorld.Remove(Jetpack);
Jetpack = null;
}
TheRegion.PhysicsWorld.Remove(CBody);
CBody = null;
Body = null;
}
public SpotLight Flashlight = null;
public bool IgnoreThis(BroadPhaseEntry entry) // TODO: PhysicsEntity?
{
if (entry is EntityCollidable && ((EntityCollidable)entry).Entity.Tag == this)
{
return false;
}
return TheRegion.Collision.ShouldCollide(entry);
}
public Dictionary<string, Matrix> SavedAdjustments = new Dictionary<string, Matrix>();
public Dictionary<string, OpenTK.Matrix4> SavedAdjustmentsOTK = new Dictionary<string, OpenTK.Matrix4>();
public void SetAdjustment(string str, Matrix matr)
{
SavedAdjustments[str] = matr;
OpenTK.Matrix4 mat = ClientUtilities.Convert(matr);
SavedAdjustmentsOTK[str] = mat;
}
public Matrix GetAdjustment(string str)
{
Matrix mat;
if (SavedAdjustments.TryGetValue(str, out mat))
{
return mat;
}
return Matrix.Identity;
}
public OpenTK.Matrix4 GetAdjustmentOTK(string str)
{
OpenTK.Matrix4 mat;
if (SavedAdjustmentsOTK.TryGetValue(str, out mat))
{
return mat;
}
return OpenTK.Matrix4.Identity;
}
public virtual Location GetWeldSpot()
{
return GetPosition();
}
public Location GetBasicEyePos()
{
Location renderrelpos = GetWeldSpot();
return renderrelpos + new Location(0, 0, CBHHeight * (CBody.StanceManager.CurrentStance == Stance.Standing ? 1.8 : 1.5));
}
public Location GetEyePosition()
{
Location renderrelpos = GetWeldSpot();
Location start = renderrelpos + new Location(0, 0, CBHHeight * (CBody.StanceManager.CurrentStance == Stance.Standing ? 1.8 : 1.5));
if (tAnim != null)
{
SingleAnimationNode head = tAnim.GetNode("special06.r");
Dictionary<string, Matrix> adjs = new Dictionary<string, Matrix>(SavedAdjustments);
Matrix rotforw = Matrix.CreateFromQuaternion(Quaternion.CreateFromAxisAngle(Vector3.UnitX, -(float)(Direction.Pitch / 1.75f * Utilities.PI180)));
adjs["spine04"] = GetAdjustment("spine04") * rotforw;
Matrix m4 = Matrix.CreateFromQuaternion(Quaternion.CreateFromAxisAngle(Vector3.UnitZ, (float)((-Direction.Yaw + 270) * Utilities.PI180) % 360f))
* head.GetBoneTotalMatrix(0, adjs) * (rotforw * Matrix.CreateTranslation(new Vector3(0, 0, 0.2f)));
m4.Transpose();
return renderrelpos + new Location(m4.Translation) * 1.5f;
}
else
{
return start;
}
}
public Location ForwardVector()
{
return Utilities.ForwardVector_Deg(Direction.Yaw, Direction.Pitch);
}
public override Location GetPosition()
{
if (Body != null)
{
RigidTransform transf = new RigidTransform(Vector3.Zero, Body.Orientation);
BoundingBox box;
Body.CollisionInformation.Shape.GetBoundingBox(ref transf, out box);
return base.GetPosition() + new Location(0, 0, box.Min.Z);
}
return base.GetPosition() - new Location(0, 0, CBHHeight);
}
public override void SetPosition(Location pos)
{
if (Body != null)
{
RigidTransform transf = new RigidTransform(Vector3.Zero, Body.Orientation);
BoundingBox box;
Body.CollisionInformation.Shape.GetBoundingBox(ref transf, out box);
base.SetPosition(pos + new Location(0, 0, -box.Min.Z));
}
else
{
base.SetPosition(pos + new Location(0, 0, CBHHeight));
}
}
public bool JPBoost = false;
public bool JPHover = false;
public virtual ItemStack GetHeldItem()
{
// TODO: Real return
return new ItemStack(TheClient, "air");
}
public bool HasChute()
{
return GetHeldItem().Name == "parachute";
}
public bool HasJetpack()
{
return GetHeldItem().Name == "jetpack";
}
public double JetpackBoostRate(out float max)
{
const double baseBoost = 1500.0;
const float baseMax = 2000.0f;
max = baseMax; // TODO: Own mod
ItemStack its = GetHeldItem();
TemplateObject mod;
if (its.SharedAttributes.TryGetValue("jetpack_boostmod", out mod))
{
NumberTag nt = NumberTag.TryFor(mod);
if (nt != null)
{
return baseBoost * nt.Internal;
}
}
return baseBoost;
}
public double JetpackHoverStrength()
{
double baseHover = GetMass();
ItemStack its = GetHeldItem();
TemplateObject mod;
if (its.SharedAttributes.TryGetValue("jetpack_hovermod", out mod))
{
NumberTag nt = NumberTag.TryFor(mod);
if (nt != null)
{
return baseHover * nt.Internal;
}
}
return baseHover;
}
void DoJetpackEffect(int count)
{
Location forw = ForwardVector();
forw = new Location(-forw.X, -forw.Y, 0).Normalize() * 0.333;
forw.Z = 1;
Location pos = GetPosition() + forw;
for (int i = 0; i < count; i++)
{
TheClient.Particles.JetpackEffect(pos, GetVelocity());
}
}
public class JetpackMotionConstraint : SingleEntityConstraint
{
public CharacterEntity Character;
public JetpackMotionConstraint(CharacterEntity character)
{
Character = character;
Entity = character.Body;
}
public Vector3 GetMoveVector(out double glen)
{
Location gravity = Character.GetGravity();
glen = gravity.Length();
gravity /= glen;
// TODO: Sprint/Walk mods?
gravity += Utilities.RotateVector(new Location(Character.YMove, -Character.XMove, 0), Character.Direction.Yaw * Utilities.PI180);
return gravity.ToBVector(); // TODO: Maybe normalize this?
}
public override void ExclusiveUpdate()
{
if (Character.HasChute())
{
entity.ModifyLinearDamping(0.8f);
}
if (Character.HasJetpack() && Character.HasFuel)
{
if (Character.JPBoost)
{
float max;
double boost = Character.JetpackBoostRate(out max);
double glen;
Vector3 move = GetMoveVector(out glen);
Vector3 vec = -(move * (float)boost) * Delta;
Character.CBody.Jump();
Entity.ApplyLinearImpulse(ref vec);
if (Entity.LinearVelocity.LengthSquared() > max * max)
{
Vector3 vel = entity.LinearVelocity;
vel.Normalize();
Entity.LinearVelocity = vel * max;
}
Character.DoJetpackEffect(10);
}
else if (Character.JPHover)
{
double hover = Character.JetpackHoverStrength();
double glen;
Vector3 move = GetMoveVector(out glen);
Vector3 vec = -(move * (float)glen * (float)hover) * Delta;
Entity.ApplyLinearImpulse(ref vec);
entity.ModifyLinearDamping(0.6f);
Character.DoJetpackEffect(3);
}
}
}
double Delta;
public override double SolveIteration()
{
return 0; // Do nothing
}
public override void Update(double dt)
{
Delta = dt;
}
}
public JetpackMotionConstraint Jetpack = null;
}
}
| |
// MIT License
//
// Copyright(c) 2022 ICARUS Consulting GmbH
//
// 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.Globalization;
using Yaapii.Atoms.Scalar;
using Yaapii.Atoms.Text;
namespace Yaapii.Atoms.Number
{
/// <summary>
/// A parsed number
/// </summary>
public sealed class NumberOf : NumberEnvelope
{
/// <summary>
/// A <see cref="IText"/> as a <see cref="INumber"/>
/// </summary>
/// <param name="text">text to parse</param>
/// <param name="blockSeperator">seperator for blocks, for example 1.000</param>
/// <param name="decimalSeperator">seperator for floating point numbers, for example 16,235 </param>
public NumberOf(string text, string decimalSeperator, string blockSeperator) : this(
new ScalarOf<long>(() => Convert.ToInt64(
text,
new NumberFormatInfo()
{
NumberDecimalSeparator = decimalSeperator,
NumberGroupSeparator = blockSeperator
})),
new ScalarOf<int>(() => Convert.ToInt32(
text,
new NumberFormatInfo()
{
NumberDecimalSeparator = decimalSeperator,
NumberGroupSeparator = blockSeperator
})),
new ScalarOf<float>(() => (float)Convert.ToDecimal(text, new NumberFormatInfo()
{
NumberDecimalSeparator = decimalSeperator,
NumberGroupSeparator = blockSeperator
})),
new ScalarOf<double>(() => Convert.ToDouble(
text,
new NumberFormatInfo()
{
NumberDecimalSeparator = decimalSeperator,
NumberGroupSeparator = blockSeperator
}))
)
{ }
/// <summary>
/// A <see cref="int"/> as a <see cref="INumber"/>
/// </summary>
/// <param name="str">The string</param>
public NumberOf(string str) : this(str, CultureInfo.InvariantCulture)
{ }
/// <summary>
/// A <see cref="string"/> as a <see cref="INumber"/>
/// </summary>
/// <param name="str">The string</param>
/// <param name="provider">a number format provider</param>
public NumberOf(string str, IScalar<IFormatProvider> provider) : this(str, provider.Value())
{ }
/// <summary>
/// A <see cref="string"/> as a <see cref="INumber"/>
/// </summary>
/// <param name="str">The string</param>
/// <param name="provider">a number format provider</param>
public NumberOf(string str, IFormatProvider provider) : this(new TextOf(str), provider)
{ }
/// <summary>
/// A <see cref="int"/> as a <see cref="INumber"/>
/// </summary>
/// <param name="text">The text</param>
public NumberOf(IText text) : this(text, CultureInfo.InvariantCulture)
{ }
/// <summary>
/// A <see cref="IText"/> as a <see cref="INumber"/>
/// </summary>
/// <param name="text">The text</param>
/// <param name="provider">a number format provider</param>
public NumberOf(IText text, IFormatProvider provider) : this(
new ScalarOf<long>(
() =>
{
try
{
return Convert.ToInt64(text.AsString(), provider);
}
catch (FormatException)
{
throw new ArgumentException(new Formatted("'{0}' is not a number.", text).AsString());
}
}),
new ScalarOf<int>(
() =>
{
try
{
return Convert.ToInt32(text.AsString(), provider);
}
catch (FormatException)
{
throw new ArgumentException(new Formatted("'{0}' is not a number.", text).AsString());
}
}),
new ScalarOf<float>(
() =>
{
try
{
return Convert.ToSingle(text.AsString(), provider);
}
catch (FormatException)
{
throw new ArgumentException(new Formatted("'{0}' is not a number.", text).AsString());
}
}),
new ScalarOf<double>(
() =>
{
try
{
return Convert.ToDouble(text.AsString(), provider);
}
catch (FormatException)
{
throw new ArgumentException(new Formatted("'{0}' is not a number.", text).AsString());
}
})
)
{ }
/// <summary>
/// A <see cref="int"/> as a <see cref="INumber"/>
/// </summary>
/// <param name="integer">The integer</param>
public NumberOf(int integer) : this(
new ScalarOf<long>(() => Convert.ToInt64(integer)),
new ScalarOf<int>(integer),
new ScalarOf<float>(() => Convert.ToSingle(integer)),
new ScalarOf<double>(() => Convert.ToDouble(integer))
)
{ }
/// <summary>
/// A <see cref="double"/> as a <see cref="INumber"/>
/// </summary>
/// <param name="dbl">The double</param>
public NumberOf(double dbl) : this(
new ScalarOf<long>(() => Convert.ToInt64(dbl)),
new ScalarOf<int>(() => Convert.ToInt32(dbl)),
new ScalarOf<float>(() => Convert.ToSingle(dbl)),
new ScalarOf<double>(dbl)
)
{ }
/// <summary>
/// A <see cref="long"/> as a <see cref="INumber"/>
/// </summary>
/// <param name="lng">The long</param>
public NumberOf(long lng) : this(
new ScalarOf<long>(() => lng),
new ScalarOf<int>(() => Convert.ToInt32(lng)),
new ScalarOf<float>(() => Convert.ToSingle(lng)),
new ScalarOf<double>(() => Convert.ToDouble(lng))
)
{ }
/// <summary>
/// A <see cref="float"/> as a <see cref="INumber"/>
/// </summary>
/// <param name="flt">The float</param>
public NumberOf(float flt) : this(
new ScalarOf<long>(() => Convert.ToInt64(flt)),
new ScalarOf<int>(() => Convert.ToInt32(flt)),
new ScalarOf<float>(() => Convert.ToSingle(flt)),
new ScalarOf<double>(() => Convert.ToDouble(flt))
)
{ }
/// <summary>
/// A <see cref="IText"/> as a <see cref="INumber"/>
/// </summary>
/// <param name="lng"></param>
/// <param name="itg"></param>
/// <param name="flt"></param>
/// <param name="dbl"></param>
public NumberOf(IScalar<long> lng, IScalar<int> itg, IScalar<float> flt, IScalar<double> dbl) : base(dbl, itg, lng, flt)
{
}
}
}
| |
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
namespace TVGL.Numerics
{
/// <summary>
/// Struct ComplexNumber
/// </summary>
public readonly struct ComplexNumber
{
/// <summary>
/// Specifies the real-value of the vector component of the ComplexNumber.
/// </summary>
public readonly double Real;
/// <summary>
/// Specifies the Imaginary-value of the vector component of the ComplexNumber.
/// </summary>
public readonly double Imaginary;
/// <summary>
/// Constructs a ComplexNumber from the given components.
/// </summary>
public ComplexNumber(double real, double imaginary)
{
Real = real;
Imaginary = imaginary;
}
/// <summary>
/// Constructs a ComplexNumber from the given components.
/// </summary>
public ComplexNumber(double real)
{
Real = real;
Imaginary = 0.0;
}
public static ComplexNumber NaN => new ComplexNumber(double.NaN, double.NaN);
/// <summary>
/// Calculates the length of the ComplexNumber.
/// </summary>
/// <returns>The computed length of the ComplexNumber.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public double Length()
{
return Math.Sqrt(LengthSquared());
}
/// <summary>
/// Calculates the length squared of the ComplexNumber. This operation is cheaper than Length().
/// </summary>
/// <returns>The length squared of the ComplexNumber.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public double LengthSquared()
{
return Real * Real + Imaginary * Imaginary;
}
/// <summary>
/// Divides each component of the ComplexNumber by the length of the ComplexNumber.
/// </summary>
/// <param name="value">The source ComplexNumber.</param>
/// <returns>The normalized ComplexNumber.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ComplexNumber Normalize(ComplexNumber value)
{
double invNorm = 1.0 / value.Length();
return new ComplexNumber(invNorm * value.Real, invNorm * value.Imaginary);
}
/// <summary>
/// Creates the conjugate of a specified ComplexNumber.
/// </summary>
/// <param name="value">The ComplexNumber of which to return the conjugate.</param>
/// <returns>A new ComplexNumber that is the conjugate of the specified one.</returns>
public static ComplexNumber Conjugate(ComplexNumber value)
{
return new ComplexNumber(value.Real, -value.Imaginary);
}
/// <summary>
/// Flips the sign of each component of the ComplexNumber.
/// </summary>
/// <param name="value">The source ComplexNumber.</param>
/// <returns>The negated ComplexNumber.</returns>
public static ComplexNumber Negate(ComplexNumber value)
{
return new ComplexNumber(-value.Real, -value.Imaginary);
}
/// <summary>
/// Flips the sign of each component of the ComplexNumber.
/// </summary>
/// <param name="value">The source ComplexNumber.</param>
/// <returns>The negated ComplexNumber.</returns>
public static ComplexNumber operator -(ComplexNumber value) => Negate(value);
/// <summary>
/// Adds two ComplexNumbers element-by-element.
/// </summary>
/// <param name="value1">The first source ComplexNumber.</param>
/// <param name="value2">The second source ComplexNumber.</param>
/// <returns>The result of adding the ComplexNumbers.</returns>
public static ComplexNumber Add(ComplexNumber value1, ComplexNumber value2)
{
return new ComplexNumber(value1.Real + value2.Real,
value1.Imaginary + value2.Imaginary);
}
/// <summary>
/// Adds two ComplexNumbers element-by-element.
/// </summary>
/// <param name="value1">The first source ComplexNumber.</param>
/// <param name="value2">The second source ComplexNumber.</param>
/// <returns>The result of adding the ComplexNumbers.</returns>
public static ComplexNumber operator +(ComplexNumber value1, ComplexNumber value2) => Add(value1, value2);
/// <summary>
/// Subtracts one ComplexNumber from another.
/// </summary>
/// <param name="value1">The first source ComplexNumber.</param>
/// <param name="value2">The second ComplexNumber, to be subtracted from the first.</param>
/// <returns>The result of the subtraction.</returns>
public static ComplexNumber Subtract(ComplexNumber value1, ComplexNumber value2)
{
return new ComplexNumber(value1.Real - value2.Real,
value1.Imaginary - value2.Imaginary);
}
/// <summary>
/// Subtracts one ComplexNumber from another.
/// </summary>
/// <param name="value1">The first source ComplexNumber.</param>
/// <param name="value2">The second ComplexNumber, to be subtracted from the first.</param>
/// <returns>The result of the subtraction.</returns>
public static ComplexNumber operator -(ComplexNumber value1, ComplexNumber value2) => Subtract(value1, value2);
/// <summary>
/// Multiplies two ComplexNumbers together.
/// </summary>
/// <param name="value1">The ComplexNumber on the left side of the multiplication.</param>
/// <param name="value2">The ComplexNumber on the right side of the multiplication.</param>
/// <returns>The result of the multiplication.</returns>
public static ComplexNumber Multiply(ComplexNumber value1, ComplexNumber value2)
{
return new ComplexNumber(value2.Real * value1.Real - value2.Imaginary * value1.Imaginary,
value2.Imaginary * value1.Real + value2.Real * value1.Imaginary);
}
/// <summary>
/// Multiplies two ComplexNumbers together.
/// </summary>
/// <param name="value1">The ComplexNumber on the left side of the multiplication.</param>
/// <param name="value2">The ComplexNumber on the right side of the multiplication.</param>
/// <returns>The result of the multiplication.</returns>
public static ComplexNumber operator *(ComplexNumber value1, ComplexNumber value2) => Multiply(value1, value2);
/// <summary>
/// Multiplies a ComplexNumber by a scalar value.
/// </summary>
/// <param name="value1">The source ComplexNumber.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the multiplication.</returns>
public static ComplexNumber Multiply(ComplexNumber value1, double value2)
{
return new ComplexNumber(value2 * value1.Real, value2 * value1.Imaginary);
}
/// <summary>
/// Multiplies a ComplexNumber by a scalar value.
/// </summary>
/// <param name="value1">The source ComplexNumber.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the multiplication.</returns>
public static ComplexNumber operator *(ComplexNumber value1, double value2) => Multiply(value1, value2);
/// <summary>
/// Multiplies a ComplexNumber by a scalar value.
/// </summary>
/// <param name="value1">The scalar value.</param>
/// <param name="value2">The source ComplexNumber.</param>
/// <returns>The result of the multiplication.</returns>
public static ComplexNumber operator *(double value1, ComplexNumber value2) => Multiply(value2, value1);
/// <summary>
/// Divides a ComplexNumber by another ComplexNumber.
/// </summary>
/// <param name="value1">The source ComplexNumber.</param>
/// <param name="value2">The divisor.</param>
/// <returns>The result of the division.</returns>
public static ComplexNumber Divide(ComplexNumber value1, double value2)
{
var oneOverDenom = 1 / value2;
return new ComplexNumber(oneOverDenom * value1.Real, oneOverDenom * value1.Imaginary);
}
/// <summary>
/// Divides a ComplexNumber by another ComplexNumber.
/// </summary>
/// <param name="value1">The source ComplexNumber.</param>
/// <param name="value2">The divisor.</param>
/// <returns>The result of the division.</returns>
public static ComplexNumber operator /(ComplexNumber value1, double value2) => Divide(value1, value2);
/// <summary>
/// Divides a ComplexNumber by another ComplexNumber.
/// </summary>
/// <param name="value1">The source ComplexNumber.</param>
/// <param name="value2">The divisor.</param>
/// <returns>The result of the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ComplexNumber Divide(ComplexNumber value1, ComplexNumber value2)
{
var oneOverDenom = 1 / (value2.Real * value2.Real + value2.Imaginary * value2.Imaginary);
return new ComplexNumber(oneOverDenom * (value1.Real * value2.Real + value1.Imaginary * value2.Imaginary),
oneOverDenom * (value1.Imaginary * value2.Real - value1.Real * value2.Imaginary));
}
/// <summary>
/// Divides a ComplexNumber by another ComplexNumber.
/// </summary>
/// <param name="value1">The source ComplexNumber.</param>
/// <param name="value2">The divisor.</param>
/// <returns>The result of the division.</returns>
public static ComplexNumber operator /(ComplexNumber value1, ComplexNumber value2) => Divide(value1, value2);
/// <summary>
/// Divides a ComplexNumber by another ComplexNumber.
/// </summary>
/// <param name="value1">The source ComplexNumber.</param>
/// <param name="value2">The divisor.</param>
/// <returns>The result of the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ComplexNumber Divide(double value1, ComplexNumber value2)
{
var oneOverDenom = 1 / (value2.Real * value2.Real + value2.Imaginary * value2.Imaginary);
return new ComplexNumber(oneOverDenom * value1 * value2.Real, -oneOverDenom * value1 * value2.Imaginary);
}
/// <summary>
/// Divides a ComplexNumber by another ComplexNumber.
/// </summary>
/// <param name="value1">The source ComplexNumber.</param>
/// <param name="value2">The divisor.</param>
/// <returns>The result of the division.</returns>
public static ComplexNumber operator /(double value1, ComplexNumber value2) => Divide(value1, value2);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ComplexNumber Sqrt(ComplexNumber value1)
{
if (value1.JustRealNumber)
{
if (value1.Real > 0)
return new ComplexNumber(Math.Sqrt(value1.Real));
return new ComplexNumber(0, Math.Sqrt(-value1.Real));
}
var angle = Math.Atan2(value1.Imaginary, value1.Real);
angle /= 2;
var radius = Math.Sqrt(value1.Length());
return new ComplexNumber(radius * Math.Cos(angle), radius * Math.Sin(angle));
}
public static ComplexNumber Cbrt(ComplexNumber value1)
{
if (value1.JustRealNumber) return new ComplexNumber(Math.Cbrt(value1.Real));
var angle = Math.Atan2(value1.Imaginary, value1.Real);
angle /= 3;
var radius = Math.Cbrt(value1.Length());
return new ComplexNumber(radius * Math.Cos(angle), radius * Math.Sin(angle));
}
/// <summary>
/// Returns a boolean indicating whether the two given ComplexNumbers are equal.
/// </summary>
/// <param name="value1">The first ComplexNumber to compare.</param>
/// <param name="value2">The second ComplexNumber to compare.</param>
/// <returns>True if the ComplexNumbers are equal; False otherwise.</returns>
public static bool operator ==(ComplexNumber value1, ComplexNumber value2)
{
return value1.Real == value2.Real &&
value1.Imaginary == value2.Imaginary;
}
/// <summary>
/// Returns a boolean indicating whether the two given ComplexNumbers are not equal.
/// </summary>
/// <param name="value1">The first ComplexNumber to compare.</param>
/// <param name="value2">The second ComplexNumber to compare.</param>
/// <returns>True if the ComplexNumbers are not equal; False if they are equal.</returns>
public static bool operator !=(ComplexNumber value1, ComplexNumber value2)
{
return value1.Real != value2.Real ||
value1.Imaginary != value2.Imaginary;
}
/// <summary>
/// Returns a boolean indicating whether the given ComplexNumber is equal to this ComplexNumber instance.
/// </summary>
/// <param name="other">The ComplexNumber to compare this instance to.</param>
/// <returns>True if the other ComplexNumber is equal to this instance; False otherwise.</returns>
public bool Equals(ComplexNumber other)
{
return Real == other.Real &&
Imaginary == other.Imaginary;
}
/// <summary>
/// Gets a value indicating whether [just a real number] i.e. the imaginary part is zero.
/// </summary>
/// <value><c>true</c> if [just real]; otherwise, <c>false</c>.</value>
public bool JustRealNumber => Imaginary.IsNegligible();
/// <summary>
/// Performs an explicit conversion from <see cref="ComplexNumber"/> to <see cref="System.Double"/>.
/// </summary>
/// <param name="value1">The value1.</param>
/// <returns>The result of the conversion.</returns>
public static double ToDouble(ComplexNumber value1)
{
return value1.Real;
}
/// <summary>
/// Performs an explicit conversion from <see cref="ComplexNumber"/> to <see cref="System.Double"/>.
/// </summary>
/// <param name="value1">The value1.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator double(ComplexNumber value1)
{
return value1.Real;
}
/// <summary>
/// Returns a boolean indicating whether the given Object is equal to this ComplexNumber instance.
/// </summary>
/// <param name="obj">The Object to compare against.</param>
/// <returns>True if the Object is equal to this ComplexNumber; False otherwise.</returns>
public override bool Equals(object obj)
{
if (obj is ComplexNumber ComplexNumber)
{
return Equals(ComplexNumber);
}
return false;
}
/// <summary>
/// Returns a String representing this ComplexNumber instance.
/// </summary>
/// <returns>The string representation.</returns>
public override string ToString()
{
if (JustRealNumber) string.Format(CultureInfo.CurrentCulture, "{0}", Real);
if (Imaginary < 0)
return string.Format(CultureInfo.CurrentCulture, "{0} - {1}i", Real, -Imaginary);
return string.Format(CultureInfo.CurrentCulture, "{0} + {1}i", Real, Imaginary);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
return unchecked(Real.GetHashCode() + 1234567890 * Imaginary.GetHashCode());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using FluentMigrator.Expressions;
using FluentMigrator.Model;
using FluentMigrator.Runner.Versioning;
using FluentMigrator.VersionTableInfo;
using FluentMigrator.Infrastructure;
namespace FluentMigrator.Runner
{
public class VersionLoader : IVersionLoader
{
private bool _versionSchemaMigrationAlreadyRun;
private bool _versionMigrationAlreadyRun;
private bool _versionUniqueMigrationAlreadyRun;
private bool _versionDescriptionMigrationAlreadyRun;
private IVersionInfo _versionInfo;
private IMigrationConventions Conventions { get; set; }
private IMigrationProcessor Processor { get; set; }
protected IAssemblyCollection Assemblies { get; set; }
public IVersionTableMetaData VersionTableMetaData { get; private set; }
public IMigrationRunner Runner { get; set; }
public VersionSchemaMigration VersionSchemaMigration { get; private set; }
public IMigration VersionMigration { get; private set; }
public IMigration VersionUniqueMigration { get; private set; }
public IMigration VersionDescriptionMigration { get; private set; }
public VersionLoader(IMigrationRunner runner, Assembly assembly, IMigrationConventions conventions)
: this(runner, new SingleAssembly(assembly), conventions)
{
}
public VersionLoader(IMigrationRunner runner, IAssemblyCollection assemblies, IMigrationConventions conventions)
{
Runner = runner;
Processor = runner.Processor;
Assemblies = assemblies;
Conventions = conventions;
VersionTableMetaData = GetVersionTableMetaData();
VersionMigration = new VersionMigration(VersionTableMetaData);
VersionSchemaMigration = new VersionSchemaMigration(VersionTableMetaData);
VersionUniqueMigration = new VersionUniqueMigration(VersionTableMetaData);
VersionDescriptionMigration = new VersionDescriptionMigration(VersionTableMetaData);
LoadVersionInfo();
}
public void UpdateVersionInfo(long version)
{
UpdateVersionInfo(version, null);
}
public void UpdateVersionInfo(long version, string description)
{
var dataExpression = new InsertDataExpression();
dataExpression.Rows.Add(CreateVersionInfoInsertionData(version, description));
dataExpression.TableName = VersionTableMetaData.TableName;
dataExpression.SchemaName = VersionTableMetaData.SchemaName;
dataExpression.ExecuteWith(Processor);
}
public IVersionTableMetaData GetVersionTableMetaData()
{
Type matchedType = Assemblies.GetExportedTypes().FirstOrDefault(t => Conventions.TypeIsVersionTableMetaData(t));
if (matchedType == null)
{
return new DefaultVersionTableMetaData();
}
return (IVersionTableMetaData)Activator.CreateInstance(matchedType);
}
protected virtual InsertionDataDefinition CreateVersionInfoInsertionData(long version, string description)
{
return new InsertionDataDefinition
{
new KeyValuePair<string, object>(VersionTableMetaData.ColumnName, version),
new KeyValuePair<string, object>(VersionTableMetaData.AppliedOnColumnName, DateTime.UtcNow),
new KeyValuePair<string, object>(VersionTableMetaData.DescriptionColumnName, description),
};
}
public IVersionInfo VersionInfo
{
get
{
return _versionInfo;
}
set
{
if (value == null)
throw new ArgumentException("Cannot set VersionInfo to null");
_versionInfo = value;
}
}
public bool AlreadyCreatedVersionSchema
{
get
{
return string.IsNullOrEmpty(VersionTableMetaData.SchemaName) ||
Processor.SchemaExists(VersionTableMetaData.SchemaName);
}
}
public bool AlreadyCreatedVersionTable
{
get
{
return Processor.TableExists(VersionTableMetaData.SchemaName, VersionTableMetaData.TableName);
}
}
public bool AlreadyMadeVersionUnique
{
get
{
return Processor.ColumnExists(VersionTableMetaData.SchemaName, VersionTableMetaData.TableName, VersionTableMetaData.AppliedOnColumnName);
}
}
public bool AlreadyMadeVersionDescription
{
get
{
return Processor.ColumnExists(VersionTableMetaData.SchemaName, VersionTableMetaData.TableName, VersionTableMetaData.DescriptionColumnName);
}
}
public bool OwnsVersionSchema
{
get
{
IVersionTableMetaDataExtended versionTableMetaDataExtended = VersionTableMetaData as IVersionTableMetaDataExtended;
return versionTableMetaDataExtended == null || versionTableMetaDataExtended.OwnsSchema;
}
}
public void LoadVersionInfo()
{
if (!AlreadyCreatedVersionSchema && !_versionSchemaMigrationAlreadyRun)
{
Runner.Up(VersionSchemaMigration);
_versionSchemaMigrationAlreadyRun = true;
}
if (!AlreadyCreatedVersionTable && !_versionMigrationAlreadyRun)
{
Runner.Up(VersionMigration);
_versionMigrationAlreadyRun = true;
}
if (!AlreadyMadeVersionUnique && !_versionUniqueMigrationAlreadyRun)
{
Runner.Up(VersionUniqueMigration);
_versionUniqueMigrationAlreadyRun = true;
}
if (!AlreadyMadeVersionDescription && !_versionDescriptionMigrationAlreadyRun)
{
Runner.Up(VersionDescriptionMigration);
_versionDescriptionMigrationAlreadyRun = true;
}
_versionInfo = new VersionInfo();
if (!AlreadyCreatedVersionTable) return;
var dataSet = Processor.ReadTableData(VersionTableMetaData.SchemaName, VersionTableMetaData.TableName);
foreach (DataRow row in dataSet.Tables[0].Rows)
{
_versionInfo.AddAppliedMigration(long.Parse(row[VersionTableMetaData.ColumnName].ToString()));
}
}
public void RemoveVersionTable()
{
var expression = new DeleteTableExpression { TableName = VersionTableMetaData.TableName, SchemaName = VersionTableMetaData.SchemaName };
expression.ExecuteWith(Processor);
if (OwnsVersionSchema && !string.IsNullOrEmpty(VersionTableMetaData.SchemaName))
{
var schemaExpression = new DeleteSchemaExpression { SchemaName = VersionTableMetaData.SchemaName };
schemaExpression.ExecuteWith(Processor);
}
}
public void DeleteVersion(long version)
{
var expression = new DeleteDataExpression { TableName = VersionTableMetaData.TableName, SchemaName = VersionTableMetaData.SchemaName };
expression.Rows.Add(new DeletionDataDefinition
{
new KeyValuePair<string, object>(VersionTableMetaData.ColumnName, version)
});
expression.ExecuteWith(Processor);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Xml.Serialization;
using VotingInfo.Database.Contracts;
using VotingInfo.Database.Contracts.Auth;
//////////////////////////////////////////////////////////////
//Do not modify this file. Use a partial class to extend. //
//Override methods in the logic front class. //
//////////////////////////////////////////////////////////////
namespace VotingInfo.Database.Logic.Auth
{
[Serializable]
public abstract partial class PermissionLogicBase : LogicBase<PermissionLogicBase>
{
//Put your code in a separate file. This is auto generated.
[XmlArray] public List<PermissionContract> Results;
public PermissionLogicBase()
{
Results = new List<PermissionContract>();
}
/// <summary>
/// Run Permission_SelectBy_UserId, and return results as a list of PermissionRow.
/// </summary>
/// <param name="fldUserId">Value for UserId</param>
/// <returns>A collection of PermissionRow.</returns>
public virtual bool SelectBy_UserId(int fldUserId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Auth].[Permission_SelectBy_UserId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@UserId", fldUserId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Permission_SelectBy_UserId, and return results as a list of PermissionRow.
/// </summary>
/// <param name="fldUserId">Value for UserId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of PermissionRow.</returns>
public virtual bool SelectBy_UserId(int fldUserId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Auth].[Permission_SelectBy_UserId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@UserId", fldUserId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Permission_Insert.
/// </summary>
/// <param name="fldPermissionName">Value for PermissionName</param>
/// <param name="fldTitle">Value for Title</param>
/// <param name="fldIsRead">Value for IsRead</param>
/// <returns>The new ID</returns>
public virtual int? Insert(string fldPermissionName
, string fldTitle
, bool fldIsRead
)
{
int? result = null;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Auth].[Permission_Insert]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionName", fldPermissionName)
,
new SqlParameter("@Title", fldTitle)
,
new SqlParameter("@IsRead", fldIsRead)
});
result = (int?)cmd.ExecuteScalar();
}
});
return result;
}
/// <summary>
/// Run Permission_Insert.
/// </summary>
/// <param name="fldPermissionName">Value for PermissionName</param>
/// <param name="fldTitle">Value for Title</param>
/// <param name="fldIsRead">Value for IsRead</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The new ID</returns>
public virtual int? Insert(string fldPermissionName
, string fldTitle
, bool fldIsRead
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Auth].[Permission_Insert]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionName", fldPermissionName)
,
new SqlParameter("@Title", fldTitle)
,
new SqlParameter("@IsRead", fldIsRead)
});
return (int?)cmd.ExecuteScalar();
}
}
/// <summary>
/// Insert by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>1, if insert was successful</returns>
public int Insert(PermissionContract row)
{
int? result = null;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Auth].[Permission_Insert]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionName", row.PermissionName)
,
new SqlParameter("@Title", row.Title)
,
new SqlParameter("@IsRead", row.IsRead)
});
result = (int?)cmd.ExecuteScalar();
row.PermissionId = result;
}
});
return result != null ? 1 : 0;
}
/// <summary>
/// Insert by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>1, if insert was successful</returns>
public int Insert(PermissionContract row, SqlConnection connection, SqlTransaction transaction)
{
int? result = null;
using (
var cmd = new SqlCommand("[Auth].[Permission_Insert]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionName", row.PermissionName)
,
new SqlParameter("@Title", row.Title)
,
new SqlParameter("@IsRead", row.IsRead)
});
result = (int?)cmd.ExecuteScalar();
row.PermissionId = result;
}
return result != null ? 1 : 0;
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <returns>The number of rows affected.</returns>
public virtual int InsertAll(List<PermissionContract> rows)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
rowCount = InsertAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int InsertAll(List<PermissionContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Insert(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Run Permission_Update.
/// </summary>
/// <returns>The number of rows affected.</returns>
/// <param name="fldPermissionId">Value for PermissionId</param>
/// <param name="fldPermissionName">Value for PermissionName</param>
/// <param name="fldTitle">Value for Title</param>
/// <param name="fldIsRead">Value for IsRead</param>
public virtual int Update(int fldPermissionId
, string fldPermissionName
, string fldTitle
, bool fldIsRead
)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Auth].[Permission_Update]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionId", fldPermissionId)
,
new SqlParameter("@PermissionName", fldPermissionName)
,
new SqlParameter("@Title", fldTitle)
,
new SqlParameter("@IsRead", fldIsRead)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Run Permission_Update.
/// </summary>
/// <param name="fldPermissionId">Value for PermissionId</param>
/// <param name="fldPermissionName">Value for PermissionName</param>
/// <param name="fldTitle">Value for Title</param>
/// <param name="fldIsRead">Value for IsRead</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(int fldPermissionId
, string fldPermissionName
, string fldTitle
, bool fldIsRead
, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Auth].[Permission_Update]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionId", fldPermissionId)
,
new SqlParameter("@PermissionName", fldPermissionName)
,
new SqlParameter("@Title", fldTitle)
,
new SqlParameter("@IsRead", fldIsRead)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Update by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(PermissionContract row)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Auth].[Permission_Update]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionId", row.PermissionId)
,
new SqlParameter("@PermissionName", row.PermissionName)
,
new SqlParameter("@Title", row.Title)
,
new SqlParameter("@IsRead", row.IsRead)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Update by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(PermissionContract row, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Auth].[Permission_Update]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionId", row.PermissionId)
,
new SqlParameter("@PermissionName", row.PermissionName)
,
new SqlParameter("@Title", row.Title)
,
new SqlParameter("@IsRead", row.IsRead)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <returns>The number of rows affected.</returns>
public virtual int UpdateAll(List<PermissionContract> rows)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
rowCount = UpdateAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int UpdateAll(List<PermissionContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Update(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Run Permission_Delete.
/// </summary>
/// <returns>The number of rows affected.</returns>
/// <param name="fldPermissionId">Value for PermissionId</param>
public virtual int Delete(int fldPermissionId
)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Auth].[Permission_Delete]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionId", fldPermissionId)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Run Permission_Delete.
/// </summary>
/// <param name="fldPermissionId">Value for PermissionId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(int fldPermissionId
, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Auth].[Permission_Delete]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionId", fldPermissionId)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Delete by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(PermissionContract row)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Auth].[Permission_Delete]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionId", row.PermissionId)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Delete by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(PermissionContract row, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Auth].[Permission_Delete]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionId", row.PermissionId)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <returns>The number of rows affected.</returns>
public virtual int DeleteAll(List<PermissionContract> rows)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
rowCount = DeleteAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int DeleteAll(List<PermissionContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Delete(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldPermissionId">Value for PermissionId</param>
/// <returns>True, if the values exist, or false.</returns>
public virtual bool Exists(int fldPermissionId
)
{
bool result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Auth].[Permission_Exists]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionId", fldPermissionId)
});
result = (bool)cmd.ExecuteScalar();
}
});
return result;
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldPermissionId">Value for PermissionId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>True, if the values exist, or false.</returns>
public virtual bool Exists(int fldPermissionId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Auth].[Permission_Exists]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionId", fldPermissionId)
});
return (bool)cmd.ExecuteScalar();
}
}
/// <summary>
/// Run Permission_Search, and return results as a list of PermissionRow.
/// </summary>
/// <param name="fldPermissionName">Value for PermissionName</param>
/// <param name="fldTitle">Value for Title</param>
/// <returns>A collection of PermissionRow.</returns>
public virtual bool Search(string fldPermissionName
, string fldTitle
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Auth].[Permission_Search]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionName", fldPermissionName)
,
new SqlParameter("@Title", fldTitle)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Permission_Search, and return results as a list of PermissionRow.
/// </summary>
/// <param name="fldPermissionName">Value for PermissionName</param>
/// <param name="fldTitle">Value for Title</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of PermissionRow.</returns>
public virtual bool Search(string fldPermissionName
, string fldTitle
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Auth].[Permission_Search]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionName", fldPermissionName)
,
new SqlParameter("@Title", fldTitle)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Permission_SelectAll, and return results as a list of PermissionRow.
/// </summary>
/// <returns>A collection of PermissionRow.</returns>
public virtual bool SelectAll()
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Auth].[Permission_SelectAll]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Permission_SelectAll, and return results as a list of PermissionRow.
/// </summary>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of PermissionRow.</returns>
public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Auth].[Permission_SelectAll]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Permission_List, and return results as a list.
/// </summary>
/// <param name="fldTitle">Value for Title</param>
/// <returns>A collection of __ListItemRow.</returns>
public virtual List<ListItemContract> List(string fldTitle
)
{
List<ListItemContract> result = null;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Auth].[Permission_List]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@Title", fldTitle)
});
using(var r = cmd.ExecuteReader()) result = ListItemLogic.ReadAllNow(r);
}
});
return result;
}
/// <summary>
/// Run Permission_List, and return results as a list.
/// </summary>
/// <param name="fldTitle">Value for Title</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of __ListItemRow.</returns>
public virtual List<ListItemContract> List(string fldTitle
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Auth].[Permission_List]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@Title", fldTitle)
});
using(var r = cmd.ExecuteReader()) return ListItemLogic.ReadAllNow(r);
}
}
/// <summary>
/// Run Permission_SelectBy_PermissionId, and return results as a list of PermissionRow.
/// </summary>
/// <param name="fldPermissionId">Value for PermissionId</param>
/// <returns>A collection of PermissionRow.</returns>
public virtual bool SelectBy_PermissionId(int fldPermissionId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Auth].[Permission_SelectBy_PermissionId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionId", fldPermissionId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Permission_SelectBy_PermissionId, and return results as a list of PermissionRow.
/// </summary>
/// <param name="fldPermissionId">Value for PermissionId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of PermissionRow.</returns>
public virtual bool SelectBy_PermissionId(int fldPermissionId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Auth].[Permission_SelectBy_PermissionId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@PermissionId", fldPermissionId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Read all items into this collection
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
public virtual bool ReadAll(SqlDataReader reader)
{
var canRead = ReadOne(reader);
var result = canRead;
while (canRead) canRead = ReadOne(reader);
return result;
}
/// <summary>
/// Read one item into Results
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
public virtual bool ReadOne(SqlDataReader reader)
{
if (reader.Read())
{
Results.Add(
new PermissionContract
{
PermissionId = reader.GetInt32(0),
PermissionName = reader.GetString(1),
Title = reader.GetString(2),
IsRead = reader.GetBoolean(3),
});
return true;
}
return false;
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <returns>The number of rows affected.</returns>
public virtual int Save(PermissionContract row)
{
if(row == null) return 0;
if(row.PermissionId != null) return Update(row);
return Insert(row);
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Save(PermissionContract row, SqlConnection connection, SqlTransaction transaction)
{
if(row == null) return 0;
if(row.PermissionId != null) return Update(row, connection, transaction);
return Insert(row, connection, transaction);
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <returns>The number of rows affected.</returns>
public virtual int SaveAll(List<PermissionContract> rows)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
foreach(var row in rows) rowCount += Save(row, x, null);
});
return rowCount;
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int SaveAll(List<PermissionContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Save(row, connection, transaction);
return rowCount;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using Newtonsoft.Json.Schema;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0
using System.Numerics;
#endif
using System.Runtime.Serialization;
using System.Text;
#if !(NET20 || NET35)
using System.Threading.Tasks;
#endif
using System.Xml;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Tests.TestObjects.Organization;
using Newtonsoft.Json.Utilities;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
namespace Newtonsoft.Json.Tests
{
[TestFixture]
public class JsonConvertTest : TestFixtureBase
{
[Test]
public void ToStringEnsureEscapedArrayLength()
{
const char nonAsciiChar = (char)257;
const char escapableNonQuoteAsciiChar = '\0';
string value = nonAsciiChar + @"\" + escapableNonQuoteAsciiChar;
string convertedValue = JsonConvert.ToString((object)value);
Assert.AreEqual(@"""" + nonAsciiChar + @"\\\u0000""", convertedValue);
}
public class PopulateTestObject
{
public decimal Prop { get; set; }
}
[Test]
public void PopulateObjectWithHeaderComment()
{
string json = @"// file header
{
""prop"": 1.0
}";
PopulateTestObject o = new PopulateTestObject();
JsonConvert.PopulateObject(json, o);
Assert.AreEqual(1m, o.Prop);
}
[Test]
public void PopulateObjectWithMultipleHeaderComment()
{
string json = @"// file header
// another file header?
{
""prop"": 1.0
}";
PopulateTestObject o = new PopulateTestObject();
JsonConvert.PopulateObject(json, o);
Assert.AreEqual(1m, o.Prop);
}
[Test]
public void PopulateObjectWithNoContent()
{
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
string json = @"";
PopulateTestObject o = new PopulateTestObject();
JsonConvert.PopulateObject(json, o);
}, "No JSON content found. Path '', line 0, position 0.");
}
[Test]
public void PopulateObjectWithOnlyComment()
{
var ex = ExceptionAssert.Throws<JsonSerializationException>(() =>
{
string json = @"// file header";
PopulateTestObject o = new PopulateTestObject();
JsonConvert.PopulateObject(json, o);
}, "No JSON content found. Path '', line 1, position 14.");
Assert.AreEqual(1, ex.LineNumber);
Assert.AreEqual(14, ex.LinePosition);
Assert.AreEqual(string.Empty, ex.Path);
}
[Test]
public void DefaultSettings()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } });
StringAssert.AreEqual(@"{
""test"": [
1,
2,
3
]
}", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
public class NameTableTestClass
{
public string Value { get; set; }
}
public class NameTableTestClassConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
reader.Read();
reader.Read();
JsonTextReader jsonTextReader = (JsonTextReader)reader;
Assert.IsNotNull(jsonTextReader.PropertyNameTable);
string s = serializer.Deserialize<string>(reader);
Assert.AreEqual("hi", s);
Assert.IsNotNull(jsonTextReader.PropertyNameTable);
NameTableTestClass o = new NameTableTestClass
{
Value = s
};
return o;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(NameTableTestClass);
}
}
[Test]
public void NameTableTest()
{
StringReader sr = new StringReader("{'property':'hi'}");
JsonTextReader jsonTextReader = new JsonTextReader(sr);
Assert.IsNull(jsonTextReader.PropertyNameTable);
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new NameTableTestClassConverter());
NameTableTestClass o = serializer.Deserialize<NameTableTestClass>(jsonTextReader);
Assert.IsNull(jsonTextReader.PropertyNameTable);
Assert.AreEqual("hi", o.Value);
}
public class CustonNameTable : JsonNameTable
{
public override string Get(char[] key, int start, int length)
{
return "_" + new string(key, start, length);
}
}
[Test]
public void CustonNameTableTest()
{
StringReader sr = new StringReader("{'property':'hi'}");
JsonTextReader jsonTextReader = new JsonTextReader(sr);
Assert.IsNull(jsonTextReader.PropertyNameTable);
var nameTable = jsonTextReader.PropertyNameTable = new CustonNameTable();
JsonSerializer serializer = new JsonSerializer();
Dictionary<string, string> o = serializer.Deserialize<Dictionary<string, string>>(jsonTextReader);
Assert.AreEqual("hi", o["_property"]);
Assert.AreEqual(nameTable, jsonTextReader.PropertyNameTable);
}
[Test]
public void DefaultSettings_Example()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
Employee e = new Employee
{
FirstName = "Eric",
LastName = "Example",
BirthDate = new DateTime(1980, 4, 20, 0, 0, 0, DateTimeKind.Utc),
Department = "IT",
JobTitle = "Web Dude"
};
string json = JsonConvert.SerializeObject(e);
// {
// "firstName": "Eric",
// "lastName": "Example",
// "birthDate": "1980-04-20T00:00:00Z",
// "department": "IT",
// "jobTitle": "Web Dude"
// }
StringAssert.AreEqual(@"{
""firstName"": ""Eric"",
""lastName"": ""Example"",
""birthDate"": ""1980-04-20T00:00:00Z"",
""department"": ""IT"",
""jobTitle"": ""Web Dude""
}", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_Override()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } }, new JsonSerializerSettings
{
Formatting = Formatting.None
});
Assert.AreEqual(@"{""test"":[1,2,3]}", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_Override_JsonConverterOrder()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
Converters = { new IsoDateTimeConverter { DateTimeFormat = "yyyy" } }
};
string json = JsonConvert.SerializeObject(new[] { new DateTime(2000, 12, 12, 4, 2, 4, DateTimeKind.Utc) }, new JsonSerializerSettings
{
Formatting = Formatting.None,
Converters =
{
// should take precedence
new JavaScriptDateTimeConverter(),
new IsoDateTimeConverter { DateTimeFormat = "dd" }
}
});
Assert.AreEqual(@"[new Date(976593724000)]", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_Create()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
IList<int> l = new List<int> { 1, 2, 3 };
StringWriter sw = new StringWriter();
JsonSerializer serializer = JsonSerializer.CreateDefault();
serializer.Serialize(sw, l);
StringAssert.AreEqual(@"[
1,
2,
3
]", sw.ToString());
sw = new StringWriter();
serializer.Formatting = Formatting.None;
serializer.Serialize(sw, l);
Assert.AreEqual(@"[1,2,3]", sw.ToString());
sw = new StringWriter();
serializer = new JsonSerializer();
serializer.Serialize(sw, l);
Assert.AreEqual(@"[1,2,3]", sw.ToString());
sw = new StringWriter();
serializer = JsonSerializer.Create();
serializer.Serialize(sw, l);
Assert.AreEqual(@"[1,2,3]", sw.ToString());
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_CreateWithSettings()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
IList<int> l = new List<int> { 1, 2, 3 };
StringWriter sw = new StringWriter();
JsonSerializer serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
{
Converters = { new IntConverter() }
});
serializer.Serialize(sw, l);
StringAssert.AreEqual(@"[
2,
4,
6
]", sw.ToString());
sw = new StringWriter();
serializer.Converters.Clear();
serializer.Serialize(sw, l);
StringAssert.AreEqual(@"[
1,
2,
3
]", sw.ToString());
sw = new StringWriter();
serializer = JsonSerializer.Create(new JsonSerializerSettings { Formatting = Formatting.Indented });
serializer.Serialize(sw, l);
StringAssert.AreEqual(@"[
1,
2,
3
]", sw.ToString());
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
public class IntConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
int i = (int)value;
writer.WriteValue(i * 2);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(int);
}
}
[Test]
public void DeserializeObject_EmptyString()
{
object result = JsonConvert.DeserializeObject(string.Empty);
Assert.IsNull(result);
}
[Test]
public void DeserializeObject_Integer()
{
object result = JsonConvert.DeserializeObject("1");
Assert.AreEqual(1L, result);
}
[Test]
public void DeserializeObject_Integer_EmptyString()
{
int? value = JsonConvert.DeserializeObject<int?>("");
Assert.IsNull(value);
}
[Test]
public void DeserializeObject_Decimal_EmptyString()
{
decimal? value = JsonConvert.DeserializeObject<decimal?>("");
Assert.IsNull(value);
}
[Test]
public void DeserializeObject_DateTime_EmptyString()
{
DateTime? value = JsonConvert.DeserializeObject<DateTime?>("");
Assert.IsNull(value);
}
[Test]
public void EscapeJavaScriptString()
{
string result;
result = JavaScriptUtils.ToEscapedJavaScriptString("How now brown cow?", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""How now brown cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("How now 'brown' cow?", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""How now 'brown' cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("How now <brown> cow?", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""How now <brown> cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("How \r\nnow brown cow?", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""How \r\nnow brown cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007""", result);
result =
JavaScriptUtils.ToEscapedJavaScriptString("\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013""", result);
result =
JavaScriptUtils.ToEscapedJavaScriptString(
"\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f ", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f """, result);
result =
JavaScriptUtils.ToEscapedJavaScriptString(
"!\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""!\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("^_`abcdefghijklmnopqrstuvwxyz{|}~", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""^_`abcdefghijklmnopqrstuvwxyz{|}~""", result);
string data =
"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
string expected =
@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~""";
result = JavaScriptUtils.ToEscapedJavaScriptString(data, '"', true, StringEscapeHandling.Default);
Assert.AreEqual(expected, result);
result = JavaScriptUtils.ToEscapedJavaScriptString("Fred's cat.", '\'', true, StringEscapeHandling.Default);
Assert.AreEqual(result, @"'Fred\'s cat.'");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are you gentlemen?"" said Cats.", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(result, @"""\""How are you gentlemen?\"" said Cats.""");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are' you gentlemen?"" said Cats.", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(result, @"""\""How are' you gentlemen?\"" said Cats.""");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"Fred's ""cat"".", '\'', true, StringEscapeHandling.Default);
Assert.AreEqual(result, @"'Fred\'s ""cat"".'");
result = JavaScriptUtils.ToEscapedJavaScriptString("\u001farray\u003caddress", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(result, @"""\u001farray<address""");
}
[Test]
public void EscapeJavaScriptString_UnicodeLinefeeds()
{
string result;
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u0085' + "after", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""before\u0085after""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2028' + "after", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""before\u2028after""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2029' + "after", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""before\u2029after""", result);
}
[Test]
public void ToStringInvalid()
{
ExceptionAssert.Throws<ArgumentException>(() => { JsonConvert.ToString(new Version(1, 0)); }, "Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.");
}
[Test]
public void GuidToString()
{
Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
string json = JsonConvert.ToString(guid);
Assert.AreEqual(@"""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""", json);
}
[Test]
public void EnumToString()
{
string json = JsonConvert.ToString(StringComparison.CurrentCultureIgnoreCase);
Assert.AreEqual("1", json);
}
[Test]
public void ObjectToString()
{
object value;
value = 1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = 1.1;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = 1.1m;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = (float)1.1;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = (short)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (long)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (byte)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (uint)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (ushort)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (sbyte)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (ulong)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
Assert.AreEqual(@"""1970-01-01T00:00:00Z""", JsonConvert.ToString(value));
value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
Assert.AreEqual(@"""\/Date(0)\/""", JsonConvert.ToString((DateTime)value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind));
#if !NET20
value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero);
Assert.AreEqual(@"""1970-01-01T00:00:00+00:00""", JsonConvert.ToString(value));
value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero);
Assert.AreEqual(@"""\/Date(0+0000)\/""", JsonConvert.ToString((DateTimeOffset)value, DateFormatHandling.MicrosoftDateFormat));
#endif
value = null;
Assert.AreEqual("null", JsonConvert.ToString(value));
#if !(PORTABLE || DNXCORE50 || PORTABLE40)
value = DBNull.Value;
Assert.AreEqual("null", JsonConvert.ToString(value));
#endif
value = "I am a string";
Assert.AreEqual(@"""I am a string""", JsonConvert.ToString(value));
value = true;
Assert.AreEqual("true", JsonConvert.ToString(value));
value = 'c';
Assert.AreEqual(@"""c""", JsonConvert.ToString(value));
}
[Test]
public void TestInvalidStrings()
{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string orig = @"this is a string ""that has quotes"" ";
string serialized = JsonConvert.SerializeObject(orig);
// *** Make string invalid by stripping \" \"
serialized = serialized.Replace(@"\""", "\"");
JsonConvert.DeserializeObject<string>(serialized);
}, "Additional text encountered after finished reading JSON content: t. Path '', line 1, position 19.");
}
[Test]
public void DeserializeValueObjects()
{
int i = JsonConvert.DeserializeObject<int>("1");
Assert.AreEqual(1, i);
#if !NET20
DateTimeOffset d = JsonConvert.DeserializeObject<DateTimeOffset>(@"""\/Date(-59011455539000+0000)\/""");
Assert.AreEqual(new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)), d);
#endif
bool b = JsonConvert.DeserializeObject<bool>("true");
Assert.AreEqual(true, b);
object n = JsonConvert.DeserializeObject<object>("null");
Assert.AreEqual(null, n);
object u = JsonConvert.DeserializeObject<object>("undefined");
Assert.AreEqual(null, u);
}
[Test]
public void FloatToString()
{
Assert.AreEqual("1.1", JsonConvert.ToString(1.1));
Assert.AreEqual("1.11", JsonConvert.ToString(1.11));
Assert.AreEqual("1.111", JsonConvert.ToString(1.111));
Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111));
Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111));
Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111));
Assert.AreEqual("1.0", JsonConvert.ToString(1.0));
Assert.AreEqual("1.0", JsonConvert.ToString(1d));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1d));
Assert.AreEqual("1.01", JsonConvert.ToString(1.01));
Assert.AreEqual("1.001", JsonConvert.ToString(1.001));
Assert.AreEqual(JsonConvert.PositiveInfinity, JsonConvert.ToString(Double.PositiveInfinity));
Assert.AreEqual(JsonConvert.NegativeInfinity, JsonConvert.ToString(Double.NegativeInfinity));
Assert.AreEqual(JsonConvert.NaN, JsonConvert.ToString(Double.NaN));
}
[Test]
public void DecimalToString()
{
Assert.AreEqual("1.1", JsonConvert.ToString(1.1m));
Assert.AreEqual("1.11", JsonConvert.ToString(1.11m));
Assert.AreEqual("1.111", JsonConvert.ToString(1.111m));
Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111m));
Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111m));
Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111m));
Assert.AreEqual("1.0", JsonConvert.ToString(1.0m));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1.0m));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1m));
Assert.AreEqual("1.0", JsonConvert.ToString(1m));
Assert.AreEqual("1.01", JsonConvert.ToString(1.01m));
Assert.AreEqual("1.001", JsonConvert.ToString(1.001m));
Assert.AreEqual("79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MaxValue));
Assert.AreEqual("-79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MinValue));
}
[Test]
public void StringEscaping()
{
string v = "It's a good day\r\n\"sunshine\"";
string json = JsonConvert.ToString(v);
Assert.AreEqual(@"""It's a good day\r\n\""sunshine\""""", json);
}
[Test]
public void ToStringStringEscapeHandling()
{
string v = "<b>hi " + '\u20AC' + "</b>";
string json = JsonConvert.ToString(v, '"');
Assert.AreEqual(@"""<b>hi " + '\u20AC' + @"</b>""", json);
json = JsonConvert.ToString(v, '"', StringEscapeHandling.EscapeHtml);
Assert.AreEqual(@"""\u003cb\u003ehi " + '\u20AC' + @"\u003c/b\u003e""", json);
json = JsonConvert.ToString(v, '"', StringEscapeHandling.EscapeNonAscii);
Assert.AreEqual(@"""<b>hi \u20ac</b>""", json);
}
[Test]
public void WriteDateTime()
{
DateTimeResult result = null;
result = TestDateTime("DateTime Max", DateTime.MaxValue);
Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateRoundtrip);
Assert.AreEqual("9999-12-31T23:59:59.9999999" + GetOffset(DateTime.MaxValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateUnspecified);
Assert.AreEqual("9999-12-31T23:59:59.9999999Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(253402300799999" + GetOffset(DateTime.MaxValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUtc);
DateTime year2000local = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local);
string localToUtcDate = year2000local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local", year2000local);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + @")\/", result.MsDateUtc);
DateTime millisecondsLocal = new DateTime(2000, 1, 1, 1, 1, 1, 999, DateTimeKind.Local);
localToUtcDate = millisecondsLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local with milliseconds", millisecondsLocal);
Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01.999", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + @")\/", result.MsDateUtc);
DateTime ticksLocal = new DateTime(636556897826822481, DateTimeKind.Local);
localToUtcDate = ticksLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local with ticks", ticksLocal);
Assert.AreEqual("2018-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2018-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2018-03-03T16:03:02.6822481", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + @")\/", result.MsDateUtc);
DateTime year2000Unspecified = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified);
result = TestDateTime("DateTime Unspecified", year2000Unspecified);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000Unspecified, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified.ToLocalTime()) + @")\/", result.MsDateUtc);
DateTime year2000Utc = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
string utcTolocalDate = year2000Utc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");
result = TestDateTime("DateTime Utc", year2000Utc);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateRoundtrip);
Assert.AreEqual(utcTolocalDate + GetOffset(year2000Utc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(946688461000" + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(year2000Utc, DateTimeKind.Unspecified)) + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateUtc);
DateTime unixEpoc = new DateTime(621355968000000000, DateTimeKind.Utc);
utcTolocalDate = unixEpoc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");
result = TestDateTime("DateTime Unix Epoc", unixEpoc);
Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateRoundtrip);
Assert.AreEqual(utcTolocalDate + GetOffset(unixEpoc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("1970-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(0)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(0" + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(unixEpoc, DateTimeKind.Unspecified)) + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(0)\/", result.MsDateUtc);
result = TestDateTime("DateTime Min", DateTime.MinValue);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(DateTime.MinValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(DateTime.MinValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);
result = TestDateTime("DateTime Default", default(DateTime));
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(default(DateTime), DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(default(DateTime), DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);
#if !NET20
result = TestDateTime("DateTimeOffset TimeSpan Zero", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
Assert.AreEqual("2000-01-01T01:01:01+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946688461000+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 1 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1)));
Assert.AreEqual("2000-01-01T01:01:01+01:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946684861000+0100)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 1.5 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1.5)));
Assert.AreEqual("2000-01-01T01:01:01+01:30", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946683061000+0130)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 13 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)));
Assert.AreEqual("2000-01-01T01:01:01+13:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946641661000+1300)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan with ticks", new DateTimeOffset(634663873826822481, TimeSpan.Zero));
Assert.AreEqual("2012-03-03T16:03:02.6822481+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(1330790582682+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Min", DateTimeOffset.MinValue);
Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Max", DateTimeOffset.MaxValue);
Assert.AreEqual("9999-12-31T23:59:59.9999999+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(253402300799999+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Default", default(DateTimeOffset));
Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);
#endif
}
public class DateTimeResult
{
public string IsoDateRoundtrip { get; set; }
public string IsoDateLocal { get; set; }
public string IsoDateUnspecified { get; set; }
public string IsoDateUtc { get; set; }
public string MsDateRoundtrip { get; set; }
public string MsDateLocal { get; set; }
public string MsDateUnspecified { get; set; }
public string MsDateUtc { get; set; }
}
private DateTimeResult TestDateTime<T>(string name, T value)
{
Console.WriteLine(name);
DateTimeResult result = new DateTimeResult()
{
IsoDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind)
};
if (value is DateTime)
{
result.IsoDateLocal = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Local);
result.IsoDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Unspecified);
result.IsoDateUtc = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Utc);
}
result.MsDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind);
if (value is DateTime)
{
result.MsDateLocal = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Local);
result.MsDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Unspecified);
result.MsDateUtc = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Utc);
}
TestDateTimeFormat(value, new IsoDateTimeConverter());
if (value is DateTime)
{
Console.WriteLine(XmlConvert.ToString((DateTime)(object)value, XmlDateTimeSerializationMode.RoundtripKind));
}
else
{
Console.WriteLine(XmlConvert.ToString((DateTimeOffset)(object)value));
}
#if !NET20
MemoryStream ms = new MemoryStream();
DataContractSerializer s = new DataContractSerializer(typeof(T));
s.WriteObject(ms, value);
string json = Encoding.UTF8.GetString(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
Console.WriteLine(json);
#endif
Console.WriteLine();
return result;
}
private static string TestDateTimeFormat<T>(T value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
{
string date = null;
if (value is DateTime)
{
date = JsonConvert.ToString((DateTime)(object)value, format, timeZoneHandling);
}
else
{
#if !NET20
date = JsonConvert.ToString((DateTimeOffset)(object)value, format);
#endif
}
Console.WriteLine(format.ToString("g") + "-" + timeZoneHandling.ToString("g") + ": " + date);
if (timeZoneHandling == DateTimeZoneHandling.RoundtripKind)
{
T parsed = JsonConvert.DeserializeObject<T>(date);
if (!value.Equals(parsed))
{
long valueTicks = GetTicks(value);
long parsedTicks = GetTicks(parsed);
valueTicks = (valueTicks / 10000) * 10000;
Assert.AreEqual(valueTicks, parsedTicks);
}
}
return date.Trim('"');
}
private static void TestDateTimeFormat<T>(T value, JsonConverter converter)
{
string date = Write(value, converter);
Console.WriteLine(converter.GetType().Name + ": " + date);
T parsed = Read<T>(date, converter);
try
{
Assert.AreEqual(value, parsed);
}
catch (Exception)
{
// JavaScript ticks aren't as precise, recheck after rounding
long valueTicks = GetTicks(value);
long parsedTicks = GetTicks(parsed);
valueTicks = (valueTicks / 10000) * 10000;
Assert.AreEqual(valueTicks, parsedTicks);
}
}
public static long GetTicks(object value)
{
return (value is DateTime) ? ((DateTime)value).Ticks : ((DateTimeOffset)value).Ticks;
}
public static string Write(object value, JsonConverter converter)
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
converter.WriteJson(writer, value, null);
writer.Flush();
return sw.ToString();
}
public static T Read<T>(string text, JsonConverter converter)
{
JsonTextReader reader = new JsonTextReader(new StringReader(text));
reader.ReadAsString();
return (T)converter.ReadJson(reader, typeof(T), null, null);
}
[Test]
public void SerializeObjectDateTimeZoneHandling()
{
string json = JsonConvert.SerializeObject(
new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc
});
Assert.AreEqual(@"""2000-01-01T01:01:01Z""", json);
}
[Test]
public void DeserializeObject()
{
string json = @"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";
Movie m = JsonConvert.DeserializeObject<Movie>(json);
string name = m.Name;
// Bad Boys
Assert.AreEqual("Bad Boys", m.Name);
}
#if !NET20
[Test]
public void TestJsonDateTimeOffsetRoundtrip()
{
var now = DateTimeOffset.Now;
var dict = new Dictionary<string, object> { { "foo", now } };
var settings = new JsonSerializerSettings()
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateParseHandling = DateParseHandling.DateTimeOffset,
DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind
};
var json = JsonConvert.SerializeObject(dict, settings);
var newDict = new Dictionary<string, object>();
JsonConvert.PopulateObject(json, newDict, settings);
var date = newDict["foo"];
Assert.AreEqual(date, now);
}
[Test]
public void MaximumDateTimeOffsetLength()
{
DateTimeOffset dt = new DateTimeOffset(2000, 12, 31, 20, 59, 59, new TimeSpan(0, 11, 33, 0, 0));
dt = dt.AddTicks(9999999);
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteValue(dt);
writer.Flush();
Assert.AreEqual(@"""2000-12-31T20:59:59.9999999+11:33""", sw.ToString());
}
#endif
[Test]
public void MaximumDateTimeLength()
{
DateTime dt = new DateTime(2000, 12, 31, 20, 59, 59, DateTimeKind.Local);
dt = dt.AddTicks(9999999);
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteValue(dt);
writer.Flush();
}
[Test]
public void MaximumDateTimeMicrosoftDateFormatLength()
{
DateTime dt = DateTime.MaxValue;
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw)
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};
writer.WriteValue(dt);
writer.Flush();
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0
[Test]
public void IntegerLengthOverflows()
{
// Maximum javascript number length (in characters) is 380
JObject o = JObject.Parse(@"{""biginteger"":" + new String('9', 380) + "}");
JValue v = (JValue)o["biginteger"];
Assert.AreEqual(JTokenType.Integer, v.Type);
Assert.AreEqual(typeof(BigInteger), v.Value.GetType());
Assert.AreEqual(BigInteger.Parse(new String('9', 380)), (BigInteger)v.Value);
ExceptionAssert.Throws<JsonReaderException>(() => JObject.Parse(@"{""biginteger"":" + new String('9', 381) + "}"), "JSON integer " + new String('9', 381) + " is too large to parse. Path 'biginteger', line 1, position 395.");
}
#endif
[Test]
public void ParseIsoDate()
{
StringReader sr = new StringReader(@"""2014-02-14T14:25:02-13:00""");
JsonReader jsonReader = new JsonTextReader(sr);
Assert.IsTrue(jsonReader.Read());
Assert.AreEqual(typeof(DateTime), jsonReader.ValueType);
}
#if false
[Test]
public void StackOverflowTest()
{
StringBuilder sb = new StringBuilder();
int depth = 900;
for (int i = 0; i < depth; i++)
{
sb.Append("{'A':");
}
// invalid json
sb.Append("{***}");
for (int i = 0; i < depth; i++)
{
sb.Append("}");
}
string json = sb.ToString();
JsonSerializer serializer = new JsonSerializer() { };
serializer.Deserialize<Nest>(new JsonTextReader(new StringReader(json)));
}
#endif
public class Nest
{
public Nest A { get; set; }
}
[Test]
public void ParametersPassedToJsonConverterConstructor()
{
ClobberMyProperties clobber = new ClobberMyProperties { One = "Red", Two = "Green", Three = "Yellow", Four = "Black" };
string json = JsonConvert.SerializeObject(clobber);
Assert.AreEqual("{\"One\":\"Uno-1-Red\",\"Two\":\"Dos-2-Green\",\"Three\":\"Tres-1337-Yellow\",\"Four\":\"Black\"}", json);
}
public class ClobberMyProperties
{
[JsonConverter(typeof(ClobberingJsonConverter), "Uno", 1)]
public string One { get; set; }
[JsonConverter(typeof(ClobberingJsonConverter), "Dos", 2)]
public string Two { get; set; }
[JsonConverter(typeof(ClobberingJsonConverter), "Tres")]
public string Three { get; set; }
public string Four { get; set; }
}
public class ClobberingJsonConverter : JsonConverter
{
public string ClobberValueString { get; private set; }
public int ClobberValueInt { get; private set; }
public ClobberingJsonConverter(string clobberValueString, int clobberValueInt)
{
ClobberValueString = clobberValueString;
ClobberValueInt = clobberValueInt;
}
public ClobberingJsonConverter(string clobberValueString)
: this(clobberValueString, 1337)
{
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(ClobberValueString + "-" + ClobberValueInt.ToString() + "-" + value.ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
}
[Test]
public void WrongParametersPassedToJsonConvertConstructorShouldThrow()
{
IncorrectJsonConvertParameters value = new IncorrectJsonConvertParameters { One = "Boom" };
ExceptionAssert.Throws<JsonException>(() => { JsonConvert.SerializeObject(value); });
}
public class IncorrectJsonConvertParameters
{
/// <summary>
/// We deliberately use the wrong number/type of arguments for ClobberingJsonConverter to ensure an
/// exception is thrown.
/// </summary>
[JsonConverter(typeof(ClobberingJsonConverter), "Uno", "Blammo")]
public string One { get; set; }
}
public class OverloadsJsonConverterer : JsonConverter
{
private readonly string _type;
// constructor with Type argument
public OverloadsJsonConverterer(Type typeParam)
{
_type = "Type";
}
public OverloadsJsonConverterer(object objectParam)
{
_type = string.Format("object({0})", objectParam.GetType().FullName);
}
// primitive type conversions
public OverloadsJsonConverterer(byte byteParam)
{
_type = "byte";
}
public OverloadsJsonConverterer(short shortParam)
{
_type = "short";
}
public OverloadsJsonConverterer(int intParam)
{
_type = "int";
}
public OverloadsJsonConverterer(long longParam)
{
_type = "long";
}
public OverloadsJsonConverterer(double doubleParam)
{
_type = "double";
}
// params argument
public OverloadsJsonConverterer(params int[] intParams)
{
_type = "int[]";
}
public OverloadsJsonConverterer(bool[] intParams)
{
_type = "bool[]";
}
// closest type resolution
public OverloadsJsonConverterer(IEnumerable<string> iEnumerableParam)
{
_type = "IEnumerable<string>";
}
public OverloadsJsonConverterer(IList<string> iListParam)
{
_type = "IList<string>";
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(_type);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(int);
}
}
public class OverloadWithTypeParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), typeof(int))]
public int Overload { get; set; }
}
[Test]
public void JsonConverterConstructor_OverloadWithTypeParam()
{
OverloadWithTypeParameter value = new OverloadWithTypeParameter();
string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"Type\"}", json);
}
public class OverloadWithUnhandledParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), "str")]
public int Overload { get; set; }
}
[Test]
public void JsonConverterConstructor_OverloadWithUnhandledParam_FallbackToObject()
{
OverloadWithUnhandledParameter value = new OverloadWithUnhandledParameter();
string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"object(System.String)\"}", json);
}
public class OverloadWithIntParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), 1)]
public int Overload { get; set; }
}
public class OverloadWithUIntParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), 1U)]
public int Overload { get; set; }
}
public class OverloadWithLongParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), 1L)]
public int Overload { get; set; }
}
public class OverloadWithULongParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), 1UL)]
public int Overload { get; set; }
}
public class OverloadWithShortParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), (short)1)]
public int Overload { get; set; }
}
public class OverloadWithUShortParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), (ushort)1)]
public int Overload { get; set; }
}
public class OverloadWithSByteParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), (sbyte)1)]
public int Overload { get; set; }
}
public class OverloadWithByteParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), (byte)1)]
public int Overload { get; set; }
}
public class OverloadWithCharParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), 'a')]
public int Overload { get; set; }
}
public class OverloadWithBoolParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), true)]
public int Overload { get; set; }
}
public class OverloadWithFloatParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), 1.5f)]
public int Overload { get; set; }
}
public class OverloadWithDoubleParameter
{
[JsonConverter(typeof(OverloadsJsonConverterer), 1.5)]
public int Overload { get; set; }
}
[Test]
public void JsonConverterConstructor_OverloadsWithPrimitiveParams()
{
{
OverloadWithIntParameter value = new OverloadWithIntParameter();
string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"int\"}", json);
}
{
// uint -> long
OverloadWithUIntParameter value = new OverloadWithUIntParameter();
string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"long\"}", json);
}
{
OverloadWithLongParameter value = new OverloadWithLongParameter();
string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"long\"}", json);
}
{
// ulong -> double
OverloadWithULongParameter value = new OverloadWithULongParameter();
string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"double\"}", json);
}
{
OverloadWithShortParameter value = new OverloadWithShortParameter();
string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"short\"}", json);
}
{
// ushort -> int
OverloadWithUShortParameter value = new OverloadWithUShortParameter();
string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"int\"}", json);
}
{
// sbyte -> short
OverloadWithSByteParameter value = new OverloadWithSByteParameter();
string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"short\"}", json);
}
{
OverloadWithByteParameter value = new OverloadWithByteParameter();
string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"byte\"}", json);
}
{
// char -> int
OverloadWithCharParameter value = new OverloadWithCharParameter();
string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"int\"}", json);
}
{
// bool -> (object)bool
OverloadWithBoolParameter value = new OverloadWithBoolParameter();
var json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"object(System.Boolean)\"}", json);
}
{
// float -> double
OverloadWithFloatParameter value = new OverloadWithFloatParameter();
string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"double\"}", json);
}
{
OverloadWithDoubleParameter value = new OverloadWithDoubleParameter();
var json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"double\"}", json);
}
}
public class OverloadWithArrayParameters
{
[JsonConverter(typeof(OverloadsJsonConverterer), new int[] { 1, 2, 3 })]
public int WithParams { get; set; }
[JsonConverter(typeof(OverloadsJsonConverterer), new bool[] { true, false })]
public int WithoutParams { get; set; }
}
[Test]
public void JsonConverterConstructor_OverloadsWithArrayParams()
{
OverloadWithArrayParameters value = new OverloadWithArrayParameters();
string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"WithParams\":\"int[]\",\"WithoutParams\":\"bool[]\"}", json);
}
public class OverloadWithBaseType
{
[JsonConverter(typeof(OverloadsJsonConverterer), new object[] { new string[] { "a", "b", "c" } })]
public int Overload { get; set; }
}
//[Test]
//[Ignore("https://github.com/dotnet/roslyn/issues/36974")]
//public void JsonConverterConstructor_OverloadsWithBaseTypes()
//{
// OverloadWithBaseType value = new OverloadWithBaseType();
// string json = JsonConvert.SerializeObject(value);
// Assert.AreEqual("{\"Overload\":\"IList<string>\"}", json);
//}
[Test]
public void CustomDoubleRounding()
{
var measurements = new Measurements
{
Loads = new List<double> { 23283.567554707258, 23224.849899771067, 23062.5, 22846.272519910868, 22594.281246368635 },
Positions = new List<double> { 57.724227689317019, 60.440934405753069, 63.444192925248643, 66.813119113482557, 70.4496501404433 },
Gain = 12345.67895111213
};
string json = JsonConvert.SerializeObject(measurements);
Assert.AreEqual("{\"Positions\":[57.72,60.44,63.44,66.81,70.45],\"Loads\":[23284.0,23225.0,23062.0,22846.0,22594.0],\"Gain\":12345.679}", json);
}
public class Measurements
{
[JsonProperty(ItemConverterType = typeof(RoundingJsonConverter))]
public List<double> Positions { get; set; }
[JsonProperty(ItemConverterType = typeof(RoundingJsonConverter), ItemConverterParameters = new object[] { 0, MidpointRounding.ToEven })]
public List<double> Loads { get; set; }
[JsonConverter(typeof(RoundingJsonConverter), 4)]
public double Gain { get; set; }
}
public class RoundingJsonConverter : JsonConverter
{
int _precision;
MidpointRounding _rounding;
public RoundingJsonConverter()
: this(2)
{
}
public RoundingJsonConverter(int precision)
: this(precision, MidpointRounding.AwayFromZero)
{
}
public RoundingJsonConverter(int precision, MidpointRounding rounding)
{
_precision = precision;
_rounding = rounding;
}
public override bool CanRead
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(double);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(Math.Round((double)value, _precision, _rounding));
}
}
[Test]
public void GenericBaseClassSerialization()
{
string json = JsonConvert.SerializeObject(new NonGenericChildClass());
Assert.AreEqual("{\"Data\":null}", json);
}
public class GenericBaseClass<O, T>
{
public virtual T Data { get; set; }
}
public class GenericIntermediateClass<O> : GenericBaseClass<O, string>
{
public override string Data { get; set; }
}
public class NonGenericChildClass : GenericIntermediateClass<int>
{
}
[Test]
public void ShouldNotPopulateReadOnlyEnumerableObjectWithNonDefaultConstructor()
{
object actual = JsonConvert.DeserializeObject<HasReadOnlyEnumerableObject>("{\"foo\":{}}");
Assert.IsNotNull(actual);
}
[Test]
public void ShouldNotPopulateReadOnlyEnumerableObjectWithDefaultConstructor()
{
object actual = JsonConvert.DeserializeObject<HasReadOnlyEnumerableObjectAndDefaultConstructor>("{\"foo\":{}}");
Assert.IsNotNull(actual);
}
[Test]
public void ShouldNotPopulateContructorArgumentEnumerableObject()
{
object actual = JsonConvert.DeserializeObject<AcceptsEnumerableObjectToConstructor>("{\"foo\":{}}");
Assert.IsNotNull(actual);
}
[Test]
public void ShouldNotPopulateEnumerableObjectProperty()
{
object actual = JsonConvert.DeserializeObject<HasEnumerableObject>("{\"foo\":{}}");
Assert.IsNotNull(actual);
}
#if !(NET40 || NET35 || NET20 || PORTABLE40)
[Test]
public void ShouldNotPopulateReadOnlyDictionaryObjectWithNonDefaultConstructor()
{
object actual = JsonConvert.DeserializeObject<HasReadOnlyDictionary>("{\"foo\":{'key':'value'}}");
Assert.IsNotNull(actual);
}
public sealed class HasReadOnlyDictionary
{
[JsonProperty("foo")]
public IReadOnlyDictionary<string, string> Foo { get; } = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>());
[JsonConstructor]
public HasReadOnlyDictionary([JsonProperty("bar")] int bar)
{
}
}
#endif
public sealed class HasReadOnlyEnumerableObject
{
[JsonProperty("foo")]
public EnumerableWithConverter Foo { get; } = new EnumerableWithConverter();
[JsonConstructor]
public HasReadOnlyEnumerableObject([JsonProperty("bar")] int bar)
{
}
}
public sealed class HasReadOnlyEnumerableObjectAndDefaultConstructor
{
[JsonProperty("foo")]
public EnumerableWithConverter Foo { get; } = new EnumerableWithConverter();
[JsonConstructor]
public HasReadOnlyEnumerableObjectAndDefaultConstructor()
{
}
}
public sealed class AcceptsEnumerableObjectToConstructor
{
[JsonConstructor]
public AcceptsEnumerableObjectToConstructor
(
[JsonProperty("foo")] EnumerableWithConverter foo,
[JsonProperty("bar")] int bar
)
{
}
}
public sealed class HasEnumerableObject
{
[JsonProperty("foo")]
public EnumerableWithConverter Foo { get; set; } = new EnumerableWithConverter();
[JsonConstructor]
public HasEnumerableObject([JsonProperty("bar")] int bar)
{
}
}
[JsonConverter(typeof(Converter))]
public sealed class EnumerableWithConverter : IEnumerable<int>
{
public sealed class Converter : JsonConverter
{
public override bool CanConvert(Type objectType)
=> objectType == typeof(Foo);
public override object ReadJson
(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
reader.Skip();
return new EnumerableWithConverter();
}
public override void WriteJson
(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WriteEndObject();
}
}
public IEnumerator<int> GetEnumerator()
{
yield break;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
[Test]
public void ShouldNotRequireIgnoredPropertiesWithItemsRequired()
{
string json = @"{
""exp"": 1483228800,
""active"": true
}";
ItemsRequiredObjectWithIgnoredProperty value = JsonConvert.DeserializeObject<ItemsRequiredObjectWithIgnoredProperty>(json);
Assert.IsNotNull(value);
Assert.AreEqual(value.Expiration, new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));
Assert.AreEqual(value.Active, true);
}
[JsonObject(ItemRequired = Required.Always)]
public sealed class ItemsRequiredObjectWithIgnoredProperty
{
private static readonly DateTime s_unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
[JsonProperty("exp")]
private int _expiration
{
get
{
return (int)((Expiration - s_unixEpoch).TotalSeconds);
}
set
{
Expiration = s_unixEpoch.AddSeconds(value);
}
}
public bool Active { get; set; }
[JsonIgnore]
public DateTime Expiration { get; set; }
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// A console
/// First published in XenServer 4.0.
/// </summary>
public partial class Console : XenObject<Console>
{
public Console()
{
}
public Console(string uuid,
console_protocol protocol,
string location,
XenRef<VM> VM,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.protocol = protocol;
this.location = location;
this.VM = VM;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Console from a Proxy_Console.
/// </summary>
/// <param name="proxy"></param>
public Console(Proxy_Console proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Console.
/// </summary>
public override void UpdateFrom(Console update)
{
uuid = update.uuid;
protocol = update.protocol;
location = update.location;
VM = update.VM;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_Console proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
protocol = proxy.protocol == null ? (console_protocol) 0 : (console_protocol)Helper.EnumParseDefault(typeof(console_protocol), (string)proxy.protocol);
location = proxy.location == null ? null : (string)proxy.location;
VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_Console ToProxy()
{
Proxy_Console result_ = new Proxy_Console();
result_.uuid = uuid ?? "";
result_.protocol = console_protocol_helper.ToString(protocol);
result_.location = location ?? "";
result_.VM = VM ?? "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new Console from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Console(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Console
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("protocol"))
protocol = (console_protocol)Helper.EnumParseDefault(typeof(console_protocol), Marshalling.ParseString(table, "protocol"));
if (table.ContainsKey("location"))
location = Marshalling.ParseString(table, "location");
if (table.ContainsKey("VM"))
VM = Marshalling.ParseRef<VM>(table, "VM");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(Console other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._protocol, other._protocol) &&
Helper.AreEqual2(this._location, other._location) &&
Helper.AreEqual2(this._VM, other._VM) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
internal static List<Console> ProxyArrayToObjectList(Proxy_Console[] input)
{
var result = new List<Console>();
foreach (var item in input)
result.Add(new Console(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Console server)
{
if (opaqueRef == null)
{
var reference = create(session, this);
return reference == null ? null : reference.opaque_ref;
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Console.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static Console get_record(Session session, string _console)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.console_get_record(session.opaque_ref, _console);
else
return new Console((Proxy_Console)session.proxy.console_get_record(session.opaque_ref, _console ?? "").parse());
}
/// <summary>
/// Get a reference to the console instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Console> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.console_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Console>.Create(session.proxy.console_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Create a new console instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Console> create(Session session, Console _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.console_create(session.opaque_ref, _record);
else
return XenRef<Console>.Create(session.proxy.console_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new console instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, Console _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_console_create(session.opaque_ref, _record);
else
return XenRef<Task>.Create(session.proxy.async_console_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified console instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static void destroy(Session session, string _console)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.console_destroy(session.opaque_ref, _console);
else
session.proxy.console_destroy(session.opaque_ref, _console ?? "").parse();
}
/// <summary>
/// Destroy the specified console instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static XenRef<Task> async_destroy(Session session, string _console)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_console_destroy(session.opaque_ref, _console);
else
return XenRef<Task>.Create(session.proxy.async_console_destroy(session.opaque_ref, _console ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static string get_uuid(Session session, string _console)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.console_get_uuid(session.opaque_ref, _console);
else
return (string)session.proxy.console_get_uuid(session.opaque_ref, _console ?? "").parse();
}
/// <summary>
/// Get the protocol field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static console_protocol get_protocol(Session session, string _console)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.console_get_protocol(session.opaque_ref, _console);
else
return (console_protocol)Helper.EnumParseDefault(typeof(console_protocol), (string)session.proxy.console_get_protocol(session.opaque_ref, _console ?? "").parse());
}
/// <summary>
/// Get the location field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static string get_location(Session session, string _console)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.console_get_location(session.opaque_ref, _console);
else
return (string)session.proxy.console_get_location(session.opaque_ref, _console ?? "").parse();
}
/// <summary>
/// Get the VM field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static XenRef<VM> get_VM(Session session, string _console)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.console_get_vm(session.opaque_ref, _console);
else
return XenRef<VM>.Create(session.proxy.console_get_vm(session.opaque_ref, _console ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static Dictionary<string, string> get_other_config(Session session, string _console)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.console_get_other_config(session.opaque_ref, _console);
else
return Maps.convert_from_proxy_string_string(session.proxy.console_get_other_config(session.opaque_ref, _console ?? "").parse());
}
/// <summary>
/// Set the other_config field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _console, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.console_set_other_config(session.opaque_ref, _console, _other_config);
else
session.proxy.console_set_other_config(session.opaque_ref, _console ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _console, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.console_add_to_other_config(session.opaque_ref, _console, _key, _value);
else
session.proxy.console_add_to_other_config(session.opaque_ref, _console ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given console. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _console, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.console_remove_from_other_config(session.opaque_ref, _console, _key);
else
session.proxy.console_remove_from_other_config(session.opaque_ref, _console ?? "", _key ?? "").parse();
}
/// <summary>
/// Return a list of all the consoles known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Console>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.console_get_all(session.opaque_ref);
else
return XenRef<Console>.Create(session.proxy.console_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the console Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Console>, Console> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.console_get_all_records(session.opaque_ref);
else
return XenRef<Console>.Create<Proxy_Console>(session.proxy.console_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// the protocol used by this console
/// </summary>
[JsonConverter(typeof(console_protocolConverter))]
public virtual console_protocol protocol
{
get { return _protocol; }
set
{
if (!Helper.AreEqual(value, _protocol))
{
_protocol = value;
Changed = true;
NotifyPropertyChanged("protocol");
}
}
}
private console_protocol _protocol;
/// <summary>
/// URI for the console service
/// </summary>
public virtual string location
{
get { return _location; }
set
{
if (!Helper.AreEqual(value, _location))
{
_location = value;
Changed = true;
NotifyPropertyChanged("location");
}
}
}
private string _location = "";
/// <summary>
/// VM to which this console is attached
/// </summary>
[JsonConverter(typeof(XenRefConverter<VM>))]
public virtual XenRef<VM> VM
{
get { return _VM; }
set
{
if (!Helper.AreEqual(value, _VM))
{
_VM = value;
Changed = true;
NotifyPropertyChanged("VM");
}
}
}
private XenRef<VM> _VM = new XenRef<VM>(Helper.NullOpaqueRef);
/// <summary>
/// additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.integeregererface.integeregererface01.integeregererface01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.integeregererface.integeregererface01.integeregererface01;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params in an interface</Title>
// <Description>Simple Declaration of a method with optional parameters in an interface</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(dynamic x = null, dynamic y = null);
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.integeregererface.integeregererface05.integeregererface05
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.integeregererface.integeregererface05.integeregererface05;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params in an interface</Title>
// <Description>Simple Declaration of a method with optional parameters in an interface.
// Multiple optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(dynamic z, int x = 2, dynamic y = default(dynamic));
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.integeregererface.integeregererface12.integeregererface12
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.integeregererface.integeregererface12.integeregererface12;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public interface Parent
{
int Foo(
[Optional]
dynamic i);
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.integeregererface.integeregererface13.integeregererface13
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.integeregererface.integeregererface13.integeregererface13;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a method with optional parameters. cast of an int to long</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public interface Parent
{
int Foo(
[Optional]
dynamic i, [Optional]
dynamic j, [Optional]
float ? f, [Optional]
decimal ? d);
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.integeregererface.integeregererface16.integeregererface16
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.integeregererface.integeregererface16.integeregererface16;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a Explicitly implemented interface</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(15,17\).*CS1066</Expects>
public interface Parent
{
int Foo(dynamic i = default(dynamic));
}
public class Derived : Parent
{
int Parent.Foo(dynamic i = default(object))
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return ((Parent)p).Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.integeregererface.integeregererface17.integeregererface17
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.integeregererface.integeregererface17.integeregererface17;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a Explicitly implemented interface</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(dynamic i = null);
}
public class Derived : Parent
{
int Parent.Foo(dynamic i)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return ((Parent)p).Foo();
}
}
//</Code>
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
namespace FileSystemTest
{
public class Seek : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
// These tests rely on underlying file system so we need to make
// sure we can format it before we start the tests. If we can't
// format it, then we assume there is no FS to test on this platform.
// delete the directory DOTNETMF_FS_EMULATION
try
{
IOTests.IntializeVolume();
Directory.CreateDirectory(TestDir);
Directory.SetCurrentDirectory(TestDir);
}
catch (Exception ex)
{
Log.Exception("Skipping: Unable to initialize file system " + ex.Message);
return InitializeResult.Skip;
}
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
}
#region local vars
private const string TestDir = "Seek";
private const string fileName = "test.tmp";
#endregion local vars
#region Helper methods
private bool TestSeek(FileStream fs, long offset, SeekOrigin origin, long expectedPosition)
{
bool result = true;
long seek = fs.Seek(offset, origin);
if (seek != fs.Position && seek != expectedPosition)
{
result = false;
Log.Exception("Unexpected seek results!");
Log.Exception("Expected position: " + expectedPosition);
Log.Exception("Seek result: " + seek);
Log.Exception("fs.Position: " + fs.Position);
}
return result;
}
private bool TestExtend(FileStream fs, long offset, SeekOrigin origin, long expectedPosition, long expectedLength)
{
bool result = TestSeek(fs, offset, origin, expectedLength);
fs.WriteByte(1);
if (fs.Length != expectedLength)
{
result = false;
Log.Exception("Expected seek past end to change length to " + expectedLength + ", but its " + fs.Length);
}
return result;
}
#endregion Helper methods
#region Test Cases
[TestMethod]
public MFTestResults InvalidCases()
{
if (File.Exists(fileName))
File.Delete(fileName);
FileStream fs = new FileStream(fileName, FileMode.Create);
FileStreamHelper.Write(fs, 1000);
long seek;
MFTestResults result = MFTestResults.Pass;
try
{
try
{
Log.Comment("Seek -1 from Begin");
seek = fs.Seek(-1, SeekOrigin.Begin);
Log.Exception( "Expected IOException, but got position " + seek );
return MFTestResults.Fail;
}
catch (IOException ioe)
{
/* pass case */ Log.Comment( "Got correct exception: " + ioe.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("Seek -1001 from Current - at end from write");
seek = fs.Seek(-1001, SeekOrigin.Current);
Log.Exception( "Expected IOException, but got position " + seek );
return MFTestResults.Fail;
}
catch (IOException ioe)
{
/* pass case */ Log.Comment( "Got correct exception: " + ioe.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("Seek -1001 from End");
seek = fs.Seek(-1001, SeekOrigin.End);
Log.Exception( "Expected IOException, but got position " + seek );
return MFTestResults.Fail;
}
catch (IOException ioe)
{
/* pass case */ Log.Comment( "Got correct exception: " + ioe.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("Seek invalid -1 origin");
seek = fs.Seek(1, (SeekOrigin)(-1));
Log.Exception( "Expected ArgumentException, but got position " + seek );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("Seek invalid 10 origin");
seek = fs.Seek(1, (SeekOrigin)10);
Log.Exception( "Expected ArgumentException, but got position " + seek );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("Seek with closed socket");
fs.Close();
seek = fs.Seek(0, SeekOrigin.Begin);
Log.Exception( "Expected ObjectDisposedException, but got position " + seek );
return MFTestResults.Fail;
}
catch (ObjectDisposedException ode)
{
/* pass case */ Log.Comment( "Got correct exception: " + ode.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("Seek with disposed socket");
fs.Dispose();
seek = fs.Seek(0, SeekOrigin.End);
Log.Exception( "Expected ObjectDisposedException, but got position " + seek );
return MFTestResults.Fail;
}
catch (ObjectDisposedException ode)
{
/* pass case */ Log.Comment( "Got correct exception: " + ode.Message );
result = MFTestResults.Pass;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
finally
{
if (fs != null)
fs.Dispose();
}
return result;
}
[TestMethod]
public MFTestResults ValidCases()
{
MFTestResults result = MFTestResults.Pass;
try
{
if (File.Exists(fileName))
File.Delete(fileName);
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
FileStreamHelper.Write(fs, 1000);
Log.Comment("Seek to beginning");
if (!TestSeek(fs, 0, SeekOrigin.Begin, 0))
return MFTestResults.Fail;
Log.Comment("Seek forward offset from begging");
if (!TestSeek(fs, 10, SeekOrigin.Begin, 0))
return MFTestResults.Fail;
Log.Comment("Seek backwards offset from current");
if (!TestSeek(fs, -5, SeekOrigin.Current, 5))
return MFTestResults.Fail;
Log.Comment("Seek forwards offset from current");
if (!TestSeek(fs, 20, SeekOrigin.Current, 25))
return MFTestResults.Fail;
Log.Comment("Seek to end");
if (!TestSeek(fs, 0, SeekOrigin.End, 1000))
return MFTestResults.Fail;
Log.Comment("Seek backwards offset from end");
if (!TestSeek(fs, -35, SeekOrigin.End, 965))
return MFTestResults.Fail;
Log.Comment("Seek past end relative to End");
if (!TestExtend(fs, 1, SeekOrigin.End, 1001, 1002))
return MFTestResults.Fail;
Log.Comment("Seek past end relative to Begin");
if (!TestExtend(fs, 1002, SeekOrigin.Begin, 1002, 1003))
return MFTestResults.Fail;
Log.Comment("Seek past end relative to Current");
if (!TestSeek(fs, 995, SeekOrigin.Begin, 995))
return MFTestResults.Fail;
if (!TestExtend(fs, 10, SeekOrigin.Current, 1005, 1006))
return MFTestResults.Fail;
// 1000 --123456
// verify 011001
Log.Comment("Verify proper bytes written at end (zero'd bytes from seek beyond end)");
byte[] buff = new byte[6];
byte[] verify = new byte[] { 0, 1, 1, 0, 0, 1 };
fs.Seek(-6, SeekOrigin.End);
fs.Read(buff, 0, buff.Length);
for (int i = 0; i < buff.Length; i++)
{
if (buff[i] != verify[i])
{
Log.Comment( "Position " + i + ":" + buff[i] + " != " + verify[i] );
return MFTestResults.Fail;
}
}
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
#endregion Test Cases
public MFTestMethod[] Tests
{
get
{
return new MFTestMethod[]
{
new MFTestMethod( InvalidCases, "InvalidCases" ),
new MFTestMethod( ValidCases, "ValidCases" ),
};
}
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.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.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetDegradedDataPersistenceRulesSpectraS3Request : Ds3Request
{
private string _dataPolicyId;
public string DataPolicyId
{
get { return _dataPolicyId; }
set { WithDataPolicyId(value); }
}
private DataIsolationLevel? _isolationLevel;
public DataIsolationLevel? IsolationLevel
{
get { return _isolationLevel; }
set { WithIsolationLevel(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private DataPlacementRuleState? _state;
public DataPlacementRuleState? State
{
get { return _state; }
set { WithState(value); }
}
private string _storageDomainId;
public string StorageDomainId
{
get { return _storageDomainId; }
set { WithStorageDomainId(value); }
}
private DataPersistenceRuleType? _type;
public DataPersistenceRuleType? Type
{
get { return _type; }
set { WithType(value); }
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithDataPolicyId(Guid? dataPolicyId)
{
this._dataPolicyId = dataPolicyId.ToString();
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId.ToString());
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithDataPolicyId(string dataPolicyId)
{
this._dataPolicyId = dataPolicyId;
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId);
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithIsolationLevel(DataIsolationLevel? isolationLevel)
{
this._isolationLevel = isolationLevel;
if (isolationLevel != null)
{
this.QueryParams.Add("isolation_level", isolationLevel.ToString());
}
else
{
this.QueryParams.Remove("isolation_level");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithState(DataPlacementRuleState? state)
{
this._state = state;
if (state != null)
{
this.QueryParams.Add("state", state.ToString());
}
else
{
this.QueryParams.Remove("state");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithStorageDomainId(Guid? storageDomainId)
{
this._storageDomainId = storageDomainId.ToString();
if (storageDomainId != null)
{
this.QueryParams.Add("storage_domain_id", storageDomainId.ToString());
}
else
{
this.QueryParams.Remove("storage_domain_id");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithStorageDomainId(string storageDomainId)
{
this._storageDomainId = storageDomainId;
if (storageDomainId != null)
{
this.QueryParams.Add("storage_domain_id", storageDomainId);
}
else
{
this.QueryParams.Remove("storage_domain_id");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithType(DataPersistenceRuleType? type)
{
this._type = type;
if (type != null)
{
this.QueryParams.Add("type", type.ToString());
}
else
{
this.QueryParams.Remove("type");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/degraded_data_persistence_rule";
}
}
}
}
| |
using System;
namespace AsterNET.FastAGI
{
/// <summary>
/// The BaseAGIScript provides some convinience methods to make it easier to
/// write custom AGIScripts.<br/>
/// Just extend it by your own AGIScripts.
/// </summary>
public abstract class AGIScript
{
#region Answer()
/// <summary>
/// Answers the channel.
/// </summary>
protected internal void Answer()
{
this.Channel.SendCommand(new Command.AnswerCommand());
}
#endregion
#region Hangup()
/// <summary>
/// Hangs the channel up.
/// </summary>
protected internal void Hangup()
{
this.Channel.SendCommand(new Command.HangupCommand());
}
#endregion
#region SetAutoHangup
/// <summary>
/// Cause the channel to automatically hangup at the given number of seconds in the future.<br/>
/// 0 disables the autohangup feature.
/// </summary>
protected internal void SetAutoHangup(int time)
{
this.Channel.SendCommand(new Command.SetAutoHangupCommand(time));
}
#endregion
#region SetCallerId
/// <summary>
/// Sets the caller id on the current channel.<br/>
/// The raw caller id to set, for example "John Doe<1234>".
/// </summary>
protected internal void SetCallerId(string callerId)
{
this.Channel.SendCommand(new Command.SetCallerIdCommand(callerId));
}
#endregion
#region PlayMusicOnHold()
/// <summary>
/// Plays music on hold from the default music on hold class.
/// </summary>
protected internal void PlayMusicOnHold()
{
this.Channel.SendCommand(new Command.SetMusicOnCommand());
}
#endregion
#region PlayMusicOnHold(string musicOnHoldClass)
/// <summary>
/// Plays music on hold from the given music on hold class.
/// </summary>
/// <param name="musicOnHoldClass">the music on hold class to play music from as configures in Asterisk's <musiconhold.conf/code$gt;.</param>
protected internal void PlayMusicOnHold(string musicOnHoldClass)
{
this.Channel.SendCommand(new Command.SetMusicOnCommand(musicOnHoldClass));
}
#endregion
#region StopMusicOnHold()
/// <summary>
/// Stops playing music on hold.
/// </summary>
protected internal void StopMusicOnHold()
{
this.Channel.SendCommand(new Command.SetMusicOffCommand());
}
#endregion
#region GetChannelStatus
/// <summary>
/// Returns the status of the channel.<br/>
/// Return values:
/// <ul>
/// <li>0 Channel is down and available</li>
/// <li>1 Channel is down, but reserved</li>
/// <li>2 Channel is off hook</li>
/// <li>3 Digits (or equivalent) have been dialed</li>
/// <li>4 Line is ringing</li>
/// <li>5 Remote end is ringing</li>
/// <li>6 Line is up</li>
/// <li>7 Line is busy</li>
/// </ul>
/// </summary>
/// <returns> the status of the channel.
/// </returns>
protected internal int GetChannelStatus()
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.ChannelStatusCommand());
return lastReply.ResultCode;
}
#endregion
#region GetData(string file)
/// <summary>
/// Plays the given file and waits for the user to enter DTMF digits until he
/// presses '#'. The user may interrupt the streaming by starting to enter
/// digits.
/// </summary>
/// <param name="file">the name of the file to play</param>
/// <returns> a String containing the DTMF the user entered</returns>
protected internal string GetData(string file)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.GetDataCommand(file));
return lastReply.GetResult();
}
#endregion
#region GetData(string file, int timeout)
/// <summary>
/// Plays the given file and waits for the user to enter DTMF digits until he
/// presses '#' or the timeout occurs. The user may interrupt the streaming
/// by starting to enter digits.
/// </summary>
/// <param name="file">the name of the file to play</param>
/// <param name="timeout">the timeout in milliseconds to wait for user input.<br/>
/// 0 means standard timeout value, -1 means "ludicrous time"
/// (essentially never times out).</param>
/// <returns> a String containing the DTMF the user entered</returns>
protected internal string GetData(string file, long timeout)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.GetDataCommand(file, timeout));
return lastReply.GetResult();
}
#endregion
#region GetData(string file, int timeout, int maxDigits)
/// <summary>
/// Plays the given file and waits for the user to enter DTMF digits until he
/// presses '#' or the timeout occurs or the maximum number of digits has
/// been entered. The user may interrupt the streaming by starting to enter
/// digits.
/// </summary>
/// <param name="file">the name of the file to play</param>
/// <param name="timeout">the timeout in milliseconds to wait for user input.<br/>
/// 0 means standard timeout value, -1 means "ludicrous time"
/// (essentially never times out).</param>
/// <param name="maxDigits">the maximum number of digits the user is allowed to enter</param>
/// <returns> a String containing the DTMF the user entered</returns>
protected internal string GetData(string file, long timeout, int maxDigits)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.GetDataCommand(file, timeout, maxDigits));
return lastReply.GetResult();
}
#endregion
#region GetOption(string file, string escapeDigits)
/// <summary>
/// Plays the given file, and waits for the user to press one of the given
/// digits. If none of the esacpe digits is pressed while streaming the file
/// it waits for the default timeout of 5 seconds still waiting for the user
/// to press a digit.
/// </summary>
/// <param name="file">the name of the file to stream, must not include extension.</param>
/// <param name="escapeDigits">contains the digits that the user is expected to press.</param>
/// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns>
protected internal char GetOption(string file, string escapeDigits)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.GetOptionCommand(file, escapeDigits));
return lastReply.ResultCodeAsChar;
}
#endregion
#region GetOption(string file, string escapeDigits, int timeout)
/// <summary>
/// Plays the given file, and waits for the user to press one of the given
/// digits. If none of the esacpe digits is pressed while streaming the file
/// it waits for the specified timeout still waiting for the user to press a
/// digit.
/// </summary>
/// <param name="file">the name of the file to stream, must not include extension.</param>
/// <param name="escapeDigits">contains the digits that the user is expected to press.</param>
/// <param name="timeout">the timeout in seconds to wait if none of the defined esacpe digits was presses while streaming.</param>
/// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns>
protected internal char GetOption(string file, string escapeDigits, int timeout)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.GetOptionCommand(file, escapeDigits, timeout));
return lastReply.ResultCodeAsChar;
}
#endregion
#region Exec(string application)
/// <summary>
/// Executes the given command.
/// </summary>
/// <param name="application">the name of the application to execute, for example "Dial".</param>
/// <returns> the return code of the application of -2 if the application was not found.</returns>
protected internal int Exec(string application)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.ExecCommand(application));
return lastReply.ResultCode;
}
#endregion
#region Exec(string application, string options)
/// <summary>
/// Executes the given command.
/// </summary>
/// <param name="application">the name of the application to execute, for example "Dial".</param>
/// <param name="options">the parameters to pass to the application, for example "SIP/123".</param>
/// <returns> the return code of the application of -2 if the application was not found.</returns>
protected internal int Exec(string application, string options)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.ExecCommand(application, options));
return lastReply.ResultCode;
}
#endregion
#region SetContext
/// <summary>
/// Sets the context for continuation upon exiting the application.
/// </summary>
protected internal void SetContext(string context)
{
this.Channel.SendCommand(new Command.SetContextCommand(context));
}
#endregion
#region SetExtension
/// <summary>
/// Sets the extension for continuation upon exiting the application.
/// </summary>
protected internal void SetExtension(string extension)
{
this.Channel.SendCommand(new Command.SetExtensionCommand(extension));
}
#endregion
#region SetPriority(int priority)
/// <summary>
/// Sets the priority for continuation upon exiting the application.
/// </summary>
protected internal void SetPriority(int priority)
{
this.Channel.SendCommand(new Command.SetPriorityCommand(priority));
}
#endregion
#region SetPriority(string label priority)
/// <summary>
/// Sets the label for continuation upon exiting the application.
/// </summary>
protected internal void SetPriority(string label)
{
this.Channel.SendCommand(new Command.SetPriorityCommand(label));
}
#endregion
#region StreamFile(string file)
/// <summary>
/// Plays the given file.
/// </summary>
/// <param name="file">name of the file to play.</param>
protected internal void StreamFile(string file)
{
this.Channel.SendCommand(new Command.StreamFileCommand(file));
}
#endregion
#region StreamFile(string file, string escapeDigits)
/// <summary>
/// Plays the given file and allows the user to escape by pressing one of the given digit.
/// </summary>
/// <param name="file">name of the file to play.</param>
/// <param name="escapeDigits">a String containing the DTMF digits that allow the user to escape.</param>
/// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns>
protected internal char StreamFile(string file, string escapeDigits)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.StreamFileCommand(file, escapeDigits));
return lastReply.ResultCodeAsChar;
}
#endregion
#region SayDigits(string digits)
/// <summary>
/// Says the given digit string.
/// </summary>
/// <param name="digits">the digit string to say.</param>
protected internal void SayDigits(string digits)
{
this.Channel.SendCommand(new Command.SayDigitsCommand(digits));
}
#endregion
#region SayDigits(string digits, string escapeDigits)
/// <summary>
/// Says the given number, returning early if any of the given DTMF number
/// are received on the channel.
/// </summary>
/// <param name="digits">the digit string to say.</param>
/// <param name="escapeDigits">a String containing the DTMF digits that allow the user to escape.</param>
/// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns>
protected internal char SayDigits(string digits, string escapeDigits)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.SayDigitsCommand(digits, escapeDigits));
return lastReply.ResultCodeAsChar;
}
#endregion
#region SayNumber(string number)
/// <summary>
/// Says the given number.
/// </summary>
/// <param name="number">the number to say.</param>
protected internal void SayNumber(string number)
{
this.Channel.SendCommand(new Command.SayNumberCommand(number));
}
#endregion
#region SayNumber(string number, string escapeDigits)
/// <summary>
/// Says the given number, returning early if any of the given DTMF number
/// are received on the channel.
/// </summary>
/// <param name="number">the number to say.</param>
/// <param name="escapeDigits">a String containing the DTMF digits that allow the user to escape.</param>
/// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns>
protected internal char SayNumber(string number, string escapeDigits)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.SayNumberCommand(number, escapeDigits));
return lastReply.ResultCodeAsChar;
}
#endregion
#region SayPhonetic(string text)
/// <summary>
/// Says the given character string with phonetics.
/// </summary>
/// <param name="text">the text to say.</param>
protected internal void SayPhonetic(string text)
{
this.Channel.SendCommand(new Command.SayPhoneticCommand(text));
}
#endregion
#region SayPhonetic(string text, string escapeDigits)
/// <summary>
/// Says the given character string with phonetics, returning early if any of
/// the given DTMF number are received on the channel.
/// </summary>
/// <param name="text">the text to say.</param>
/// <param name="escapeDigits">a String containing the DTMF digits that allow the user to escape.</param>
/// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns>
protected internal char SayPhonetic(string text, string escapeDigits)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.SayPhoneticCommand(text, escapeDigits));
return lastReply.ResultCodeAsChar;
}
#endregion
#region SayAlpha(string text)
/// <summary>
/// Says the given character string.
/// </summary>
/// <param name="text">the text to say.</param>
protected internal void SayAlpha(string text)
{
this.Channel.SendCommand(new Command.SayAlphaCommand(text));
}
#endregion
#region SayAlpha(string text, string escapeDigits)
/// <summary>
/// Says the given character string, returning early if any of the given DTMF
/// number are received on the channel.
/// </summary>
/// <param name="text">the text to say.</param>
/// <param name="escapeDigits">a String containing the DTMF digits that allow the user to escape.</param>
/// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns>
protected internal char SayAlpha(string text, string escapeDigits)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.SayAlphaCommand(text, escapeDigits));
return lastReply.ResultCodeAsChar;
}
#endregion
#region SayTime(long time)
/// <summary>
/// Says the given time.
/// </summary>
/// <param name="time">the time to say in seconds since 00:00:00 on January 1, 1970.</param>
protected internal void SayTime(long time)
{
this.Channel.SendCommand(new Command.SayTimeCommand(time));
}
#endregion
#region SayTime(long time, string escapeDigits)
/// <summary>
/// Says the given time, returning early if any of the given DTMF number are
/// received on the channel.
/// </summary>
/// <param name="time">the time to say in seconds since 00:00:00 on January 1, 1970.</param>
/// <param name="escapeDigits">a String containing the DTMF digits that allow the user to escape.</param>
/// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns>
protected internal char SayTime(long time, string escapeDigits)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.SayTimeCommand(time, escapeDigits));
return lastReply.ResultCodeAsChar;
}
#endregion
#region GetVariable(string name)
/// <summary>
/// Returns the value of the given channel variable.
/// </summary>
/// <param name="name">the name of the variable to retrieve.</param>
/// <returns> the value of the given variable or null if not set.</returns>
protected internal string GetVariable(string name)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.GetVariableCommand(name));
if (lastReply.ResultCode != 1)
return null;
return lastReply.Extra;
}
#endregion
#region SetVariable(string name, string value_Renamed)
/// <summary>
/// Sets the value of the given channel variable to a new value.
/// </summary>
/// <param name="name">the name of the variable to retrieve.</param>
/// <param name="val">the new value to set.</param>
protected internal void SetVariable(string name, string val)
{
this.Channel.SendCommand(new Command.SetVariableCommand(name, val));
}
#endregion
#region WaitForDigit(int timeout)
/// <summary>
/// Waits up to 'timeout' milliseconds to receive a DTMF digit.
/// </summary>
/// <param name="timeout">timeout the milliseconds to wait for the channel to receive a DTMF digit, -1 will wait forever.</param>
/// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns>
protected internal char WaitForDigit(int timeout)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.WaitForDigitCommand(timeout));
return lastReply.ResultCodeAsChar;
}
#endregion
#region GetFullVariable(string name)
/// <summary>
/// Returns the value of the current channel variable, unlike getVariable()
/// this method understands complex variable names and builtin variables.<br/>
/// Available since Asterisk 1.2.
/// </summary>
/// <param name="name">the name of the variable to retrieve.</param>
/// <returns>the value of the given variable or null if not et.</returns>
protected internal string GetFullVariable(string name)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.GetFullVariableCommand(name));
if (lastReply.ResultCode != 1)
return null;
return lastReply.Extra;
}
#endregion
#region GetFullVariable(string name, string channel)
/// <summary>
/// Returns the value of the given channel variable.<br/>
/// Available since Asterisk 1.2.
/// </summary>
/// <param name="name">the name of the variable to retrieve.</param>
/// <param name="channel">the name of the channel.</param>
/// <returns>the value of the given variable or null if not set.</returns>
protected internal string GetFullVariable(string name, string channelName)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.GetFullVariableCommand(name, channelName));
if (lastReply.ResultCode != 1)
return null;
return lastReply.Extra;
}
#endregion
#region SayDateTime(...)
/// <summary>
/// Says the given time.<br/>
/// Available since Asterisk 1.2.
/// </summary>
/// <param name="time">the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC)</param>
protected internal void SayDateTime(long time)
{
this.Channel.SendCommand(new Command.SayDateTimeCommand(time));
}
/// <summary>
/// Says the given time and allows interruption by one of the given escape digits.<br/>
/// Available since Asterisk 1.2.
/// </summary>
/// <param name="time">the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC)</param>
/// <param name="escapeDigits">the digits that allow the user to interrupt this command or null for none.</param>
/// <returns>the DTMF digit pressed or 0x0 if none was pressed.</returns>
protected internal char SayDateTime(long time, string escapeDigits)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.SayDateTimeCommand(time, escapeDigits));
return lastReply.ResultCodeAsChar;
}
/// <summary>
/// Says the given time in the given format and allows interruption by one of the given escape digits.<br/>
/// Available since Asterisk 1.2.
/// </summary>
/// <param name="time">the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC)</param>
/// <param name="escapeDigits">the digits that allow the user to interrupt this command or null for none.</param>
/// <param name="format">the format the time should be said in</param>
/// <returns>the DTMF digit pressed or 0x0 if none was pressed.</returns>
protected internal char SayDateTime(long time, string escapeDigits, string format)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.SayDateTimeCommand(time, escapeDigits, format));
return lastReply.ResultCodeAsChar;
}
/// <summary>
/// Says the given time in the given format and timezone and allows interruption by one of the given escape digits.<br/>
/// Available since Asterisk 1.2.
/// </summary>
/// <param name="time">the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC)</param>
/// <param name="escapeDigits">the digits that allow the user to interrupt this command or null for none.</param>
/// <param name="format">the format the time should be said in</param>
/// <param name="timezone">the timezone to use when saying the time, for example "UTC" or "Europe/Berlin".</param>
/// <returns>the DTMF digit pressed or 0x0 if none was pressed.</returns>
protected internal char SayDateTime(long time, string escapeDigits, string format, string timezone)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.SayDateTimeCommand(time, escapeDigits, format, timezone));
return lastReply.ResultCodeAsChar;
}
#endregion
#region DatabaseGet(string family, string key)
/// <summary>
/// Retrieves an entry in the Asterisk database for a given family and key.
/// </summary>
/// <param name="family">the family of the entry to retrieve.</param>
/// <param name="key">key the key of the entry to retrieve.</param>
/// <return>the value of the given family and key or null if there is no such value.</return>
protected internal string DatabaseGet(string family, string key)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.DatabaseGetCommand(family, key));
if (lastReply.ResultCode != 1)
return null;
return lastReply.Extra;
}
#endregion
#region DatabasePut(string family, string key, string value)
/// <summary>
/// Adds or updates an entry in the Asterisk database for a given family, key and value.
/// </summary>
/// <param name="family">the family of the entry to add or update.</param>
/// <param name="key">the key of the entry to add or update.</param>
/// <param name="value">the new value of the entry.</param>
protected internal void DatabasePut(string family, string key, string value)
{
this.Channel.SendCommand(new Command.DatabasePutCommand(family, key, value));
}
#endregion
#region DatabaseDel(string family, string key)
/// <summary>
/// Deletes an entry in the Asterisk database for a given family and key.
/// </summary>
/// <param name="family">the family of the entry to delete.</param>
/// <param name="key">the key of the entry to delete.</param>
protected internal void DatabaseDel(string family, string key)
{
this.Channel.SendCommand(new Command.DatabaseDelCommand(family, key));
}
#endregion
#region DatabaseDelTree(String family)
/// <summary>
/// Deletes a whole family of entries in the Asterisk database.
/// </summary>
/// <param name="family">the family to delete.</param>
protected internal void DatabaseDelTree(string family)
{
this.Channel.SendCommand(new Command.DatabaseDelTreeCommand(family));
}
#endregion
#region DatabaseDelTree(string family, string keytree)
/// <summary>
/// Deletes all entries of a given family in the Asterisk database that have a key that starts with a given prefix.
/// </summary>
/// <param name="family">the family of the entries to delete.</param>
/// <param name="keytree">the prefix of the keys of the entries to delete.</param>
protected internal void DatabaseDelTree(string family, string keytree)
{
this.Channel.SendCommand(new Command.DatabaseDelTreeCommand(family, keytree));
}
#endregion
#region Verbose(string message, int level)
/// <summary>
/// Sends a message to the Asterisk console via the verbose message system.
/// </summary>
/// <param name="message">the message to send</param>
/// <param name="level">the verbosity level to use. Must be in [1..4]</param>
public void Verbose(string message, int level)
{
this.Channel.SendCommand(new Command.VerboseCommand(message, level));
}
#endregion
#region RecordFile(...)
/// <summary>
/// Record to a file until a given dtmf digit in the sequence is received.<br/>
/// Returns -1 on hangup or error.<br/>
/// The format will specify what kind of file will be recorded. The timeout is
/// the maximum record time in milliseconds, or -1 for no timeout. Offset samples
/// is optional, and if provided will seek to the offset without exceeding the
/// end of the file. "maxSilence" is the number of seconds of maxSilence allowed
/// before the function returns despite the lack of dtmf digits or reaching
/// timeout.
/// </summary>
/// <param name="file">the name of the file to stream, must not include extension.</param>
/// <param name="format">the format of the file to be recorded, for example "wav".</param>
/// <param name="escapeDigits">contains the digits that allow the user to end recording.</param>
/// <param name="timeout">the maximum record time in milliseconds, or -1 for no timeout.</param>
/// <returns>result code</returns>
protected internal int RecordFile(string file, string format, string escapeDigits, int timeout)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.RecordFileCommand(file, format, escapeDigits, timeout));
return lastReply.ResultCode;
}
/// <summary>
/// Record to a file until a given dtmf digit in the sequence is received.<br/>
/// Returns -1 on hangup or error.<br/>
/// The format will specify what kind of file will be recorded. The timeout is
/// the maximum record time in milliseconds, or -1 for no timeout. Offset samples
/// is optional, and if provided will seek to the offset without exceeding the
/// end of the file. "maxSilence" is the number of seconds of maxSilence allowed
/// before the function returns despite the lack of dtmf digits or reaching
/// timeout.
/// </summary>
/// <param name="file">the name of the file to stream, must not include extension.</param>
/// <param name="format">the format of the file to be recorded, for example "wav".</param>
/// <param name="escapeDigits">contains the digits that allow the user to end recording.</param>
/// <param name="timeout">the maximum record time in milliseconds, or -1 for no timeout.</param>
/// <param name="offset">the offset samples to skip.</param>
/// <param name="beep">true if a beep should be played before recording.</param>
/// <param name="maxSilence">The amount of silence (in seconds) to allow before returning despite the lack of dtmf digits or reaching timeout.</param>
/// <returns>result code</returns>
protected internal int RecordFile(string file, string format, string escapeDigits, int timeout, int offset, bool beep, int maxSilence)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.RecordFileCommand(file, format, escapeDigits, timeout, offset, beep, maxSilence));
return lastReply.ResultCode;
}
#endregion
#region ControlStreamFile(...)
/// <summary>
/// Plays the given file, allowing playback to be interrupted by the given
/// digits, if any, and allows the listner to control the stream.<br/>
/// If offset is provided then the audio will seek to sample offset before play
/// starts.<br/>
/// Returns 0 if playback completes without a digit being pressed, or the ASCII
/// numerical value of the digit if one was pressed, or -1 on error or if the
/// channel was disconnected. <br/>
/// Remember, the file extension must not be included in the filename.<br/>
/// Available since Asterisk 1.2
/// </summary>
/// <seealso cref="Command.ControlStreamFileCommand"/>
/// <param name="file">the name of the file to stream, must not include extension.</param>
/// <returns>result code</returns>
protected internal int ControlStreamFile(string file)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.ControlStreamFileCommand(file));
return lastReply.ResultCode;
}
/// <summary>
/// Plays the given file, allowing playback to be interrupted by the given
/// digits, if any, and allows the listner to control the stream.<br/>
/// If offset is provided then the audio will seek to sample offset before play
/// starts.<br/>
/// Returns 0 if playback completes without a digit being pressed, or the ASCII
/// numerical value of the digit if one was pressed, or -1 on error or if the
/// channel was disconnected. <br/>
/// Remember, the file extension must not be included in the filename.<br/>
/// Available since Asterisk 1.2
/// </summary>
/// <seealso cref="Command.ControlStreamFileCommand"/>
/// <param name="file">the name of the file to stream, must not include extension.</param>
/// <param name="escapeDigits">contains the digits that allow the user to interrupt this command.</param>
/// <returns>result code</returns>
protected internal int ControlStreamFile(string file, string escapeDigits)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.ControlStreamFileCommand(file, escapeDigits));
return lastReply.ResultCode;
}
/// <summary>
/// Plays the given file, allowing playback to be interrupted by the given
/// digits, if any, and allows the listner to control the stream.<br/>
/// If offset is provided then the audio will seek to sample offset before play
/// starts.<br/>
/// Returns 0 if playback completes without a digit being pressed, or the ASCII
/// numerical value of the digit if one was pressed, or -1 on error or if the
/// channel was disconnected. <br/>
/// Remember, the file extension must not be included in the filename.<br/>
/// Available since Asterisk 1.2
/// </summary>
/// <seealso cref="Command.ControlStreamFileCommand"/>
/// <param name="file">the name of the file to stream, must not include extension.</param>
/// <param name="escapeDigits">contains the digits that allow the user to interrupt this command.</param>
/// <param name="offset">the offset samples to skip before streaming.</param>
/// <returns>result code</returns>
protected internal int ControlStreamFile(string file, string escapeDigits, int offset)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.ControlStreamFileCommand(file, escapeDigits, offset));
return lastReply.ResultCode;
}
/// <summary>
/// Plays the given file, allowing playback to be interrupted by the given
/// digits, if any, and allows the listner to control the stream.<br/>
/// If offset is provided then the audio will seek to sample offset before play
/// starts.<br/>
/// Returns 0 if playback completes without a digit being pressed, or the ASCII
/// numerical value of the digit if one was pressed, or -1 on error or if the
/// channel was disconnected. <br/>
/// Remember, the file extension must not be included in the filename.<br/>
/// Available since Asterisk 1.2
/// </summary>
/// <seealso cref="Command.ControlStreamFileCommand"/>
/// <param name="file">the name of the file to stream, must not include extension.</param>
/// <param name="escapeDigits">contains the digits that allow the user to interrupt this command.</param>
/// <param name="offset">the offset samples to skip before streaming.</param>
/// <param name="forwardDigit">the digit for fast forward.</param>
/// <param name="rewindDigit">the digit for rewind.</param>
/// <param name="pauseDigit">the digit for pause and unpause.</param>
/// <returns>result code</returns>
protected internal int ControlStreamFile(string file, string escapeDigits, int offset, string forwardDigit, string rewindDigit, string pauseDigit)
{
AGIChannel channel = this.Channel;
AGIReply lastReply = channel.SendCommand(new Command.ControlStreamFileCommand(file, escapeDigits, offset, forwardDigit, rewindDigit, pauseDigit));
return lastReply.ResultCode;
}
#endregion
#region SendCommand(Command.AGICommand command)
/// <summary>
/// Sends the given command to the channel attached to the current thread.
/// </summary>
/// <param name="command">the command to send to Asterisk</param>
/// <returns> the reply received from Asterisk</returns>
/// <throws> AGIException if the command could not be processed properly </throws>
private AGIReply SendCommand(Command.AGICommand command)
{
return this.Channel.SendCommand(command);
}
#endregion
#region Channel
protected internal AGIChannel Channel
{
get
{
AGIChannel channel = AGIConnectionHandler.Channel;
if (channel == null)
throw new SystemException("Trying to send command from an invalid thread");
return channel;
}
}
#endregion
#region Service(AGIRequest param1, AGIChannel param2);
public abstract void Service(AGIRequest param1, AGIChannel param2);
#endregion
}
}
| |
/*
Copyright 2015-2018 Developer Express Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Data;
using Xunit;
namespace DevExpress.DataAccess.BigQuery.Tests {
public class BigQueryConnectionTests {
[Fact]
public void OpenConnectionTest() {
using(BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString)) {
Assert.NotNull(connection.ConnectionString);
Assert.Equal(ConnectionStringHelper.OAuthConnectionString, connection.ConnectionString, ignoreCase: true);
Assert.Equal(ConnectionState.Closed, connection.State);
Assert.Null(connection.Service);
connection.Open();
Assert.NotNull(connection.ConnectionString);
Assert.Equal(ConnectionStringHelper.OAuthConnectionString, connection.ConnectionString, ignoreCase: true);
Assert.Equal(ConnectionState.Open, connection.State);
Assert.NotNull(connection.Service);
}
}
[Fact]
public async void OpenConnectionTest_Async() {
using (BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString)) {
Assert.NotNull(connection.ConnectionString);
Assert.Equal(ConnectionStringHelper.OAuthConnectionString, connection.ConnectionString, ignoreCase: true);
Assert.Equal(ConnectionState.Closed, connection.State);
Assert.Null(connection.Service);
await connection.OpenAsync();
Assert.NotNull(connection.ConnectionString);
Assert.Equal(ConnectionStringHelper.OAuthConnectionString, connection.ConnectionString, ignoreCase: true);
Assert.Equal(ConnectionState.Open, connection.State);
Assert.NotNull(connection.Service);
}
}
[Fact]
public void OpenCloseConnectionTest() {
using(BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString)) {
Assert.NotNull(connection.ConnectionString);
Assert.Equal(ConnectionStringHelper.OAuthConnectionString, connection.ConnectionString, ignoreCase: true);
Assert.Equal(ConnectionState.Closed, connection.State);
Assert.Null(connection.Service);
connection.Open();
Assert.NotNull(connection.ConnectionString);
Assert.Equal(ConnectionStringHelper.OAuthConnectionString, connection.ConnectionString, ignoreCase: true);
Assert.Equal(ConnectionState.Open, connection.State);
Assert.NotNull(connection.Service);
connection.Close();
Assert.Equal(ConnectionState.Closed, connection.State);
}
}
[Fact]
public void OpenDisposeConnectionTest() {
BigQueryConnection connection;
using(connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString)) {
Assert.NotNull(connection.ConnectionString);
Assert.Equal(ConnectionStringHelper.OAuthConnectionString, connection.ConnectionString, ignoreCase: true);
Assert.Equal(ConnectionState.Closed, connection.State);
Assert.Null(connection.Service);
connection.Open();
Assert.NotNull(connection.ConnectionString);
Assert.Equal(ConnectionStringHelper.OAuthConnectionString, connection.ConnectionString, ignoreCase: true);
Assert.Equal(ConnectionState.Open, connection.State);
Assert.NotNull(connection.Service);
connection.Dispose();
}
Assert.Equal(ConnectionState.Closed, connection.State);
}
[Fact]
public void GetTableNamesTest() {
using(BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString)) {
connection.Open();
string[] tableNames = connection.GetTableNames();
Assert.Equal(3, tableNames.Length);
Assert.Equal(TestingInfrastructureHelper.NatalityTableName, tableNames[0]);
Assert.Equal(TestingInfrastructureHelper.Natality2TableName, tableNames[1]);
Assert.Equal(TestingInfrastructureHelper.TimesTableName, tableNames[2]);
}
}
[Fact]
public void GetViewNamesTest() {
using(BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString)) {
connection.Open();
string[] tableNames = connection.GetViewNames();
Assert.Single(tableNames);
Assert.Equal(TestingInfrastructureHelper.NatalityViewName, tableNames[0]);
}
}
[Fact]
public void GetDataSetNamesTest() {
using(BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString)) {
connection.Open();
string[] dataSetNames = connection.GetDataSetNames();
Assert.Single(dataSetNames);
Assert.Equal("testdata", dataSetNames[0]);
}
}
[Fact]
public void CreateDbCommandTest() {
using(BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString)) {
connection.Open();
var dbCommand = connection.CreateCommand();
Assert.NotNull(dbCommand);
Assert.NotNull(dbCommand.Connection);
Assert.Same(connection, dbCommand.Connection);
Assert.Equal("", dbCommand.CommandText);
Assert.Null(dbCommand.Transaction);
Assert.NotNull(dbCommand.Parameters);
Assert.Empty(dbCommand.Parameters);
Assert.Equal((CommandType)0, dbCommand.CommandType);
}
}
[Fact(Skip = "No database for it")]
public void ChangeDatabaseOpenTest() {
using(BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString)) {
connection.Open();
string newDatabase = "";
connection.ChangeDatabase(newDatabase);
Assert.NotNull(connection.Service);
Assert.Equal(connection.DataSetId, newDatabase);
Assert.Equal(ConnectionState.Open, connection.State);
}
}
[Fact(Skip = "No database for it")]
public void ChangeDatabaseCloseTest() {
using(BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString)) {
string newDatabase = "";
connection.ChangeDatabase(newDatabase);
Assert.NotNull(connection.Service);
Assert.Equal(connection.DataSetId, newDatabase);
Assert.Equal(ConnectionState.Open, connection.State);
}
}
[Fact]
public void DisposeChangeDatabaseTest() {
BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString);
connection.Open();
connection.Dispose();
Assert.Throws<ObjectDisposedException>(() => {
connection.ChangeDatabase("");
});
}
[Fact]
public void DisposeGetTableNamesTest() {
BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString);
connection.Dispose();
Assert.Throws<ObjectDisposedException>(() => { connection.GetTableNames(); });
}
[Fact]
public void DisposeCreateDbCommandTest() {
BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString);
connection.Dispose();
Assert.Throws<ObjectDisposedException>(() => { connection.CreateCommand(); });
}
[Fact]
public void DisposeOpenConnectionTest() {
BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString);
connection.Dispose();
Assert.Throws<ObjectDisposedException>(() => { connection.Open(); });
}
[Fact]
public void DisposeCloseConnectionTest() {
BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString);
connection.Dispose();
Assert.Throws<ObjectDisposedException>(() => {
connection.Close();
});
}
[Fact]
public void DisposeDisposeConnectionTest() {
BigQueryConnection connection = new BigQueryConnection(ConnectionStringHelper.OAuthConnectionString);
connection.Dispose();
connection.Dispose();
}
}
}
| |
//#define GSOLVER_LOG
//#define ALWAYS_CHECK_THRESHOLD
#define AGGREGATE_CONSTANTS
using System;
using AutoDiff;
using AD=AutoDiff;
using System.IO;
using System.Text;
using Castor;
using System.Collections.Generic;
using DotNetMatrix;
namespace Alica.Reasoner
{
public class SecondOrderSolver {
protected class RpropResult : IComparable<RpropResult> {
public double[] initialValue;
public double[] finalValue;
public double initialUtil;
public double finalUtil;
public bool aborted;
public int CompareTo (RpropResult other) {
return (this.finalUtil > other.finalUtil)?-1:1;
}
public double DistanceTraveled() {
double ret = 0;
for(int i=0; i<initialValue.Length; i++) {
ret+= (initialValue[i]-finalValue[i])*(initialValue[i]-finalValue[i]);
}
return Math.Sqrt(ret);
}
public double DistanceTraveledNormed(double[] ranges) {
double ret = 0;
for(int i=0; i<initialValue.Length; i++) {
ret+= (initialValue[i]-finalValue[i])*(initialValue[i]-finalValue[i])/(ranges[i]*ranges[i]);
}
return Math.Sqrt(ret);
}
}
public long Runs {get; private set;}
public long FEvals {get; private set;}
public long MaxFEvals {get; set;}
double initialStepSize = 0.005;
public double RPropConvergenceStepSize {get; private set;}
internal double utilitySignificanceThreshold = 1E-22;
Random rand;
int dim;
double[,] limits;
double[] ranges;
double[] rpropStepWidth;
double[] rpropStepConvergenceThreshold;
double utilityThreshold;
ulong maxSolveTime;
//double[][] seeds;
AD.ICompiledTerm term;
StreamWriter sw;
List<RpropResult> rResults;
protected static int fcounter =0;
//Configuration:
protected bool seedWithUtilOptimum;
public SecondOrderSolver () {
AD.Term.SetAnd(AD.Term.AndType.and);
AD.Term.SetOr(AD.Term.OrType.max);
this.rand = new Random();
this.rResults = new List<RpropResult>();
this.seedWithUtilOptimum = true;
this.MaxFEvals = SystemConfig.LocalInstance["Alica"].GetInt("Alica","CSPSolving","MaxFunctionEvaluations");
this.maxSolveTime = ((ulong)SystemConfig.LocalInstance["Alica"].GetInt("Alica","CSPSolving","MaxSolveTime"))*1000000;
RPropConvergenceStepSize = 1E-2;
}
protected void InitLog() {
string logFile = "/tmp/test"+(fcounter++)+".dbg";
FileStream file = new FileStream(logFile, FileMode.Create);
this.sw = new StreamWriter(file);
sw.AutoFlush = true;
}
protected void Log(double util, double[] val) {
sw.Write(util);
sw.Write("\t");
for(int i=0; i <dim; i++) {
sw.Write(val[i]); sw.Write("\t");
}
sw.WriteLine();
}
protected void LogStep() {
sw.WriteLine();
sw.WriteLine();
}
protected void CloseLog() {
if (sw != null) {
sw.Close();
sw=null;
}
}
public double[] Solve(AD.Term equation, AD.Variable[] args, double[,] limits, out double util) {
return Solve(equation,args,limits,null,Double.MaxValue, out util);
}
public bool SolveSimple(AD.Term equation, AD.Variable[] args, double[,] limits) {
return SolveSimple(equation,args,limits,null);
}
public double[] Solve(AD.Term equation, AD.Variable[] args, double[,] limits, double[][] seeds,double sufficientUtility, out double util) {
this.FEvals = 0;
this.Runs = 0;
util = 0;
this.utilityThreshold = sufficientUtility;
#if (GSOLVER_LOG)
InitLog();
#endif
rResults.Clear();
ulong begin = RosCS.RosSharp.Now();
this.dim = args.Length;
this.limits = limits;
this.ranges = new double[dim];
for(int i=0; i<dim; i++) {
this.ranges[i] = (this.limits[i,1]-this.limits[i,0]);
}
#if AGGREGATE_CONSTANTS
equation = equation.AggregateConstants();
#endif
term = AD.TermUtils.Compile(equation,args);
AD.ConstraintUtility cu = (AD.ConstraintUtility) equation;
bool utilIsConstant =(cu.Utility is AD.Constant);
if (utilIsConstant) this.utilityThreshold = 0.75;
bool constraintIsConstant = (cu.Constraint is AD.Constant);
if (constraintIsConstant) {
if(((AD.Constant)cu.Constraint).Value < 0.25) {
util = ((AD.Constant)cu.Constraint).Value;
double[] ret = new double[dim];
for(int i=0; i<dim; i++) {
ret[i] = this.ranges[i]/2.0+this.limits[i,0];
}
return ret;
}
}
//Optimize given seeds
this.rpropStepWidth = new double[dim];
this.rpropStepConvergenceThreshold = new double[dim];
if (seeds != null) {
this.Runs++;
//Run with prefered cached seed
RpropResult rpfirst = RPropLoop(seeds[0],true);
if (rpfirst.finalUtil > this.utilityThreshold) {
util = rpfirst.finalUtil;
//Console.WriteLine("FEvals: {0}",this.FEvals);
return rpfirst.finalValue;
}
rResults.Add(rpfirst);
//run with seeds of all other agends
for(int i=1; i<seeds.Length; i++) {
if (begin + this.maxSolveTime < RosCS.RosSharp.Now() || this.FEvals > this.MaxFEvals) {
break; //do not check any further seeds
}
this.Runs++;
RpropResult rp = RPropLoop(seeds[i],false);
if (rp.finalUtil > this.utilityThreshold) {
util = rp.finalUtil;
//Console.WriteLine("FEvals: {0}",this.FEvals);
return rp.finalValue;
}
rResults.Add(rp);
}
}
//Here: Ignore all constraints search optimum
if (begin + this.maxSolveTime > RosCS.RosSharp.Now() && this.FEvals < this.MaxFEvals) {
//if time allows, do an unconstrained run
if(!constraintIsConstant && !utilIsConstant && seedWithUtilOptimum) {
AD.ICompiledTerm curProb = term;
term = AD.TermUtils.Compile(((AD.ConstraintUtility)equation).Utility,args);
this.Runs++;
double[] utilitySeed = RPropLoop(null).finalValue;
term = curProb;
//Take result and search with constraints
RpropResult ru = RPropLoop(utilitySeed,false);
/*if (ru.finalUtil > this.utilityThreshold) {
util = ru.finalUtil;
return ru.finalValue;
}*/
rResults.Add(ru);
}
}
do { //Do runs until termination criteria, running out of time, or too many function evaluations
this.Runs++;
RpropResult rp = RPropLoop(null,false);
if(rp.finalUtil > this.utilityThreshold) {
util = rp.finalUtil;
//Console.WriteLine("FEvals: {0}",this.FEvals);
return rp.finalValue;
}
rResults.Add(rp);
} while(begin + this.maxSolveTime > RosCS.RosSharp.Now() && this.FEvals < this.MaxFEvals);
//return best result
int resIdx = 0;
RpropResult res = rResults[0];
for(int i=1; i< rResults.Count; i++) {
if (Double.IsNaN(res.finalUtil) || rResults[i].finalUtil > res.finalUtil) {
if (resIdx == 0 && seeds!=null && !Double.IsNaN(res.finalUtil)) {
if (rResults[i].finalUtil - res.finalUtil > utilitySignificanceThreshold && rResults[i].finalUtil > 0.75) {
res = rResults[i];
resIdx = i;
}
} else {
res = rResults[i];
resIdx = i;
}
}
}
//Console.WriteLine("ResultIndex: {0} Delta {1}",resIdx,res.finalUtil-rResults[0].finalUtil);
#if (GSOLVER_LOG)
CloseLog();
#endif
// Console.Write("Found: ");
// for(int i=0; i<dim; i++) {
// Console.Write("{0}\t",res.finalValue[i]);
// }
// Console.WriteLine();
//
//Console.WriteLine("Runs: {0} FEvals: {1}",this.Runs,this.FEvals);
util = res.finalUtil;
return res.finalValue;
}
public bool SolveSimple(AD.Term equation, AD.Variable[] args, double[,] limits, double[][] seeds) {
rResults.Clear();
this.dim = args.Length;
this.limits = limits;
this.ranges = new double[dim];
for(int i=0; i<dim; i++) {
this.ranges[i] = (this.limits[i,1]-this.limits[i,0]);
}
equation = equation.AggregateConstants();
term = AD.TermUtils.Compile(equation,args);
this.rpropStepWidth = new double[dim];
this.rpropStepConvergenceThreshold = new double[dim];
if (seeds != null) {
for(int i=0; i<seeds.Length; i++) {
RpropResult r = RPropLoopSimple(seeds[i]);
rResults.Add(r);
if (r.finalUtil > 0.75) return true;
}
}
int runs = 2*dim - (seeds==null?0:seeds.Length);
for(int i=0; i<runs; i++) {
RpropResult r = RPropLoopSimple(null);
rResults.Add(r);
if (r.finalUtil > 0.75) return true;
}
int adit = 0;
while(!EvalResults() && adit++ < 20) {
RpropResult r = RPropLoopSimple(null);
rResults.Add(r);
if(r.finalUtil > 0.75) return true;
}
if (adit > 20) {
Console.WriteLine("Failed to satisfy heuristic!");
}
return false;
}
public double[] SolveTest(AD.Term equation, AD.Variable[] args, double[,] limits) {
#if (GSOLVER_LOG)
InitLog();
#endif
rResults.Clear();
double[] res = null;
this.dim = args.Length;
this.limits = limits;
this.ranges = new double[dim];
for(int i=0; i<dim; i++) {
this.ranges[i] = (this.limits[i,1]-this.limits[i,0]);
}
term = AD.TermUtils.Compile(equation,args);
this.rpropStepWidth = new double[dim];
this.rpropStepConvergenceThreshold = new double[dim];
this.Runs = 0;
this.FEvals = 0;
//int runs = 1000000;
while(true) {
this.Runs++;
//RpropResult r = RPropLoopSimple(null);
RpropResult r = RPropLoop(null,false);
//Console.WriteLine("Run: {0} Util: {1}",i,r.finalUtil);
/*for(int k=0; k<dim; k++) {
Console.Write("{0}\t",r.finalValue[k]);
}
Console.WriteLine();*/
if (r.finalUtil > 0.75) {
res = r.finalValue;
break;
}
}
#if (GSOLVER_LOG)
CloseLog();
#endif
return res;
}
public double[] SolveTest(AD.Term equation, AD.Variable[] args, double[,] limits,int maxRuns, out bool found) {
#if (GSOLVER_LOG)
InitLog();
#endif
found = false;
rResults.Clear();
double[] res = null;
this.dim = args.Length;
this.limits = limits;
this.ranges = new double[dim];
for(int i=0; i<dim; i++) {
this.ranges[i] = (this.limits[i,1]-this.limits[i,0]);
}
term = AD.TermUtils.Compile(equation,args);
this.rpropStepWidth = new double[dim];
this.rpropStepConvergenceThreshold = new double[dim];
this.Runs = 0;
this.FEvals = 0;
while(this.Runs < maxRuns) {
this.Runs++;
//RpropResult r = RPropLoopSimple(null);
RpropResult r = RPropLoop(null,false);
//Console.WriteLine("Run: {0} Util: {1}",i,r.finalUtil);
/*for(int k=0; k<dim; k++) {
Console.Write("{0}\t",r.finalValue[k]);
}
Console.WriteLine();*/
if (r.finalUtil > 0.75) {
res = r.finalValue;
found = true;
break;
}
}
#if (GSOLVER_LOG)
CloseLog();
#endif
return res;
}
protected double[] InitialPointFromSeed(RpropResult res, double[] seed) {
Tuple<double[],double> tup;
res.initialValue = new double[dim];
res.finalValue = new double[dim];
for(int i=0; i<dim; i++) {
if (Double.IsNaN(seed[i])) {
res.initialValue[i] = rand.NextDouble()*ranges[i]+limits[i,0];
} else {
res.initialValue[i] = Math.Min(Math.Max(seed[i],limits[i,0]),limits[i,1]);
}
}
tup = term.Differentiate(res.initialValue);
res.initialUtil = tup.Item2;
res.finalUtil = tup.Item2;
Buffer.BlockCopy(res.initialValue,0,res.finalValue,0,sizeof(double)*dim);
return tup.Item1;
}
protected double[] InitialPoint(RpropResult res) {
Tuple<double[],double> tup;
bool found = true;
res.initialValue = new double[dim];
res.finalValue = new double[dim];
do {
for(int i=0; i<dim; i++) {
//double range = limits[i,1]-limits[i,0];
res.initialValue[i] = rand.NextDouble()*ranges[i]+limits[i,0];
}
this.FEvals++;
tup = term.Differentiate(res.initialValue);
for(int i=0; i<dim; i++) {
if (Double.IsNaN(tup.Item1[i])) {
//Console.WriteLine("NaN in Gradient, retrying");
found = false;
break;
} else found = true;
}
} while(!found);
res.initialUtil = tup.Item2;
res.finalUtil = tup.Item2;
Buffer.BlockCopy(res.initialValue,0,res.finalValue,0,sizeof(double)*dim);
return tup.Item1;
}
protected RpropResult RPropLoop(double[] seed) {
return RPropLoop(seed,false);
}
protected RpropResult RPropLoop(double[] seed, bool precise) {
//Console.WriteLine("RpropLoop");
InitialStepSize();
double[] curGradient;
RpropResult ret = new RpropResult();
if(seed != null) {
curGradient = InitialPointFromSeed(ret,seed);
}
else {
curGradient = InitialPoint(ret);
}
double curUtil = ret.initialUtil;
double oldUtil = curUtil;
double[] formerGradient = new double[dim];
double[] curValue = new double[dim];
double[] testValue = new double[dim];
double lambda = 0.1;
Tuple<double[],double> tup;
Buffer.BlockCopy(ret.initialValue,0,curValue,0,sizeof(double)*dim);
formerGradient = curGradient;
//Buffer.BlockCopy(curGradient,0,formerGradient,0,sizeof(double)*dim);
int itcounter = 0;
int badcounter = 0;
/*Console.WriteLine("Initial Sol:");
for(int i=0; i<dim;i++) {
Console.Write("{0} ",curValue[i]);
}
Console.WriteLine();
Console.WriteLine("Initial Util: {0}",curUtil);
*/
#if (GSOLVER_LOG)
Log(curUtil,curValue);
#endif
int maxIter = 60;
int maxBad = 30;
double minStep = 1E-11;
if(precise) {
maxIter = 120; //110
maxBad = 60; //60
minStep = 1E-15;//15
}
int convergendDims = 0;
while(itcounter++ < maxIter && badcounter < maxBad) {
convergendDims = 0;
//First Order resp. approximated Second Order Gradient
for(int i=0; i<dim; i++) {
if (curGradient[i] * formerGradient[i] > 0) rpropStepWidth[i] *= 1.3;
else if (curGradient[i] * formerGradient[i] < 0) rpropStepWidth[i] *= 0.5;
rpropStepWidth[i] = Math.Max(minStep,rpropStepWidth[i]);
//rpropStepWidth[i] = Math.Max(0.000001,rpropStepWidth[i]);
if(curUtil>0.0) {
//if (curGradient[i] > 0) curValue[i] += rpropStepWidth[i];
//else if (curGradient[i] < 0) curValue[i] -= rpropStepWidth[i];
} else {
//linear assumption
//curValue[i] += -curUtil/curGradient[i];
//quadratic assumption
/*double ypSquare = 0;
for(int j=0; j<dim; j++) {
ypSquare += curGradient[j]*curGradient[j];
}
double m=ypSquare/curUtil;
curValue[i] = -curGradient[i]/(2*m) + curValue[i];*/
}
if (curValue[i] > limits[i,1]) curValue[i] = limits[i,1];
else if (curValue[i] < limits[i,0]) curValue[i] = limits[i,0];
if(rpropStepWidth[i] < rpropStepConvergenceThreshold[i]) {
++convergendDims;
}
}
//Abort if all dimensions are converged
if(!precise && convergendDims>=dim) {
if (curUtil > ret.finalUtil) {
ret.finalUtil = curUtil;
Buffer.BlockCopy(curValue,0,ret.finalValue,0,sizeof(double)*dim);
}
return ret;
}
// Conjugate Gradient
if(curUtil<0.5) {
DotNetMatrix.GeneralMatrix X = new DotNetMatrix.GeneralMatrix(dim*2+1,dim);
DotNetMatrix.GeneralMatrix Y = new DotNetMatrix.GeneralMatrix(dim*2+1,1);
for(int n=0; n<dim; n++) {
X.SetElement(0,n, curValue[n]);
}
Y.SetElement(0,0, 0);
for(int j=0; j<dim*2; j++) {
for(int n=0; n<dim; n++) {
double rVal = rand.NextDouble()*rpropStepConvergenceThreshold[n]*1000.0;
testValue[n] = curValue[n] + rVal;
}
tup = term.Differentiate(testValue);
for(int n=0; n<dim; n++) {
X.SetElement(j+1, n, tup.Item1[n]);
}
Y.SetElement(j+1, 0, tup.Item2-curUtil);
}
DotNetMatrix.GeneralMatrix JJ = X.Transpose().Multiply(X);
/*if(curUtil>oldUtil) lambda *= 10;
else lambda *= 0.1;*/
//DotNetMatrix.GeneralMatrix B = JJ.Add(GeneralMatrix.Identity(dim, dim).Multiply(lambda)).Inverse().Multiply(X.Transpose()).Multiply(Y);
DotNetMatrix.GeneralMatrix B = JJ.Add(JJ.SVD().S.Multiply(lambda)).Inverse().Multiply(X.Transpose()).Multiply(Y);
//DotNetMatrix.GeneralMatrix B = JJ.Inverse().Multiply(X.Transpose()).Multiply(Y);
for(int j=0; j<dim; j++) {
curValue[j] += 0.01*B.GetElement(j, 0);
}
Console.WriteLine(curUtil);
Console.Write(B.Transpose());
Console.WriteLine();
}
/////////////////////////
this.FEvals++;
tup = term.Differentiate(curValue);
bool allZero = true;
for(int i=0; i < dim; i++) {
if (Double.IsNaN(tup.Item1[i])) {
ret.aborted=true;
#if (GSOLVER_LOG)
LogStep();
#endif
return ret;
}
allZero &= (tup.Item1[i]==0);
}
oldUtil = curUtil;
curUtil = tup.Item2;
formerGradient = curGradient;
curGradient = tup.Item1;
#if (GSOLVER_LOG)
Log(curUtil,curValue);
#endif
//Console.WriteLine("CurUtil: {0} Final {1}",curUtil,ret.finalUtil);
if (curUtil > ret.finalUtil) {
badcounter = 0;//Math.Max(0,badcounter-1);
//if (curUtil-ret.finalUtil < 0.00000000000001) {
//Console.WriteLine("not better");
// badcounter++;
//} else {
//badcounter = 0;
//}
ret.finalUtil = curUtil;
Buffer.BlockCopy(curValue,0,ret.finalValue,0,sizeof(double)*dim);
//ret.finalValue = curValue;
#if (ALWAYS_CHECK_THRESHOLD)
if(curUtil > utilityThreshold) return ret;
#endif
} else {
//if (curUtil < ret.finalUtil || curUtil > 0) badcounter++;
badcounter++;
}
if (allZero) {
//Console.WriteLine("All Zero!");
/*Console.WriteLine("Util {0}",curUtil);
Console.Write("Vals: ");
for(int i=0; i < dim; i++) {
Console.Write("{0}\t",curValue[i]);
}
Console.WriteLine();*/
ret.aborted = false;
#if (GSOLVER_LOG)
LogStep();
#endif
return ret;
}
}
#if (GSOLVER_LOG)
LogStep();
#endif
ret.aborted = false;
return ret;
}
protected RpropResult RPropLoopSimple(double[] seed) {
InitialStepSize();
double[] curGradient;
RpropResult ret = new RpropResult();
if(seed != null) {
curGradient = InitialPointFromSeed(ret,seed);
}
else {
curGradient = InitialPoint(ret);
}
double curUtil = ret.initialUtil;
if (ret.initialUtil > 0.75) {
return ret;
}
double[] formerGradient = new double[dim];
double[] curValue = new double[dim];
Tuple<double[],double> tup;
Buffer.BlockCopy(ret.initialValue,0,curValue,0,sizeof(double)*dim);
formerGradient = curGradient;
//Buffer.BlockCopy(curGradient,0,formerGradient,0,sizeof(double)*dim);
int itcounter = 0;
int badcounter = 0;
//Log(curUtil,curValue);
while(itcounter++ < 40 && badcounter < 6) {
for(int i=0; i<dim; i++) {
if (curGradient[i] * formerGradient[i] > 0) rpropStepWidth[i] *= 1.3;
else if (curGradient[i] * formerGradient[i] < 0) rpropStepWidth[i] *= 0.5;
rpropStepWidth[i] = Math.Max(0.0001,rpropStepWidth[i]);
if (curGradient[i] > 0) curValue[i] += rpropStepWidth[i];
else if (curGradient[i] < 0) curValue[i] -= rpropStepWidth[i];
if (curValue[i] > limits[i,1]) curValue[i] = limits[i,1];
else if (curValue[i] < limits[i,0]) curValue[i] = limits[i,0];
}
tup = term.Differentiate(curValue);
bool allZero = true;
for(int i=0; i < dim; i++) {
if (Double.IsNaN(tup.Item1[i])) {
Console.WriteLine("NaN in gradient, aborting!");
ret.aborted=false;//true; //HACK!
return ret;
}
allZero &= (tup.Item1[i]==0);
}
curUtil = tup.Item2;
formerGradient = curGradient;
curGradient = tup.Item1;
//Log(curUtil,curValue);
//Console.WriteLine("CurUtil: {0} Final {1}",curUtil,ret.finalUtil);
if (curUtil > ret.finalUtil) {
badcounter = 0;
ret.finalUtil = curUtil;
Buffer.BlockCopy(curValue,0,ret.finalValue,0,sizeof(double)*dim);
if (curUtil > 0.75) return ret;
} else {
badcounter++;
}
if (allZero) {
//Console.WriteLine("All Zero!");
ret.aborted = false;
return ret;
}
}
ret.aborted = false;
return ret;
}
protected void InitialStepSize() {
for(int i=0; i<this.dim; i++) {
//double range = this.limits[i,1]-this.limits[i,0];
this.rpropStepWidth[i] = 1.0;//initialStepSize*ranges[i];
this.rpropStepConvergenceThreshold[i] = initialStepSize*ranges[i]*this.RPropConvergenceStepSize;
}
}
protected bool EvalResults() {
/*
* TODO: Compare Average Distance between start and end point to
* Average distance between any two arbitrary points.
*
* Latter one can be found in http://www.math.uni-muenster.de/reine/u/burgstal/d18.pdf :
* maxDist = sqrt(dim)
* avgDist <= 1 / sqrt(6) * sqrt((1+2*sqrt(1-3/(5*dim)))/3) * maxDist
*
* aprox: (http://www.jstor.org/pss/1427094)
*
* avgDist = sqrt(dim/3) * (1 - 1/(10*k) - 13/(280*k^2) - 101/ (2800*k^3) - 37533 / (1232000 k^4) * O(sqrt(k)) (?)
* */
int count = this.rResults.Count;
//Console.WriteLine("Eval");
/*
double maxDist = Math.Sqrt(dim);
double avgDist = 1 / Math.Sqrt(6) * Math.Sqrt((1+2*Math.Sqrt(1-3/(5*dim)))/3) * maxDist;
double allDist = 0;
for(int i=0; i<count; i++) {
if (rResults[i].aborted) {
abortedCount++;
} else {
allDist += rResults[i].DistanceTraveledNormed(this.ranges);
}
}
double avgDistTraveled = allDist / (count-abortedCount);
Console.WriteLine("Traveled: {0} Expected: {1}",avgDistTraveled,avgDist);
*/
//if (avgDistTraveled < 0.66* avgDist) return false;
int abortedCount = 0;
//double[] midValue = new double[dim];
double[] midInitValue = new double[dim];
//double[] valueDev = new double[dim];
double[] valueInitDev = new double[dim];
//double midUtil =0;
for(int i=0; i<count; i++) {
if (rResults[i].aborted) {
abortedCount++;
} else {
//midUtil += rResults[i].finalUtil;
for(int j=0; j<dim; j++) {
//midValue[j] += rResults[i].finalValue[j];
midInitValue[j] += rResults[i].initialValue[j];
}
}
}
if (count-abortedCount < dim) return false;
for(int j=0; j<dim; j++) {
//midValue[j] /= (count-abortedCount);
midInitValue[j] /= (count-abortedCount);
}
for(int i=0; i<count; i++) {
if (rResults[i].aborted) continue;
for (int j=0; j<dim; j++) {
//valueDev[j] += Math.Pow((rResults[i].finalValue[j]-midValue[j])/ranges[j],2);
valueInitDev[j] += Math.Pow((rResults[i].initialValue[j]-midInitValue[j])/ranges[j],2);
}
}
for(int j=0; j<dim; j++) {
//if (valueDev[j] > valueInitDev[j]) return false;
//valueDev[j] /= (count-abortedCount);
valueInitDev[j] /= (count-abortedCount);
//if (Math.Sqrt(valueInitDev[j]) < 0.22) return false;
if (valueInitDev[j] < 0.0441) return false;
}
Console.WriteLine("Runs: {0} Aborted: {1}",count,abortedCount);
/*Console.WriteLine("Final Std Deviation: ");
for(int j=0; j<dim; j++) {
Console.Write("{0}\t",Math.Sqrt(valueDev[j]));
}
Console.WriteLine();
Console.WriteLine("Initial Std Deviation: ");
for(int j=0; j<dim; j++) {
Console.Write("{0}\t",Math.Sqrt(valueInitDev[j]));
}
Console.WriteLine();
*/
/*for(int j=0; j<dim; j++) {
if (valueDev[j] > valueInitDev[j]) return false;
}*/
return true;
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Portal.ExchangeServer
{
public partial class ExchangeMailboxGeneralSettings : WebsitePanelModuleBase
{
private PackageContext cntx = null;
private PackageContext Cntx
{
get
{
if (cntx == null)
cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId);
return cntx;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Utils.CheckQouta(Quotas.EXCHANGE2007_DISCLAIMERSALLOWED, Cntx))
{
ddDisclaimer.Items.Add(new System.Web.UI.WebControls.ListItem("None", "-1"));
ExchangeDisclaimer[] disclaimers = ES.Services.ExchangeServer.GetExchangeDisclaimers(PanelRequest.ItemID);
foreach (ExchangeDisclaimer disclaimer in disclaimers)
ddDisclaimer.Items.Add(new System.Web.UI.WebControls.ListItem(disclaimer.DisclaimerName, disclaimer.ExchangeDisclaimerId.ToString()));
}
else
{
locDisclaimer.Visible = false;
ddDisclaimer.Visible = false;
}
BindSettings();
UserInfo user = UsersHelper.GetUser(PanelSecurity.EffectiveUserId);
if (user != null)
{
if ((user.Role == UserRole.User) & (Utils.CheckQouta(Quotas.EXCHANGE2007_ISCONSUMER, Cntx)))
{
chkHideAddressBook.Visible = false;
chkDisable.Visible = false;
}
}
secRetentionPolicy.Visible = Utils.CheckQouta(Quotas.EXCHANGE2013_ALLOWRETENTIONPOLICY, Cntx);
if (GetLocalizedString("buttonPanel.OnSaveClientClick") != null)
buttonPanel.OnSaveClientClick = GetLocalizedString("buttonPanel.OnSaveClientClick");
}
int planId = -1;
int.TryParse(mailboxPlanSelector.MailboxPlanId, out planId);
ExchangeMailboxPlan plan = ES.Services.ExchangeServer.GetExchangeMailboxPlan(PanelRequest.ItemID, planId);
if (plan != null)
{
secArchiving.Visible = plan.EnableArchiving;
secLitigationHoldSettings.Visible = plan.AllowLitigationHold && Utils.CheckQouta(Quotas.EXCHANGE2007_ALLOWLITIGATIONHOLD, Cntx);
}
else
{
secArchiving.Visible = false;
secLitigationHoldSettings.Visible = false;
}
}
private void BindSettings()
{
try
{
// get settings
ExchangeMailbox mailbox = ES.Services.ExchangeServer.GetMailboxGeneralSettings(PanelRequest.ItemID,
PanelRequest.AccountID);
//get statistics
ExchangeMailboxStatistics stats = ES.Services.ExchangeServer.GetMailboxStatistics(PanelRequest.ItemID,
PanelRequest.AccountID);
// mailbox plan
// title
litDisplayName.Text = mailbox.DisplayName;
// bind form
chkHideAddressBook.Checked = mailbox.HideFromAddressBook;
chkDisable.Checked = mailbox.Disabled;
lblExchangeGuid.Text = string.IsNullOrEmpty(mailbox.ExchangeGuid) ? "<>" : mailbox.ExchangeGuid ;
// get account meta
ExchangeAccount account = ES.Services.ExchangeServer.GetAccount(PanelRequest.ItemID, PanelRequest.AccountID);
// get mailbox plan
ExchangeMailboxPlan plan = ES.Services.ExchangeServer.GetExchangeMailboxPlan(PanelRequest.ItemID, account.MailboxPlanId);
chkPmmAllowed.Checked = (account.MailboxManagerActions & MailboxManagerActions.GeneralSettings) > 0;
if (account.MailboxPlanId == 0)
{
mailboxPlanSelector.AddNone = true;
mailboxPlanSelector.MailboxPlanId = "-1";
}
else
{
mailboxPlanSelector.MailboxPlanId = account.MailboxPlanId.ToString();
}
if (account.ArchivingMailboxPlanId<1)
{
mailboxRetentionPolicySelector.MailboxPlanId = "-1";
}
else
{
mailboxRetentionPolicySelector.MailboxPlanId = account.ArchivingMailboxPlanId.ToString();
}
mailboxSize.QuotaUsedValue = Convert.ToInt32(stats.TotalSize / 1024 / 1024);
mailboxSize.QuotaValue = (stats.MaxSize == -1) ? -1 : (int)Math.Round((double)(stats.MaxSize / 1024 / 1024));
secCalendarSettings.Visible = ((account.AccountType == ExchangeAccountType.Equipment) | (account.AccountType == ExchangeAccountType.Room));
secLitigationHoldSettings.Visible = mailbox.EnableLitigationHold;
litigationHoldSpace.QuotaUsedValue = Convert.ToInt32(stats.LitigationHoldTotalSize / 1024 / 1024);
litigationHoldSpace.QuotaValue = (stats.LitigationHoldMaxSize == -1) ? -1 : (int)Math.Round((double)(stats.LitigationHoldMaxSize / 1024 / 1024));
if (Utils.CheckQouta(Quotas.EXCHANGE2007_DISCLAIMERSALLOWED, Cntx))
{
int disclaimerId = ES.Services.ExchangeServer.GetExchangeAccountDisclaimerId(PanelRequest.ItemID, PanelRequest.AccountID);
ddDisclaimer.SelectedValue = disclaimerId.ToString();
}
int ArchivingMaxSize = -1;
if (plan != null) ArchivingMaxSize = plan.ArchiveSizeMB;
chkEnableArchiving.Checked = account.EnableArchiving;
archivingQuotaViewer.QuotaUsedValue = Convert.ToInt32(stats.ArchivingTotalSize / 1024 / 1024);
archivingQuotaViewer.QuotaValue = ArchivingMaxSize;
rowArchiving.Visible = chkEnableArchiving.Checked;
if (account.LevelId > 0 && Cntx.Groups.ContainsKey(ResourceGroups.ServiceLevels))
{
WebsitePanel.EnterpriseServer.Base.HostedSolution.ServiceLevel serviceLevel = ES.Services.Organizations.GetSupportServiceLevel(account.LevelId);
litServiceLevel.Visible = true;
litServiceLevel.Text = serviceLevel.LevelName;
litServiceLevel.ToolTip = serviceLevel.LevelDescription;
}
imgVipUser.Visible = account.IsVIP && Cntx.Groups.ContainsKey(ResourceGroups.ServiceLevels);
if (account.AccountType == ExchangeAccountType.SharedMailbox)
litDisplayName.Text += GetSharedLocalizedString("SharedMailbox.Text");
if (account.AccountType == ExchangeAccountType.Room)
litDisplayName.Text += GetSharedLocalizedString("RoomMailbox.Text");
if (account.AccountType == ExchangeAccountType.Equipment)
litDisplayName.Text += GetSharedLocalizedString("EquipmentMailbox.Text");
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("EXCHANGE_GET_MAILBOX_SETTINGS", ex);
}
}
private void SaveSettings()
{
if (!Page.IsValid)
return;
try
{
if (mailboxPlanSelector.MailboxPlanId == "-1")
{
messageBox.ShowErrorMessage("EXCHANGE_SPECIFY_PLAN");
return;
}
int result = ES.Services.ExchangeServer.SetMailboxGeneralSettings(
PanelRequest.ItemID, PanelRequest.AccountID,
chkHideAddressBook.Checked,
chkDisable.Checked);
if (result < 0)
{
messageBox.ShowResultMessage(result);
return;
}
else
{
int planId = Convert.ToInt32(mailboxPlanSelector.MailboxPlanId);
int policyId = -1;
int.TryParse(mailboxRetentionPolicySelector.MailboxPlanId, out policyId);
bool EnableArchiving = chkEnableArchiving.Checked;
result = ES.Services.ExchangeServer.SetExchangeMailboxPlan(PanelRequest.ItemID, PanelRequest.AccountID, planId,
policyId, EnableArchiving);
if (result < 0)
{
messageBox.ShowResultMessage(result);
return;
}
}
if (Utils.CheckQouta(Quotas.EXCHANGE2007_DISCLAIMERSALLOWED, Cntx))
{
int disclaimerId;
if (int.TryParse(ddDisclaimer.SelectedValue, out disclaimerId))
ES.Services.ExchangeServer.SetExchangeAccountDisclaimerId(PanelRequest.ItemID, PanelRequest.AccountID, disclaimerId);
}
messageBox.ShowSuccessMessage("EXCHANGE_UPDATE_MAILBOX_SETTINGS");
BindSettings();
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("EXCHANGE_UPDATE_MAILBOX_SETTINGS", ex);
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
SaveSettings();
}
protected void btnSaveExit_Click(object sender, EventArgs e)
{
SaveSettings();
Response.Redirect(PortalUtils.EditUrl("ItemID", PanelRequest.ItemID.ToString(),
"mailboxes",
"SpaceID=" + PanelSecurity.PackageId));
}
protected void chkPmmAllowed_CheckedChanged(object sender, EventArgs e)
{
try
{
int result = ES.Services.ExchangeServer.SetMailboxManagerSettings(PanelRequest.ItemID, PanelRequest.AccountID,
chkPmmAllowed.Checked, MailboxManagerActions.GeneralSettings);
if (result < 0)
{
messageBox.ShowResultMessage(result);
return;
}
messageBox.ShowSuccessMessage("EXCHANGE_UPDATE_MAILMANAGER");
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("EXCHANGE_UPDATE_MAILMANAGER", ex);
}
}
private int ConvertMbxSizeToIntMB(string inputValue)
{
int result = 0;
if ((inputValue == null) || (inputValue == ""))
return 0;
if (inputValue.Contains("TB"))
{
result = Convert.ToInt32(inputValue.Replace(" TB", ""));
result = result * 1024 * 1024;
}
else
if (inputValue.Contains("GB"))
{
result = Convert.ToInt32(inputValue.Replace(" GB", ""));
result = result * 1024;
}
else
if (inputValue.Contains("MB"))
{
result = Convert.ToInt32(inputValue.Replace(" MB", ""));
}
return result;
}
public void mailboxPlanSelector_Changed(object sender, EventArgs e)
{
}
}
}
| |
using System;
using FluentAssertions;
using RxGen.Core.Utils;
using RxGen.People.Models;
using Xunit;
using Moq;
using RxGen.People;
using RxGen.People.Api;
using Microsoft.Reactive.Testing;
using System.Reactive.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace RxGen.Tests
{
public class RxPeopleTests
{
private static readonly TimeSpan RepeatDelay = TimeSpan.FromMilliseconds(1000);
private Mock<IRandomGenerator> _randomGenerator;
private Mock<IGenPeopleApiClient> _peopleApiClient;
private GenPeopleResponse CreateReponse(GenPeopleRequest request) =>
new GenPeopleResponse
{
Info = new GenInfo { Page = request.Page, Seed = request.Seed },
Result = new List<GenUser> { new GenUser { Email = "j@j.com" } }
};
public RxPeopleTests()
{
_randomGenerator = new Mock<IRandomGenerator>();
var errorProbability = 0.6;
_randomGenerator.Setup(x => x.NextDouble()).Returns(errorProbability);
RandomGeneratorFactory.SetFactory(() => _randomGenerator.Object);
_peopleApiClient = new Mock<IGenPeopleApiClient>();
_peopleApiClient.Setup(x =>
x.GetPeople(
It.IsAny<GenPeopleRequest>()))
.Returns((GenPeopleRequest req) =>
Task.FromResult(CreateReponse(req)));
}
[Fact]
public void Should_throw_exception_when_configured_with_invalid_results()
{
var numberOfUsers = -5;
// configure request
Action action = () => RxGen.People()
.Ammount(numberOfUsers);
action.ShouldThrow<ArgumentException>();
}
[Fact]
public void Should_throw_exception_when_configured_with_invalid_page()
{
var numberOfUsers = 5;
var page = -1;
// configure request
Action action = () => RxGen.People()
.Ammount(numberOfUsers)
.Page(page);
action.ShouldThrow<ArgumentException>();
}
[Fact]
public void Should_throw_exception_when_configured_to_include_and_exclude_fields_at_the_same_time()
{
var numberOfUsers = 5;
var includeFieldName = Field.Login;
var excludeFieldName = Field.Nationality;
// configure request
Action incExcAction = () => RxGen.People()
.Ammount(numberOfUsers)
.IncludeField(includeFieldName)
.ExcludeField(excludeFieldName);
Action excIncAction = () => RxGen.People()
.Ammount(numberOfUsers)
.ExcludeField(excludeFieldName)
.IncludeField(includeFieldName);
incExcAction.ShouldThrow<ArgumentException>();
excIncAction.ShouldThrow<ArgumentException>();
}
[Fact]
public void Should_build_valid_url_with_from_request()
{
var numberOfUsers = 5;
var gender = Gender.Female;
var genderAsString = gender.ToString().ToLower();
var nationalities = new Nationality[] { Nationality.ES, Nationality.US };
var nationalitiesAsString = string.Join(",", nationalities);
var includeFields = new Field[] { Field.Nationality, Field.Email };
var includeFieldsAsString = string.Join(",", includeFields);
var seedName = "myseed";
var page = 5;
var expectedUrl = $"?page={page}&results={numberOfUsers}&seed={seedName}&gender={genderAsString}&inc={includeFieldsAsString}&nat={nationalitiesAsString}";
// configure request
var request = RxGen.People()
.Ammount(numberOfUsers)
.Gender(gender)
.Nationality(nationalities[0], nationalities[1])
.IncludeField(includeFields[0], includeFields[1])
.Seed(seedName)
.Page(page)
.AsRequest();
var url = request.AsUrl();
url.Should().Be(expectedUrl);
}
[Fact]
public async Task Should_paginate_using_seed_to_given_page()
{
var seedName = "mypeople";
var generator = new RxPeople(_peopleApiClient.Object)
.Seed(seedName)
.Ammount(5);
var pagesToNavigate = new int[] { 1, 2, 3, 2, 1, 5 };
foreach(var page in pagesToNavigate)
{
var source = generator
.Page(page)
.AsObservable();
var response = await source;
response.Info.Seed.Should().Be(seedName);
response.Info.Page.Should().Be(page);
}
}
[Fact]
public void Should_auto_paginate_with_paging_delay()
{
var generator = new RxPeople(_peopleApiClient.Object)
.Seed("mypeople")
.Ammount(5);
var maxPages = 5;
var currentPage = 0;
var scheduler = new TestScheduler();
var source = generator
.AutoPagination(maxPages, RepeatDelay, scheduler)
.Subscribe(
(res) => currentPage = res.Info.Page
);
currentPage.Should().Be(1);
scheduler.AdvanceBy(RepeatDelay.Ticks);
currentPage.Should().Be(2);
// advance to last page
scheduler.AdvanceBy(RepeatDelay.Ticks * (maxPages - 2));
currentPage.Should().Be(maxPages);
// should restart the cycle and decrease
scheduler.AdvanceBy(RepeatDelay.Ticks);
currentPage.Should().Be(maxPages - 1);
}
[Fact]
public void Should_repeat_forever_getting_data()
{
var generator = new RxPeople(_peopleApiClient.Object)
.Ammount(5);
var scheduler = new TestScheduler();
var counter = 0;
var source = generator
.AsObservable()
.RepeatForever(RepeatDelay, scheduler)
.Subscribe(
(res) => counter++,
(ex) => {}
);
counter.Should().Be(1);
scheduler.AdvanceBy(RepeatDelay.Ticks);
counter.Should().Be(2);
scheduler.AdvanceBy(RepeatDelay.Ticks);
counter.Should().Be(3);
}
[Fact]
public void Should_not_throw_when_given_error_probability_greater_than_random()
{
var errorProbability = 0.4; // > 0.6
var exceptionThrown = false;
var scheduler = new TestScheduler();
var generator = new RxPeople(_peopleApiClient.Object)
.Ammount(5);
var source = generator
.AsObservable()
.RepeatWithRandomError(errorProbability, RepeatDelay, scheduler)
.Subscribe(
(res) => {},
(ex) => exceptionThrown = true
);
exceptionThrown.Should().BeFalse();
}
[Fact]
public void Should_throw_when_given_error_probability_less_than_random()
{
var errorProbability = 0.7; // < 0.6
var exceptionThrown = false;
var scheduler = new TestScheduler();
var generator = new RxPeople(_peopleApiClient.Object)
.Ammount(5);
var source = generator
.AsObservable()
.RepeatWithRandomError(errorProbability, RepeatDelay, scheduler)
.Subscribe(
(res) => {},
(ex) => exceptionThrown = true
);
exceptionThrown.Should().BeTrue();
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using GuruComponents.Netrix.ComInterop;
using GuruComponents.Netrix.WebEditing.Elements;
namespace GuruComponents.Netrix.Events
{
/// <summary>
/// This class provides event arguments for DHTML events.
/// </summary>
/// <remarks>
/// These events are fired when an .NET event handler is attached to a DHTML event during design time.
/// </remarks>
public class DocumentEventArgs : CancelEventArgs
{
private Point clientXY;
private Point screenXY;
private MouseButtons button;
private IElement sourceElement = null;
private bool ctrlKey, altKey, shftKey;
private Keys keyCode;
private string type;
private Interop.IHTMLEventObj referenceObject;
/// <summary>
/// Internally used ctor.
/// </summary>
/// <param name="e"></param>
/// <param name="sourceElement"></param>
public DocumentEventArgs(Interop.IHTMLEventObj e, IElement sourceElement)
{
//System.Diagnostics.Debug.Assert(e != null, "NULL Event E");
//System.Diagnostics.Debug.Assert(sourceElement != null, "NULL Event SRC");
referenceObject = e;
this.sourceElement = sourceElement;
if (e != null)
{
clientXY = new Point(e.clientX, e.clientY);
screenXY = new Point(e.screenX, e.screenY);
switch (e.button)
{
default:
case 0:
button = Control.MouseButtons;
break;
case 1:
button = MouseButtons.Left;
break;
case 2:
button = MouseButtons.Right;
break;
case 3:
button = MouseButtons.Left | MouseButtons.Right;
break;
case 4:
button = MouseButtons.Middle;
break;
case 5:
button = MouseButtons.Left | MouseButtons.Middle;
break;
case 6:
button = MouseButtons.Right | MouseButtons.Middle;
break;
case 7:
button = MouseButtons.Left | MouseButtons.Middle | MouseButtons.Right;
break;
}
ctrlKey = e.ctrlKey;
shftKey = e.shiftKey;
altKey = e.altKey;
keyCode = ((Keys) e.keyCode) | ((altKey) ? Keys.Alt : Keys.None) | ((ctrlKey) ? Keys.Control : Keys.None) | ((shftKey) ? Keys.Shift : Keys.None);
type = e.type.ToLower();
}
}
/// <summary>
/// Set the event bubble chain cancel.
/// </summary>
/// <param name="val"></param>
public void SetCancelBubble(bool val)
{
referenceObject.cancelBubble = val;
}
/// <summary>
/// Set or overwrite the return value.
/// </summary>
/// <param name="val"></param>
public void SetReturnValue(bool val)
{
referenceObject.returnValue = val;
}
# region Public Properties
/// <summary>
/// The property which was changed.
/// </summary>
/// <remarks>
/// This property applies only when OnPropertyChange event has been fired.
/// </remarks>
public string PropertyName
{
get
{
return ((Interop.IHTMLEventObj2)referenceObject).propertyName;
}
}
/// <summary>
/// TODO: Add comment.
/// </summary>
public new bool Cancel
{
get
{
return base.Cancel;
}
set
{
base.Cancel = value;
if (referenceObject != null)
{
referenceObject.returnValue = !base.Cancel;
referenceObject.cancelBubble = base.Cancel;
}
}
}
/// <summary>
/// Mousebutton was clicked during event.
/// </summary>
public MouseButtons MouseButton
{
get
{
return this.button;
}
}
/// <summary>
/// The element causes the event.
/// </summary>
public IElement SrcElement
{
get
{
return this.sourceElement;
}
}
/// <summary>
/// The position of mouse pointer in client area.
/// </summary>
/// <remarks>
/// Retrieves the coordinates of the mouse pointer's position relative to the client area of the window, excluding window decorations and scroll bars.
/// </remarks>
public Point ClientXY
{
get
{
return this.clientXY;
}
}
/// <summary>
/// The position of mouse pointer in screen coordinates.
/// </summary>
/// <remarks>
/// Retrieves the coordinates of the mouse pointer's position relative to the user's screen.
/// </remarks>
public Point ScreenXY
{
get
{
return this.screenXY;
}
}
/// <summary>
/// The state of the shift key during mouse events.
/// </summary>
public bool ShiftKey
{
get
{
return this.shftKey;
}
}
/// <summary>
/// The state of the alt key during mouse events.
/// </summary>
public bool AltKey
{
get
{
return this.altKey;
}
}
/// <summary>
/// Retrieves a value that indicates the state of the left ALT key.
/// </summary>
public bool LeftAltKey
{
get
{
return ((Interop.IHTMLEventObj3)this.referenceObject).altLeft;
}
}
/// <summary>
/// Retrieves a value that indicates the state of the left SHIFT key.
/// </summary>
public bool LeftShftKey
{
get
{
return ((Interop.IHTMLEventObj3)this.referenceObject).shiftLeft;
}
}
/// <summary>
/// Retrieves the distance and direction the wheel button has rolled.
/// </summary>
/// <remarks>
/// This property indicates the distance that the wheel has rotated, expressed in multiples of 120. A positive value indicates
/// that the wheel has rotated away from the user. A negative value indicates that the wheel has rotated toward the user.
/// </remarks>
public int WheelButton
{
get
{
return ((Interop.IHTMLEventObj4)this.referenceObject).wheelDelta;
}
}
/// <summary>
/// The state of the control key during mouse events.
/// </summary>
public bool ControlKey
{
get
{
return this.ctrlKey;
}
}
/// <summary>
/// The state of the left CTRL key.
/// </summary>
public bool LeftCtrlKey
{
get
{
return ((Interop.IHTMLEventObj3)this.referenceObject).ctrlLeft;
}
}
/// <summary>
/// The keycode if a key causes the event.
/// </summary>
public Keys KeyCode
{
get
{
return this.keyCode;
}
}
/// <summary>
/// The event type fired the event.
/// </summary>
public DocumentEventType EventType
{
get
{
try
{
return (DocumentEventType) Enum.Parse(typeof(DocumentEventType), type, true);
}
catch
{
return DocumentEventType.Unknown;
}
}
}
/// <summary>
/// Retrieves a data object that contains information about dragged or copied data.
/// </summary>
/// <remarks>
/// This data object can be used to change or retrieve the data being involved in the current
/// drag or copy operation which causes the event this object is attached to.
/// </remarks>
public DataTransfer ClipboardData
{
get
{
return new DataTransfer(((Interop.IHTMLEventObj2) referenceObject).dataTransfer);
}
}
# endregion
# region Subclass
/// <summary>
/// This class provides access to predefined clipboard formats for use in data transfer operations.
/// </summary>
public class DataTransfer : Interop.IHTMLDataTransfer
{
private Interop.IHTMLDataTransfer native;
internal DataTransfer(Interop.IHTMLDataTransfer native)
{
this.native = native;
}
#region IHTMLDataTransfer Members
/// <summary>
/// Assigns data in a specified format to the dataTransfer or clipboardData object.
/// </summary>
/// <param name="format"></param>
/// <param name="data"></param>
/// <returns></returns>
public Boolean setData(String format, Object data)
{
return native.setData(format, data);
}
/// <summary>
/// Retrieves the data in the specified format from the clipboard through the dataTransfer or clipboardData objects.
/// </summary>
/// <param name="format"></param>
/// <returns></returns>
public Object getData(String format)
{
return native.getData(format);
}
/// <summary>
/// Removes one or more data formats from the clipboard through dataTransfer or clipboardData object.
/// </summary>
/// <param name="format"></param>
/// <returns></returns>
public Boolean clearData(String format)
{
return native.clearData(format);
}
/// <summary>
/// Sets or retrieves the type of drag-and-drop operation and the type of cursor to display.
/// </summary>
public String dropEffect
{
get
{
return native.dropEffect;
}
set
{
native.dropEffect = value;
}
}
/// <summary>
/// Sets or retrieves, on the source element, which data transfer operations are allowed for the object.
/// </summary>
public String effectAllowed
{
get
{
return native.effectAllowed;
}
set
{
native.effectAllowed = value;
}
}
#endregion
}
# endregion
}
}
| |
// 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 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Authorization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
/// <summary>
/// Role based access control provides you a way to apply granular level
/// policy administration down to individual resources or resource groups.
/// These operations enable you to manage role definitions and role
/// assignments. A role definition describes the set of actions that can be
/// performed on resources. A role assignment grants access to Azure Active
/// Directory users.
/// </summary>
public partial class AuthorizationManagementClient : ServiceClient<AuthorizationManagementClient>, IAuthorizationManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The ID of the target subscription.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// The API version to use for this operation.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IClassicAdministratorsOperations.
/// </summary>
public virtual IClassicAdministratorsOperations ClassicAdministrators { get; private set; }
/// <summary>
/// Gets the IPermissionsOperations.
/// </summary>
public virtual IPermissionsOperations Permissions { get; private set; }
/// <summary>
/// Gets the IProviderOperationsMetadataOperations.
/// </summary>
public virtual IProviderOperationsMetadataOperations ProviderOperationsMetadata { get; private set; }
/// <summary>
/// Gets the IRoleAssignmentsOperations.
/// </summary>
public virtual IRoleAssignmentsOperations RoleAssignments { get; private set; }
/// <summary>
/// Gets the IRoleDefinitionsOperations.
/// </summary>
public virtual IRoleDefinitionsOperations RoleDefinitions { get; private set; }
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AuthorizationManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AuthorizationManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AuthorizationManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AuthorizationManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AuthorizationManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AuthorizationManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AuthorizationManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AuthorizationManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.ClassicAdministrators = new ClassicAdministratorsOperations(this);
this.Permissions = new PermissionsOperations(this);
this.ProviderOperationsMetadata = new ProviderOperationsMetadataOperations(this);
this.RoleAssignments = new RoleAssignmentsOperations(this);
this.RoleDefinitions = new RoleDefinitionsOperations(this);
this.BaseUri = new Uri("https://management.azure.com");
this.ApiVersion = "2015-07-01";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using AstUtils = System.Linq.Expressions.Utils;
namespace System.Linq.Expressions.Interpreter
{
[DebuggerDisplay("{DebugView,nq}")]
public partial class LightLambda
{
private readonly IStrongBox[] _closure;
private readonly Interpreter _interpreter;
#if NO_FEATURE_STATIC_DELEGATE
private static readonly CacheDict<Type, Func<LightLambda, Delegate>> _runCache = new CacheDict<Type, Func<LightLambda, Delegate>>(100);
#endif
// Adaptive compilation support
private readonly LightDelegateCreator _delegateCreator;
internal LightLambda(LightDelegateCreator delegateCreator, IStrongBox[] closure)
{
_delegateCreator = delegateCreator;
_closure = closure;
_interpreter = delegateCreator.Interpreter;
}
private string DebugView => new DebugViewPrinter(_interpreter).ToString();
private class DebugViewPrinter
{
private readonly Interpreter _interpreter;
private readonly Dictionary<int, int> _tryStart = new Dictionary<int, int>();
private readonly Dictionary<int, string> _handlerEnter = new Dictionary<int, string>();
private readonly Dictionary<int, int> _handlerExit = new Dictionary<int, int>();
private string _indent = " ";
public DebugViewPrinter(Interpreter interpreter)
{
_interpreter = interpreter;
Analyze();
}
private void Analyze()
{
Instruction[] instructions = _interpreter.Instructions.Instructions;
foreach (Instruction instruction in instructions)
{
var enterTryCatchFinally = instruction as EnterTryCatchFinallyInstruction;
if (enterTryCatchFinally != null)
{
TryCatchFinallyHandler handler = enterTryCatchFinally.Handler;
AddTryStart(handler.TryStartIndex);
AddHandlerExit(handler.TryEndIndex + 1 /* include Goto instruction that acts as a "leave" */);
if (handler.IsFinallyBlockExist)
{
_handlerEnter.Add(handler.FinallyStartIndex, "finally");
AddHandlerExit(handler.FinallyEndIndex);
}
if (handler.IsCatchBlockExist)
{
foreach (ExceptionHandler catchHandler in handler.Handlers)
{
_handlerEnter.Add(catchHandler.HandlerStartIndex - 1 /* include EnterExceptionHandler instruction */, catchHandler.ToString());
AddHandlerExit(catchHandler.HandlerEndIndex);
ExceptionFilter filter = catchHandler.Filter;
if (filter != null)
{
_handlerEnter.Add(filter.StartIndex - 1 /* include EnterExceptionFilter instruction */, "filter");
AddHandlerExit(filter.EndIndex);
}
}
}
}
var enterTryFault = instruction as EnterTryFaultInstruction;
if (enterTryFault != null)
{
TryFaultHandler handler = enterTryFault.Handler;
AddTryStart(handler.TryStartIndex);
AddHandlerExit(handler.TryEndIndex + 1 /* include Goto instruction that acts as a "leave" */);
_handlerEnter.Add(handler.FinallyStartIndex, "fault");
AddHandlerExit(handler.FinallyEndIndex);
}
}
}
private void AddTryStart(int index)
{
int count;
if (!_tryStart.TryGetValue(index, out count))
{
_tryStart.Add(index, 1);
return;
}
_tryStart[index] = count + 1;
}
private void AddHandlerExit(int index)
{
int count;
_handlerExit[index] = _handlerExit.TryGetValue(index, out count) ? count + 1 : 1;
}
private void Indent()
{
_indent = new string(' ', _indent.Length + 2);
}
private void Dedent()
{
_indent = new string(' ', _indent.Length - 2);
}
public override string ToString()
{
var sb = new StringBuilder();
string name = _interpreter.Name ?? "lambda_method";
sb.Append("object ").Append(name).AppendLine("(object[])");
sb.AppendLine("{");
sb.Append(" .locals ").Append(_interpreter.LocalCount).AppendLine();
sb.Append(" .maxstack ").Append(_interpreter.Instructions.MaxStackDepth).AppendLine();
sb.Append(" .maxcontinuation ").Append(_interpreter.Instructions.MaxContinuationDepth).AppendLine();
sb.AppendLine();
Instruction[] instructions = _interpreter.Instructions.Instructions;
InstructionArray.DebugView debugView = new InstructionArray.DebugView(_interpreter.Instructions);
InstructionList.DebugView.InstructionView[] instructionViews = debugView.GetInstructionViews(includeDebugCookies: false);
for (int i = 0; i < instructions.Length; i++)
{
EmitExits(sb, i);
int startCount;
if (_tryStart.TryGetValue(i, out startCount))
{
for (int j = 0; j < startCount; j++)
{
sb.Append(_indent).AppendLine(".try");
sb.Append(_indent).AppendLine("{");
Indent();
}
}
string handler;
if (_handlerEnter.TryGetValue(i, out handler))
{
sb.Append(_indent).AppendLine(handler);
sb.Append(_indent).AppendLine("{");
Indent();
}
InstructionList.DebugView.InstructionView instructionView = instructionViews[i];
sb.AppendFormat(CultureInfo.InvariantCulture, "{0}IP_{1}: {2}", _indent, i.ToString().PadLeft(4, '0'), instructionView.GetValue()).AppendLine();
}
EmitExits(sb, instructions.Length);
sb.AppendLine("}");
return sb.ToString();
}
private void EmitExits(StringBuilder sb, int index)
{
int exitCount;
if (_handlerExit.TryGetValue(index, out exitCount))
{
for (int j = 0; j < exitCount; j++)
{
Dedent();
sb.Append(_indent).AppendLine("}");
}
}
}
}
#if NO_FEATURE_STATIC_DELEGATE
private static Func<LightLambda, Delegate> GetRunDelegateCtor(Type delegateType)
{
lock (_runCache)
{
Func<LightLambda, Delegate> fastCtor;
if (_runCache.TryGetValue(delegateType, out fastCtor))
{
return fastCtor;
}
return MakeRunDelegateCtor(delegateType);
}
}
private static Func<LightLambda, Delegate> MakeRunDelegateCtor(Type delegateType)
{
MethodInfo method = delegateType.GetInvokeMethod();
ParameterInfo[] paramInfos = method.GetParametersCached();
Type[] paramTypes;
string name = "Run";
if (paramInfos.Length >= MaxParameters)
{
return null;
}
if (method.ReturnType == typeof(void))
{
name += "Void";
paramTypes = new Type[paramInfos.Length];
}
else
{
paramTypes = new Type[paramInfos.Length + 1];
paramTypes[paramTypes.Length - 1] = method.ReturnType;
}
MethodInfo runMethod;
if (method.ReturnType == typeof(void) && paramTypes.Length == 2 &&
paramInfos[0].ParameterType.IsByRef && paramInfos[1].ParameterType.IsByRef)
{
runMethod = typeof(LightLambda).GetMethod("RunVoidRef2", BindingFlags.NonPublic | BindingFlags.Instance);
paramTypes[0] = paramInfos[0].ParameterType.GetElementType();
paramTypes[1] = paramInfos[1].ParameterType.GetElementType();
}
else if (method.ReturnType == typeof(void) && paramTypes.Length == 0)
{
runMethod = typeof(LightLambda).GetMethod("RunVoid0", BindingFlags.NonPublic | BindingFlags.Instance);
}
else
{
for (int i = 0; i < paramInfos.Length; i++)
{
paramTypes[i] = paramInfos[i].ParameterType;
if (paramTypes[i].IsByRef)
{
return null;
}
}
#if FEATURE_MAKE_RUN_METHODS
if (DelegateHelpers.MakeDelegate(paramTypes) == delegateType)
{
name = "Make" + name + paramInfos.Length;
MethodInfo ctorMethod = typeof(LightLambda).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(paramTypes);
return _runCache[delegateType] = (Func<LightLambda, Delegate>)ctorMethod.CreateDelegate(typeof(Func<LightLambda, Delegate>));
}
#endif
runMethod = typeof(LightLambda).GetMethod(name + paramInfos.Length, BindingFlags.NonPublic | BindingFlags.Instance);
}
/*
try {
DynamicMethod dm = new DynamicMethod("FastCtor", typeof(Delegate), new[] { typeof(LightLambda) }, typeof(LightLambda), true);
var ilgen = dm.GetILGenerator();
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Ldftn, runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod);
ilgen.Emit(OpCodes.Newobj, delegateType.GetConstructor(new[] { typeof(object), typeof(IntPtr) }));
ilgen.Emit(OpCodes.Ret);
return _runCache[delegateType] = (Func<LightLambda, Delegate>)dm.CreateDelegate(typeof(Func<LightLambda, Delegate>));
} catch (SecurityException) {
}*/
// we don't have permission for restricted skip visibility dynamic methods, use the slower Delegate.CreateDelegate.
var targetMethod = runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod;
return _runCache[delegateType] = lambda => targetMethod.CreateDelegate(delegateType, lambda);
}
//TODO enable sharing of these custom delegates
private Delegate CreateCustomDelegate(Type delegateType)
{
//PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Synchronously compiling a custom delegate");
MethodInfo method = delegateType.GetInvokeMethod();
ParameterInfo[] paramInfos = method.GetParametersCached();
var parameters = new ParameterExpression[paramInfos.Length];
var parametersAsObject = new Expression[paramInfos.Length];
bool hasByRef = false;
for (int i = 0; i < paramInfos.Length; i++)
{
ParameterExpression parameter = Expression.Parameter(paramInfos[i].ParameterType, paramInfos[i].Name);
hasByRef = hasByRef || paramInfos[i].ParameterType.IsByRef;
parameters[i] = parameter;
parametersAsObject[i] = Expression.Convert(parameter, typeof(object));
}
NewArrayExpression data = Expression.NewArrayInit(typeof(object), parametersAsObject);
var dlg = new Func<object[], object>(Run);
ConstantExpression dlgExpr = Expression.Constant(dlg);
ParameterExpression argsParam = Expression.Parameter(typeof(object[]), "$args");
Expression body;
if (method.ReturnType == typeof(void))
{
body = Expression.Block(typeof(void), Expression.Invoke(dlgExpr, argsParam));
}
else
{
body = Expression.Convert(Expression.Invoke(dlgExpr, argsParam), method.ReturnType);
}
if (hasByRef)
{
List<Expression> updates = new List<Expression>();
for (int i = 0; i < paramInfos.Length; i++)
{
if (paramInfos[i].ParameterType.IsByRef)
{
updates.Add(
Expression.Assign(
parameters[i],
Expression.Convert(
Expression.ArrayAccess(argsParam, Expression.Constant(i)),
paramInfos[i].ParameterType.GetElementType()
)
)
);
}
}
body = Expression.TryFinally(body, Expression.Block(typeof(void), updates));
}
body = Expression.Block(
method.ReturnType,
new[] { argsParam },
Expression.Assign(argsParam, data),
body
);
var lambda = Expression.Lambda(delegateType, body, parameters);
//return System.Linq.Expressions.Compiler.LambdaCompiler.Compile(lambda, null);
throw new NotImplementedException("byref delegate");
}
#endif
internal Delegate MakeDelegate(Type delegateType)
{
#if !NO_FEATURE_STATIC_DELEGATE
MethodInfo method = delegateType.GetInvokeMethod();
if (method.ReturnType == typeof(void))
{
return System.Dynamic.Utils.DelegateHelpers.CreateObjectArrayDelegate(delegateType, RunVoid);
}
else
{
return System.Dynamic.Utils.DelegateHelpers.CreateObjectArrayDelegate(delegateType, Run);
}
#else
Func<LightLambda, Delegate> fastCtor = GetRunDelegateCtor(delegateType);
if (fastCtor != null)
{
return fastCtor(this);
}
else
{
return CreateCustomDelegate(delegateType);
}
#endif
}
private InterpretedFrame MakeFrame()
{
return new InterpretedFrame(_interpreter, _closure);
}
#if NO_FEATURE_STATIC_DELEGATE
internal void RunVoidRef2<T0, T1>(ref T0 arg0, ref T1 arg1)
{
// copy in and copy out for today...
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
var currentFrame = frame.Enter();
try
{
_interpreter.Run(frame);
}
finally
{
frame.Leave(currentFrame);
arg0 = (T0)frame.Data[0];
arg1 = (T1)frame.Data[1];
}
}
#endif
public object Run(params object[] arguments)
{
InterpretedFrame frame = MakeFrame();
for (int i = 0; i < arguments.Length; i++)
{
frame.Data[i] = arguments[i];
}
InterpretedFrame currentFrame = frame.Enter();
try
{
_interpreter.Run(frame);
}
finally
{
for (int i = 0; i < arguments.Length; i++)
{
arguments[i] = frame.Data[i];
}
frame.Leave(currentFrame);
}
return frame.Pop();
}
public object RunVoid(params object[] arguments)
{
InterpretedFrame frame = MakeFrame();
for (int i = 0; i < arguments.Length; i++)
{
frame.Data[i] = arguments[i];
}
InterpretedFrame currentFrame = frame.Enter();
try
{
_interpreter.Run(frame);
}
finally
{
for (int i = 0; i < arguments.Length; i++)
{
arguments[i] = frame.Data[i];
}
frame.Leave(currentFrame);
}
return null;
}
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using System;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReader = Lucene.Net.Index.AtomicReader;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
using Field = Field;
using FieldInvertState = Lucene.Net.Index.FieldInvertState;
using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using NumericDocValues = Lucene.Net.Index.NumericDocValues;
using PerFieldSimilarityWrapper = Lucene.Net.Search.Similarities.PerFieldSimilarityWrapper;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
using SlowCompositeReaderWrapper = Lucene.Net.Index.SlowCompositeReaderWrapper;
using Term = Lucene.Net.Index.Term;
using TFIDFSimilarity = Lucene.Net.Search.Similarities.TFIDFSimilarity;
[TestFixture]
public class TestSimilarityProvider : LuceneTestCase
{
private Directory directory;
private DirectoryReader reader;
private IndexSearcher searcher;
[SetUp]
public override void SetUp()
{
base.SetUp();
directory = NewDirectory();
PerFieldSimilarityWrapper sim = new ExampleSimilarityProvider(this);
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetSimilarity(sim);
RandomIndexWriter iw = new RandomIndexWriter(Random, directory, iwc);
Document doc = new Document();
Field field = NewTextField("foo", "", Field.Store.NO);
doc.Add(field);
Field field2 = NewTextField("bar", "", Field.Store.NO);
doc.Add(field2);
field.SetStringValue("quick brown fox");
field2.SetStringValue("quick brown fox");
iw.AddDocument(doc);
field.SetStringValue("jumps over lazy brown dog");
field2.SetStringValue("jumps over lazy brown dog");
iw.AddDocument(doc);
reader = iw.GetReader();
iw.Dispose();
searcher = NewSearcher(reader);
searcher.Similarity = sim;
}
[TearDown]
public override void TearDown()
{
reader.Dispose();
directory.Dispose();
base.TearDown();
}
[Test]
public virtual void TestBasics()
{
// sanity check of norms writer
// TODO: generalize
AtomicReader slow = SlowCompositeReaderWrapper.Wrap(reader);
NumericDocValues fooNorms = slow.GetNormValues("foo");
NumericDocValues barNorms = slow.GetNormValues("bar");
for (int i = 0; i < slow.MaxDoc; i++)
{
Assert.IsFalse(fooNorms.Get(i) == barNorms.Get(i));
}
// sanity check of searching
TopDocs foodocs = searcher.Search(new TermQuery(new Term("foo", "brown")), 10);
Assert.IsTrue(foodocs.TotalHits > 0);
TopDocs bardocs = searcher.Search(new TermQuery(new Term("bar", "brown")), 10);
Assert.IsTrue(bardocs.TotalHits > 0);
Assert.IsTrue(foodocs.ScoreDocs[0].Score < bardocs.ScoreDocs[0].Score);
}
private class ExampleSimilarityProvider : PerFieldSimilarityWrapper
{
private readonly TestSimilarityProvider outerInstance;
public ExampleSimilarityProvider(TestSimilarityProvider outerInstance)
{
this.outerInstance = outerInstance;
sim1 = new Sim1(outerInstance);
sim2 = new Sim2(outerInstance);
}
private readonly Similarity sim1;
private readonly Similarity sim2;
public override Similarity Get(string field)
{
if (field.Equals("foo", StringComparison.Ordinal))
{
return sim1;
}
else
{
return sim2;
}
}
}
private class Sim1 : TFIDFSimilarity
{
private readonly TestSimilarityProvider outerInstance;
public Sim1(TestSimilarityProvider outerInstance)
{
this.outerInstance = outerInstance;
}
public override long EncodeNormValue(float f)
{
return (long)f;
}
public override float DecodeNormValue(long norm)
{
return norm;
}
public override float Coord(int overlap, int maxOverlap)
{
return 1f;
}
public override float QueryNorm(float sumOfSquaredWeights)
{
return 1f;
}
public override float LengthNorm(FieldInvertState state)
{
return 1f;
}
public override float SloppyFreq(int distance)
{
return 1f;
}
public override float Tf(float freq)
{
return 1f;
}
public override float Idf(long docFreq, long numDocs)
{
return 1f;
}
public override float ScorePayload(int doc, int start, int end, BytesRef payload)
{
return 1f;
}
}
private class Sim2 : TFIDFSimilarity
{
private readonly TestSimilarityProvider outerInstance;
public Sim2(TestSimilarityProvider outerInstance)
{
this.outerInstance = outerInstance;
}
public override long EncodeNormValue(float f)
{
return (long)f;
}
public override float DecodeNormValue(long norm)
{
return norm;
}
public override float Coord(int overlap, int maxOverlap)
{
return 1f;
}
public override float QueryNorm(float sumOfSquaredWeights)
{
return 1f;
}
public override float LengthNorm(FieldInvertState state)
{
return 10f;
}
public override float SloppyFreq(int distance)
{
return 10f;
}
public override float Tf(float freq)
{
return 10f;
}
public override float Idf(long docFreq, long numDocs)
{
return 10f;
}
public override float ScorePayload(int doc, int start, int end, BytesRef payload)
{
return 1f;
}
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.Maintainability.CodeMetrics.CodeMetricsAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.Maintainability.CodeMetrics.CodeMetricsAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.CodeQuality.Analyzers.Maintainability.CodeMetrics.UnitTests
{
public class CodeMetricsAnalyzerTests
{
#region CA1501: Avoid excessive inheritance
[Fact]
public async Task CA1501_CSharp_VerifyDiagnostic()
{
var source = @"
class BaseClass { }
class FirstDerivedClass : BaseClass { }
class SecondDerivedClass : FirstDerivedClass { }
class ThirdDerivedClass : SecondDerivedClass { }
class FourthDerivedClass : ThirdDerivedClass { }
class FifthDerivedClass : FourthDerivedClass { }
// This class violates the rule.
class SixthDerivedClass : FifthDerivedClass { }
";
DiagnosticResult[] expected = new[] {
GetCSharpCA1501ExpectedDiagnostic(10, 7, "SixthDerivedClass", 6, 6, "FifthDerivedClass, FourthDerivedClass, ThirdDerivedClass, SecondDerivedClass, FirstDerivedClass, BaseClass")};
await VerifyCS.VerifyAnalyzerAsync(source, expected);
}
[Fact]
public async Task CA1501_Basic_VerifyDiagnostic()
{
var source = @"
Class BaseClass
End Class
Class FirstDerivedClass
Inherits BaseClass
End Class
Class SecondDerivedClass
Inherits FirstDerivedClass
End Class
Class ThirdDerivedClass
Inherits SecondDerivedClass
End Class
Class FourthDerivedClass
Inherits ThirdDerivedClass
End Class
Class FifthDerivedClass
Inherits FourthDerivedClass
End Class
Class SixthDerivedClass
Inherits FifthDerivedClass
End Class
";
DiagnosticResult[] expected = new[] {
GetBasicCA1501ExpectedDiagnostic(25, 7, "SixthDerivedClass", 6, 6, "FifthDerivedClass, FourthDerivedClass, ThirdDerivedClass, SecondDerivedClass, FirstDerivedClass, BaseClass")};
await VerifyVB.VerifyAnalyzerAsync(source, expected);
}
[Fact]
public async Task CA1501_Configuration_CSharp_VerifyDiagnostic()
{
var source = @"
class BaseClass { }
class FirstDerivedClass : BaseClass { }
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1501: 0
";
DiagnosticResult[] expected = new[] {
GetCSharpCA1501ExpectedDiagnostic(3, 7, "FirstDerivedClass", 1, 1, "BaseClass")};
await VerifyCSharpAsync(source, additionalText, expected);
}
[Fact]
public async Task CA1501_Configuration_Basic_VerifyDiagnostic()
{
var source = @"
Class BaseClass
End Class
Class FirstDerivedClass
Inherits BaseClass
End Class
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1501: 0
";
DiagnosticResult[] expected = new[] {
GetBasicCA1501ExpectedDiagnostic(5, 7, "FirstDerivedClass", 1, 1, "BaseClass")};
await VerifyBasicAsync(source, additionalText, expected);
}
[Theory, WorkItem(1839, "https://github.com/dotnet/roslyn-analyzers/issues/1839")]
[InlineData("")]
[InlineData("dotnet_code_quality.CA1501.additional_inheritance_excluded_symbol_names = T:SomeClass")]
// The following entries are invalid but won't remove the default filter
[InlineData("dotnet_code_quality.CA1501.additional_inheritance_excluded_symbol_names = *Contro*")]
[InlineData("dotnet_code_quality.CA1501.additional_inheritance_excluded_symbol_names = User*ontrol")]
public async Task CA1501_AlwaysExcludesTypesInSystemNamespace(string editorConfigText)
{
// This test assumes that WinForms UserControl is over the default threshold.
await new VerifyCS.Test
{
TestState =
{
Sources = { "public class MyUC : System.Windows.Forms.UserControl {}", },
AdditionalFiles = { (".editorconfig", editorConfigText) },
},
ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithWinForms,
}.RunAsync();
await new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Public Class MyUC
Inherits System.Windows.Forms.UserControl
End Class",
},
AdditionalFiles = { (".editorconfig", editorConfigText) },
},
ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithWinForms,
}.RunAsync();
}
[Fact]
public async Task CA1501_AlwaysExcludesErrorTypes()
{
await new VerifyCS.Test
{
TestState =
{
Sources = { "public class MyUC : System.{|#0:NonExistentType|} {}", },
ExpectedDiagnostics =
{
// /0/Test0.cs(1,28): error CS0234: The type or namespace name 'NonExistentType' does not exist in the namespace 'System' (are you missing an assembly reference?)
DiagnosticResult.CompilerError("CS0234").WithLocation(0).WithArguments("NonExistentType", "System"),
},
},
}.RunAsync();
await new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Public Class MyUC
Inherits {|#0:System.NonExistentType|}
End Class",
},
ExpectedDiagnostics =
{
// /0/Test0.vb(3) : error BC30002: Type 'System.NonExistentType' is not defined.
DiagnosticResult.CompilerError("BC30002").WithLocation(0).WithArguments("System.NonExistentType"),
},
},
}.RunAsync();
}
[Theory, WorkItem(1839, "https://github.com/dotnet/roslyn-analyzers/issues/1839")]
[InlineData("dotnet_code_quality.CA1501.additional_inheritance_excluded_symbol_names = T:SomeClass*")]
[InlineData("dotnet_code_quality.CA1501.additional_inheritance_excluded_symbol_names = T:MyCompany.MyProduct.MyFunction.SomeClass*")]
public async Task CA1501_WildcardTypePrefixNoNamespace(string editorConfigText)
{
var codeMetricsConfigText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1501: 0
";
var csharpTest = new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
namespace MyCompany.MyProduct.MyFunction
{
public class SomeClass {}
public class C1 : SomeClass {}
public class SomeClass1 {}
public class SomeClass2 : SomeClass1 {}
public class C2 : SomeClass2 {}
}
public class SomeClass {}
public class C1 : SomeClass {}
public class SomeClass1 {}
public class SomeClass2 : SomeClass1 {}
public class C2 : SomeClass2 {}"
},
AdditionalFiles =
{
(".editorconfig", editorConfigText),
(AdditionalFileName, codeMetricsConfigText),
},
},
};
if (editorConfigText.Contains("T:SomeClass", StringComparison.Ordinal))
{
csharpTest.ExpectedDiagnostics.AddRange(new[]
{
GetCSharpCA1501ExpectedDiagnostic(5, 18, "C1", 1, 1, "SomeClass"),
GetCSharpCA1501ExpectedDiagnostic(8, 18, "SomeClass2", 1, 1, "SomeClass1"),
GetCSharpCA1501ExpectedDiagnostic(9, 18, "C2", 2, 1, "SomeClass2, SomeClass1"),
});
}
else
{
csharpTest.ExpectedDiagnostics.AddRange(new[]
{
GetCSharpCA1501ExpectedDiagnostic(13, 14, "C1", 1, 1, "SomeClass"),
GetCSharpCA1501ExpectedDiagnostic(16, 14, "SomeClass2", 1, 1, "SomeClass1"),
GetCSharpCA1501ExpectedDiagnostic(17, 14, "C2", 2, 1, "SomeClass2, SomeClass1"),
});
}
await csharpTest.RunAsync();
var vbnetTest = new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Namespace MyCompany.MyProduct.MyFunction
Public Class SomeClass
End Class
Public Class C1
Inherits SomeClass
End Class
Public Class SomeClass1
End Class
Public Class SomeClass2
Inherits SomeClass1
End Class
Public Class C2
Inherits SomeClass2
End Class
End Namespace
Public Class SomeClass
End Class
Public Class C1
Inherits SomeClass
End Class
Public Class SomeClass1
End Class
Public Class SomeClass2
Inherits SomeClass1
End Class
Public Class C2
Inherits SomeClass2
End Class"
},
AdditionalFiles =
{
(".editorconfig", editorConfigText),
(AdditionalFileName, codeMetricsConfigText),
},
},
};
if (editorConfigText.Contains("T:SomeClass", StringComparison.Ordinal))
{
vbnetTest.ExpectedDiagnostics.AddRange(new[]
{
GetCSharpCA1501ExpectedDiagnostic(6, 18, "C1", 1, 1, "SomeClass"),
GetCSharpCA1501ExpectedDiagnostic(13, 18, "SomeClass2", 1, 1, "SomeClass1"),
GetCSharpCA1501ExpectedDiagnostic(17, 18, "C2", 2, 1, "SomeClass2, SomeClass1"),
});
}
else
{
vbnetTest.ExpectedDiagnostics.AddRange(new[]
{
GetCSharpCA1501ExpectedDiagnostic(25, 14, "C1", 1, 1, "SomeClass"),
GetCSharpCA1501ExpectedDiagnostic(32, 14, "SomeClass2", 1, 1, "SomeClass1"),
GetCSharpCA1501ExpectedDiagnostic(36, 14, "C2", 2, 1, "SomeClass2, SomeClass1"),
});
}
await vbnetTest.RunAsync();
}
[Theory, WorkItem(1839, "https://github.com/dotnet/roslyn-analyzers/issues/1839")]
[InlineData("dotnet_code_quality.CA1501.additional_inheritance_excluded_symbol_names = N:MyCompany.MyProduct.MyFunction.*")]
[InlineData("dotnet_code_quality.CA1501.additional_inheritance_excluded_symbol_names = N:MyCompany.MyProduct.*")]
// The presence of the '.' before the wildcard matters for the match
[InlineData("dotnet_code_quality.CA1501.additional_inheritance_excluded_symbol_names = N:MyCompany.*")]
[InlineData("dotnet_code_quality.CA1501.additional_inheritance_excluded_symbol_names = N:MyCompany*")]
public async Task CA1501_WildcardNamespacePrefix(string editorConfigText)
{
var codeMetricsConfigText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1501: 0
";
var csharpTest = new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
namespace MyCompany.MyProduct.MyFunction
{
public class SomeClass {}
public class C1 : SomeClass {}
}
namespace MyCompany2.SomeOtherProduct
{
public class SomeClass {}
public class C1 : SomeClass {}
}
public class SomeClass {}
public class C1 : SomeClass {}
"
},
AdditionalFiles =
{
(".editorconfig", editorConfigText),
(AdditionalFileName, codeMetricsConfigText),
},
ExpectedDiagnostics =
{
GetCSharpCA1501ExpectedDiagnostic(15, 14, "C1", 1, 1, "SomeClass"),
},
},
};
if (!editorConfigText.Contains("N:MyCompany*", StringComparison.Ordinal))
{
csharpTest.ExpectedDiagnostics.Add(GetCSharpCA1501ExpectedDiagnostic(11, 18, "C1", 1, 1, "SomeClass"));
}
await csharpTest.RunAsync();
var vbnetTest = new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Namespace MyCompany.MyProduct.MyFunction
Public Class SomeClass
End Class
Public Class C1
Inherits SomeClass
End Class
End Namespace
Namespace MyCompany2.SomeOtherProduct
Public Class SomeClass
End Class
Public Class C1
Inherits SomeClass
End Class
End Namespace
Public Class SomeClass
End Class
Public Class C1
Inherits SomeClass
End Class"
},
AdditionalFiles =
{
(".editorconfig", editorConfigText),
(AdditionalFileName, codeMetricsConfigText),
},
ExpectedDiagnostics =
{
GetBasicCA1501ExpectedDiagnostic(23, 14, "C1", 1, 1, "SomeClass"),
},
},
};
if (!editorConfigText.Contains("N:MyCompany*", StringComparison.Ordinal))
{
vbnetTest.ExpectedDiagnostics.Add(GetBasicCA1501ExpectedDiagnostic(15, 18, "C1", 1, 1, "SomeClass"));
}
await vbnetTest.RunAsync();
}
[Fact, WorkItem(1839, "https://github.com/dotnet/roslyn-analyzers/issues/1839")]
public async Task CA1501_WildcardNoPrefix()
{
var editorConfigText = "dotnet_code_quality.CA1501.additional_inheritance_excluded_symbol_names = Some*";
var codeMetricsConfigText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1501: 1
";
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
namespace SomeNamespace
{
public class C {}
public class C1 : C {}
}
namespace MyCompany.SomeProduct
{
public class C {}
public class C1 : C {}
}
namespace MyNamespace
{
public class SomeClass
{
public class C {}
}
public class C2 : SomeClass.C {} // excluded because C's containing type starts with 'Some'
}
public class SomeClass {}
public class C1 : SomeClass {}
"
},
AdditionalFiles =
{
(".editorconfig", editorConfigText),
(AdditionalFileName, codeMetricsConfigText),
},
},
}.RunAsync();
await new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Namespace SomeNamespace
Public Class C
End Class
Public Class C1
Inherits C
End Class
End Namespace
Namespace MyCompany.SomeProduct
Public Class C
End Class
Public Class C1
Inherits C
End Class
End Namespace
Namespace MyNamespace
Public Class SomeClass
Public Class C
End Class
End Class
Public Class C2
Inherits SomeClass.C
End Class
End Namespace
Public Class SomeClass
End Class
Public Class C1
Inherits SomeClass
End Class"
},
AdditionalFiles =
{
(".editorconfig", editorConfigText),
(AdditionalFileName, codeMetricsConfigText),
},
},
}.RunAsync();
}
#endregion
#region CA1502: Avoid excessive complexity
[Fact]
public async Task CA1502_CSharp_VerifyDiagnostic()
{
var source = @"
class C
{
void M(bool b)
{
// Default threshold = 25
var x = b && b && b && b && b && b && b &&
b && b && b && b && b && b && b &&
b && b && b && b && b && b && b &&
b && b && b && b && b && b && b;
}
}
";
DiagnosticResult[] expected = new[] {
// Test0.cs(4,10): warning CA1502: 'M' has a cyclomatic complexity of '28'. Rewrite or refactor the code to decrease its complexity below '26'.
GetCSharpCA1502ExpectedDiagnostic(4, 10, "M", 28, 26)};
await VerifyCS.VerifyAnalyzerAsync(source, expected);
}
[Fact]
public async Task CA1502_Basic_VerifyDiagnostic()
{
var source = @"
Class C
Private Sub M(ByVal b As Boolean)
Dim x = b AndAlso b AndAlso b AndAlso b AndAlso b AndAlso b AndAlso
b AndAlso b AndAlso b AndAlso b AndAlso b AndAlso b AndAlso b AndAlso
b AndAlso b AndAlso b AndAlso b AndAlso b AndAlso b AndAlso b AndAlso
b AndAlso b AndAlso b AndAlso b AndAlso b AndAlso b AndAlso b AndAlso b
End Sub
End Class
";
DiagnosticResult[] expected = new[] {
// Test0.vb(3,17): warning CA1502: 'M' has a cyclomatic complexity of '28'. Rewrite or refactor the code to decrease its complexity below '26'.
GetBasicCA1502ExpectedDiagnostic(3, 17, "M", 28, 26)};
await VerifyVB.VerifyAnalyzerAsync(source, expected);
}
[Fact]
public async Task CA1502_Configuration_CSharp_VerifyDiagnostic()
{
var source = @"
class C
{
void M1(bool b)
{
var x = b && b && b && b;
}
void M2(bool b)
{
var x = b && b;
}
}
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1502: 2
";
DiagnosticResult[] expected = new[] {
// Test0.cs(4,10): warning CA1502: 'M1' has a cyclomatic complexity of '4'. Rewrite or refactor the code to decrease its complexity below '3'.
GetCSharpCA1502ExpectedDiagnostic(4, 10, "M1", 4, 3)};
await VerifyCSharpAsync(source, additionalText, expected);
}
[Fact]
public async Task CA1502_Configuration_Basic_VerifyDiagnostic()
{
var source = @"
Class C
Private Sub M1(ByVal b As Boolean)
Dim x = b AndAlso b AndAlso b AndAlso b
End Sub
Private Sub M2(ByVal b As Boolean)
Dim x = b AndAlso b
End Sub
End Class
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1502: 2
";
DiagnosticResult[] expected = new[] {
// Test0.vb(3,17): warning CA1502: 'M1' has a cyclomatic complexity of '4'. Rewrite or refactor the code to decrease its complexity below '3'.
GetBasicCA1502ExpectedDiagnostic(3, 17, "M1", 4, 3)};
await VerifyBasicAsync(source, additionalText, expected);
}
[Fact]
public async Task CA1502_SymbolBasedConfiguration_CSharp_VerifyDiagnostic()
{
var source = @"
class C
{
void M1(bool b)
{
var x = b && b && b && b;
}
void M2(bool b)
{
var x = b && b;
}
}
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1502(Type): 4
CA1502(Method): 2
";
DiagnosticResult[] expected = new[] {
// Test0.cs(2,7): warning CA1502: 'C' has a cyclomatic complexity of '6'. Rewrite or refactor the code to decrease its complexity below '5'.
GetCSharpCA1502ExpectedDiagnostic(2, 7, "C", 6, 5),
// Test0.cs(4,10): warning CA1502: 'M1' has a cyclomatic complexity of '4'. Rewrite or refactor the code to decrease its complexity below '3'.
GetCSharpCA1502ExpectedDiagnostic(4, 10, "M1", 4, 3)};
await VerifyCSharpAsync(source, additionalText, expected);
}
[Fact]
public async Task CA1502_SymbolBasedConfiguration_Basic_VerifyDiagnostic()
{
var source = @"
Class C
Private Sub M1(ByVal b As Boolean)
Dim x = b AndAlso b AndAlso b AndAlso b
End Sub
Private Sub M2(ByVal b As Boolean)
Dim x = b AndAlso b
End Sub
End Class
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1502(Type): 4
CA1502(Method): 2
";
DiagnosticResult[] expected = new[] {
// Test0.vb(2,7): warning CA1502: 'C' has a cyclomatic complexity of '6'. Rewrite or refactor the code to decrease its complexity below '5'.
GetBasicCA1502ExpectedDiagnostic(2, 7, "C", 6, 5),
// Test0.vb(3,17): warning CA1502: 'M1' has a cyclomatic complexity of '4'. Rewrite or refactor the code to decrease its complexity below '3'.
GetBasicCA1502ExpectedDiagnostic(3, 17, "M1", 4, 3)};
await VerifyBasicAsync(source, additionalText, expected);
}
#endregion
#region CA1505: Avoid unmaintainable code
[Fact]
public async Task CA1505_Configuration_CSharp_VerifyDiagnostic()
{
var source = @"
class C
{
void M1(bool b)
{
var x = b && b && b && b;
}
}
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1505: 95
";
DiagnosticResult[] expected = new[] {
// Test0.cs(2,7): warning CA1505: 'C' has a maintainability index of '91'. Rewrite or refactor the code to increase its maintainability index (MI) above '94'.
GetCSharpCA1505ExpectedDiagnostic(2, 7, "C", 91, 94),
// Test0.cs(4,10): warning CA1505: 'M1' has a maintainability index of '91'. Rewrite or refactor the code to increase its maintainability index (MI) above '94'.
GetCSharpCA1505ExpectedDiagnostic(4, 10, "M1", 91, 94)};
await VerifyCSharpAsync(source, additionalText, expected);
}
[Fact]
public async Task CA1505_Configuration_Basic_VerifyDiagnostic()
{
var source = @"
Class C
Private Sub M1(ByVal b As Boolean)
Dim x = b AndAlso b AndAlso b AndAlso b
End Sub
End Class
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1505: 95
";
DiagnosticResult[] expected = new[] {
// Test0.vb(2,7): warning CA1505: 'C' has a maintainability index of '91'. Rewrite or refactor the code to increase its maintainability index (MI) above '94'.
GetBasicCA1505ExpectedDiagnostic(2, 7, "C", 91, 94),
// Test0.vb(3,17): warning CA1505: 'M1' has a maintainability index of '91'. Rewrite or refactor the code to increase its maintainability index (MI) above '94'.
GetBasicCA1505ExpectedDiagnostic(3, 17, "M1", 91, 94)};
await VerifyBasicAsync(source, additionalText, expected);
}
[Fact]
public async Task CA1505_SymbolBasedConfiguration_CSharp_VerifyDiagnostic()
{
var source = @"
class C
{
void M1(bool b)
{
var x = b && b && b && b;
}
}
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1505(Type): 95
";
DiagnosticResult[] expected = new[] {
// Test0.cs(2,7): warning CA1505: 'C' has a maintainability index of '91'. Rewrite or refactor the code to increase its maintainability index (MI) above '94'.
GetCSharpCA1505ExpectedDiagnostic(2, 7, "C", 91, 94)};
await VerifyCSharpAsync(source, additionalText, expected);
}
[Fact]
public async Task CA1505_SymbolBasedConfiguration_Basic_VerifyDiagnostic()
{
var source = @"
Class C
Private Sub M1(ByVal b As Boolean)
Dim x = b AndAlso b AndAlso b AndAlso b
End Sub
End Class
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1505(Type): 95
";
DiagnosticResult[] expected = new[] {
// Test0.vb(2,7): warning CA1505: 'C' has a maintainability index of '91'. Rewrite or refactor the code to increase its maintainability index (MI) above '94'.
GetBasicCA1505ExpectedDiagnostic(2, 7, "C", 91, 94)};
await VerifyBasicAsync(source, additionalText, expected);
}
#endregion
#region CA1506: Avoid excessive class coupling
[Fact]
public async Task CA1506_Configuration_CSharp_VerifyDiagnostic()
{
var source = @"
class C
{
void M1(C1 c1, C2 c2, C3 c3, N.C4 c4)
{
}
}
class C1 { }
class C2 { }
class C3 { }
namespace N { class C4 { } }
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1506: 2
";
DiagnosticResult[] expected = new[] {
// Test0.cs(2,7): warning CA1506: 'C' is coupled with '4' different types from '2' different namespaces. Rewrite or refactor the code to decrease its class coupling below '3'.
GetCSharpCA1506ExpectedDiagnostic(2, 7, "C", 4, 2, 3),
// Test0.cs(4,10): warning CA1506: 'M1' is coupled with '4' different types from '2' different namespaces. Rewrite or refactor the code to decrease its class coupling below '3'.
GetCSharpCA1506ExpectedDiagnostic(4, 10, "M1", 4, 2, 3)};
await VerifyCSharpAsync(source, additionalText, expected);
}
[Fact, WorkItem(2133, "https://github.com/dotnet/roslyn-analyzers/issues/2133")]
public async Task CA1506_Configuration_CSharp_Linq()
{
var source = @"
using System.Linq;
using System.Collections.Generic;
class C
{
IEnumerable<int> TestCa1506()
{
var ints = new[] { 1, 2 };
return from a in ints
from b in ints
from c in ints
from d in ints
from e in ints
from f in ints
from g in ints
from h in ints
from i in ints
from j in ints
from k in ints
from l in ints
from m in ints
from n in ints
from o in ints
from p in ints
select p;
}
}
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1506: 2
";
DiagnosticResult[] expected = new[] {
// Test0.cs(4,7): warning CA1506: 'C' is coupled with '4' different types from '3' different namespaces. Rewrite or refactor the code to decrease its class coupling below '3'.
GetCSharpCA1506ExpectedDiagnostic(4, 7, "C", 4, 3, 3),
// Test0.cs(4,10): warning CA1506: 'TestCa1506' is coupled with '4' different types from '3' different namespaces. Rewrite or refactor the code to decrease its class coupling below '3'.
GetCSharpCA1506ExpectedDiagnostic(6, 22, "TestCa1506", 4, 3, 3)};
await VerifyCSharpAsync(source, additionalText, expected);
}
[Fact]
public async Task CA1506_Configuration_Basic_VerifyDiagnostic()
{
var source = @"
Class C
Private Sub M1(c1 As C1, c2 As C2, c3 As C3, c4 As N.C4)
End Sub
End Class
Class C1
End Class
Class C2
End Class
Class C3
End Class
Namespace N
Class C4
End Class
End Namespace
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1506: 2
";
DiagnosticResult[] expected = new[] {
// Test0.vb(2,7): warning CA1506: 'C' is coupled with '4' different types from '2' different namespaces. Rewrite or refactor the code to decrease its class coupling below '3'.
GetBasicCA1506ExpectedDiagnostic(2, 7, "C", 4, 2, 3),
// Test0.vb(3,17): warning CA1506: 'M1' is coupled with '4' different types from '2' different namespaces. Rewrite or refactor the code to decrease its class coupling below '3'.
GetBasicCA1506ExpectedDiagnostic(3, 17, "M1", 4, 2, 3)};
await VerifyBasicAsync(source, additionalText, expected);
}
[Fact]
public async Task CA1506_SymbolBasedConfiguration_CSharp_VerifyDiagnostic()
{
var source = @"
class C
{
void M1(C1 c1, C2 c2, C3 c3, N.C4 c4)
{
}
}
class C1 { }
class C2 { }
class C3 { }
namespace N { class C4 { } }
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1506(Method): 2
CA1506(Type): 10
";
DiagnosticResult[] expected = new[] {
// Test0.cs(4,10): warning CA1506: 'M1' is coupled with '4' different types from '2' different namespaces. Rewrite or refactor the code to decrease its class coupling below '3'.
GetCSharpCA1506ExpectedDiagnostic(4, 10, "M1", 4, 2, 3)};
await VerifyCSharpAsync(source, additionalText, expected);
}
[Fact]
public async Task CA1506_SymbolBasedConfiguration_Basic_VerifyDiagnostic()
{
var source = @"
Class C
Private Sub M1(c1 As C1, c2 As C2, c3 As C3, c4 As N.C4)
End Sub
End Class
Class C1
End Class
Class C2
End Class
Class C3
End Class
Namespace N
Class C4
End Class
End Namespace
";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1506(Method): 2
CA1506(Type): 10
";
DiagnosticResult[] expected = new[] {
// Test0.vb(3,17): warning CA1506: 'M1' is coupled with '4' different types from '2' different namespaces. Rewrite or refactor the code to decrease its class coupling below '3'.
GetBasicCA1506ExpectedDiagnostic(3, 17, "M1", 4, 2, 3)};
await VerifyBasicAsync(source, additionalText, expected);
}
[Fact, WorkItem(2133, "https://github.com/dotnet/roslyn-analyzers/issues/2133")]
public async Task CA1506_CountCorrectlyGenericTypes()
{
await VerifyCSharpAsync(@"
using System.Collections.Generic;
public class A {}
public class B {}
public class C
{
private IEnumerable<A> a;
private IEnumerable<B> b;
}",
@"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1506: 2
",
GetCSharpCA1506ExpectedDiagnostic(7, 14, "C", 3, 2, 3));
await VerifyBasicAsync(@"
Imports System.Collections.Generic
Public Class A
End Class
Public Class B
End Class
Public Class C
Private a As IEnumerable(Of A)
Private b As IEnumerable(Of B)
End Class",
@"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1506: 2
",
GetCSharpCA1506ExpectedDiagnostic(10, 14, "C", 3, 2, 3));
}
[Fact, WorkItem(2133, "https://github.com/dotnet/roslyn-analyzers/issues/2133")]
public async Task CA1506_LinqAnonymousType()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Collections.Generic;
using System.Linq;
public static class Ca1506Tester
{
public static IEnumerable<int> TestCa1506()
{
var ints = new[] { 1, 2 };
return from a in ints
from b in ints
from c in ints
from d in ints
from e in ints
from f in ints
from g in ints
from h in ints
from i in ints
from j in ints
from k in ints
from l in ints
from m in ints
from n in ints
from o in ints
from p in ints
select p;
}
}");
}
[Fact, WorkItem(2133, "https://github.com/dotnet/roslyn-analyzers/issues/2133")]
public async Task CA1506_ExcludeCompilerGeneratedTypes()
{
await VerifyCSharpAsync(@"
[System.Runtime.CompilerServices.CompilerGeneratedAttribute]
public class A {}
[System.CodeDom.Compiler.GeneratedCodeAttribute(""SampleCodeGenerator"", ""2.0.0.0"")]
public class B {}
public class C
{
private A a;
private B b;
}",
@"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1506: 1
");
await VerifyBasicAsync(@"
Imports System.Collections.Generic
<System.Runtime.CompilerServices.CompilerGeneratedAttribute>
Public Class A
End Class
<System.CodeDom.Compiler.GeneratedCodeAttribute(""SampleCodeGenerator"", ""2.0.0.0"")>
Public Class B
End Class
Public Class C
Private a As A
Private b As B
End Class",
@"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA1506: 1
");
}
#endregion
#region CA1509: Invalid entry in code metrics rule specification file
[Fact]
public async Task CA1509_VerifyDiagnostics()
{
var source = @"";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
# 1. Multiple colons
CA1501: 1 : 2
# 2. Whitespace in RuleId
CA 1501: 1
# 3. Invalid Code Metrics RuleId
CA1600: 1
# 4. Non-integral Threshold.
CA1501: None
# 5. Not supported SymbolKind.
CA1501(Local): 1
# 6. Missing SymbolKind.
CA1501(: 1
# 7. Missing CloseParens after SymbolKind.
CA1501(Method: 1
# 8. Multiple SymbolKinds.
CA1501(Method)(Type): 1
# 9. Missing Threshold.
CA1501
";
DiagnosticResult[] expected = new[] {
// CodeMetricsConfig.txt(6,1): warning CA1509: Invalid entry 'CA1501: 1 : 2' in code metrics rule specification file 'CodeMetricsConfig.txt'
GetCA1509ExpectedDiagnostic(6, 1, "CA1501: 1 : 2", AdditionalFileName),
// CodeMetricsConfig.txt(9,1): warning CA1509: Invalid entry 'CA 1501: 1' in code metrics rule specification file 'CodeMetricsConfig.txt'
GetCA1509ExpectedDiagnostic(9, 1, "CA 1501: 1", AdditionalFileName),
// CodeMetricsConfig.txt(12,1): warning CA1509: Invalid entry 'CA1600: 1' in code metrics rule specification file 'CodeMetricsConfig.txt'
GetCA1509ExpectedDiagnostic(12, 1, "CA1600: 1", AdditionalFileName),
// CodeMetricsConfig.txt(15,1): warning CA1509: Invalid entry 'CA1501: None' in code metrics rule specification file 'CodeMetricsConfig.txt'
GetCA1509ExpectedDiagnostic(15, 1, "CA1501: None", AdditionalFileName),
// CodeMetricsConfig.txt(18,1): warning CA1509: Invalid entry 'CA1501(Local): 1' in code metrics rule specification file 'CodeMetricsConfig.txt'
GetCA1509ExpectedDiagnostic(18, 1, "CA1501(Local): 1", AdditionalFileName),
// CodeMetricsConfig.txt(21,1): warning CA1509: Invalid entry 'CA1501(: 1' in code metrics rule specification file 'CodeMetricsConfig.txt'
GetCA1509ExpectedDiagnostic(21, 1, "CA1501(: 1", AdditionalFileName),
// CodeMetricsConfig.txt(24,1): warning CA1509: Invalid entry 'CA1501(Method: 1' in code metrics rule specification file 'CodeMetricsConfig.txt'
GetCA1509ExpectedDiagnostic(24, 1, "CA1501(Method: 1", AdditionalFileName),
// CodeMetricsConfig.txt(27,1): warning CA1509: Invalid entry 'CA1501(Method)(Type): 1' in code metrics rule specification file 'CodeMetricsConfig.txt'
GetCA1509ExpectedDiagnostic(27, 1, "CA1501(Method)(Type): 1", AdditionalFileName),
// CodeMetricsConfig.txt(30,1): warning CA1509: Invalid entry 'CA1501' in code metrics rule specification file 'CodeMetricsConfig.txt'
GetCA1509ExpectedDiagnostic(30, 1, "CA1501", AdditionalFileName)};
await VerifyCSharpAsync(source, additionalText, expected);
}
[Fact]
public async Task CA1509_NoDiagnostics()
{
var source = @"";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
# 1. Duplicates are allowed
CA1501: 1
CA1501: 2
# 2. Duplicate RuleId-SymbolKind pairs are allowed.
CA1501(Method): 1
CA1501(Method): 1
# 3. All valid symbol kinds
CA1502(Assembly): 1
CA1502(Namespace): 1
CA1502(Type): 1
CA1502(Method): 1
CA1502(Field): 1
CA1502(Property): 1
CA1502(Event): 1
# 4. Whitespaces before and after the key-value pair are allowed.
CA1501: 1
# 5. Whitespaces before and after the colon are allowed.
CA1501 : 1
";
await VerifyCSharpAsync(source, additionalText);
}
[Fact]
public async Task CA1509_VerifyNoMetricDiagnostics()
{
// Ensure we don't report any code metric diagnostics when we have invalid entries in code metrics configuration file.
var source = @"
class BaseClass { }
class FirstDerivedClass : BaseClass { }
class SecondDerivedClass : FirstDerivedClass { }
class ThirdDerivedClass : SecondDerivedClass { }
class FourthDerivedClass : ThirdDerivedClass { }
// This class violates the CA1501 rule for default threshold.
class FifthDerivedClass : FourthDerivedClass { }";
string additionalText = @"
# FORMAT:
# 'RuleId'(Optional 'SymbolKind'): 'Threshold'
CA 1501: 10
";
DiagnosticResult[] expected = new[] {
// CodeMetricsConfig.txt(5,1): warning CA1509: Invalid entry 'CA 1501: 10' in code metrics rule specification file 'CodeMetricsConfig.txt'
GetCA1509ExpectedDiagnostic(5, 1, "CA 1501: 10", AdditionalFileName)};
await VerifyCSharpAsync(source, additionalText, expected);
}
#endregion
#region Helpers
private static DiagnosticResult GetCSharpCA1501ExpectedDiagnostic(int line, int column, string symbolName, int metricValue, int threshold, string baseTypes)
=> VerifyCS.Diagnostic(CodeMetricsAnalyzer.CA1501Rule)
.WithLocation(line, column)
.WithArguments(symbolName, metricValue, threshold, baseTypes);
private static DiagnosticResult GetBasicCA1501ExpectedDiagnostic(int line, int column, string symbolName, int metricValue, int threshold, string baseTypes)
=> VerifyVB.Diagnostic(CodeMetricsAnalyzer.CA1501Rule)
.WithLocation(line, column)
.WithArguments(symbolName, metricValue, threshold, baseTypes);
private static DiagnosticResult GetCSharpCA1502ExpectedDiagnostic(int line, int column, string symbolName, int metricValue, int threshold)
=> VerifyCS.Diagnostic(CodeMetricsAnalyzer.CA1502Rule)
.WithLocation(line, column)
.WithArguments(symbolName, metricValue, threshold);
private static DiagnosticResult GetBasicCA1502ExpectedDiagnostic(int line, int column, string symbolName, int metricValue, int threshold)
=> VerifyVB.Diagnostic(CodeMetricsAnalyzer.CA1502Rule)
.WithLocation(line, column)
.WithArguments(symbolName, metricValue, threshold);
private static DiagnosticResult GetCSharpCA1505ExpectedDiagnostic(int line, int column, string symbolName, int metricValue, int threshold)
=> VerifyCS.Diagnostic(CodeMetricsAnalyzer.CA1505Rule)
.WithLocation(line, column)
.WithArguments(symbolName, metricValue, threshold);
private static DiagnosticResult GetBasicCA1505ExpectedDiagnostic(int line, int column, string symbolName, int metricValue, int threshold)
=> VerifyVB.Diagnostic(CodeMetricsAnalyzer.CA1505Rule)
.WithLocation(line, column)
.WithArguments(symbolName, metricValue, threshold);
private static DiagnosticResult GetCSharpCA1506ExpectedDiagnostic(int line, int column, string symbolName, int coupledTypesCount, int namespaceCount, int threshold)
=> VerifyCS.Diagnostic(CodeMetricsAnalyzer.CA1506Rule)
.WithLocation(line, column)
.WithArguments(symbolName, coupledTypesCount, namespaceCount, threshold);
private static DiagnosticResult GetBasicCA1506ExpectedDiagnostic(int line, int column, string symbolName, int coupledTypesCount, int namespaceCount, int threshold)
=> VerifyVB.Diagnostic(CodeMetricsAnalyzer.CA1506Rule)
.WithLocation(line, column)
.WithArguments(symbolName, coupledTypesCount, namespaceCount, threshold);
private static DiagnosticResult GetCA1509ExpectedDiagnostic(int line, int column, string entry, string additionalFile)
=> VerifyCS.Diagnostic(CodeMetricsAnalyzer.InvalidEntryInCodeMetricsConfigFileRule)
.WithLocation(additionalFile, line, column)
.WithArguments(entry, additionalFile);
private const string AdditionalFileName = "CodeMetricsConfig.txt";
private async Task VerifyCSharpAsync(string source, string codeMetricsConfigSource, params DiagnosticResult[] expected)
{
var csharpTest = new VerifyCS.Test
{
TestState =
{
Sources = { source },
AdditionalFiles = { (AdditionalFileName, codeMetricsConfigSource) }
}
};
csharpTest.ExpectedDiagnostics.AddRange(expected);
await csharpTest.RunAsync();
}
private async Task VerifyBasicAsync(string source, string codeMetricsConfigSource, params DiagnosticResult[] expected)
{
var vbTest = new VerifyVB.Test
{
TestState =
{
Sources = { source },
AdditionalFiles = { (AdditionalFileName, codeMetricsConfigSource) }
}
};
vbTest.ExpectedDiagnostics.AddRange(expected);
await vbTest.RunAsync();
}
#endregion
}
}
| |
//#define DEBUG_SHADERS
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using OpenTK.Graphics.OpenGL;
using ValveResourceFormat.ThirdParty;
namespace GUI.Types.Renderer
{
public class ShaderLoader
{
private const string ShaderDirectory = "GUI.Types.Renderer.Shaders.";
private const int ShaderSeed = 0x13141516;
private static Regex RegexInclude = new Regex(@"^#include ""(?<IncludeName>[^""]+)""", RegexOptions.Multiline);
private static Regex RegexDefine = new Regex(@"^#define param_(?<ParamName>\S+) (?<DefaultValue>\S+)", RegexOptions.Multiline);
#if !DEBUG_SHADERS || !DEBUG
private readonly Dictionary<uint, Shader> CachedShaders = new Dictionary<uint, Shader>();
private readonly Dictionary<string, List<string>> ShaderDefines = new Dictionary<string, List<string>>();
#endif
public Shader LoadShader(string shaderName, IDictionary<string, bool> arguments)
{
var shaderFileName = GetShaderFileByName(shaderName);
#if !DEBUG_SHADERS || !DEBUG
if (ShaderDefines.ContainsKey(shaderFileName))
{
var shaderCacheHash = CalculateShaderCacheHash(shaderFileName, arguments);
if (CachedShaders.TryGetValue(shaderCacheHash, out var cachedShader))
{
return cachedShader;
}
}
#endif
var defines = new List<string>();
/* Vertex shader */
var vertexShader = GL.CreateShader(ShaderType.VertexShader);
var assembly = Assembly.GetExecutingAssembly();
#if DEBUG_SHADERS && DEBUG
using (var stream = File.Open(GetShaderDiskPath($"{shaderFileName}.vert"), FileMode.Open))
#else
using (var stream = assembly.GetManifestResourceStream($"{ShaderDirectory}{shaderFileName}.vert"))
#endif
using (var reader = new StreamReader(stream))
{
var shaderSource = reader.ReadToEnd();
GL.ShaderSource(vertexShader, PreprocessVertexShader(shaderSource, arguments));
// Find defines supported from source
defines.AddRange(FindDefines(shaderSource));
}
GL.CompileShader(vertexShader);
GL.GetShader(vertexShader, ShaderParameter.CompileStatus, out var shaderStatus);
if (shaderStatus != 1)
{
GL.GetShaderInfoLog(vertexShader, out var vsInfo);
throw new InvalidProgramException($"Error setting up Vertex Shader \"{shaderName}\": {vsInfo}");
}
/* Fragment shader */
var fragmentShader = GL.CreateShader(ShaderType.FragmentShader);
#if DEBUG_SHADERS && DEBUG
using (var stream = File.Open(GetShaderDiskPath($"{shaderFileName}.frag"), FileMode.Open))
#else
using (var stream = assembly.GetManifestResourceStream($"{ShaderDirectory}{shaderFileName}.frag"))
#endif
using (var reader = new StreamReader(stream))
{
var shaderSource = reader.ReadToEnd();
GL.ShaderSource(fragmentShader, UpdateDefines(shaderSource, arguments));
// Find render modes supported from source, take union to avoid duplicates
defines = defines.Union(FindDefines(shaderSource)).ToList();
}
GL.CompileShader(fragmentShader);
GL.GetShader(fragmentShader, ShaderParameter.CompileStatus, out shaderStatus);
if (shaderStatus != 1)
{
GL.GetShaderInfoLog(fragmentShader, out var fsInfo);
throw new InvalidProgramException($"Error setting up Fragment Shader \"{shaderName}\": {fsInfo}");
}
const string renderMode = "renderMode_";
var renderModes = defines
.Where(k => k.StartsWith(renderMode))
.Select(k => k.Substring(renderMode.Length))
.ToList();
var shader = new Shader
{
Name = shaderName,
Parameters = arguments,
Program = GL.CreateProgram(),
RenderModes = renderModes,
};
GL.AttachShader(shader.Program, vertexShader);
GL.AttachShader(shader.Program, fragmentShader);
GL.LinkProgram(shader.Program);
GL.GetProgram(shader.Program, GetProgramParameterName.LinkStatus, out var linkStatus);
if (linkStatus != 1)
{
GL.GetProgramInfoLog(shader.Program, out var programLog);
throw new InvalidProgramException($"Error linking shader \"{shaderName}\": {programLog}");
}
GL.ValidateProgram(shader.Program);
GL.GetProgram(shader.Program, GetProgramParameterName.ValidateStatus, out var validateStatus);
if (validateStatus != 1)
{
GL.GetProgramInfoLog(shader.Program, out var programLog);
throw new InvalidProgramException($"Error validating shader \"{shaderName}\": {programLog}");
}
GL.DetachShader(shader.Program, vertexShader);
GL.DeleteShader(vertexShader);
GL.DetachShader(shader.Program, fragmentShader);
GL.DeleteShader(fragmentShader);
#if !DEBUG_SHADERS || !DEBUG
ShaderDefines[shaderFileName] = defines;
var newShaderCacheHash = CalculateShaderCacheHash(shaderFileName, arguments);
CachedShaders[newShaderCacheHash] = shader;
Console.WriteLine($"Shader {newShaderCacheHash} ({shaderName}) ({string.Join(", ", arguments.Keys)}) compiled and linked succesfully");
#endif
return shader;
}
//Preprocess a vertex shader's source to include the #version plus #defines for parameters
private static string PreprocessVertexShader(string source, IDictionary<string, bool> arguments)
{
//Update parameter defines
var paramSource = UpdateDefines(source, arguments);
//Inject code into shader based on #includes
var includedSource = ResolveIncludes(paramSource);
return includedSource;
}
//Update default defines with possible overrides from the model
private static string UpdateDefines(string source, IDictionary<string, bool> arguments)
{
//Find all #define param_(paramName) (paramValue) using regex
var defines = RegexDefine.Matches(source);
foreach (Match define in defines)
{
//Check if this parameter is in the arguments
if (!arguments.TryGetValue(define.Groups["ParamName"].Value, out var value))
{
continue;
}
//Overwrite default value
var defaultValue = define.Groups["DefaultValue"];
var index = defaultValue.Index;
var length = defaultValue.Length;
var newValue = value ? "1" : "0";
source = source.Remove(index, Math.Min(length, source.Length - index)).Insert(index, newValue);
}
return source;
}
//Remove any #includes from the shader and replace with the included code
private static string ResolveIncludes(string source)
{
var assembly = Assembly.GetExecutingAssembly();
var includes = RegexInclude.Matches(source);
foreach (Match define in includes)
{
//Read included code
#if DEBUG_SHADERS && DEBUG
using (var stream = File.Open(GetShaderDiskPath(define.Groups["IncludeName"].Value), FileMode.Open))
#else
using (var stream = assembly.GetManifestResourceStream($"{ShaderDirectory}{define.Groups["IncludeName"].Value}"))
#endif
using (var reader = new StreamReader(stream))
{
var includedCode = reader.ReadToEnd();
//Recursively resolve includes in the included code. (Watch out for cyclic dependencies!)
includedCode = ResolveIncludes(includedCode);
//Replace the include with the code
source = source.Replace(define.Value, includedCode);
}
}
return source;
}
private static List<string> FindDefines(string source)
{
var defines = RegexDefine.Matches(source);
return defines.Select(match => match.Groups["ParamName"].Value).ToList();
}
// Map shader names to shader files
private static string GetShaderFileByName(string shaderName)
{
switch (shaderName)
{
case "vrf.error":
return "error";
case "vrf.grid":
return "debug_grid";
case "vrf.particle.sprite":
return "particle_sprite";
case "vrf.particle.trail":
return "particle_trail";
case "vr_unlit.vfx":
case "vr_black_unlit.vfx":
return "vr_unlit";
case "water_dota.vfx":
return "water";
case "hero.vfx":
case "hero_underlords.vfx":
return "dota_hero";
case "multiblend.vfx":
return "multiblend";
default:
if (shaderName.StartsWith("vr_"))
{
return "vr_standard";
}
//Console.WriteLine($"Unknown shader {shaderName}, defaulting to simple.");
//Shader names that are supposed to use this:
//vr_simple.vfx
return "simple";
}
}
#if !DEBUG_SHADERS || !DEBUG
private uint CalculateShaderCacheHash(string shaderFileName, IDictionary<string, bool> arguments)
{
var shaderCacheHashString = new StringBuilder();
shaderCacheHashString.AppendLine(shaderFileName);
var parameters = ShaderDefines[shaderFileName].Intersect(arguments.Keys);
foreach (var key in parameters)
{
shaderCacheHashString.AppendLine(key);
shaderCacheHashString.AppendLine(arguments[key] ? "t" : "f");
}
return MurmurHash2.Hash(shaderCacheHashString.ToString(), ShaderSeed);
}
#endif
#if DEBUG_SHADERS && DEBUG
// Reload shaders at runtime
private static string GetShaderDiskPath(string name)
{
return Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule?.FileName), "../../../", ShaderDirectory.Replace('.', '/'), name);
}
#endif
}
}
| |
// 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.Numerics;
using System.IO;
internal partial class VectorTest
{
public static bool CheckValue<T>(T value, T expectedValue)
{
bool returnVal;
if (typeof(T) == typeof(float))
{
returnVal = Math.Abs(((float)(object)value) - ((float)(object)expectedValue)) <= Single.Epsilon;
}
if (typeof(T) == typeof(double))
{
returnVal = Math.Abs(((double)(object)value) - ((double)(object)expectedValue)) <= Double.Epsilon;
}
else
{
returnVal = value.Equals(expectedValue);
}
if (returnVal == false)
{
Console.WriteLine("CheckValue failed for " + expectedValue + " of type " + typeof(T).ToString());
}
return returnVal;
}
private static bool CheckVector<T>(Vector<T> V, T value) where T : struct, IComparable<T>, IEquatable<T>
{
for (int i = 0; i < Vector<T>.Count; i++)
{
if (!(CheckValue<T>(V[i], value)))
{
return false;
}
}
return true;
}
public static T GetValueFromInt<T>(int value)
{
if (typeof(T) == typeof(float))
{
float floatValue = (float)value;
return (T)(object)floatValue;
}
if (typeof(T) == typeof(double))
{
double doubleValue = (double)value;
return (T)(object)doubleValue;
}
if (typeof(T) == typeof(int))
{
return (T)(object)value;
}
if (typeof(T) == typeof(uint))
{
uint uintValue = (uint)value;
return (T)(object)uintValue;
}
if (typeof(T) == typeof(long))
{
long longValue = (long)value;
return (T)(object)longValue;
}
if (typeof(T) == typeof(ulong))
{
ulong longValue = (ulong)value;
return (T)(object)longValue;
}
if (typeof(T) == typeof(ushort))
{
return (T)(object)(ushort)value;
}
if (typeof(T) == typeof(byte))
{
return (T)(object)(byte)value;
}
if (typeof(T) == typeof(short))
{
return (T)(object)(short)value;
}
if (typeof(T) == typeof(sbyte))
{
return (T)(object)(sbyte)value;
}
else
{
throw new ArgumentException();
}
}
private static void VectorPrint<T>(string mesg, Vector<T> v) where T : struct, IComparable<T>, IEquatable<T>
{
Console.Write(mesg + "[");
for (int i = 0; i < Vector<T>.Count; i++)
{
Console.Write(" " + v[i]);
if (i < (Vector<T>.Count - 1)) Console.Write(",");
}
Console.WriteLine(" ]");
}
private static T Add<T>(T left, T right) where T : struct, IComparable<T>, IEquatable<T>
{
if (typeof(T) == typeof(float))
{
return (T)(object)(((float)(object)left) + ((float)(object)right));
}
if (typeof(T) == typeof(double))
{
return (T)(object)(((double)(object)left) + ((double)(object)right));
}
if (typeof(T) == typeof(int))
{
return (T)(object)(((int)(object)left) + ((int)(object)right));
}
if (typeof(T) == typeof(uint))
{
return (T)(object)(((uint)(object)left) + ((uint)(object)right));
}
if (typeof(T) == typeof(ushort))
{
return (T)(object)(((ushort)(object)left) + ((ushort)(object)right));
}
if (typeof(T) == typeof(byte))
{
return (T)(object)(((byte)(object)left) + ((byte)(object)right));
}
if (typeof(T) == typeof(short))
{
return (T)(object)(((short)(object)left) + ((short)(object)right));
}
if (typeof(T) == typeof(sbyte))
{
return (T)(object)(((sbyte)(object)left) + ((sbyte)(object)right));
}
if (typeof(T) == typeof(long))
{
return (T)(object)(((long)(object)left) + ((long)(object)right));
}
if (typeof(T) == typeof(ulong))
{
return (T)(object)(((ulong)(object)left) + ((ulong)(object)right));
}
else
{
throw new ArgumentException();
}
}
private static T Multiply<T>(T left, T right) where T : struct, IComparable<T>, IEquatable<T>
{
if (typeof(T) == typeof(float))
{
return (T)(object)(((float)(object)left) * ((float)(object)right));
}
if (typeof(T) == typeof(double))
{
return (T)(object)(((double)(object)left) * ((double)(object)right));
}
if (typeof(T) == typeof(int))
{
return (T)(object)(((int)(object)left) * ((int)(object)right));
}
if (typeof(T) == typeof(uint))
{
return (T)(object)(((uint)(object)left) * ((uint)(object)right));
}
if (typeof(T) == typeof(ushort))
{
return (T)(object)(((ushort)(object)left) * ((ushort)(object)right));
}
if (typeof(T) == typeof(byte))
{
return (T)(object)(((byte)(object)left) * ((byte)(object)right));
}
if (typeof(T) == typeof(short))
{
return (T)(object)(((short)(object)left) * ((short)(object)right));
}
if (typeof(T) == typeof(sbyte))
{
return (T)(object)(((sbyte)(object)left) * ((sbyte)(object)right));
}
if (typeof(T) == typeof(long))
{
return (T)(object)(((long)(object)left) * ((long)(object)right));
}
if (typeof(T) == typeof(ulong))
{
return (T)(object)(((ulong)(object)left) * ((ulong)(object)right));
}
else
{
throw new ArgumentException();
}
}
public static T[] GetRandomArray<T>(int size, Random random)
where T : struct, IComparable<T>, IEquatable<T>
{
T[] result = new T[size];
for (int i = 0; i < size; i++)
{
int data = random.Next(100);
result[i] = GetValueFromInt<T>(data);
}
return result;
}
}
class JitLog : IDisposable
{
FileStream fileStream;
bool simdIntrinsicsSupported;
private static String GetLogFileName()
{
String jitLogFileName = Environment.GetEnvironmentVariable("COMPlus_JitFuncInfoLogFile");
return jitLogFileName;
}
public JitLog()
{
fileStream = null;
simdIntrinsicsSupported = Vector.IsHardwareAccelerated;
String jitLogFileName = GetLogFileName();
if (jitLogFileName == null)
{
Console.WriteLine("No JitLogFile");
return;
}
if (!File.Exists(jitLogFileName))
{
Console.WriteLine("JitLogFile " + jitLogFileName + " not found.");
return;
}
File.Copy(jitLogFileName, "Temp.log", true);
fileStream = new FileStream("Temp.log", FileMode.Open, FileAccess.Read, FileShare.Read);
}
public void Dispose()
{
if (fileStream != null)
{
fileStream.Dispose();
}
}
public bool IsEnabled()
{
return (fileStream != null);
}
//------------------------------------------------------------------------
// Check: Check to see whether 'method' was recognized as an intrinsic by the JIT.
//
// Arguments:
// method - The method name, as a string
//
// Return Value:
// If the JitLog is not enabled (either the environment variable is not set,
// or the file was not found, e.g. if the JIT doesn't support it):
// - Returns true
// If SIMD intrinsics are enabled:
// - Returns true if the method was NOT compiled, otherwise false
// Else (if SIMD intrinsics are NOT enabled):
// - Returns true.
// Note that it might be useful to return false if the method was not compiled,
// but it will not be logged as compiled if it is inlined.
//
// Assumptions:
// The JitLog constructor queries Vector.IsHardwareAccelerated to determine
// if SIMD intrinsics are enabled, and depends on its correctness.
//
// Notes:
// It searches for the string verbatim. If 'method' is not fully qualified
// or its signature is not provided, it may result in false matches.
//
// Example:
// CheckJitLog("System.Numerics.Vector4:op_Addition(struct,struct):struct");
//
public bool Check(String method)
{
// Console.WriteLine("Checking for " + method + ":");
if (!IsEnabled())
{
Console.WriteLine("JitLog not enabled.");
return true;
}
try
{
fileStream.Position = 0;
StreamReader reader = new StreamReader(fileStream);
bool methodFound = false;
while ((reader.Peek() >= 0) && (methodFound == false))
{
String s = reader.ReadLine();
if (s.IndexOf(method) != -1)
{
methodFound = true;
}
}
if (simdIntrinsicsSupported && methodFound)
{
Console.WriteLine("Method " + method + " was compiled but should not have been");
return false;
}
// Useful when developing / debugging just to be sure that we reached here:
// Console.WriteLine(method + ((methodFound) ? " WAS COMPILED" : " WAS NOT COMPILED"));
return true;
}
catch (Exception e)
{
Console.WriteLine("Error checking JitLogFile: " + e.Message);
return false;
}
}
// Check: Check to see Vector<'elementType'>:'method' was recognized as an
// intrinsic by the JIT.
//
// Arguments:
// method - The method name, without its containing type (which is Vector<T>)
// elementType - The type with which Vector<T> is instantiated.
//
// Return Value:
// See the other overload, above.
//
// Assumptions:
// The JitLog constructor queries Vector.IsHardwareAccelerated to determine
// if SIMD intrinsics are enabled, and depends on its correctness.
//
// Notes:
// It constructs the search string based on the way generic types are currently
// dumped by the CLR. If the signature is not provided for the method, it
// may result in false matches.
//
// Example:
// CheckJitLog("op_Addition(struct,struct):struct", "Single");
//
public bool Check(String method, String elementType)
{
String checkString = "System.Numerics.Vector`1[" + elementType + "][System." + elementType + "]:" + method;
return Check(checkString);
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Abp.Application.Features;
using Abp.Authorization.Roles;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.Domain.Uow;
using Abp.IdentityFramework;
using Abp.Localization;
using Abp.MultiTenancy;
using Abp.Organizations;
using Abp.Runtime.Caching;
using Abp.Runtime.Security;
using Abp.Runtime.Session;
using Abp.Zero;
using Abp.Zero.Configuration;
using Microsoft.AspNet.Identity;
namespace Abp.Authorization.Users
{
/// <summary>
/// Extends <see cref="UserManager{TUser,TKey}"/> of ASP.NET Identity Framework.
/// </summary>
public abstract class AbpUserManager<TRole, TUser>
: UserManager<TUser, long>,
IDomainService
where TRole : AbpRole<TUser>, new()
where TUser : AbpUser<TUser>
{
protected IUserPermissionStore<TUser> UserPermissionStore
{
get
{
if (!(Store is IUserPermissionStore<TUser>))
{
throw new AbpException("Store is not IUserPermissionStore");
}
return Store as IUserPermissionStore<TUser>;
}
}
public ILocalizationManager LocalizationManager { get; }
public IAbpSession AbpSession { get; set; }
public FeatureDependencyContext FeatureDependencyContext { get; set; }
protected AbpRoleManager<TRole, TUser> RoleManager { get; }
public AbpUserStore<TRole, TUser> AbpStore { get; }
public IMultiTenancyConfig MultiTenancy { get; set; }
private readonly IPermissionManager _permissionManager;
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly ICacheManager _cacheManager;
private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;
private readonly IOrganizationUnitSettings _organizationUnitSettings;
private readonly ISettingManager _settingManager;
protected AbpUserManager(
AbpUserStore<TRole, TUser> userStore,
AbpRoleManager<TRole, TUser> roleManager,
IPermissionManager permissionManager,
IUnitOfWorkManager unitOfWorkManager,
ICacheManager cacheManager,
IRepository<OrganizationUnit, long> organizationUnitRepository,
IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
IOrganizationUnitSettings organizationUnitSettings,
ILocalizationManager localizationManager,
IdentityEmailMessageService emailService,
ISettingManager settingManager,
IUserTokenProviderAccessor userTokenProviderAccessor)
: base(userStore)
{
AbpStore = userStore;
RoleManager = roleManager;
LocalizationManager = localizationManager;
_settingManager = settingManager;
_permissionManager = permissionManager;
_unitOfWorkManager = unitOfWorkManager;
_cacheManager = cacheManager;
_organizationUnitRepository = organizationUnitRepository;
_userOrganizationUnitRepository = userOrganizationUnitRepository;
_organizationUnitSettings = organizationUnitSettings;
AbpSession = NullAbpSession.Instance;
UserLockoutEnabledByDefault = true;
DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
MaxFailedAccessAttemptsBeforeLockout = 5;
EmailService = emailService;
UserTokenProvider = userTokenProviderAccessor.GetUserTokenProviderOrNull<TUser>();
}
public override async Task<IdentityResult> CreateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
var tenantId = GetCurrentTenantId();
if (tenantId.HasValue && !user.TenantId.HasValue)
{
user.TenantId = tenantId.Value;
}
return await base.CreateAsync(user);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permissionName">Permission name</param>
public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName)
{
return await IsGrantedAsync(
userId,
_permissionManager.GetPermission(permissionName)
);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission)
{
return IsGrantedAsync(user.Id, permission);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permission">Permission</param>
public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission)
{
//Check for multi-tenancy side
if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide()))
{
return false;
}
//Check for depended features
if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant)
{
FeatureDependencyContext.TenantId = GetCurrentTenantId();
if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext))
{
return false;
}
}
//Get cached user permissions
var cacheItem = await GetUserPermissionCacheItemAsync(userId);
if (cacheItem == null)
{
return false;
}
//Check for user-specific value
if (cacheItem.GrantedPermissions.Contains(permission.Name))
{
return true;
}
if (cacheItem.ProhibitedPermissions.Contains(permission.Name))
{
return false;
}
//Check for roles
foreach (var roleId in cacheItem.RoleIds)
{
if (await RoleManager.IsGrantedAsync(roleId, permission))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets granted permissions for a user.
/// </summary>
/// <param name="user">Role</param>
/// <returns>List of granted permissions</returns>
public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user)
{
var permissionList = new List<Permission>();
foreach (var permission in _permissionManager.GetAllPermissions())
{
if (await IsGrantedAsync(user.Id, permission))
{
permissionList.Add(permission);
}
}
return permissionList;
}
/// <summary>
/// Sets all granted permissions of a user at once.
/// Prohibits all other permissions.
/// </summary>
/// <param name="user">The user</param>
/// <param name="permissions">Permissions</param>
public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions)
{
var oldPermissions = await GetGrantedPermissionsAsync(user);
var newPermissions = permissions.ToArray();
foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p)))
{
await ProhibitPermissionAsync(user, permission);
}
foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p)))
{
await GrantPermissionAsync(user, permission);
}
}
/// <summary>
/// Prohibits all permissions for a user.
/// </summary>
/// <param name="user">User</param>
public async Task ProhibitAllPermissionsAsync(TUser user)
{
foreach (var permission in _permissionManager.GetAllPermissions())
{
await ProhibitPermissionAsync(user, permission);
}
}
/// <summary>
/// Resets all permission settings for a user.
/// It removes all permission settings for the user.
/// User will have permissions according to his roles.
/// This method does not prohibit all permissions.
/// For that, use <see cref="ProhibitAllPermissionsAsync"/>.
/// </summary>
/// <param name="user">User</param>
public async Task ResetAllPermissionsAsync(TUser user)
{
await UserPermissionStore.RemoveAllPermissionSettingsAsync(user);
}
/// <summary>
/// Grants a permission for a user if not already granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task GrantPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
if (await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
}
/// <summary>
/// Prohibits a permission for a user if it's granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
if (!await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
}
public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress)
{
return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress);
}
public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login)
{
return AbpStore.FindAllAsync(login);
}
/// <summary>
/// Gets a user by given id.
/// Throws exception if no user found with given id.
/// </summary>
/// <param name="userId">User id</param>
/// <returns>User</returns>
/// <exception cref="AbpException">Throws exception if no user found with given id</exception>
public virtual async Task<TUser> GetUserByIdAsync(long userId)
{
var user = await FindByIdAsync(userId);
if (user == null)
{
throw new AbpException("There is no user with id: " + userId);
}
return user;
}
public async override Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType)
{
var identity = await base.CreateIdentityAsync(user, authenticationType);
if (user.TenantId.HasValue)
{
identity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString(CultureInfo.InvariantCulture)));
}
return identity;
}
public async override Task<IdentityResult> UpdateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
//Admin user's username can not be changed!
if (user.UserName != AbpUser<TUser>.AdminUserName)
{
if ((await GetOldUserNameAsync(user.Id)) == AbpUser<TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotRenameAdminUser"), AbpUser<TUser>.AdminUserName));
}
}
return await base.UpdateAsync(user);
}
public async override Task<IdentityResult> DeleteAsync(TUser user)
{
if (user.UserName == AbpUser<TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteAdminUser"), AbpUser<TUser>.AdminUserName));
}
return await base.DeleteAsync(user);
}
public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword)
{
var result = await PasswordValidator.ValidateAsync(newPassword);
if (!result.Succeeded)
{
return result;
}
await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword));
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress)
{
var user = (await FindByNameAsync(userName));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateUserName"), userName));
}
user = (await FindByEmailAsync(emailAddress));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress));
}
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames)
{
//Remove from removed roles
foreach (var userRole in user.Roles.ToList())
{
var role = await RoleManager.FindByIdAsync(userRole.RoleId);
if (roleNames.All(roleName => role.Name != roleName))
{
var result = await RemoveFromRoleAsync(user.Id, role.Name);
if (!result.Succeeded)
{
return result;
}
}
}
//Add to added roles
foreach (var roleName in roleNames)
{
var role = await RoleManager.GetRoleByNameAsync(roleName);
if (user.Roles.All(ur => ur.RoleId != role.Id))
{
var result = await AddToRoleAsync(user.Id, roleName);
if (!result.Succeeded)
{
return result;
}
}
}
return IdentityResult.Success;
}
public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId)
{
return await IsInOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
return await _userOrganizationUnitRepository.CountAsync(uou =>
uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id
) > 0;
}
public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId)
{
await AddToOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
var currentOus = await GetOrganizationUnitsAsync(user);
if (currentOus.Any(cou => cou.Id == ou.Id))
{
return;
}
await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1);
await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id));
}
public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId)
{
await RemoveFromOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id);
}
public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds)
{
await SetOrganizationUnitsAsync(
await GetUserByIdAsync(userId),
organizationUnitIds
);
}
private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount)
{
var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId);
if (requestedCount > maxCount)
{
throw new AbpException(string.Format("Can not set more than {0} organization unit for a user!", maxCount));
}
}
public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds)
{
if (organizationUnitIds == null)
{
organizationUnitIds = new long[0];
}
await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length);
var currentOus = await GetOrganizationUnitsAsync(user);
//Remove from removed OUs
foreach (var currentOu in currentOus)
{
if (!organizationUnitIds.Contains(currentOu.Id))
{
await RemoveFromOrganizationUnitAsync(user, currentOu);
}
}
//Add to added OUs
foreach (var organizationUnitId in organizationUnitIds)
{
if (currentOus.All(ou => ou.Id != organizationUnitId))
{
await AddToOrganizationUnitAsync(
user,
await _organizationUnitRepository.GetAsync(organizationUnitId)
);
}
}
}
[UnitOfWork]
public virtual Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user)
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
where uou.UserId == user.Id
select ou;
return Task.FromResult(query.ToList());
}
[UnitOfWork]
public virtual Task<List<TUser>> GetUsersInOrganizationUnit(OrganizationUnit organizationUnit, bool includeChildren = false)
{
if (!includeChildren)
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join user in AbpStore.Users on uou.UserId equals user.Id
where uou.OrganizationUnitId == organizationUnit.Id
select user;
return Task.FromResult(query.ToList());
}
else
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join user in AbpStore.Users on uou.UserId equals user.Id
join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
where ou.Code.StartsWith(organizationUnit.Code)
select user;
return Task.FromResult(query.ToList());
}
}
public virtual void RegisterTwoFactorProviders(int? tenantId)
{
TwoFactorProviders.Clear();
if (!IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled, tenantId))
{
return;
}
if (EmailService != null &&
IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, tenantId))
{
RegisterTwoFactorProvider(
L("Email"),
new EmailTokenProvider<TUser, long>
{
Subject = L("EmailSecurityCodeSubject"),
BodyFormat = L("EmailSecurityCodeBody")
}
);
}
if (SmsService != null &&
IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, tenantId))
{
RegisterTwoFactorProvider(
L("Sms"),
new PhoneNumberTokenProvider<TUser, long>
{
MessageFormat = L("SmsSecurityCodeMessage")
}
);
}
}
public virtual void InitializeLockoutSettings(int? tenantId)
{
UserLockoutEnabledByDefault = IsTrue(AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId);
DefaultAccountLockoutTimeSpan = TimeSpan.FromSeconds(GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId));
MaxFailedAccessAttemptsBeforeLockout = GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId);
}
public override async Task<IList<string>> GetValidTwoFactorProvidersAsync(long userId)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.GetValidTwoFactorProvidersAsync(userId);
}
public override async Task<IdentityResult> NotifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.NotifyTwoFactorTokenAsync(userId, twoFactorProvider, token);
}
public override async Task<string> GenerateTwoFactorTokenAsync(long userId, string twoFactorProvider)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.GenerateTwoFactorTokenAsync(userId, twoFactorProvider);
}
public override async Task<bool> VerifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.VerifyTwoFactorTokenAsync(userId, twoFactorProvider, token);
}
protected virtual Task<string> GetOldUserNameAsync(long userId)
{
return AbpStore.GetUserNameFromDatabaseAsync(userId);
}
private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId)
{
var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0);
return await _cacheManager.GetUserPermissionCache().GetAsync(cacheKey, async () =>
{
var user = await FindByIdAsync(userId);
if (user == null)
{
return null;
}
var newCacheItem = new UserPermissionCacheItem(userId);
foreach (var roleName in await GetRolesAsync(userId))
{
newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id);
}
foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId))
{
if (permissionInfo.IsGranted)
{
newCacheItem.GrantedPermissions.Add(permissionInfo.Name);
}
else
{
newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name);
}
}
return newCacheItem;
});
}
private bool IsTrue(string settingName, int? tenantId)
{
return GetSettingValue<bool>(settingName, tenantId);
}
private T GetSettingValue<T>(string settingName, int? tenantId) where T : struct
{
return tenantId == null
? _settingManager.GetSettingValueForApplication<T>(settingName)
: _settingManager.GetSettingValueForTenant<T>(settingName, tenantId.Value);
}
private string L(string name)
{
return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name);
}
private int? GetCurrentTenantId()
{
if (_unitOfWorkManager.Current != null)
{
return _unitOfWorkManager.Current.GetTenantId();
}
return AbpSession.TenantId;
}
private MultiTenancySides GetCurrentMultiTenancySide()
{
if (_unitOfWorkManager.Current != null)
{
return MultiTenancy.IsEnabled && !_unitOfWorkManager.Current.GetTenantId().HasValue
? MultiTenancySides.Host
: MultiTenancySides.Tenant;
}
return AbpSession.MultiTenancySide;
}
}
}
| |
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
namespace Orleans.Runtime
{
/// <summary>
/// Extension methods which preserves legacy orleans log methods style
/// </summary>
public static class OrleansLoggerExtension
{
/// <summary>
/// Writes a log entry at the Debug severity level.
/// </summary>
/// <param name="logger">The logger</param>
/// <param name="format">Format string of the log message with named parameters
/// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks>
/// </param>
/// <param name="args">Any arguments to the format string.</param>
public static void Debug(this ILogger logger, string format, params object[] args)
{
logger.LogDebug(format, args);
}
/// <summary>
/// Writes a log entry at the Verbose severity level.
/// Verbose is suitable for debugging information that should usually not be logged in production.
/// Verbose is lower than Info.
/// </summary>
/// <param name="logger">The logger</param>
/// <param name="message">The log message.</param>
public static void Debug(this ILogger logger, string message)
{
logger.LogDebug(message);
}
/// <summary>
/// Writes a log entry at the Trace logLevel.
/// </summary>
/// <param name="logger">The logger</param>
/// <param name="format">Format string of the log message with named parameters
/// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks>
/// </param>
/// <param name="args">Any arguments to the format string.</param>
public static void Trace(this ILogger logger, string format, params object[] args)
{
logger.LogTrace(format, args);
}
/// <summary>
/// Writes a log entry at the Verbose2 severity level.
/// Verbose2 is lower than Verbose.
/// </summary>
/// <param name="logger">The logger</param>
/// <param name="message">The log message.</param>
public static void Trace(this ILogger logger, string message)
{
logger.LogTrace(message);
}
/// <summary>
/// Writes a log entry at the Information Level
/// </summary>
/// <param name="logger">Target logger.</param>
/// <param name="format">Format string of the log message with named parameters
/// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks>
/// </param>
/// <param name="args">Any arguments to the format string.</param>
public static void Info(this ILogger logger, string format, params object[] args)
{
logger.LogInformation(format, args);
}
/// <summary>
/// Writes a log entry at the Info logLevel
/// </summary>
/// <param name="logger">Target logger.</param>
/// <param name="message">The log message.</param>
public static void Info(this ILogger logger, string message)
{
logger.LogInformation(message);
}
/// <summary>
/// Writes a log entry at the Debug logLevel
/// </summary>
/// <param name="logger">The logger</param>
/// <param name="logCode">The log code associated with this message.</param>
/// <param name="format">Format string of the log message with named parameters
/// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks>
/// </param>
/// <param name="args">Any arguments to the format string.</param>
public static void Debug(this ILogger logger, int logCode, string format, params object[] args)
{
logger.LogDebug(logCode, format, args);
}
public static void Debug(this ILogger logger, ErrorCode logCode, string format, params object[] args)
{
logger.LogDebug(LoggingUtils.CreateEventId(logCode), format, args);
}
/// <summary>
/// Writes a log entry at the Debug logLevel
/// </summary>
/// <param name="logger">The logger</param>
/// <param name="logCode">The log code associated with this message.</param>
/// <param name="message">The log message.</param>
public static void Debug(this ILogger logger, int logCode, string message)
{
logger.LogDebug(logCode, message);
}
public static void Debug(this ILogger logger, ErrorCode logCode, string message)
{
logger.LogDebug(LoggingUtils.CreateEventId(logCode), message);
}
/// <summary>
/// Writes a log entry at the Trace logLevel
/// </summary>
/// <param name="logger">The logger</param>
/// <param name="logCode">The log code associated with this message.</param>
/// <param name="format">Format string of the log message with named parameters
/// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks>
/// </param>
/// <param name="args">Any arguments to the format string.</param>
public static void Trace(this ILogger logger, int logCode, string format, params object[] args)
{
logger.LogTrace(logCode, format, args);
}
public static void Trace(this ILogger logger, ErrorCode logCode, string format, params object[] args)
{
logger.LogTrace(LoggingUtils.CreateEventId(logCode), format, args);
}
/// <summary>
/// Writes a log entry at the Trace logLevel
/// </summary>
/// <param name="logger">The logger</param>
/// <param name="logCode">The log code associated with this message.</param>
/// <param name="message">The log message.</param>
public static void Trace(this ILogger logger, int logCode, string message)
{
logger.LogTrace(logCode, message);
}
public static void Trace(this ILogger logger, ErrorCode logCode, string message)
{
logger.LogTrace(LoggingUtils.CreateEventId(logCode), message);
}
/// <summary>
/// Writes a log entry at the Information logLevel
/// </summary>
/// <param name="logger">The logger</param>
/// <param name="logCode">The log code associated with this message.</param>
/// <param name="format">Format string of the log message with named parameters
/// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks>
/// </param>
/// <param name="args">Any arguments to the format string.</param>
public static void Info(this ILogger logger, int logCode, string format, params object[] args)
{
logger.LogInformation(logCode, format, args);
}
public static void Info(this ILogger logger, ErrorCode logCode, string format, params object[] args)
{
logger.LogInformation(LoggingUtils.CreateEventId(logCode), format, args);
}
/// <summary>
/// Writes a log entry at the Information logLevel
/// </summary>
/// <param name="logger">The logger</param>
/// <param name="logCode">The log code associated with this message.</param>
/// <param name="message">The log message.</param>
public static void Info(this ILogger logger, int logCode, string message)
{
logger.LogInformation(logCode, message);
}
public static void Info(this ILogger logger, ErrorCode logCode, string message)
{
logger.LogInformation(LoggingUtils.CreateEventId(logCode), message);
}
/// <summary>
/// Writes a log entry at the Warning level
/// </summary>
/// <param name="logger">The logger</param>
/// <param name="logCode">The log code associated with this message.</param>
/// <param name="format">Format string of the log message with named parameters
/// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks>
/// </param>
/// <param name="args">Any arguments to the format string.</param>
public static void Warn(this ILogger logger, int logCode, string format, params object[] args)
{
logger.LogWarning(logCode, format, args);
}
public static void Warn(this ILogger logger, ErrorCode logCode, string format, params object[] args)
{
logger.LogWarning(LoggingUtils.CreateEventId(logCode), format, args);
}
/// <summary>
/// Writes a log entry at the Warning level
/// </summary>
/// <param name="logger">The logger</param>
/// <param name="logCode">The log code associated with this message.</param>
/// <param name="message">The warning message to log.</param>
/// <param name="exception">An exception related to the warning, if any.</param>
public static void Warn(this ILogger logger, int logCode, string message, Exception exception = null)
{
logger.LogWarning(logCode, exception, message);
}
public static void Warn(this ILogger logger, ErrorCode logCode, string message, Exception exception = null)
{
logger.LogWarning(LoggingUtils.CreateEventId(logCode), exception, message);
}
/// <summary>
/// Writes a log entry at the Error level
/// </summary>
/// <param name="logger">The logger</param>
/// <param name="logCode">The log code associated with this message.</param>
/// <param name="message">The error message to log.</param>
/// <param name="exception">An exception related to the error, if any.</param>
public static void Error(this ILogger logger, int logCode, string message, Exception exception = null)
{
logger.LogError(logCode, exception, message);
}
public static void Error(this ILogger logger, ErrorCode logCode, string message, Exception exception = null)
{
logger.LogError(LoggingUtils.CreateEventId(logCode), exception, message);
}
public static void Assert(this ILogger logger, ErrorCode errorCode, bool condition, string message = null)
{
if (condition) return;
if (message == null)
{
message = "Internal contract assertion has failed!";
}
logger.Fail(errorCode, "Assert failed with message = " + message);
}
public static void Fail(this ILogger logger, ErrorCode errorCode, string message)
{
if (message == null)
{
message = "Internal Fail!";
}
if (errorCode == 0)
{
errorCode = ErrorCode.Runtime;
}
logger.Error(errorCode, "INTERNAL FAILURE! About to crash! Fail message is: " + message + Environment.NewLine + Environment.StackTrace);
// Kill process
if (Debugger.IsAttached)
{
Debugger.Break();
}
else
{
logger.Error(ErrorCode.Logger_ProcessCrashing, "INTERNAL FAILURE! Process crashing!");
// Environment.FailFast triggers a popup on some machine "xxx has stopped working"
Environment.Exit(128);
}
}
}
}
| |
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;
namespace EdiEngine.Standards.X12_004010.Maps
{
public class M_837 : MapLoop
{
public M_837() : base(null)
{
Content.AddRange(new MapBaseEntity[] {
new BHT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new L_NM1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_HL(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
});
}
//1000
public class L_NM1 : MapLoop
{
public L_NM1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
});
}
}
//2000
public class L_HL : MapLoop
{
public L_HL(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new HL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new PRV() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new SBR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PAT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_NM1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_CLM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 },
});
}
}
//2010
public class L_NM1_1 : MapLoop
{
public L_NM1_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
});
}
}
//2300
public class L_CLM : MapLoop
{
public L_CLM(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new CLM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 150 },
new CL1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DN1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DN2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 35 },
new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new CN1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DSB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new UR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 40 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 30 },
new K3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new NTE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new CR1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new CR2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new CR3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new CR4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new CR5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new CR6() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new CR8() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new CRC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 },
new HI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new HCP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_CR7(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 6 },
new L_NM1_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new L_SBR(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2305
public class L_CR7 : MapLoop
{
public L_CR7(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new CR7() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new HSD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
});
}
}
//2310
public class L_NM1_2 : MapLoop
{
public L_NM1_2(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new PRV() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
});
}
}
//2320
public class L_SBR : MapLoop
{
public L_SBR(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SBR() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new CAS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 15 },
new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new OI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new MIA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new MOA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_NM1_3(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//2330
public class L_NM1_3 : MapLoop
{
public L_NM1_3(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
});
}
}
//2400
public class L_LX : MapLoop
{
public L_LX(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new SV1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new SV2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new SV3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new TOO() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 32 },
new SV4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new SV5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new SV6() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new SV7() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new HI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new CR1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new CR2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new CR3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new CR4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new CR5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new CRC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 15 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new CN1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 30 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 15 },
new K3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new NTE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new PS1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new IMM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new HSD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new HCP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_LIN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_NM1_4(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_SVD(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2410
public class L_LIN : MapLoop
{
public L_LIN(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LIN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2420
public class L_NM1_4 : MapLoop
{
public L_NM1_4(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new PRV() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
});
}
}
//2430
public class L_SVD : MapLoop
{
public L_SVD(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SVD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new CAS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
});
}
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERLevel;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C03_Continent_Child (editable child object).<br/>
/// This is a generated base class of <see cref="C03_Continent_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="C02_Continent"/> collection.
/// </remarks>
[Serializable]
public partial class C03_Continent_Child : BusinessBase<C03_Continent_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "SubContinents Child Name");
/// <summary>
/// Gets or sets the SubContinents Child Name.
/// </summary>
/// <value>The SubContinents Child Name.</value>
public string Continent_Child_Name
{
get { return GetProperty(Continent_Child_NameProperty); }
set { SetProperty(Continent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C03_Continent_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="C03_Continent_Child"/> object.</returns>
internal static C03_Continent_Child NewC03_Continent_Child()
{
return DataPortal.CreateChild<C03_Continent_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="C03_Continent_Child"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID1">The Continent_ID1 parameter of the C03_Continent_Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="C03_Continent_Child"/> object.</returns>
internal static C03_Continent_Child GetC03_Continent_Child(int continent_ID1)
{
return DataPortal.FetchChild<C03_Continent_Child>(continent_ID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C03_Continent_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public C03_Continent_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="C03_Continent_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="C03_Continent_Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="continent_ID1">The Continent ID1.</param>
protected void Child_Fetch(int continent_ID1)
{
var args = new DataPortalHookArgs(continent_ID1);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var dal = dalManager.GetProvider<IC03_Continent_ChildDal>();
var data = dal.Fetch(continent_ID1);
Fetch(data);
}
OnFetchPost(args);
}
private void Fetch(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="C03_Continent_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Continent_Child_NameProperty, dr.GetString("Continent_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="C03_Continent_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(C02_Continent parent)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IC03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.Continent_ID,
Continent_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="C03_Continent_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(C02_Continent parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IC03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.Continent_ID,
Continent_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="C03_Continent_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(C02_Continent parent)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IC03_Continent_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Continent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection.Emit
{
using System.Text;
using System;
using CultureInfo = System.Globalization.CultureInfo;
using System.Diagnostics.SymbolStore;
using System.Reflection;
using System.Security;
using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
[HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_MethodBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class MethodBuilder : MethodInfo, _MethodBuilder
{
#region Private Data Members
// Identity
internal String m_strName; // The name of the method
private MethodToken m_tkMethod; // The token of this method
private ModuleBuilder m_module;
internal TypeBuilder m_containingType;
// IL
private int[] m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups.
private byte[] m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise.
internal LocalSymInfo m_localSymInfo; // keep track debugging local information
internal ILGenerator m_ilGenerator; // Null if not used.
private byte[] m_ubBody; // The IL for the method
private ExceptionHandler[] m_exceptions; // Exception handlers or null if there are none.
private const int DefaultMaxStack = 16;
private int m_maxStack = DefaultMaxStack;
// Flags
internal bool m_bIsBaked;
private bool m_bIsGlobalMethod;
private bool m_fInitLocals; // indicating if the method stack frame will be zero initialized or not.
// Attributes
private MethodAttributes m_iAttributes;
private CallingConventions m_callingConvention;
private MethodImplAttributes m_dwMethodImplFlags;
// Parameters
private SignatureHelper m_signature;
internal Type[] m_parameterTypes;
private ParameterBuilder m_retParam;
private Type m_returnType;
private Type[] m_returnTypeRequiredCustomModifiers;
private Type[] m_returnTypeOptionalCustomModifiers;
private Type[][] m_parameterTypeRequiredCustomModifiers;
private Type[][] m_parameterTypeOptionalCustomModifiers;
// Generics
private GenericTypeParameterBuilder[] m_inst;
private bool m_bIsGenMethDef;
#endregion
#region Constructor
internal MethodBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
Init(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, mod, type, bIsGlobalMethod);
}
internal MethodBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
Init(name, attributes, callingConvention,
returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
mod, type, bIsGlobalMethod);
}
private void Init(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
if (name == null)
throw new ArgumentNullException("name");
if (name.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
if (name[0] == '\0')
throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "name");
if (mod == null)
throw new ArgumentNullException("mod");
Contract.EndContractBlock();
if (parameterTypes != null)
{
foreach(Type t in parameterTypes)
{
if (t == null)
throw new ArgumentNullException("parameterTypes");
}
}
m_strName = name;
m_module = mod;
m_containingType = type;
//
//if (returnType == null)
//{
// m_returnType = typeof(void);
//}
//else
{
m_returnType = returnType;
}
if ((attributes & MethodAttributes.Static) == 0)
{
// turn on the has this calling convention
callingConvention = callingConvention | CallingConventions.HasThis;
}
else if ((attributes & MethodAttributes.Virtual) != 0)
{
// A method can't be both static and virtual
throw new ArgumentException(Environment.GetResourceString("Arg_NoStaticVirtual"));
}
if ((attributes & MethodAttributes.SpecialName) != MethodAttributes.SpecialName)
{
if ((type.Attributes & TypeAttributes.Interface) == TypeAttributes.Interface)
{
// methods on interface have to be abstract + virtual except special name methods such as type initializer
if ((attributes & (MethodAttributes.Abstract | MethodAttributes.Virtual)) !=
(MethodAttributes.Abstract | MethodAttributes.Virtual) &&
(attributes & MethodAttributes.Static) == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_BadAttributeOnInterfaceMethod"));
}
}
m_callingConvention = callingConvention;
if (parameterTypes != null)
{
m_parameterTypes = new Type[parameterTypes.Length];
Array.Copy(parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length);
}
else
{
m_parameterTypes = null;
}
m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers;
m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers;
m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
// m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention,
// returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
// parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
m_iAttributes = attributes;
m_bIsGlobalMethod = bIsGlobalMethod;
m_bIsBaked = false;
m_fInitLocals = true;
m_localSymInfo = new LocalSymInfo();
m_ubBody = null;
m_ilGenerator = null;
// Default is managed IL. Manged IL has bit flag 0x0020 set off
m_dwMethodImplFlags = MethodImplAttributes.IL;
}
#endregion
#region Internal Members
internal void CheckContext(params Type[][] typess)
{
m_module.CheckContext(typess);
}
internal void CheckContext(params Type[] types)
{
m_module.CheckContext(types);
}
[System.Security.SecurityCritical] // auto-generated
internal void CreateMethodBodyHelper(ILGenerator il)
{
// Sets the IL of the method. An ILGenerator is passed as an argument and the method
// queries this instance to get all of the information which it needs.
if (il == null)
{
throw new ArgumentNullException("il");
}
Contract.EndContractBlock();
__ExceptionInfo[] excp;
int counter=0;
int[] filterAddrs;
int[] catchAddrs;
int[] catchEndAddrs;
Type[] catchClass;
int[] type;
int numCatch;
int start, end;
ModuleBuilder dynMod = (ModuleBuilder) m_module;
m_containingType.ThrowIfCreated();
if (m_bIsBaked)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodHasBody"));
}
if (il.m_methodBuilder != this && il.m_methodBuilder != null)
{
// you don't need to call DefineBody when you get your ILGenerator
// through MethodBuilder::GetILGenerator.
//
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadILGeneratorUsage"));
}
ThrowIfShouldNotHaveBody();
if (il.m_ScopeTree.m_iOpenScopeCount != 0)
{
// There are still unclosed local scope
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_OpenLocalVariableScope"));
}
m_ubBody = il.BakeByteArray();
m_mdMethodFixups = il.GetTokenFixups();
//Okay, now the fun part. Calculate all of the exceptions.
excp = il.GetExceptions();
int numExceptions = CalculateNumberOfExceptions(excp);
if (numExceptions > 0)
{
m_exceptions = new ExceptionHandler[numExceptions];
for (int i = 0; i < excp.Length; i++)
{
filterAddrs = excp[i].GetFilterAddresses();
catchAddrs = excp[i].GetCatchAddresses();
catchEndAddrs = excp[i].GetCatchEndAddresses();
catchClass = excp[i].GetCatchClass();
numCatch = excp[i].GetNumberOfCatches();
start = excp[i].GetStartAddress();
end = excp[i].GetEndAddress();
type = excp[i].GetExceptionTypes();
for (int j = 0; j < numCatch; j++)
{
int tkExceptionClass = 0;
if (catchClass[j] != null)
{
tkExceptionClass = dynMod.GetTypeTokenInternal(catchClass[j]).Token;
}
switch (type[j])
{
case __ExceptionInfo.None:
case __ExceptionInfo.Fault:
case __ExceptionInfo.Filter:
m_exceptions[counter++] = new ExceptionHandler(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
break;
case __ExceptionInfo.Finally:
m_exceptions[counter++] = new ExceptionHandler(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
break;
}
}
}
}
m_bIsBaked=true;
if (dynMod.GetSymWriter() != null)
{
// set the debugging information such as scope and line number
// if it is in a debug module
//
SymbolToken tk = new SymbolToken(MetadataTokenInternal);
ISymbolWriter symWriter = dynMod.GetSymWriter();
// call OpenMethod to make this method the current method
symWriter.OpenMethod(tk);
// call OpenScope because OpenMethod no longer implicitly creating
// the top-levelsmethod scope
//
symWriter.OpenScope(0);
if (m_symCustomAttrs != null)
{
foreach(SymCustomAttr symCustomAttr in m_symCustomAttrs)
dynMod.GetSymWriter().SetSymAttribute(
new SymbolToken (MetadataTokenInternal),
symCustomAttr.m_name,
symCustomAttr.m_data);
}
if (m_localSymInfo != null)
m_localSymInfo.EmitLocalSymInfo(symWriter);
il.m_ScopeTree.EmitScopeTree(symWriter);
il.m_LineNumberInfo.EmitLineNumberInfo(symWriter);
symWriter.CloseScope(il.ILOffset);
symWriter.CloseMethod();
}
}
// This is only called from TypeBuilder.CreateType after the method has been created
internal void ReleaseBakedStructures()
{
if (!m_bIsBaked)
{
// We don't need to do anything here if we didn't baked the method body
return;
}
m_ubBody = null;
m_localSymInfo = null;
m_mdMethodFixups = null;
m_localSignature = null;
m_exceptions = null;
}
internal override Type[] GetParameterTypes()
{
if (m_parameterTypes == null)
m_parameterTypes = EmptyArray<Type>.Value;
return m_parameterTypes;
}
internal static Type GetMethodBaseReturnType(MethodBase method)
{
MethodInfo mi = null;
ConstructorInfo ci = null;
if ( (mi = method as MethodInfo) != null )
{
return mi.ReturnType;
}
else if ( (ci = method as ConstructorInfo) != null)
{
return ci.GetReturnType();
}
else
{
Contract.Assert(false, "We should never get here!");
return null;
}
}
internal void SetToken(MethodToken token)
{
m_tkMethod = token;
}
internal byte[] GetBody()
{
// Returns the il bytes of this method.
// This il is not valid until somebody has called BakeByteArray
return m_ubBody;
}
internal int[] GetTokenFixups()
{
return m_mdMethodFixups;
}
[System.Security.SecurityCritical] // auto-generated
internal SignatureHelper GetMethodSignature()
{
if (m_parameterTypes == null)
m_parameterTypes = EmptyArray<Type>.Value;
m_signature = SignatureHelper.GetMethodSigHelper (m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0,
m_returnType == null ? typeof(void) : m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers,
m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers);
return m_signature;
}
// Returns a buffer whose initial signatureLength bytes contain encoded local signature.
internal byte[] GetLocalSignature(out int signatureLength)
{
if (m_localSignature != null)
{
signatureLength = m_localSignature.Length;
return m_localSignature;
}
if (m_ilGenerator != null)
{
if (m_ilGenerator.m_localCount != 0)
{
// If user is using ILGenerator::DeclareLocal, then get local signaturefrom there.
return m_ilGenerator.m_localSignature.InternalGetSignature(out signatureLength);
}
}
return SignatureHelper.GetLocalVarSigHelper(m_module).InternalGetSignature(out signatureLength);
}
internal int GetMaxStack()
{
if (m_ilGenerator != null)
{
return m_ilGenerator.GetMaxStackSize() + ExceptionHandlerCount;
}
else
{
// this is the case when client provide an array of IL byte stream rather than going through ILGenerator.
return m_maxStack;
}
}
internal ExceptionHandler[] GetExceptionHandlers()
{
return m_exceptions;
}
internal int ExceptionHandlerCount
{
get { return m_exceptions != null ? m_exceptions.Length : 0; }
}
internal int CalculateNumberOfExceptions(__ExceptionInfo[] excp)
{
int num=0;
if (excp==null)
{
return 0;
}
for (int i=0; i<excp.Length; i++)
{
num+=excp[i].GetNumberOfCatches();
}
return num;
}
internal bool IsTypeCreated()
{
return (m_containingType != null && m_containingType.IsCreated());
}
internal TypeBuilder GetTypeBuilder()
{
return m_containingType;
}
internal ModuleBuilder GetModuleBuilder()
{
return m_module;
}
#endregion
#region Object Overrides
[System.Security.SecuritySafeCritical] // auto-generated
public override bool Equals(Object obj) {
if (!(obj is MethodBuilder)) {
return false;
}
if (!(this.m_strName.Equals(((MethodBuilder)obj).m_strName))) {
return false;
}
if (m_iAttributes!=(((MethodBuilder)obj).m_iAttributes)) {
return false;
}
SignatureHelper thatSig = ((MethodBuilder)obj).GetMethodSignature();
if (thatSig.Equals(GetMethodSignature())) {
return true;
}
return false;
}
public override int GetHashCode()
{
return this.m_strName.GetHashCode();
}
[System.Security.SecuritySafeCritical] // auto-generated
public override String ToString()
{
StringBuilder sb = new StringBuilder(1000);
sb.Append("Name: " + m_strName + " " + Environment.NewLine);
sb.Append("Attributes: " + (int)m_iAttributes + Environment.NewLine);
sb.Append("Method Signature: " + GetMethodSignature() + Environment.NewLine);
sb.Append(Environment.NewLine);
return sb.ToString();
}
#endregion
#region MemberInfo Overrides
public override String Name
{
get
{
return m_strName;
}
}
internal int MetadataTokenInternal
{
get
{
return GetToken().Token;
}
}
public override Module Module
{
get
{
return m_containingType.Module;
}
}
public override Type DeclaringType
{
get
{
if (m_containingType.m_isHiddenGlobalType == true)
return null;
return m_containingType;
}
}
public override ICustomAttributeProvider ReturnTypeCustomAttributes
{
get
{
return null;
}
}
public override Type ReflectedType
{
get
{
return DeclaringType;
}
}
#endregion
#region MethodBase Overrides
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return m_dwMethodImplFlags;
}
public override MethodAttributes Attributes
{
get { return m_iAttributes; }
}
public override CallingConventions CallingConvention
{
get {return m_callingConvention;}
}
public override RuntimeMethodHandle MethodHandle
{
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
}
public override bool IsSecurityCritical
{
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
}
public override bool IsSecuritySafeCritical
{
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
}
public override bool IsSecurityTransparent
{
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
}
#endregion
#region MethodInfo Overrides
public override MethodInfo GetBaseDefinition()
{
return this;
}
public override Type ReturnType
{
get
{
return m_returnType;
}
}
[Pure]
public override ParameterInfo[] GetParameters()
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_TypeNotCreated"));
MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes);
return rmi.GetParameters();
}
public override ParameterInfo ReturnParameter
{
get
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeNotCreated"));
MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes);
return rmi.ReturnParameter;
}
}
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
#endregion
#region Generic Members
public override bool IsGenericMethodDefinition { get { return m_bIsGenMethDef; } }
public override bool ContainsGenericParameters { get { throw new NotSupportedException(); } }
public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); return this; }
public override bool IsGenericMethod { get { return m_inst != null; } }
public override Type[] GetGenericArguments() { return m_inst; }
public override MethodInfo MakeGenericMethod(params Type[] typeArguments)
{
return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments);
}
public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
{
if (names == null)
throw new ArgumentNullException("names");
if (names.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "names");
Contract.EndContractBlock();
if (m_inst != null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GenericParametersAlreadySet"));
for (int i = 0; i < names.Length; i ++)
if (names[i] == null)
throw new ArgumentNullException("names");
if (m_tkMethod.Token != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBuilderBaked"));
m_bIsGenMethDef = true;
m_inst = new GenericTypeParameterBuilder[names.Length];
for (int i = 0; i < names.Length; i ++)
m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this));
return m_inst;
}
internal void ThrowIfGeneric () { if (IsGenericMethod && !IsGenericMethodDefinition) throw new InvalidOperationException (); }
#endregion
#region Public Members
[System.Security.SecuritySafeCritical] // auto-generated
public MethodToken GetToken()
{
// We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498
// we only "tokenize" a method when requested. But the order in which the methods are tokenized
// didn't change: the same order the MethodBuilders are constructed. The recursion introduced
// will overflow the stack when there are many methods on the same type (10000 in my experiment).
// The change also introduced race conditions. Before the code change GetToken is called from
// the MethodBuilder .ctor which is protected by lock(ModuleBuilder.SyncRoot). Now it
// could be called more than once on the the same method introducing duplicate (invalid) tokens.
// I don't fully understand this change. So I will keep the logic and only fix the recursion and
// the race condition.
if (m_tkMethod.Token != 0)
{
return m_tkMethod;
}
MethodBuilder currentMethod = null;
MethodToken currentToken = new MethodToken(0);
int i;
// We need to lock here to prevent a method from being "tokenized" twice.
// We don't need to synchronize this with Type.DefineMethod because it only appends newly
// constructed MethodBuilders to the end of m_listMethods
lock (m_containingType.m_listMethods)
{
if (m_tkMethod.Token != 0)
{
return m_tkMethod;
}
// If m_tkMethod is still 0 when we obtain the lock, m_lastTokenizedMethod must be smaller
// than the index of the current method.
for (i = m_containingType.m_lastTokenizedMethod + 1; i < m_containingType.m_listMethods.Count; ++i)
{
currentMethod = m_containingType.m_listMethods[i];
currentToken = currentMethod.GetTokenNoLock();
if (currentMethod == this)
break;
}
m_containingType.m_lastTokenizedMethod = i;
}
Contract.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods");
Contract.Assert(currentToken.Token != 0, "The token should not be 0");
return currentToken;
}
[System.Security.SecurityCritical] // auto-generated
private MethodToken GetTokenNoLock()
{
Contract.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized");
int sigLength;
byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength);
int token = TypeBuilder.DefineMethod(m_module.GetNativeHandle(), m_containingType.MetadataTokenInternal, m_strName, sigBytes, sigLength, Attributes);
m_tkMethod = new MethodToken(token);
if (m_inst != null)
foreach (GenericTypeParameterBuilder tb in m_inst)
if (!tb.m_type.IsCreated()) tb.m_type.CreateType();
TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), token, m_dwMethodImplFlags);
return m_tkMethod;
}
public void SetParameters (params Type[] parameterTypes)
{
CheckContext(parameterTypes);
SetSignature (null, null, null, parameterTypes, null, null);
}
public void SetReturnType (Type returnType)
{
CheckContext(returnType);
SetSignature (returnType, null, null, null, null, null);
}
public void SetSignature(
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
{
// We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked.
// But we cannot because that would be a breaking change from V2.
if (m_tkMethod.Token != 0)
return;
CheckContext(returnType);
CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes);
CheckContext(parameterTypeRequiredCustomModifiers);
CheckContext(parameterTypeOptionalCustomModifiers);
ThrowIfGeneric();
if (returnType != null)
{
m_returnType = returnType;
}
if (parameterTypes != null)
{
m_parameterTypes = new Type[parameterTypes.Length];
Array.Copy (parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length);
}
m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers;
m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers;
m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
}
[System.Security.SecuritySafeCritical] // auto-generated
public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String strParamName)
{
if (position < 0)
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence"));
Contract.EndContractBlock();
ThrowIfGeneric();
m_containingType.ThrowIfCreated ();
if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length))
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence"));
attributes = attributes & ~ParameterAttributes.ReservedMask;
return new ParameterBuilder(this, position, attributes, strParamName);
}
[System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public void SetMarshal(UnmanagedMarshal unmanagedMarshal)
{
ThrowIfGeneric ();
// set Marshal info for the return type
m_containingType.ThrowIfCreated();
if (m_retParam == null)
{
m_retParam = new ParameterBuilder(this, 0, 0, null);
}
m_retParam.SetMarshal(unmanagedMarshal);
}
private List<SymCustomAttr> m_symCustomAttrs;
private struct SymCustomAttr
{
public SymCustomAttr(String name, byte[] data)
{
m_name = name;
m_data = data;
}
public String m_name;
public byte[] m_data;
}
public void SetSymCustomAttribute(String name, byte[] data)
{
// Note that this API is rarely used. Support for custom attributes in PDB files was added in
// Whidbey and as of 8/2007 the only known user is the C# compiler. There seems to be little
// value to this for Reflection.Emit users since they can always use metadata custom attributes.
// Some versions of the symbol writer used in the CLR will ignore these entirely. This API has
// been removed from the Silverlight API surface area, but we should also consider removing it
// from future desktop product versions as well.
ThrowIfGeneric ();
// This is different from CustomAttribute. This is stored into the SymWriter.
m_containingType.ThrowIfCreated();
ModuleBuilder dynMod = (ModuleBuilder) m_module;
if ( dynMod.GetSymWriter() == null)
{
// Cannot SetSymCustomAttribute when it is not a debug module
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
}
if (m_symCustomAttrs == null)
m_symCustomAttrs = new List<SymCustomAttr>();
m_symCustomAttrs.Add(new SymCustomAttr(name, data));
}
#if FEATURE_CAS_POLICY
[System.Security.SecuritySafeCritical] // auto-generated
public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset)
{
if (pset == null)
throw new ArgumentNullException("pset");
Contract.EndContractBlock();
ThrowIfGeneric ();
#pragma warning disable 618
if (!Enum.IsDefined(typeof(SecurityAction), action) ||
action == SecurityAction.RequestMinimum ||
action == SecurityAction.RequestOptional ||
action == SecurityAction.RequestRefuse)
{
throw new ArgumentOutOfRangeException("action");
}
#pragma warning restore 618
// cannot declarative security after type is created
m_containingType.ThrowIfCreated();
// Translate permission set into serialized format (uses standard binary serialization format).
byte[] blob = null;
int length = 0;
if (!pset.IsEmpty())
{
blob = pset.EncodeXml();
length = blob.Length;
}
// Write the blob into the metadata.
TypeBuilder.AddDeclarativeSecurity(m_module.GetNativeHandle(), MetadataTokenInternal, action, blob, length);
}
#endif // FEATURE_CAS_POLICY
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
{
if (il == null)
{
throw new ArgumentNullException("il", Environment.GetResourceString("ArgumentNull_Array"));
}
if (maxStack < 0)
{
throw new ArgumentOutOfRangeException("maxStack", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
if (m_bIsBaked)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked"));
}
m_containingType.ThrowIfCreated();
ThrowIfGeneric();
byte[] newLocalSignature = null;
ExceptionHandler[] newHandlers = null;
int[] newTokenFixups = null;
byte[] newIL = (byte[])il.Clone();
if (localSignature != null)
{
newLocalSignature = (byte[])localSignature.Clone();
}
if (exceptionHandlers != null)
{
newHandlers = ToArray(exceptionHandlers);
CheckExceptionHandlerRanges(newHandlers, newIL.Length);
// Note: Fixup entries for type tokens stored in ExceptionHandlers are added by the method body emitter.
}
if (tokenFixups != null)
{
newTokenFixups = ToArray(tokenFixups);
int maxTokenOffset = newIL.Length - 4;
for (int i = 0; i < newTokenFixups.Length; i++)
{
// Check that fixups are within the range of this method's IL, otherwise some random memory might get "fixed up".
if (newTokenFixups[i] < 0 || newTokenFixups[i] > maxTokenOffset)
{
throw new ArgumentOutOfRangeException("tokenFixups[" + i + "]", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, maxTokenOffset));
}
}
}
m_ubBody = newIL;
m_localSignature = newLocalSignature;
m_exceptions = newHandlers;
m_mdMethodFixups = newTokenFixups;
m_maxStack = maxStack;
// discard IL generator, all information stored in it is now irrelevant
m_ilGenerator = null;
m_bIsBaked = true;
}
private static T[] ToArray<T>(IEnumerable<T> sequence)
{
T[] array = sequence as T[];
if (array != null)
{
return (T[])array.Clone();
}
return new List<T>(sequence).ToArray();
}
private static void CheckExceptionHandlerRanges(ExceptionHandler[] exceptionHandlers, int maxOffset)
{
// Basic checks that the handler ranges are within the method body (ranges are end-exclusive).
// Doesn't verify that the ranges are otherwise correct - it is very well possible to emit invalid IL.
for (int i = 0; i < exceptionHandlers.Length; i++)
{
var handler = exceptionHandlers[i];
if (handler.m_filterOffset > maxOffset || handler.m_tryEndOffset > maxOffset || handler.m_handlerEndOffset > maxOffset)
{
throw new ArgumentOutOfRangeException("exceptionHandlers[" + i + "]", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, maxOffset));
}
// Type token might be 0 if the ExceptionHandler was created via a default constructor.
// Other tokens migth also be invalid. We only check nil tokens as the implementation (SectEH_Emit in corhlpr.cpp) requires it,
// and we can't check for valid tokens until the module is baked.
if (handler.Kind == ExceptionHandlingClauseOptions.Clause && handler.ExceptionTypeToken == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", handler.ExceptionTypeToken), "exceptionHandlers[" + i + "]");
}
}
}
/// <summary>
/// Obsolete.
/// </summary>
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public void CreateMethodBody(byte[] il, int count)
{
ThrowIfGeneric();
// Note that when user calls this function, there are a few information that client is
// not able to supply: local signature, exception handlers, max stack size, a list of Token fixup, a list of RVA fixup
if (m_bIsBaked)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked"));
}
m_containingType.ThrowIfCreated();
if (il != null && (count < 0 || count > il.Length))
{
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (il == null)
{
m_ubBody = null;
return;
}
m_ubBody = new byte[count];
Buffer.BlockCopy(il, 0, m_ubBody, 0, count);
m_localSignature = null;
m_exceptions = null;
m_mdMethodFixups = null;
m_maxStack = DefaultMaxStack;
m_bIsBaked = true;
}
[System.Security.SecuritySafeCritical] // auto-generated
public void SetImplementationFlags(MethodImplAttributes attributes)
{
ThrowIfGeneric ();
m_containingType.ThrowIfCreated ();
m_dwMethodImplFlags = attributes;
m_canBeRuntimeImpl = true;
TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), MetadataTokenInternal, attributes);
}
public ILGenerator GetILGenerator() {
Contract.Ensures(Contract.Result<ILGenerator>() != null);
ThrowIfGeneric();
ThrowIfShouldNotHaveBody();
if (m_ilGenerator == null)
m_ilGenerator = new ILGenerator(this);
return m_ilGenerator;
}
public ILGenerator GetILGenerator(int size) {
Contract.Ensures(Contract.Result<ILGenerator>() != null);
ThrowIfGeneric ();
ThrowIfShouldNotHaveBody();
if (m_ilGenerator == null)
m_ilGenerator = new ILGenerator(this, size);
return m_ilGenerator;
}
private void ThrowIfShouldNotHaveBody() {
if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL ||
(m_dwMethodImplFlags & MethodImplAttributes.Unmanaged) != 0 ||
(m_iAttributes & MethodAttributes.PinvokeImpl) != 0 ||
m_isDllImport)
{
// cannot attach method body if methodimpl is marked not marked as managed IL
//
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ShouldNotHaveMethodBody"));
}
}
public bool InitLocals
{
// Property is set to true if user wishes to have zero initialized stack frame for this method. Default to false.
get { ThrowIfGeneric (); return m_fInitLocals; }
set { ThrowIfGeneric (); m_fInitLocals = value; }
}
public Module GetModule()
{
return GetModuleBuilder();
}
public String Signature
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return GetMethodSignature().ToString();
}
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
throw new ArgumentNullException("con");
if (binaryAttribute == null)
throw new ArgumentNullException("binaryAttribute");
Contract.EndContractBlock();
ThrowIfGeneric();
TypeBuilder.DefineCustomAttribute(m_module, MetadataTokenInternal,
((ModuleBuilder)m_module).GetConstructorToken(con).Token,
binaryAttribute,
false, false);
if (IsKnownCA(con))
ParseCA(con, binaryAttribute);
}
[System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
throw new ArgumentNullException("customBuilder");
Contract.EndContractBlock();
ThrowIfGeneric();
customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataTokenInternal);
if (IsKnownCA(customBuilder.m_con))
ParseCA(customBuilder.m_con, customBuilder.m_blob);
}
// this method should return true for any and every ca that requires more work
// than just setting the ca
private bool IsKnownCA(ConstructorInfo con)
{
Type caType = con.DeclaringType;
if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) return true;
else if (caType == typeof(DllImportAttribute)) return true;
else return false;
}
private void ParseCA(ConstructorInfo con, byte[] blob)
{
Type caType = con.DeclaringType;
if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute))
{
// dig through the blob looking for the MethodImplAttributes flag
// that must be in the MethodCodeType field
// for now we simply set a flag that relaxes the check when saving and
// allows this method to have no body when any kind of MethodImplAttribute is present
m_canBeRuntimeImpl = true;
}
else if (caType == typeof(DllImportAttribute)) {
m_canBeRuntimeImpl = true;
m_isDllImport = true;
}
}
internal bool m_canBeRuntimeImpl = false;
internal bool m_isDllImport = false;
#endregion
#if !FEATURE_CORECLR
void _MethodBuilder.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _MethodBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _MethodBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
internal class LocalSymInfo
{
// This class tracks the local variable's debugging information
// and namespace information with a given active lexical scope.
#region Internal Data Members
internal String[] m_strName;
internal byte[][] m_ubSignature;
internal int[] m_iLocalSlot;
internal int[] m_iStartOffset;
internal int[] m_iEndOffset;
internal int m_iLocalSymCount; // how many entries in the arrays are occupied
internal String[] m_namespace;
internal int m_iNameSpaceCount;
internal const int InitialSize = 16;
#endregion
#region Constructor
internal LocalSymInfo()
{
// initialize data variables
m_iLocalSymCount = 0;
m_iNameSpaceCount = 0;
}
#endregion
#region Private Members
private void EnsureCapacityNamespace()
{
if (m_iNameSpaceCount == 0)
{
m_namespace = new String[InitialSize];
}
else if (m_iNameSpaceCount == m_namespace.Length)
{
String [] strTemp = new String [checked(m_iNameSpaceCount * 2)];
Array.Copy(m_namespace, 0, strTemp, 0, m_iNameSpaceCount);
m_namespace = strTemp;
}
}
private void EnsureCapacity()
{
if (m_iLocalSymCount == 0)
{
// First time. Allocate the arrays.
m_strName = new String[InitialSize];
m_ubSignature = new byte[InitialSize][];
m_iLocalSlot = new int[InitialSize];
m_iStartOffset = new int[InitialSize];
m_iEndOffset = new int[InitialSize];
}
else if (m_iLocalSymCount == m_strName.Length)
{
// the arrays are full. Enlarge the arrays
// why aren't we just using lists here?
int newSize = checked(m_iLocalSymCount * 2);
int[] temp = new int [newSize];
Array.Copy(m_iLocalSlot, 0, temp, 0, m_iLocalSymCount);
m_iLocalSlot = temp;
temp = new int [newSize];
Array.Copy(m_iStartOffset, 0, temp, 0, m_iLocalSymCount);
m_iStartOffset = temp;
temp = new int [newSize];
Array.Copy(m_iEndOffset, 0, temp, 0, m_iLocalSymCount);
m_iEndOffset = temp;
String [] strTemp = new String [newSize];
Array.Copy(m_strName, 0, strTemp, 0, m_iLocalSymCount);
m_strName = strTemp;
byte[][] ubTemp = new byte[newSize][];
Array.Copy(m_ubSignature, 0, ubTemp, 0, m_iLocalSymCount);
m_ubSignature = ubTemp;
}
}
#endregion
#region Internal Members
internal void AddLocalSymInfo(String strName,byte[] signature,int slot,int startOffset,int endOffset)
{
// make sure that arrays are large enough to hold addition info
EnsureCapacity();
m_iStartOffset[m_iLocalSymCount] = startOffset;
m_iEndOffset[m_iLocalSymCount] = endOffset;
m_iLocalSlot[m_iLocalSymCount] = slot;
m_strName[m_iLocalSymCount] = strName;
m_ubSignature[m_iLocalSymCount] = signature;
checked {m_iLocalSymCount++; }
}
internal void AddUsingNamespace(String strNamespace)
{
EnsureCapacityNamespace();
m_namespace[m_iNameSpaceCount] = strNamespace;
checked { m_iNameSpaceCount++; }
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal virtual void EmitLocalSymInfo(ISymbolWriter symWriter)
{
int i;
for (i = 0; i < m_iLocalSymCount; i ++)
{
symWriter.DefineLocalVariable(
m_strName[i],
FieldAttributes.PrivateScope,
m_ubSignature[i],
SymAddressKind.ILOffset,
m_iLocalSlot[i],
0, // addr2 is not used yet
0, // addr3 is not used
m_iStartOffset[i],
m_iEndOffset[i]);
}
for (i = 0; i < m_iNameSpaceCount; i ++)
{
symWriter.UsingNamespace(m_namespace[i]);
}
}
#endregion
}
/// <summary>
/// Describes exception handler in a method body.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
[ComVisible(false)]
public struct ExceptionHandler : IEquatable<ExceptionHandler>
{
// Keep in sync with unmanged structure.
internal readonly int m_exceptionClass;
internal readonly int m_tryStartOffset;
internal readonly int m_tryEndOffset;
internal readonly int m_filterOffset;
internal readonly int m_handlerStartOffset;
internal readonly int m_handlerEndOffset;
internal readonly ExceptionHandlingClauseOptions m_kind;
public int ExceptionTypeToken
{
get { return m_exceptionClass; }
}
public int TryOffset
{
get { return m_tryStartOffset; }
}
public int TryLength
{
get { return m_tryEndOffset - m_tryStartOffset; }
}
public int FilterOffset
{
get { return m_filterOffset; }
}
public int HandlerOffset
{
get { return m_handlerStartOffset; }
}
public int HandlerLength
{
get { return m_handlerEndOffset - m_handlerStartOffset; }
}
public ExceptionHandlingClauseOptions Kind
{
get { return m_kind; }
}
#region Constructors
/// <summary>
/// Creates a description of an exception handler.
/// </summary>
/// <param name="tryOffset">The offset of the first instruction protected by this handler.</param>
/// <param name="tryLength">The number of bytes protected by this handler.</param>
/// <param name="filterOffset">The filter code begins at the specified offset and ends at the first instruction of the handler block. Specify 0 if not applicable (this is not a filter handler).</param>
/// <param name="handlerOffset">The offset of the first instruction of this handler.</param>
/// <param name="handlerLength">The number of bytes of the handler.</param>
/// <param name="kind">The kind of handler, the handler might be a catch handler, filter handler, fault handler, or finally handler.</param>
/// <param name="exceptionTypeToken">The token of the exception type handled by this handler. Specify 0 if not applicable (this is finally handler).</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Some of the instruction offset is negative,
/// the end offset of specified range is less than its start offset,
/// or <paramref name="kind"/> has an invalid value.
/// </exception>
public ExceptionHandler(int tryOffset, int tryLength, int filterOffset, int handlerOffset, int handlerLength,
ExceptionHandlingClauseOptions kind, int exceptionTypeToken)
{
if (tryOffset < 0)
{
throw new ArgumentOutOfRangeException("tryOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (tryLength < 0)
{
throw new ArgumentOutOfRangeException("tryLength", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (filterOffset < 0)
{
throw new ArgumentOutOfRangeException("filterOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (handlerOffset < 0)
{
throw new ArgumentOutOfRangeException("handlerOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (handlerLength < 0)
{
throw new ArgumentOutOfRangeException("handlerLength", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if ((long)tryOffset + tryLength > Int32.MaxValue)
{
throw new ArgumentOutOfRangeException("tryLength", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - tryOffset));
}
if ((long)handlerOffset + handlerLength > Int32.MaxValue)
{
throw new ArgumentOutOfRangeException("handlerLength", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - handlerOffset));
}
// Other tokens migth also be invalid. We only check nil tokens as the implementation (SectEH_Emit in corhlpr.cpp) requires it,
// and we can't check for valid tokens until the module is baked.
if (kind == ExceptionHandlingClauseOptions.Clause && (exceptionTypeToken & 0x00FFFFFF) == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", exceptionTypeToken), "exceptionTypeToken");
}
Contract.EndContractBlock();
if (!IsValidKind(kind))
{
throw new ArgumentOutOfRangeException("kind", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
}
m_tryStartOffset = tryOffset;
m_tryEndOffset = tryOffset + tryLength;
m_filterOffset = filterOffset;
m_handlerStartOffset = handlerOffset;
m_handlerEndOffset = handlerOffset + handlerLength;
m_kind = kind;
m_exceptionClass = exceptionTypeToken;
}
internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset,
int kind, int exceptionTypeToken)
{
Contract.Assert(tryStartOffset >= 0);
Contract.Assert(tryEndOffset >= 0);
Contract.Assert(filterOffset >= 0);
Contract.Assert(handlerStartOffset >= 0);
Contract.Assert(handlerEndOffset >= 0);
Contract.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind));
Contract.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0);
m_tryStartOffset = tryStartOffset;
m_tryEndOffset = tryEndOffset;
m_filterOffset = filterOffset;
m_handlerStartOffset = handlerStartOffset;
m_handlerEndOffset = handlerEndOffset;
m_kind = (ExceptionHandlingClauseOptions)kind;
m_exceptionClass = exceptionTypeToken;
}
private static bool IsValidKind(ExceptionHandlingClauseOptions kind)
{
switch (kind)
{
case ExceptionHandlingClauseOptions.Clause:
case ExceptionHandlingClauseOptions.Filter:
case ExceptionHandlingClauseOptions.Finally:
case ExceptionHandlingClauseOptions.Fault:
return true;
default:
return false;
}
}
#endregion
#region Equality
public override int GetHashCode()
{
return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind;
}
public override bool Equals(Object obj)
{
return obj is ExceptionHandler && Equals((ExceptionHandler)obj);
}
public bool Equals(ExceptionHandler other)
{
return
other.m_exceptionClass == m_exceptionClass &&
other.m_tryStartOffset == m_tryStartOffset &&
other.m_tryEndOffset == m_tryEndOffset &&
other.m_filterOffset == m_filterOffset &&
other.m_handlerStartOffset == m_handlerStartOffset &&
other.m_handlerEndOffset == m_handlerEndOffset &&
other.m_kind == m_kind;
}
public static bool operator ==(ExceptionHandler left, ExceptionHandler right)
{
return left.Equals(right);
}
public static bool operator !=(ExceptionHandler left, ExceptionHandler right)
{
return !left.Equals(right);
}
#endregion
}
}
| |
// PhysX Plug-in
//
// Copyright 2015 University of Central Florida
//
//
// This plug-in uses NVIDIA's PhysX library to handle physics for OpenSim.
// Its goal is to provide all the functions that the Bullet plug-in does.
//
//
// 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.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.CoreModules;
using OpenSim.Region.Framework;
using OpenSim.Region.Physics.Manager;
using Logging = OpenSim.Region.CoreModules.Framework.Statistics.Logging;
using Nini.Config;
using log4net;
using OpenMetaverse;
using System.Security;
namespace OpenSim.Region.Physics.PhysXPlugin
{
/// <summary>
/// A scene which represents the collection of physics objects found in
/// a designated region of the OpenSim instance. The scene will simulate
/// the behavior of the objects over time.
/// </summary>
public sealed class PxScene : PhysicsScene, IPhysicsParameters
{
#region Fields
/// <summary>
/// Keep track of all physical objects added to the scene.
/// The unique ID, from OpenSim, is used as the key.
/// </summary>
public Dictionary<uint, PxPhysObject> m_physObjectsDict;
/// <summary>
/// Keep track of all the avatars so we can send them a collision event
/// every tick to update the animations of OpenSim.
/// </summary>
public HashSet<PxPhysObject> m_avatarsSet;
/// <summary>
/// Keep track of all the objects with collisions so we can report
/// the beginning and end of a collision.
/// </summary>
public HashSet<PxPhysObject> m_objectsWithCollisions =
new HashSet<PxPhysObject>();
/// <summary>
/// Keep track of all the objects with NO collisions so we can report
/// to the avatars their proper collisions.
/// </summary>
public HashSet<PxPhysObject> m_objectWithNoMoreCollisions =
new HashSet<PxPhysObject>();
/// <summary>
/// Keeps track of the current objects that have been updated during
/// this step of the simulation.
/// <summary>
public HashSet<PxPhysObject> m_updatedObjects = new
HashSet<PxPhysObject>();
/// <summary>
/// Keeps track of the objects that were updated during the last
/// step of the simulation. Objects that occur during the current step
/// of the simulation are removed from this list to find any objects
/// that no longer are updating. In this way locating objects that have
/// ceased moving can be found and set their velocities to zero.
/// </summary>
public HashSet<PxPhysObject> m_lastUpdatedObjects = new
HashSet<PxPhysObject>();
/// <summary>
/// The logger for this plugin.
/// </summary>
internal static readonly ILog m_log = LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Header used for logger to highlight logs made in this plugin.
/// </summary>
internal static readonly string LogHeader = "[PHYSX SCENE]";
/// <summary>
/// Indicates an invalid time step; used to denote events that have not
/// occurred.
/// </summary>
public static readonly int InvalidTime = -1;
/// <summary>
/// Pinned memory that passes updated entity properties sent
/// by PhysX.
/// </summary>
internal EntityProperties[] m_updateArray;
/// <summary>
/// Pinned memory that passes updated collision properties sent
/// by PhysX.
/// </summary>
internal CollisionProperties[] m_collisionArray;
/// <summary>
/// States whether the PhysX engine is initialized and ready to do
/// simulation steps.
/// </summary>
private bool m_isInitialized = false;
/// <summary>
/// The next available unique joint identifier.
/// </summary>
private uint m_nextJointID = 1;
/// <summary>
/// The water height declared statically throughout the scene.
/// </summary>
private float m_waterHeight = 21.0f;
/// <summary>
/// The next available unique shape identifier.
/// </summary>
private uint m_nextShapeID = 1;
/// <summary>
/// The ID used when creating the terrain shape from a height field.
/// </summary>
private const uint TERRAIN_ACTOR_ID = 0;
/// <summary>
/// The unique identifier used for the height field shape of the
/// terrain. Will be generated at terrain creation time.
/// </summary>
private uint m_terrainShapeID;
/// <summary>
/// A library of various material archetypes and their physical
/// properties.
/// </summary>
public PxMaterialLibrary MaterialLibrary { get; private set; }
/// <summary>
/// The size of the region.
/// </summary>
private Vector3 m_regionExtents;
/// <summary>
/// A value of time given by the Util class that allows for easier
/// access when synchronizing collisions and updates for the prims and
/// avatars.
/// </summary>
public int m_simulationTime;
/// <summary>
/// A dictionary containing tainted objects that need to be rebuilt
/// before the next simulation step.
/// </summary>
private ConcurrentDictionary<uint, PxPhysObject> m_taintedObjects =
new ConcurrentDictionary<uint, PxPhysObject>();
#endregion Fields
#region Delegates
/// <summary>
/// Delegate method to handle the updates to the different vehicle and
/// prim actors before updating PhysX.
/// </summary>
public delegate void PreStepAction(float timeStep);
/// <summary>
/// List of PreStepActions to take before running the PhysX update.
/// </summary>
public event PreStepAction BeforeStep;
/// <summary>
/// Delegate method to handle the updates to the different vehicle and
/// prim actors after updating PhysX.
/// </summary>
public delegate void PostStepAction(float timeStep);
/// <summary>
/// List of PostStepActions to take after running the PhysX update.
/// </summary>
public event PostStepAction AfterStep;
#endregion
#region Properties
/// <summary>
/// The name of the region that we're working for.
/// </summary>
public string RegionName { get; private set; }
/// <summary>
/// Interface to the PhysX implementation.
/// </summary>
public PxAPIManager PhysX { get; private set; }
/// <summary>
/// The mesher used to convert shape descriptions to meshes.
/// </summary>
public IMesher SceneMesher { get; private set; }
/// <summary>
/// The configuration that will be used in initializing this plugin.
/// </summary>
public PxConfiguration UserConfig { get; private set; }
/// <summary>
/// Identifier used to represent the terrain in the physics engine.
/// </summary>
public int TerrainID
{
get
{
// Return the unique identifier of the terrain
return (int) TERRAIN_ACTOR_ID;
}
}
/// <summary>
/// Getter and setter for the water height within the scene
/// used to help calculate and determine buoyancy.
/// </summary>
public float WaterHeight
{
get
{
return m_waterHeight;
}
protected set
{
m_waterHeight = value;
}
}
#endregion Properties
#region Construction and Initialization
/// <summary>
/// Constructor for the PhysX scene.
/// </summary>
/// <param name="engineType">Name of physics engine</param>
/// <param name="name">Name of region</param>
/// <param name="physX">PhysX class interface</param>
public PxScene(string engineType, string name, PxAPIManager physX)
{
// The name of the region that we're working for is passed to us;
// keep for identification
RegionName = name;
// Set the identifying variables in the PhysicsScene interface
EngineType = engineType;
Name = EngineType + "/" + RegionName;
// Save reference to the PhysX interface for future calls to the
// PhysX engine
PhysX = physX;
// Create the configuration with default values
UserConfig = new PxConfiguration();
}
/// <summary>
/// Method to set up the intial values of necessary variables.
/// </summary>
/// <param name="meshmerizer">Mesher used for creating meshes from
/// shape descriptions</param>
/// <param name="config">Configuration file that will load the initial
/// values set up inside of TBD</param>
public override void Initialise(
IMesher meshmerizer, IConfigSource config)
{
Vector3 regionExtent;
// Create region extents based on the old assigned values of
// 256x256
// NOTE: This is for older versions of OpenSim that doesn't send the
// size of the region when creating it
// NOTE: The third value is not used and is assigned arbitrarily to
// match the value BulletSim used, it is here to match the override
// method of Initialise inside of the PhysicsScene class
regionExtent = new Vector3(Constants.RegionSize,
Constants.RegionSize, Constants.RegionSize);
// Call the actual initialization method with the new extents
Initialise(meshmerizer, config, regionExtent);
}
/// <summary>
/// Method to set up the initial values of necessary variables.
/// <summary>
/// <param name="meshmerizer">Mesher used for creating meshes from
/// shape descriptions</param>
/// <param name="config">Configuration file that will load the initial
/// values set up inside of TBD</param>
/// <param name="regionExtent">The size of the region which will either
/// be the basic 256 by 256 or a value given by the scene class</param>
public override void Initialise(IMesher meshmerizer,
IConfigSource config, Vector3 regionExtent)
{
// Get the PhysX configuration section
IConfig physicsConfig = config.Configs["PhysX"];
// Create the configuration using the user given values inside
// of the PhysX.ini file located in the bin/config-include
UserConfig.Initialize(physicsConfig);
// Create the PhysX scene that will be used to represent the
// region; all physics objects will be depicted in this scene;
PhysX.CreateScene(UserConfig.GPUEnabled, UserConfig.CPUMaxThreads);
// Create the initial ground plane for the physics engine
PhysX.CreateGroundPlane(0.0f, 0.0f, -500.0f);
// The scene has now been initialized
m_isInitialized = true;
// Initialize the mesher
SceneMesher = meshmerizer;
// Store the size of the region for use with height field
// generation
m_regionExtents = regionExtent;
// New dictionary to keep track of physical objects
// added to the scene
m_physObjectsDict = new Dictionary<uint, PxPhysObject>();
// New dictionary to keep track of avatars that need to send a
// collision update for OpenSim to update animations
m_avatarsSet = new HashSet<PxPhysObject>();
// Allocate memory for returning of the updates from the
// physics engine and send data to the PhysX engine
m_updateArray = new EntityProperties[
UserConfig.MaxUpdatesPerFrame];
PhysX.InitEntityUpdate(ref m_updateArray,
UserConfig.MaxUpdatesPerFrame);
// Allocate memory for returning of the collisions
// from the physics engine and send data to the PhysX engine
m_collisionArray =
new CollisionProperties[UserConfig.MaxCollisionsPerFrame];
PhysX.InitCollisionUpdate(
ref m_collisionArray, UserConfig.MaxCollisionsPerFrame);
// Create the material library that will track various material
// archetypes
MaterialLibrary = new PxMaterialLibrary(UserConfig);
}
#endregion Construction and Initialization
#region Prim and Avatar addition and removal
/// <summary>
/// This function is not currently implemented please use the AddAvatar
/// that include the localID as this is necessary to uniquely identify
/// the physical object.
/// </summary>
/// <param name="avName"></param>
/// <param name="position">The current position of the new user avatar
/// inside of the scene</param>
/// <param name="velocity">The current velocity of the new user avatar
/// inside of the scene</param>
/// <param name="size">The size of the new user avatar, that will be
/// used to scale the physical object</param>
/// <param name="isFlying">A flag that determines if the user's
/// physical object avatar is currently flying</param>
/// <returns>A null value as this function is not currently implemented
/// </returns>
public override PhysicsActor AddAvatar(string avName, Vector3 position,
Vector3 velocity, Vector3 size, bool isFlying)
{
// This function is being ignored, because we need the unique ID to
// identify the physics actor
return null;
}
/// <summary>
/// This function will add a user's avatar to the physics plugin.
/// </summary>
/// <param name="localID">The unique ID used by OpenSim to track the
/// physical objects inside of the world</param>
/// <param name="avName">Given name of the avatar</param>
/// <param name="position">The current position of the new user avatar
/// inside of the scene</param>
/// <param name="velocity">The current velocity of the new user avatar
/// inside of the scene</param>
/// <param name="size">The size of the new user avatar, that will be
/// used to scale the physical object</param>
/// <param name="isFlying">A flag that determines if the user's
/// physical object avatar is currently flying</param>
/// <returns>The physical object that was added to the physics engine
/// that will represent the user's avatar</returns>
public override PhysicsActor AddAvatar(uint localID, string avName,
Vector3 position, Vector3 velocity, Vector3 size, bool isFlying)
{
// Can't add avatar if the scene hasn't been initialized yet
if (!m_isInitialized)
return null;
// Create a physical object to represent the user avatar
PxPhysObject actor = new PxPhysObject(
localID, avName, this, position, velocity, size, isFlying);
// Add the new actor to the dictionary of all physical objects;
// lock dictionary to ensure no changes are made during addition
lock (m_physObjectsDict)
{
m_physObjectsDict.Add(localID, actor);
}
// Add the new avatar to the avatar dictionary to make sure that
// OpenSim updates the animations for the avatars, specific to the
// avatar sending the collision event
lock (m_avatarsSet)
{
m_avatarsSet.Add(actor);
}
// Give OpenSim a handle to the physical object of the user's
// physical object
return actor;
}
/// <summary>
/// Remove a user avatar from the physical objects inside of the
/// physics engine.
/// </summary>
/// <param name="actor">The user's physical object that represents the
/// user's avatar inside of the physics engine that is to be removed
/// from the scene</param>
public override void RemoveAvatar(PhysicsActor actor)
{
PxPhysObject pxActor;
// Make sure the scene has been initialized before removing avatar
if (!m_isInitialized)
{
return;
}
// Cast the abstract class to the specific PhysX class
pxActor = actor as PxPhysObject;
// Check that the actor was cast succesfully
if (pxActor != null)
{
// Tell PhysX to remove this actor from the scene
PhysX.RemoveActor(pxActor.LocalID);
// Prevent updates being made to the object dictionary
lock (m_physObjectsDict)
{
// Remove object from the dictionary; if removal
// was unsuccessful, say so
if (m_physObjectsDict.Remove(pxActor.LocalID) == false)
{
m_log.WarnFormat("{0}: Attempted to remove avatar " +
"that is not in the physics scene", LogHeader);
}
}
// Prevent updates being made to the avatar set
lock (m_avatarsSet)
{
// Remove the avatar from the dictionary
if (m_avatarsSet.Remove(pxActor) == false)
{
// Warn the user that the avatar was unable to be
// removed from the avatar list
m_log.WarnFormat("{0}: Attempted to remove avatar " +
"from the avatar list and it didn't exist.",
LogHeader);
}
else
{
// Clean up the actor
pxActor.Destroy();
}
}
}
else
{
// Log that the given actor could not be removed
m_log.ErrorFormat("{0}: Requested to remove avatar that is " +
"not a Physics Object", LogHeader);
}
}
/// <summary>
/// Add a new prim object to the scene.
/// </summary>
/// <param name="primName">Given name of the prim object</param>
/// <param name="pbs">Basic prim shape info used for
/// determining the object's mass and geometry</param>
/// <param name="position">Current position of the new prim inside
/// the scene</param>
/// <param name="size">Size of the new avatar, that will be used
/// to scale the physical object</param>
/// <param name="rotation">Current rotation of the new prim
/// inside the scene</param>
/// <param name="isPhysical">Whether the prim should react
/// to forces and collisions</param>
/// <param name="localid">The unique ID used to track the object
/// inside of the world</param>
public override PhysicsActor AddPrimShape(string primName,
PrimitiveBaseShape pbs, Vector3 position, Vector3 size,
Quaternion rotation, bool isPhysical, uint localid)
{
// Can't add prim if the scene hasn't been initialized yet
if (!m_isInitialized)
{
m_log.ErrorFormat("{0}: Unable to create prim shape because " +
"PxScene has not been initialized.", LogHeader);
return null;
}
// Create a physical object to represent the primitive object
PxPhysObject prim = new PxPhysObject(localid, primName, this,
position, size, rotation, pbs, isPhysical);
// Lock dictionary to ensure no changes are made during addition
lock (m_physObjectsDict)
{
// Add the new prim to the dictionary of all physical objects
m_physObjectsDict.Add(localid, prim);
}
// Give OpenSim a handle to the physical object of the prim
return prim;
}
/// <summary>
/// Remove a pimitive, by value, from the scene.
/// </summary>
public override void RemovePrim(PhysicsActor prim)
{
PxPhysObject pxPrim;
// Make sure the scene has been initialized before removing avatar
if (!m_isInitialized)
{
return;
}
// Cast the abstract class to the specific PhysX class
pxPrim = prim as PxPhysObject;
// Check that the actor was cast succesfully
if (pxPrim != null)
{
// Clean up the prim's associated PhysX objects
pxPrim.Destroy();
// Prevent updates being made to the object dictionary
lock (m_physObjectsDict)
{
// Remove object from the dictionary; if removal
// was unsuccessful, say so
if (m_physObjectsDict.Remove(pxPrim.LocalID) == false)
{
m_log.WarnFormat("{0}: Attempted to remove avatar " +
"that is not in the physics scene", LogHeader);
}
}
}
else
{
// Log that the given actor could not be removed
m_log.ErrorFormat("{0}: Requested to remove avatar that is " +
"not a Physics Object", LogHeader);
}
}
public override void AddPhysicsActorTaint(PhysicsActor prim)
{
}
/// <summary>
/// Returns the next available unique joint identifier for this scene.
/// </summary>
public uint GetNewJointID()
{
uint newID;
// Fetch the next available unique joint identifier and
// update the next one
newID = m_nextJointID;
m_nextJointID++;
// Return the new joint identifier
return newID;
}
/// <summary>
/// Returns the next available unique shape identifier for this scene.
/// </summary>
public uint GetNewShapeID()
{
uint newID;
// Fetch the next available unique shape identifier and update
// the next one
newID = m_nextShapeID;
m_nextShapeID++;
// Return the new shape identifier
return newID;
}
#endregion Prim and Avatar addition and removal
#region Simulation
/// <summary>
/// After the simulation has occured, pass the updates to the OpenSim
/// PxPhysObjects for this scene.
/// </summary>
public void SimulateUpdatedEntities(uint updatedEntityCount)
{
EntityProperties entityProperties;
PxPhysObject physObject;
// Lock the dictionary of physical objects to prevent
// any changes while the objects are being updated
lock (m_physObjectsDict)
{
// Go through the list of updated entities
for (int i = 0; i < updatedEntityCount; i++)
{
// Grab the set of properties for the current
// physical object; this data is updated and sent
// from the PhysX engine
entityProperties = m_updateArray[i];
// Check to make sure that we're keeping track
// of this object
if (m_physObjectsDict.TryGetValue(
entityProperties.ID, out physObject) == true)
{
// Update the physical properties, that were
// sent from PhysX, for OpenSim to match
physObject.UpdateProperties(entityProperties);
// Ask the scene to update the position for
// all physical objects that have been updated
physObject.RequestPhysicsterseUpdate();
// Add the physical object to the list of objects that
// were updated during this timestep
m_updatedObjects.Add(physObject);
// Attempt to remove the updated object from the
// previous list of updated objects
// NOTE: Remove will only return false if the object
// could not be found, no crash or error message will
// occur
m_lastUpdatedObjects.Remove(physObject);
}
}
// Go through all of the objects that were updated during the
// last simulation step, but were not updated during this
// simulation step
foreach (PxPhysObject obj in m_lastUpdatedObjects)
{
// Build an update for the object that sets the velocity of
// the object to 0
entityProperties.ID = obj.LocalID;
entityProperties.PositionX = obj.Position.X;
entityProperties.PositionY = obj.Position.Y;
entityProperties.PositionZ = obj.Position.Z;
entityProperties.RotationX = obj.Orientation.X;
entityProperties.RotationY = obj.Orientation.Y;
entityProperties.RotationZ = obj.Orientation.Z;
entityProperties.RotationW = obj.Orientation.W;
entityProperties.VelocityX = 0.0f;
entityProperties.VelocityY = 0.0f;
entityProperties.VelocityZ = 0.0f;
entityProperties.AngularVelocityX = 0.0f;
entityProperties.AngularVelocityY = 0.0f;
entityProperties.AngularVelocityZ = 0.0f;
// Update the object with the new velocity in order to
// prevent viewers from changing the position of the
// object
obj.UpdateProperties(entityProperties);
// Send the updated values to OpenSim which will use the
// SendScheduledUpdates call inside of SceneObjectPart to
// send the information to a viewer
obj.RequestPhysicsterseUpdate();
}
// Clear all the updates from the list now that they have been
// updated with a zero velocity
m_lastUpdatedObjects.Clear();
// Loop through all of the objects updated during this time
// step and add them to the list of previously updated list
foreach (PxPhysObject obj in m_updatedObjects)
{
m_lastUpdatedObjects.Add(obj);
}
// Remove all objects from the list now that they are stored in
// the previous timestep list
m_updatedObjects.Clear();
}
}
/// <summary>
/// After the simulation has occured, simulate and update entities
/// in OpenSim by allowing OpenSim to handle the collisions.
/// </summary>
/// <param name="updatedCollisionCount">The number of collisions that
/// have occured in the last simulation step.</param>
public void SimulateUpdatedCollisions(uint updatedCollisionCount)
{
CollisionProperties collisionProperties;
uint localID;
uint collidingWith;
float penetration;
Vector3 collidePoint;
Vector3 collideNormal;
// Lock the collision array so that no collisions can be modified
lock (m_collisionArray)
{
// Iterate through the list of update collisions
for (int i = 0; i < updatedCollisionCount; i++)
{
// Grab the set of properties for the current
// physical object; this data is sent to OpenSim
// for processing
collisionProperties = m_collisionArray[i];
// Form instances of the vectors and such to be
// passed to the "SendCollision" method
localID = collisionProperties.ActorId1;
collidingWith = collisionProperties.ActorId2;
collidePoint =
new Vector3(collisionProperties.PositionX,
collisionProperties.PositionY,
collisionProperties.PositionZ);
collideNormal =
new Vector3(collisionProperties.NormalX,
collisionProperties.NormalY,
collisionProperties.NormalZ);
penetration = collisionProperties.Penetration;
// Send the collision to OpenSim
SendCollision(localID, collidingWith, collidePoint,
collideNormal, penetration);
SendCollision(collidingWith, localID, collidePoint,
-collideNormal, penetration);
}
// Iterate through each of the objects that were sent collisions
// and send each their own respective collisions, as well as
// add them to the set signaling they have no more collisions
foreach (PxPhysObject pxObj in m_objectsWithCollisions)
{
if (!pxObj.SendCollisions())
{
m_objectWithNoMoreCollisions.Add(pxObj);
}
}
// Iterate through the avatars, and send them collisions
// as long as they are not contained within the current
// objects with collisions set
foreach (PxPhysObject pxObj in m_avatarsSet)
{
if (!m_objectsWithCollisions.Contains(pxObj))
{
pxObj.SendCollisions();
}
}
// Iterate through the objects with no more collisions,
// and remove them from the objects with collisions list
foreach (PxPhysObject pxObj in m_objectWithNoMoreCollisions)
{
m_objectsWithCollisions.Remove(pxObj);
}
// Clear the objects with no more collisions list
m_objectWithNoMoreCollisions.Clear();
}
}
/// <summary>
/// Adds a tainted object to the list of tainted objects. These objects
/// will be re-built before the next simulation step.
/// </summary>
/// <param name="obj">The tainted physics object that needs to be
/// re-built</param>
public void AddTaintedObject(PxPhysObject obj)
{
// Attempt to add this object to the list of tainted objects in
// a thread-safe manner. If the object already exists within
// the list, this operation is ignored
lock (m_taintedObjects)
{
m_taintedObjects.GetOrAdd(obj.LocalID, obj);
}
}
/// <summary>
/// Simulate the physics scene, and do all the related actions.
/// </summary>
/// <param name="timeStep">The timestep amount to be simulated</param>
public override float Simulate(float timeStep)
{
Stopwatch physicsFrameTime;
uint updatedEntityCount = 0;
uint updateCollisionCount = 0;
// Create a profile timer that will profile the different parts of
// running PhysX
#if DEBUG
Stopwatch profileTimer = new Stopwatch();
#endif
// Start a stopwatch to get the total time it took PhysX to
// complete an update of the physics
physicsFrameTime = new Stopwatch();
physicsFrameTime.Start();
// Start the profiler to acquire the time it takes to update all
// the avatar velocities
#if DEBUG
profileTimer.Start();
#endif
// Update all script movement and vehicle movement before starting
// the PhysX update
TriggerPreStepEvent(timeStep);
// Re-build any tainted objects in a thread-safe manner
lock (m_taintedObjects)
{
// Go through each of the tainted objects in the dictionary
foreach (KeyValuePair<uint, PxPhysObject> currPair
in m_taintedObjects)
{
// Rebuild the current object
currPair.Value.BuildPhysicalShape();
}
// Now that the objects have been re-built, clear the list
// so that they do not get repeatedly re-built
m_taintedObjects.Clear();
}
// Prevent the avatar set from being manipulated
lock (m_avatarsSet)
{
// Update all avatars in the scene, during this frame
foreach (PxPhysObject pxObj in m_avatarsSet)
{
// Set the avatar's linear velocity, during each simulation
// frame, to ensure that it has a constant velocity
// while it is colliding with something (e.g. terrain)
if (pxObj.IsColliding)
{
// Use the target velocity which should
// indicate the desired velocity of the avatar
PhysX.SetLinearVelocity(
pxObj.LocalID, pxObj.TargetVelocity);
}
}
}
// Report how long it took for the avatar velocities to be updated
// and start the timer again for the time PhysX runs the simulation
// call
#if DEBUG
profileTimer.Stop();
m_log.DebugFormat("{0}: Time for avatar velocity to be" +
" updated = {1}MS", LogHeader,
profileTimer.Elapsed.TotalMilliseconds);
profileTimer.Restart();
#endif
// Tell PhysX to advance the simulation
PhysX.RunSimulation(
timeStep, out updatedEntityCount, out updateCollisionCount);
// Report how long it took for the PhysX simulation call and start
// the timer again for the time OpenSim took to process all the
// collisions that occurred
#if DEBUG
profileTimer.Stop();
m_log.DebugFormat("{0}: Time for PhysX Simulation call" +
" = {1}MS", LogHeader,
profileTimer.Elapsed.TotalMilliseconds);
profileTimer.Restart();
#endif
// Update the current simulation time; this is used to synchronize
// the updates between collisions and physical objects
m_simulationTime = Util.EnvironmentTickCount();
// Update the physical object collisions and their physical
// properties
SimulateUpdatedCollisions(updateCollisionCount);
// Report how long it took for OpenSim to process all the
// collisions for this frame and start the timer again for the time
// OpenSim took to process all the updates that occurred
#if DEBUG
profileTimer.Stop();
m_log.DebugFormat("{0}: Time for OpenSim to process the " +
"frame collisions = {1}MS", LogHeader,
profileTimer.Elapsed.TotalMilliseconds);
profileTimer.Restart();
#endif
SimulateUpdatedEntities(updatedEntityCount);
// Report how long it took for OpenSim to process all the updates
// that occurred and turn off the profiling timer since that is the
// last profiling value that is needed
#if DEBUG
profileTimer.Stop();
m_log.DebugFormat("{0}: Time for OpenSim to update the " +
"entities = {1}MS", LogHeader,
profileTimer.Elapsed.TotalMilliseconds);
#endif
// Stop the stopwatch now that PhysX has completed the update
// of the physics scene
physicsFrameTime.Stop();
// Return the amount of time (in seconds) it took for the
// PhysX engine to process the scene
return (float)physicsFrameTime.Elapsed.TotalMilliseconds * 1000.0f;
}
/// <summary>
/// Updates the latest physics scene.
/// </summary>
/// <note>Used when the physics engine is running on its own thread
/// </note>
public override void GetResults()
{
}
#endregion Simulation
#region Terrain
/// <summary>
/// Create the terrain inside of the physics engine using the height
/// map provided by OpenSim.
/// <summary>
/// <param name="heightMap">The list of heights for the entire
/// terrain</param>
public override void SetTerrain(float[] heightMap)
{
// Fetch a new unique identifier for the height field shape
m_terrainShapeID = GetNewShapeID();
// Send the height map to the PhysX wrapper, so the wrapper can
// generate the terrain
PhysX.SetHeightField(TERRAIN_ACTOR_ID, m_terrainShapeID,
(int)m_regionExtents.X, (int)m_regionExtents.Y, 1.0f, 1.0f,
heightMap, UserConfig.HeightFieldScaleFactor);
}
/// <summary>
/// Send and add the collision to the physics object, as well as the
/// hashset of collided objects.
/// </summary>
/// <param name="localId">The local id of the collider object</param>
/// <param name="collidingWith">The local id of object that is
/// colliding with the collider</param>
/// <param name="collidePoint">The vector of the point that has
/// collided</param>
/// <param name="collideNormal">The vector of the point that has
/// collided relative to the collider</param>
/// <param name="penetration">The amount of seperation/penetration
/// between the two object</param>
private void SendCollision(uint localId, uint collidingWith,
Vector3 collidePoint, Vector3 collideNormal, float penetration)
{
PxPhysObject collider;
PxPhysObject collidee;
// This is a check to make sure that the terrain does not throw
// an entity not found exception while trying to get it from
// the dictionary (OpenSim id is nonexistant, while PhysX is)
if (localId == TERRAIN_ACTOR_ID)
{
return;
}
// Ensure no changes are made to the dictionary while it
// is being read from
lock (m_physObjectsDict)
{
// Try to get the collider object out of the scene
// Otherwise print the error/log and return
if (!m_physObjectsDict.TryGetValue(localId, out collider))
{
m_log.InfoFormat("{0}, Collider ID not found in " +
"object list, ID = {1}", LogHeader, localId);
return;
}
// Set the collidee to null as this will represent a collision
// with the terrain
collidee = null;
// Try to get the collidee object out of the scene a value of
// null means the collider is colliding with the terrain
m_physObjectsDict.TryGetValue(collidingWith, out collidee);
// If the collision was successful, from the PhysX object
// add the object to the objects with collision hashset
if (collider.Collide(collidingWith, collidee, collidePoint,
collideNormal, penetration))
{
m_objectsWithCollisions.Add(collider);
}
}
}
public override void SetWaterLevel(float baseheight)
{
}
public override void DeleteTerrain()
{
}
#endregion Terrain
/// <summary>
/// Clean up all objects in the scene and the scene itself.
/// </summary>
public override void Dispose()
{
// Make sure that a physics step doesn't happen during
// object deletion
m_isInitialized = false;
// Remove all physical objects that are being tracked
m_physObjectsDict.Clear();
// Delete the scene
PhysX.DisposeScene();
}
public override Dictionary<uint, float> GetTopColliders()
{
List<PxPhysObject> colliderList;
// Go through each of the objects in the scene and evaluate their
// collision scores
foreach (KeyValuePair<uint, PxPhysObject> currPair in
m_physObjectsDict)
{
// Evaluate the current object's collision score
currPair.Value.EvaluateCollisionScore();
}
// Construct a list of objects with descending collision scores
colliderList = new List<PxPhysObject>(m_physObjectsDict.Values);
colliderList.OrderByDescending(obj => obj.CollisionScore);
// Take the top 25 colliders and return them
return colliderList.Take(25).ToDictionary(
obj => obj.LocalID, obj => obj.CollisionScore);
}
/// <summary>
/// This method is called internally before the PhysX update in order
/// to process script movement and vehicle movement.
/// </summary>
/// <param name="timeStep">The amount of time that will elapse in the
/// next PhysX update</param>
private void TriggerPreStepEvent(float timeStep)
{
// Get the action that needs to be called before PhysX updates
PreStepAction actions = BeforeStep;
// Make sure there is a function to call before calling the
// function
if (actions != null)
{
// Go ahead and call the function
actions(timeStep);
}
}
/// <summary>
/// This method is called internally after the PhysX update in order
/// to process script movement and vehicle movement.
/// </summary>
/// <param name="timeStep">The amount of time that elapsed in the
/// PhysX update</param>
private void TriggerPostStepEvent(float timeStep)
{
// Get the action that needs to be called before PhysX updates
PostStepAction actions = AfterStep;
// Make sure there is a function to call before calling it
if (actions != null)
{
// Go ahead and call the function
actions(timeStep);
}
}
public override bool IsThreaded
{
get { return false; }
}
#region IPhysicsParameters
public bool SetPhysicsParameter(string param, string val, uint localID)
{
bool returnVal = false;
return returnVal;
}
public bool GetPhysicsParameter(string param, out string value)
{
value = String.Empty;
return false;
}
public PhysParameterEntry[] GetParameterList()
{
return null;
}
#endregion IPhysicsParameters
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xunit;
namespace NuGet.Test
{
public class PathResolverTest
{
[Fact]
public void GetPathToEnumerateReturnsSearchPathIfSearchPathIsNotUnderBasePath()
{
// Arrange
var basePath = @"c:\packages\bin";
var searchPath = @"d:\work\projects\project1\bin\*\*.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"d:\work\projects\project1\bin", result);
}
[Fact]
public void GetPathToEnumerateReturnsSearchPathIfSearchPathIsUnderBasePath()
{
// Arrange
var basePath = @"d:\work";
var searchPath = @"d:\work\projects\project1\bin\*\*.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"d:\work\projects\project1\bin", result);
}
[Fact]
public void GetPathToEnumerateReturnsSearchPathIfItIsANetworkPath()
{
// Arrange
var basePath = @"c:\work";
var searchPath = @"\\build-vm\shared\drops\nuget.*";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"\\build-vm\shared\drops", result);
}
[Fact]
public void GetPathToEnumerateReturnsSearchPathIfItIsRootedPath()
{
// Arrange
var basePath = @"c:\work";
var searchPath = @"\Volumes\Storage\users\test\repos\nuget\packages\test.*";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"\Volumes\Storage\users\test\repos\nuget\packages", result);
}
[Fact]
public void GetPathToEnumerateReturnsCombinedPathFromBaseForSearchWithWildcardFileName()
{
// Arrange
var basePath = @"c:\work\projects\my-project";
var searchPath = @"bin\debug\*.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"c:\work\projects\my-project\bin\debug", result);
}
[Fact]
public void GetPathToEnumerateReturnsCombinedPathFromBaseForSearchWithWildcardInPath()
{
// Arrange
var basePath = @"c:\work\projects\my-project";
var searchPath = @"output\*\binaries\NuGet.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"c:\work\projects\my-project\output", result);
}
[Fact]
public void GetPathToEnumerateReturnsBasePathIfSearchPathStartsWithRecursiveWildcard()
{
// Arrange
var basePath = @"c:\work\projects\my-project";
var searchPath = @"**\*.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"c:\work\projects\my-project", result);
}
[Fact]
public void GetPathToEnumerateReturnsBasePathIfSearchPathStartsWithWildcard()
{
// Arrange
var basePath = @"c:\work\projects\my-project\bin";
var searchPath = @"*.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"c:\work\projects\my-project\bin", result);
}
[Fact]
public void GetPathToEnumerateReturnsFullPathIfSearchPathDoesNotContainWildCards()
{
// Arrange
var basePath = @"c:\work\projects\my-project\";
var searchPath = @"bin\release\SuperBin.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"c:\work\projects\my-project\bin\release", result);
}
[Fact]
public void ResolvePackagePathPreservesPortionOfWildCardInPackagePath()
{
// Arrange
var basePath = @"c:\work\projects\my-project\";
var searchPattern = @"bin\release\**\*.dll";
var fullPath = @"c:\work\projects\my-project\bin\release\net40\foo.dll";
var targetPath = @"lib";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"lib\net40\foo.dll", result);
}
[Fact]
public void ResolvePackagePathAppendsFullTargetPathToPortionOfWildCardInPackagePath()
{
// Arrange
var basePath = @"c:\work\projects\my-project\";
var searchPattern = @"bin\release\**\*.dll";
var fullPath = @"c:\work\projects\my-project\bin\release\net40\foo.dll";
var targetPath = @"lib\assemblies\";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"lib\assemblies\net40\foo.dll", result);
}
[Fact]
public void ResolvePackagePathAppendsFileNameToTargetForWildCardInExtension()
{
// Arrange
var basePath = @"c:\work\projects\my-project\";
var searchPattern = @"bin\release\NuGet.*";
var fullPath = @"c:\work\projects\my-project\bin\release\NuGet.pdb";
var targetPath = @"lib\";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"lib\NuGet.pdb", result);
}
[Fact]
public void ResolvePackagePathAppendsFileNameToTargetForWildCardInFileName()
{
// Arrange
var basePath = @"c:\work\projects\my-project\";
var searchPattern = @"bin\release\*.dll";
var fullPath = @"c:\work\projects\my-project\bin\release\NuGet.dll";
var targetPath = @"lib\net40";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"lib\net40\NuGet.dll", result);
}
[Fact]
public void ResolvePackagePathAppendsFileNameToTargetForWildCardInPath()
{
// Arrange
var basePath = @"c:\work\projects\my-project\";
var searchPattern = @"out\*\NuGet*.dll";
var fullPath = @"c:\work\projects\my-project\out\NuGet.Core\NuGet.dll";
var targetPath = @"lib\net35";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"lib\net35\NuGet.dll", result);
}
[Fact]
public void ResolvePackagePathAppendsFileNameToTargetForMultipleWildCardInPath()
{
// Arrange
var basePath = @"c:\work\";
var searchPattern = @"src\Nu*\bin\*\NuGet*.dll";
var fullPath = @"c:\My Documents\Temporary Internet Files\NuGet\src\NuGet.Core\bin\release\NuGet.dll";
var targetPath = @"lib";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"lib\NuGet.dll", result);
}
[Fact]
public void ResolvePackagePathReturnsTargetPathIfNoWildCardIsPresentInSearchPatternAndTargetPathHasSameExtension()
{
// Arrange
var basePath = @"c:\work\";
var searchPattern = @"site\css\main.css";
var fullPath = @"c:\work\site\css\main.css";
var targetPath = @"content\css\site.css";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"content\css\site.css", result);
}
[Fact]
public void GetMatchesFiltersByWildCards()
{
// Arrange
var files = new[] {
new PhysicalPackageFile { SourcePath = @"content\1.txt" },
new PhysicalPackageFile { SourcePath = @"content\foo\bar.txt" },
new PhysicalPackageFile { SourcePath = @"baz.pdb" },
};
// Act
var matches = PathResolver.GetMatches(files, f => f.SourcePath, new[] { @"content\*.txt", "*.pdb" });
// Assert
Assert.Equal(2, matches.Count());
Assert.Equal(@"content\1.txt", matches.ElementAt(0).SourcePath);
Assert.Equal(@"baz.pdb", matches.ElementAt(1).SourcePath);
}
[Fact]
public void GetMatchesAllowsRecursiveWildcardMatches()
{
// Arrange
var files = new[] {
new PhysicalPackageFile { SourcePath = @"content\1.txt" },
new PhysicalPackageFile { SourcePath = @"content\foo\bar.txt" },
new PhysicalPackageFile { SourcePath = @"lib\baz.pdb" },
new PhysicalPackageFile { SourcePath = @"baz.dll" },
};
// Act
var matches = PathResolver.GetMatches(files, f => f.SourcePath, new[] { @"content\**\.txt", "**.pdb" });
// Assert
Assert.Equal(3, matches.Count());
Assert.Equal(@"content\1.txt", matches.ElementAt(0).SourcePath);
Assert.Equal(@"content\foo\bar.txt", matches.ElementAt(1).SourcePath);
Assert.Equal(@"lib\baz.pdb", matches.ElementAt(2).SourcePath);
}
[Fact]
public void GetMatchesAgainstUnixStylePaths()
{
// Arrange
var files = new[] {
new PhysicalPackageFile { SourcePath = @"content\1.txt" },
new PhysicalPackageFile { SourcePath = @"content\foo\bar.txt" },
new PhysicalPackageFile { SourcePath = @"lib\baz.pdb" },
new PhysicalPackageFile { SourcePath = @"baz.dll" },
};
// Act
var matches = PathResolver.GetMatches(files, f => f.SourcePath, new[] { @"content/**/.txt", "**.pdb" });
// Assert
Assert.Equal(3, matches.Count());
Assert.Equal(@"content\1.txt", matches.ElementAt(0).SourcePath);
Assert.Equal(@"content\foo\bar.txt", matches.ElementAt(1).SourcePath);
Assert.Equal(@"lib\baz.pdb", matches.ElementAt(2).SourcePath);
}
[Fact]
public void GetMatchesPerformsRecursiveWildcardSearch()
{
// Arrange
var files = new[] {
new PhysicalPackageFile { SourcePath = @"content\1.txt" },
new PhysicalPackageFile { SourcePath = @"content\foo\bar.txt" },
new PhysicalPackageFile { SourcePath = @"lib\baz.pdb" },
new PhysicalPackageFile { SourcePath = @"baz.dll" },
};
// Act
var matches = PathResolver.GetMatches(files, f => f.SourcePath, new[] { @"content\**\.txt", "**.pdb" });
// Assert
Assert.Equal(3, matches.Count());
Assert.Equal(@"content\1.txt", matches.ElementAt(0).SourcePath);
Assert.Equal(@"content\foo\bar.txt", matches.ElementAt(1).SourcePath);
Assert.Equal(@"lib\baz.pdb", matches.ElementAt(2).SourcePath);
}
[Fact]
public void GetMatchesPerformsExactMatches()
{
// Arrange
var files = new[] {
new PhysicalPackageFile { SourcePath = @"foo.dll" },
new PhysicalPackageFile { SourcePath = @"content\foo.dll" },
new PhysicalPackageFile { SourcePath = @"bin\debug\baz.dll" },
new PhysicalPackageFile { SourcePath = @"bin\debug\notbaz.dll" },
};
// Act
var matches = PathResolver.GetMatches(files, f => f.SourcePath, new[] { @"foo.dll", @"bin\*\b*.dll" });
// Assert
Assert.Equal(2, matches.Count());
Assert.Equal(@"foo.dll", matches.ElementAt(0).SourcePath);
Assert.Equal(@"bin\debug\baz.dll", matches.ElementAt(1).SourcePath);
}
[Fact]
public void FilterPathRemovesItemsThatMatchWildcard()
{
// Arrange
var files = new List<IPackageFile>(new[] {
new PhysicalPackageFile { TargetPath = @"foo.dll" },
new PhysicalPackageFile { TargetPath = @"content\foo.dll" },
new PhysicalPackageFile { TargetPath = @"bin\debug\baz.dll" },
new PhysicalPackageFile { TargetPath = @"bin\debug\notbaz.dll" },
new PhysicalPackageFile { TargetPath = @"bin\debug\baz.pdb" },
new PhysicalPackageFile { TargetPath = @"bin\debug\notbaz.pdb" },
});
// Act
PathResolver.FilterPackageFiles(files, f => f.Path, new[] { @"**\f*.dll", @"**\*.pdb" });
// Assert
Assert.Equal(2, files.Count());
Assert.Equal(@"bin\debug\baz.dll", files[0].Path);
Assert.Equal(@"bin\debug\notbaz.dll", files[1].Path);
}
[Fact]
public void NormalizeExcludeWildcardIgnoresBasePathForWildcardMatchingAnySubdirectory()
{
// Arrange
var wildcard = @"**\exclude.me";
var basePath = @"c:\base\path";
// Act
var result = PathResolver.NormalizeWildcardForExcludedFiles(basePath, wildcard);
// Assert
Assert.Equal(wildcard, result);
}
}
}
| |
using System;
using System.IO;
using GitVersion.MsBuild.Tests.Mocks;
using GitVersion.Core.Tests.Helpers;
using Microsoft.Build.Framework;
using NUnit.Framework;
namespace GitVersion.MsBuild.Tests
{
[TestFixture]
public class InvalidFileCheckerTests : TestBase
{
private string projectDirectory;
private string projectFile;
[SetUp]
public void CreateTemporaryProject()
{
projectDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
projectFile = Path.Combine(projectDirectory, "Fake.csproj");
Directory.CreateDirectory(projectDirectory);
File.Create(projectFile).Close();
}
[TearDown]
public void Cleanup()
{
Directory.Delete(projectDirectory, true);
}
[Test]
public void VerifyIgnoreNonAssemblyInfoFile()
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "SomeOtherFile.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
[assembly: AssemblyVersion(""1.0.0.0"")]
");
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "SomeOtherFile.cs" } }, projectFile);
}
[Test]
public void VerifyAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")] string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
[assembly:{0}(""1.0.0.0"")]
", attribute);
}
var ex = Assert.Throws<WarningException>(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile), attribute);
Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.cs"));
}
[Test]
public void VerifyUnformattedAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System . Reflection . AssemblyVersion")] string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
[ assembly :
{0} ( ""1.0.0.0"")]
", attribute);
}
var ex = Assert.Throws<WarningException>(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile), attribute);
Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.cs"));
}
[Test]
public void VerifyCommentWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
//[assembly: {0}(""1.0.0.0"")]
", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile);
}
[Test]
public void VerifyCommentWithNoNewLineAtEndWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
//[assembly: {0}(""1.0.0.0"")]", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile);
}
[Test]
public void VerifyStringWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
public class Temp
{{
static const string Foo = ""[assembly: {0}(""""1.0.0.0"""")]"";
}}
", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile);
}
[Test]
public void VerifyIdentifierWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
public class {0}
{{
}}
", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile);
}
[Test]
public void VerifyAttributeFoundVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")] string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb")))
{
writer.Write(@"
Imports System
Imports System.Reflection
<Assembly:{0}(""1.0.0.0"")>
", attribute);
}
var ex = Assert.Throws<WarningException>(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile), attribute);
Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.vb"));
}
[Test]
public void VerifyUnformattedAttributeFoundVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System . Reflection . AssemblyVersion")] string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb")))
{
writer.Write(@"
Imports System
Imports System.Reflection
< Assembly :
{0} ( ""1.0.0.0"")>
", attribute);
}
var ex = Assert.Throws<WarningException>(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile), attribute);
Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.vb"));
}
[Test]
public void VerifyCommentWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb")))
{
writer.Write(@"
Imports System
Imports System.Reflection
'<Assembly: {0}(""1.0.0.0"")>
", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile);
}
[Test]
public void VerifyCommentWithNoNewLineAtEndWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb")))
{
writer.Write(@"
Imports System
Imports System.Reflection
'<Assembly: {0}(""1.0.0.0"")>", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile);
}
[Test]
public void VerifyStringWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb")))
{
writer.Write(@"
Imports System
Imports System.Reflection
Public Class Temp
static const string Foo = ""<Assembly: {0}(""""1.0.0.0"""")>"";
End Class
", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile);
}
[Test]
public void VerifyIdentifierWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb")))
{
writer.Write(@"
Imports System
Imports System.Reflection
Public Class {0}
End Class
", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AdminSite.Database;
using AdminSite.Models;
using AdminSite.Pokemon;
using AdminSite.Utilities;
using InsurgenceData;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace AdminSite.Controllers
{
[Authorize(Policy = "Developer")]
public class DirectGiftController : Controller
{
public async Task<IActionResult> Index(string id)
{
if (id != "")
await GetGifts(id);
return View();
}
public async Task<PartialViewResult> GetGifts(string username = "")
{
var ls = await DbDirectGifts.GetGifts(username.StripSpecialCharacters());
var model = new DirectGiftModel
{
request = username,
gifts = ls
};
return PartialView("DirectGiftTable", model);
}
[HttpPost]
public ActionResult FindGifts(string request)
{
return Redirect("/DirectGift/Index/" + request);
}
public async Task<IActionResult> Details(string id)
{
var data = id.Split('?');
var username = data[0];
var giftIndex = int.Parse(data[1]);
var newgift = bool.Parse(data[2]);
var giftType = data[3];
var ls = await DbDirectGifts.GetGifts(username.StripSpecialCharacters());
if (newgift)
{
if (giftType == "pokemon")
{
var model = new DirectGiftDetailModel
{
username = username,
gift = new PokemonDirectGift(),
giftIndex = ls.Count
};
return View("PkmnGiftDetails", model);
}
else
{
var model = new DirectGiftDetailModel
{
username = username,
gift = new ItemDirectGift(),
giftIndex = ls.Count
};
return View("ItemGiftDetails", model);
}
}
else
{
if (giftType == "pokemon")
{
var model = new DirectGiftDetailModel
{
username = username,
gift = ls[giftIndex],
giftIndex = giftIndex
};
return View("PkmnGiftDetails", model);
}
else
{
var model = new DirectGiftDetailModel
{
username = username,
gift = ls[giftIndex],
giftIndex = giftIndex
};
return View("ItemGiftDetails", model);
}
}
}
public class GiftModel
{
public string Type { get; set; }
public string Username { get; set; }
public GamePokemon Pokemon { get; set; }
public int? Item { get; set; }
public int? ItemAmount { get; set; }
}
[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> AddGiftApi([FromBody]GiftModel model)
{
if (string.Equals(Request.Headers["api-token"], Startup.Token, StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("Wrong token given: " + Request.Headers["api-token"]);
return Forbid();
}
var username = model.Username.StripSpecialCharacters();
var ls = await DbDirectGifts.GetGifts(username);
if (model.Type == "pokemon")
{
model.Pokemon.exp = GrowthRates.CalculateExp(model.Pokemon.species, model.Pokemon.level);
var rand = new Random();
var id = rand.Next(int.MinValue, int.MaxValue);
model.Pokemon.personalID = (uint) id;
model.Pokemon.timeReceived = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
var gift = new PokemonDirectGift()
{
Pokemon = model.Pokemon,
Username = username,
Index = ls.Count
};
ls.Add(gift);
await DbDirectGifts.SetDirectGifts(username, ls);
DbAdminLog.Log(DbAdminLog.LogType.DirectGiftPokemon, "Bot Endpoint", JsonConvert.SerializeObject(gift));
}
else if (model.Type == "item")
{
var item = model.Item.Value;
var amount = model.ItemAmount.Value;
var gift = new ItemDirectGift()
{
Amount = (uint) amount,
Index = ls.Count,
Username = username,
Item = (ItemList) item
};
ls.Add(gift);
await DbDirectGifts.SetDirectGifts(username, ls);
DbAdminLog.Log(DbAdminLog.LogType.DirectGiftItem, "Bot Endpoint", JsonConvert.SerializeObject(gift));
}
return Ok();
}
[HttpPost]
public async Task<IActionResult> AddPokemonGift()
{
var otgender = int.Parse(Request.Form["pokemonModel.Pokemon.otgender"]);
if (otgender == 2) otgender = 0;
var pkmn = new GamePokemon
{
species = short.Parse(Request.Form["pokemonModel.Pokemon.species"]),
name = Request.Form["pokemonModel.Pokemon.name"].ToString(),
ot = Request.Form["pokemonModel.Pokemon.ot"].ToString(),
isShiny = bool.Parse(Request.Form["pokemonModel.Pokemon.isShiny"][0]),
level = byte.Parse(Request.Form["pokemonModel.Pokemon.level"]),
gender = byte.Parse(Request.Form["pokemonModel.Pokemon.gender"]),
nature = byte.Parse(Request.Form["pokemonModel.Pokemon.nature"]),
happiness = byte.Parse(Request.Form["pokemonModel.Pokemon.happiness"]),
item = short.Parse(Request.Form["pokemonModel.Pokemon.item"]),
iv = new[]
{
int.Parse(Request.Form["pokemonModel.Pokemon.iv[0]"]),
int.Parse(Request.Form["pokemonModel.Pokemon.iv[1]"]),
int.Parse(Request.Form["pokemonModel.Pokemon.iv[2]"]),
int.Parse(Request.Form["pokemonModel.Pokemon.iv[3]"]),
int.Parse(Request.Form["pokemonModel.Pokemon.iv[4]"]),
int.Parse(Request.Form["pokemonModel.Pokemon.iv[5]"])
},
ev = new[]
{
int.Parse(Request.Form["pokemonModel.Pokemon.ev[0]"]),
int.Parse(Request.Form["pokemonModel.Pokemon.ev[1]"]),
int.Parse(Request.Form["pokemonModel.Pokemon.ev[2]"]),
int.Parse(Request.Form["pokemonModel.Pokemon.ev[3]"]),
int.Parse(Request.Form["pokemonModel.Pokemon.ev[4]"]),
int.Parse(Request.Form["pokemonModel.Pokemon.ev[5]"])
},
moves = new[] {
new GameMove
{
id = int.Parse(Request.Form["pokemonModel.Pokemon.moves[0].id"]),
pp = int.Parse(Request.Form["pokemonModel.Pokemon.moves[0].pp"]),
ppup = int.Parse(Request.Form["pokemonModel.Pokemon.moves[0].ppup"]),
},
new GameMove
{
id = int.Parse(Request.Form["pokemonModel.Pokemon.moves[1].id"]),
pp = int.Parse(Request.Form["pokemonModel.Pokemon.moves[1].pp"]),
ppup = int.Parse(Request.Form["pokemonModel.Pokemon.moves[1].ppup"]),
},
new GameMove
{
id = int.Parse(Request.Form["pokemonModel.Pokemon.moves[2].id"]),
pp = int.Parse(Request.Form["pokemonModel.Pokemon.moves[2].pp"]),
ppup = int.Parse(Request.Form["pokemonModel.Pokemon.moves[2].ppup"]),
},
new GameMove
{
id = int.Parse(Request.Form["pokemonModel.Pokemon.moves[3].id"]),
pp = int.Parse(Request.Form["pokemonModel.Pokemon.moves[3].pp"]),
ppup = int.Parse(Request.Form["pokemonModel.Pokemon.moves[3].ppup"]),
}
},
otgender = (byte) otgender,
obtainMode = 4
};
pkmn.exp = GrowthRates.CalculateExp(pkmn.species, pkmn.level);
var rand = new Random();
var id = rand.Next(int.MinValue, int.MaxValue);
pkmn.personalID = (uint) id;
var data = PokemonDatabase.GetData(pkmn.species);
var abil = byte.Parse(Request.Form["pokemonModel.Pokemon.abilityflag"]);
if (data.Abilities.Count < 2 && abil == 1)
{
abil = 0;
}
if (data.HiddenAbility.Count < 1 && abil == 2)
{
abil = 0;
}
pkmn.abilityflag = abil;
pkmn.timeReceived = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
var username = Request.Form["username"].ToString().StripSpecialCharacters();
var ls = await DbDirectGifts.GetGifts(username);
var index = int.Parse(Request.Form["giftIndex"]);
var gift = new PokemonDirectGift
{
Pokemon = pkmn,
Index = index,
Username = username,
};
if (index >= ls.Count)
{
ls.Add(gift);
}
else
{
ls[index] = gift;
}
await DbDirectGifts.SetDirectGifts(username, ls);
DbAdminLog.Log(DbAdminLog.LogType.DirectGiftPokemon, User.Identity.Name, JsonConvert.SerializeObject(gift));
return Redirect("/DirectGift/Index/" + username);
}
public async Task<IActionResult> DeleteGift(string username, string index)
{
var i = int.Parse(index);
var ls = await DbDirectGifts.GetGifts(username.StripSpecialCharacters());
ls.RemoveAt(i);
await DbDirectGifts.SetDirectGifts(username.StripSpecialCharacters(), ls);
DbAdminLog.Log(DbAdminLog.LogType.DirectGiftDelete, User.Identity.Name, username);
return Redirect("/DirectGift/Index/" + username.StripSpecialCharacters());
}
[HttpPost]
public async Task<IActionResult> AddItemGift()
{
var username = Request.Form["username"].ToString().StripSpecialCharacters();
var ls = await DbDirectGifts.GetGifts(username);
var index = int.Parse(Request.Form["giftIndex"]);
var gift = new ItemDirectGift
{
Item = (ItemList)Enum.Parse(typeof(ItemList), Request.Form["ItemGift.Item"]),
Amount = uint.Parse(Request.Form["ItemGift.Amount"]),
Index =index,
Username = username
};
if (index >= ls.Count)
{
ls.Add(gift);
}
else
{
ls[index] = gift;
}
await DbDirectGifts.SetDirectGifts(username, ls);
DbAdminLog.Log(DbAdminLog.LogType.DirectGiftItem, User.Identity.Name, JsonConvert.SerializeObject(gift));
return Redirect("/DirectGift/Index/" + username);
}
}
}
| |
namespace PokerTell.PokerHand.Services
{
using System;
using PokerTell.Infrastructure.Interfaces.PokerHand;
using Tools.WPF.ViewModels;
[Serializable]
public class HandHistoriesFilter : NotifyPropertyChanged, IHandHistoriesFilter
{
string _heroName;
bool _selectHero;
bool _showAll;
bool _showMoneyInvested;
bool _showPreflopFolds;
bool _showSawFlop;
bool _showSelectedOnly;
[field: NonSerialized]
public event Action HeroNameChanged;
[field: NonSerialized]
public event Action SelectHeroChanged;
[field: NonSerialized]
public event Action ShowAllChanged;
[field: NonSerialized]
public event Action ShowMoneyInvestedChanged;
[field: NonSerialized]
public event Action ShowPreflopFoldsChanged;
[field: NonSerialized]
public event Action ShowSawFlopChanged;
[field: NonSerialized]
public event Action ShowSelectedOnlyChanged;
public string HeroName
{
get { return _heroName; }
set
{
_heroName = value;
InvokeHeroNameChanged();
}
}
public bool SelectHero
{
get { return _selectHero; }
set
{
_selectHero = value;
InvokeSelectHeroChanged();
}
}
public bool ShowAll
{
get { return _showAll; }
set
{
_showAll = value;
InvokeShowAllChanged();
}
}
public bool ShowMoneyInvested
{
get { return _showMoneyInvested; }
set
{
_showMoneyInvested = value;
InvokeShowMoneyInvestedChanged();
}
}
public bool ShowPreflopFolds
{
get { return _showPreflopFolds; }
set
{
_showPreflopFolds = value;
InvokeShowPreflopFoldsChanged();
}
}
public bool ShowSawFlop
{
get { return _showSawFlop; }
set
{
_showSawFlop = value;
InvokeShowSawFlopChanged();
}
}
public bool ShowSelectedOnly
{
get { return _showSelectedOnly; }
set
{
_showSelectedOnly = value;
InvokeShowSelectedOnlyChanged();
}
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof(HandHistoriesFilter))
{
return false;
}
return Equals((HandHistoriesFilter)obj);
}
public bool Equals(HandHistoriesFilter other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return other.GetHashCode().Equals(GetHashCode());
}
public override int GetHashCode()
{
unchecked
{
int result = _heroName != null ? _heroName.GetHashCode() : 0;
result = (result * 397) ^ _selectHero.GetHashCode();
result = (result * 397) ^ _showAll.GetHashCode();
result = (result * 397) ^ _showMoneyInvested.GetHashCode();
result = (result * 397) ^ _showPreflopFolds.GetHashCode();
result = (result * 397) ^ _showSawFlop.GetHashCode();
result = (result * 397) ^ _showSelectedOnly.GetHashCode();
return result;
}
}
public override string ToString()
{
return
string.Format(
"HeroName: {0}, SelectHero: {1}, ShowAll: {2}, ShowMoneyInvested: {3}, ShowPreflopFolds: {4}, ShowSawFlop: {5}, ShowSelectedOnly: {6}",
_heroName,
_selectHero,
_showAll,
_showMoneyInvested,
_showPreflopFolds,
_showSawFlop,
_showSelectedOnly);
}
void InvokeHeroNameChanged()
{
Action changed = HeroNameChanged;
if (changed != null)
{
changed();
}
}
void InvokeSelectHeroChanged()
{
Action changed = SelectHeroChanged;
if (changed != null)
{
changed();
}
}
void InvokeShowAllChanged()
{
Action changed = ShowAllChanged;
if (changed != null)
{
changed();
}
}
void InvokeShowMoneyInvestedChanged()
{
Action changed = ShowMoneyInvestedChanged;
if (changed != null)
{
changed();
}
}
void InvokeShowPreflopFoldsChanged()
{
Action changed = ShowPreflopFoldsChanged;
if (changed != null)
{
changed();
}
}
void InvokeShowSawFlopChanged()
{
Action changed = ShowSawFlopChanged;
if (changed != null)
{
changed();
}
}
void InvokeShowSelectedOnlyChanged()
{
Action changed = ShowSelectedOnlyChanged;
if (changed != null)
{
changed();
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCustomerUserAccessInvitationServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCustomerUserAccessInvitationRequestObject()
{
moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient>(moq::MockBehavior.Strict);
GetCustomerUserAccessInvitationRequest request = new GetCustomerUserAccessInvitationRequest
{
ResourceNameAsCustomerUserAccessInvitationName = gagvr::CustomerUserAccessInvitationName.FromCustomerInvitation("[CUSTOMER_ID]", "[INVITATION_ID]"),
};
gagvr::CustomerUserAccessInvitation expectedResponse = new gagvr::CustomerUserAccessInvitation
{
ResourceNameAsCustomerUserAccessInvitationName = gagvr::CustomerUserAccessInvitationName.FromCustomerInvitation("[CUSTOMER_ID]", "[INVITATION_ID]"),
InvitationId = -4996900927385391354L,
AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified,
EmailAddress = "email_addressf3aae0b5",
CreationDateTime = "creation_date_time2f8c0159",
InvitationStatus = gagve::AccessInvitationStatusEnum.Types.AccessInvitationStatus.Pending,
};
mockGrpcClient.Setup(x => x.GetCustomerUserAccessInvitation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerUserAccessInvitationServiceClient client = new CustomerUserAccessInvitationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerUserAccessInvitation response = client.GetCustomerUserAccessInvitation(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerUserAccessInvitationRequestObjectAsync()
{
moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient>(moq::MockBehavior.Strict);
GetCustomerUserAccessInvitationRequest request = new GetCustomerUserAccessInvitationRequest
{
ResourceNameAsCustomerUserAccessInvitationName = gagvr::CustomerUserAccessInvitationName.FromCustomerInvitation("[CUSTOMER_ID]", "[INVITATION_ID]"),
};
gagvr::CustomerUserAccessInvitation expectedResponse = new gagvr::CustomerUserAccessInvitation
{
ResourceNameAsCustomerUserAccessInvitationName = gagvr::CustomerUserAccessInvitationName.FromCustomerInvitation("[CUSTOMER_ID]", "[INVITATION_ID]"),
InvitationId = -4996900927385391354L,
AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified,
EmailAddress = "email_addressf3aae0b5",
CreationDateTime = "creation_date_time2f8c0159",
InvitationStatus = gagve::AccessInvitationStatusEnum.Types.AccessInvitationStatus.Pending,
};
mockGrpcClient.Setup(x => x.GetCustomerUserAccessInvitationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerUserAccessInvitation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerUserAccessInvitationServiceClient client = new CustomerUserAccessInvitationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerUserAccessInvitation responseCallSettings = await client.GetCustomerUserAccessInvitationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerUserAccessInvitation responseCancellationToken = await client.GetCustomerUserAccessInvitationAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomerUserAccessInvitation()
{
moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient>(moq::MockBehavior.Strict);
GetCustomerUserAccessInvitationRequest request = new GetCustomerUserAccessInvitationRequest
{
ResourceNameAsCustomerUserAccessInvitationName = gagvr::CustomerUserAccessInvitationName.FromCustomerInvitation("[CUSTOMER_ID]", "[INVITATION_ID]"),
};
gagvr::CustomerUserAccessInvitation expectedResponse = new gagvr::CustomerUserAccessInvitation
{
ResourceNameAsCustomerUserAccessInvitationName = gagvr::CustomerUserAccessInvitationName.FromCustomerInvitation("[CUSTOMER_ID]", "[INVITATION_ID]"),
InvitationId = -4996900927385391354L,
AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified,
EmailAddress = "email_addressf3aae0b5",
CreationDateTime = "creation_date_time2f8c0159",
InvitationStatus = gagve::AccessInvitationStatusEnum.Types.AccessInvitationStatus.Pending,
};
mockGrpcClient.Setup(x => x.GetCustomerUserAccessInvitation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerUserAccessInvitationServiceClient client = new CustomerUserAccessInvitationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerUserAccessInvitation response = client.GetCustomerUserAccessInvitation(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerUserAccessInvitationAsync()
{
moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient>(moq::MockBehavior.Strict);
GetCustomerUserAccessInvitationRequest request = new GetCustomerUserAccessInvitationRequest
{
ResourceNameAsCustomerUserAccessInvitationName = gagvr::CustomerUserAccessInvitationName.FromCustomerInvitation("[CUSTOMER_ID]", "[INVITATION_ID]"),
};
gagvr::CustomerUserAccessInvitation expectedResponse = new gagvr::CustomerUserAccessInvitation
{
ResourceNameAsCustomerUserAccessInvitationName = gagvr::CustomerUserAccessInvitationName.FromCustomerInvitation("[CUSTOMER_ID]", "[INVITATION_ID]"),
InvitationId = -4996900927385391354L,
AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified,
EmailAddress = "email_addressf3aae0b5",
CreationDateTime = "creation_date_time2f8c0159",
InvitationStatus = gagve::AccessInvitationStatusEnum.Types.AccessInvitationStatus.Pending,
};
mockGrpcClient.Setup(x => x.GetCustomerUserAccessInvitationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerUserAccessInvitation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerUserAccessInvitationServiceClient client = new CustomerUserAccessInvitationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerUserAccessInvitation responseCallSettings = await client.GetCustomerUserAccessInvitationAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerUserAccessInvitation responseCancellationToken = await client.GetCustomerUserAccessInvitationAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomerUserAccessInvitationResourceNames()
{
moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient>(moq::MockBehavior.Strict);
GetCustomerUserAccessInvitationRequest request = new GetCustomerUserAccessInvitationRequest
{
ResourceNameAsCustomerUserAccessInvitationName = gagvr::CustomerUserAccessInvitationName.FromCustomerInvitation("[CUSTOMER_ID]", "[INVITATION_ID]"),
};
gagvr::CustomerUserAccessInvitation expectedResponse = new gagvr::CustomerUserAccessInvitation
{
ResourceNameAsCustomerUserAccessInvitationName = gagvr::CustomerUserAccessInvitationName.FromCustomerInvitation("[CUSTOMER_ID]", "[INVITATION_ID]"),
InvitationId = -4996900927385391354L,
AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified,
EmailAddress = "email_addressf3aae0b5",
CreationDateTime = "creation_date_time2f8c0159",
InvitationStatus = gagve::AccessInvitationStatusEnum.Types.AccessInvitationStatus.Pending,
};
mockGrpcClient.Setup(x => x.GetCustomerUserAccessInvitation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerUserAccessInvitationServiceClient client = new CustomerUserAccessInvitationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerUserAccessInvitation response = client.GetCustomerUserAccessInvitation(request.ResourceNameAsCustomerUserAccessInvitationName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerUserAccessInvitationResourceNamesAsync()
{
moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient>(moq::MockBehavior.Strict);
GetCustomerUserAccessInvitationRequest request = new GetCustomerUserAccessInvitationRequest
{
ResourceNameAsCustomerUserAccessInvitationName = gagvr::CustomerUserAccessInvitationName.FromCustomerInvitation("[CUSTOMER_ID]", "[INVITATION_ID]"),
};
gagvr::CustomerUserAccessInvitation expectedResponse = new gagvr::CustomerUserAccessInvitation
{
ResourceNameAsCustomerUserAccessInvitationName = gagvr::CustomerUserAccessInvitationName.FromCustomerInvitation("[CUSTOMER_ID]", "[INVITATION_ID]"),
InvitationId = -4996900927385391354L,
AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified,
EmailAddress = "email_addressf3aae0b5",
CreationDateTime = "creation_date_time2f8c0159",
InvitationStatus = gagve::AccessInvitationStatusEnum.Types.AccessInvitationStatus.Pending,
};
mockGrpcClient.Setup(x => x.GetCustomerUserAccessInvitationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerUserAccessInvitation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerUserAccessInvitationServiceClient client = new CustomerUserAccessInvitationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerUserAccessInvitation responseCallSettings = await client.GetCustomerUserAccessInvitationAsync(request.ResourceNameAsCustomerUserAccessInvitationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerUserAccessInvitation responseCancellationToken = await client.GetCustomerUserAccessInvitationAsync(request.ResourceNameAsCustomerUserAccessInvitationName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCustomerUserAccessInvitationRequestObject()
{
moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient>(moq::MockBehavior.Strict);
MutateCustomerUserAccessInvitationRequest request = new MutateCustomerUserAccessInvitationRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new CustomerUserAccessInvitationOperation(),
};
MutateCustomerUserAccessInvitationResponse expectedResponse = new MutateCustomerUserAccessInvitationResponse
{
Result = new MutateCustomerUserAccessInvitationResult(),
};
mockGrpcClient.Setup(x => x.MutateCustomerUserAccessInvitation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerUserAccessInvitationServiceClient client = new CustomerUserAccessInvitationServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerUserAccessInvitationResponse response = client.MutateCustomerUserAccessInvitation(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCustomerUserAccessInvitationRequestObjectAsync()
{
moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient>(moq::MockBehavior.Strict);
MutateCustomerUserAccessInvitationRequest request = new MutateCustomerUserAccessInvitationRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new CustomerUserAccessInvitationOperation(),
};
MutateCustomerUserAccessInvitationResponse expectedResponse = new MutateCustomerUserAccessInvitationResponse
{
Result = new MutateCustomerUserAccessInvitationResult(),
};
mockGrpcClient.Setup(x => x.MutateCustomerUserAccessInvitationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerUserAccessInvitationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerUserAccessInvitationServiceClient client = new CustomerUserAccessInvitationServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerUserAccessInvitationResponse responseCallSettings = await client.MutateCustomerUserAccessInvitationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCustomerUserAccessInvitationResponse responseCancellationToken = await client.MutateCustomerUserAccessInvitationAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCustomerUserAccessInvitation()
{
moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient>(moq::MockBehavior.Strict);
MutateCustomerUserAccessInvitationRequest request = new MutateCustomerUserAccessInvitationRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new CustomerUserAccessInvitationOperation(),
};
MutateCustomerUserAccessInvitationResponse expectedResponse = new MutateCustomerUserAccessInvitationResponse
{
Result = new MutateCustomerUserAccessInvitationResult(),
};
mockGrpcClient.Setup(x => x.MutateCustomerUserAccessInvitation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerUserAccessInvitationServiceClient client = new CustomerUserAccessInvitationServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerUserAccessInvitationResponse response = client.MutateCustomerUserAccessInvitation(request.CustomerId, request.Operation);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCustomerUserAccessInvitationAsync()
{
moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient> mockGrpcClient = new moq::Mock<CustomerUserAccessInvitationService.CustomerUserAccessInvitationServiceClient>(moq::MockBehavior.Strict);
MutateCustomerUserAccessInvitationRequest request = new MutateCustomerUserAccessInvitationRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new CustomerUserAccessInvitationOperation(),
};
MutateCustomerUserAccessInvitationResponse expectedResponse = new MutateCustomerUserAccessInvitationResponse
{
Result = new MutateCustomerUserAccessInvitationResult(),
};
mockGrpcClient.Setup(x => x.MutateCustomerUserAccessInvitationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerUserAccessInvitationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerUserAccessInvitationServiceClient client = new CustomerUserAccessInvitationServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerUserAccessInvitationResponse responseCallSettings = await client.MutateCustomerUserAccessInvitationAsync(request.CustomerId, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCustomerUserAccessInvitationResponse responseCancellationToken = await client.MutateCustomerUserAccessInvitationAsync(request.CustomerId, request.Operation, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\EnvironmentQuery\Generators\EnvQueryGenerator_Cone.h:15
namespace UnrealEngine
{
[ManageType("ManageEnvQueryGenerator_Cone")]
public partial class ManageEnvQueryGenerator_Cone : UEnvQueryGenerator_Cone, IManageWrapper
{
public ManageEnvQueryGenerator_Cone(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_UpdateNodeVersion(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryGenerator_Cone_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
public override void UpdateNodeVersion()
=> E__Supper__UEnvQueryGenerator_Cone_UpdateNodeVersion(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__UEnvQueryGenerator_Cone_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__UEnvQueryGenerator_Cone_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__UEnvQueryGenerator_Cone_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__UEnvQueryGenerator_Cone_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__UEnvQueryGenerator_Cone_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__UEnvQueryGenerator_Cone_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__UEnvQueryGenerator_Cone_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__UEnvQueryGenerator_Cone_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__UEnvQueryGenerator_Cone_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__UEnvQueryGenerator_Cone_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__UEnvQueryGenerator_Cone_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__UEnvQueryGenerator_Cone_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__UEnvQueryGenerator_Cone_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__UEnvQueryGenerator_Cone_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__UEnvQueryGenerator_Cone_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageEnvQueryGenerator_Cone self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageEnvQueryGenerator_Cone(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageEnvQueryGenerator_Cone>(PtrDesc);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ReadOnlyBindingList.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>A readonly version of BindingList(Of T)</summary>
//-----------------------------------------------------------------------
using System;
using Csla.Properties;
namespace Csla.Core
{
/// <summary>
/// A readonly version of BindingList(Of T)
/// </summary>
/// <typeparam name="C">Type of item contained in the list.</typeparam>
/// <remarks>
/// This is a subclass of BindingList(Of T) that implements
/// a readonly list, preventing adding and removing of items
/// from the list. Use the IsReadOnly property
/// to unlock the list for loading/unloading data.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming",
"CA1710:IdentifiersShouldHaveCorrectSuffix")]
[Serializable()]
public abstract class ReadOnlyBindingList<C> :
Core.ExtendedBindingList<C>, Core.IBusinessObject, Core.IReadOnlyBindingList
{
#region Identity
int IBusinessObject.Identity
{
get { return 0; }
}
#endregion
private bool _isReadOnly = true;
/// <summary>
/// Gets or sets a value indicating whether the list is readonly.
/// </summary>
/// <remarks>
/// Subclasses can set this value to unlock the collection
/// in order to alter the collection's data.
/// </remarks>
/// <value>True indicates that the list is readonly.</value>
public bool IsReadOnly
{
get { return IsReadOnlyCore; }
protected set { IsReadOnlyCore = value; }
}
/// <summary>
/// Gets or sets a value indicating whether
/// the list is readonly.
/// </summary>
protected virtual bool IsReadOnlyCore
{
get { return _isReadOnly; }
set { _isReadOnly = value; }
}
bool Core.IReadOnlyBindingList.IsReadOnly
{
get { return IsReadOnly; }
set { IsReadOnly = value; }
}
/// <summary>
/// Sets the LoadListMode for the collection
/// </summary>
/// <param name="enabled">Enable or disable mode</param>
protected override void SetLoadListMode(bool enabled)
{
IsReadOnly = !enabled;
base.SetLoadListMode(enabled);
}
/// <summary>
/// Creates an instance of the object.
/// </summary>
protected ReadOnlyBindingList()
{
this.RaiseListChangedEvents = false;
AllowEdit = false;
AllowRemove = false;
AllowNew = false;
this.RaiseListChangedEvents = true;
}
/// <summary>
/// Prevents clearing the collection.
/// </summary>
protected override void ClearItems()
{
if (!IsReadOnly)
{
bool oldValue = AllowRemove;
AllowRemove = true;
base.ClearItems();
AllowRemove = oldValue;
}
else
throw new NotSupportedException(Resources.ClearInvalidException);
}
/// <summary>
/// Prevents insertion of items into the collection.
/// </summary>
#if NETFX_CORE || (ANDROID || IOS)
protected override void AddNewCore()
{
if (!IsReadOnly)
base.AddNewCore();
else
throw new NotSupportedException(Resources.InsertInvalidException);
}
#else
protected override object AddNewCore()
{
if (!IsReadOnly)
return base.AddNewCore();
else
throw new NotSupportedException(Resources.InsertInvalidException);
}
#endif
/// <summary>
/// Prevents insertion of items into the collection.
/// </summary>
/// <param name="index">Index at which to insert the item.</param>
/// <param name="item">Item to insert.</param>
protected override void InsertItem(int index, C item)
{
if (!IsReadOnly)
{
base.InsertItem(index, item);
}
else
throw new NotSupportedException(Resources.InsertInvalidException);
}
/// <summary>
/// Removes the item at the specified index if the collection is
/// not in readonly mode.
/// </summary>
/// <param name="index">Index of the item to remove.</param>
protected override void RemoveItem(int index)
{
if (!IsReadOnly)
{
bool oldValue = AllowRemove;
AllowRemove = true;
base.RemoveItem(index);
AllowRemove = oldValue;
}
else
throw new NotSupportedException(Resources.RemoveInvalidException);
}
/// <summary>
/// Replaces the item at the specified index with the
/// specified item if the collection is not in
/// readonly mode.
/// </summary>
/// <param name="index">Index of the item to replace.</param>
/// <param name="item">New item for the list.</param>
protected override void SetItem(int index, C item)
{
if (!IsReadOnly)
{
base.SetItem(index, item);
}
else
throw new NotSupportedException(Resources.ChangeInvalidException);
}
#region ITrackStatus
/// <summary>
/// Gets a value indicating whether this object or its
/// child objects are busy.
/// </summary>
public override bool IsBusy
{
get
{
// run through all the child objects
// and if any are dirty then then
// collection is dirty
foreach (C child in this)
{
INotifyBusy busy = child as INotifyBusy;
if (busy != null && busy.IsBusy)
return true;
}
return false;
}
}
#endregion
#region MobileFormatter
/// <summary>
/// Override this method to insert your field values
/// into the MobileFormatter serialzation stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
protected override void OnGetState(Csla.Serialization.Mobile.SerializationInfo info)
{
base.OnGetState(info);
info.AddValue("Csla.Core.ReadOnlyBindingList._isReadOnly", _isReadOnly);
}
/// <summary>
/// Override this method to retrieve your field values
/// from the MobileFormatter serialzation stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
protected override void OnSetState(Csla.Serialization.Mobile.SerializationInfo info)
{
base.OnSetState(info);
_isReadOnly = info.GetValue<bool>("Csla.Core.ReadOnlyBindingList._isReadOnly");
}
/// <summary>
/// Override this method to retrieve your child object
/// references from the MobileFormatter serialzation stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
/// <param name="formatter">
/// Reference to MobileFormatter instance. Use this to
/// convert child references to/from reference id values.
/// </param>
protected override void OnSetChildren(Csla.Serialization.Mobile.SerializationInfo info, Csla.Serialization.Mobile.MobileFormatter formatter)
{
var old = IsReadOnly;
IsReadOnly = false;
base.OnSetChildren(info, formatter);
IsReadOnly = old;
}
#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.AutoScaling.Model
{
/// <summary>
/// <para> The <c>AutoScalingInstanceDetails</c> data type. </para>
/// </summary>
public class AutoScalingInstanceDetails
{
private string instanceId;
private string autoScalingGroupName;
private string availabilityZone;
private string lifecycleState;
private string healthStatus;
private string launchConfigurationName;
/// <summary>
/// The instance ID of the Amazon EC2 instance.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 16</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string InstanceId
{
get { return this.instanceId; }
set { this.instanceId = value; }
}
/// <summary>
/// Sets the InstanceId property
/// </summary>
/// <param name="instanceId">The value to set for the InstanceId 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 AutoScalingInstanceDetails WithInstanceId(string instanceId)
{
this.instanceId = instanceId;
return this;
}
// Check to see if InstanceId property is set
internal bool IsSetInstanceId()
{
return this.instanceId != null;
}
/// <summary>
/// The name of the Auto Scaling group associated with this instance.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string AutoScalingGroupName
{
get { return this.autoScalingGroupName; }
set { this.autoScalingGroupName = value; }
}
/// <summary>
/// Sets the AutoScalingGroupName property
/// </summary>
/// <param name="autoScalingGroupName">The value to set for the AutoScalingGroupName 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 AutoScalingInstanceDetails WithAutoScalingGroupName(string autoScalingGroupName)
{
this.autoScalingGroupName = autoScalingGroupName;
return this;
}
// Check to see if AutoScalingGroupName property is set
internal bool IsSetAutoScalingGroupName()
{
return this.autoScalingGroupName != null;
}
/// <summary>
/// The Availability Zone in which this instance resides.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string AvailabilityZone
{
get { return this.availabilityZone; }
set { this.availabilityZone = value; }
}
/// <summary>
/// Sets the AvailabilityZone property
/// </summary>
/// <param name="availabilityZone">The value to set for the AvailabilityZone 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 AutoScalingInstanceDetails WithAvailabilityZone(string availabilityZone)
{
this.availabilityZone = availabilityZone;
return this;
}
// Check to see if AvailabilityZone property is set
internal bool IsSetAvailabilityZone()
{
return this.availabilityZone != null;
}
/// <summary>
/// The life cycle state of this instance. for more information, see <a
/// href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/AS_Concepts.html#instance-lifecycle">Instance Lifecycle State</a> in the
/// <i>Auto Scaling Developer Guide</i>.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 32</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string LifecycleState
{
get { return this.lifecycleState; }
set { this.lifecycleState = value; }
}
/// <summary>
/// Sets the LifecycleState property
/// </summary>
/// <param name="lifecycleState">The value to set for the LifecycleState 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 AutoScalingInstanceDetails WithLifecycleState(string lifecycleState)
{
this.lifecycleState = lifecycleState;
return this;
}
// Check to see if LifecycleState property is set
internal bool IsSetLifecycleState()
{
return this.lifecycleState != null;
}
/// <summary>
/// The health status of this instance. "Healthy" means that the instance is healthy and should remain in service. "Unhealthy" means that the
/// instance is unhealthy. Auto Scaling should terminate and replace it.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 32</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string HealthStatus
{
get { return this.healthStatus; }
set { this.healthStatus = value; }
}
/// <summary>
/// Sets the HealthStatus property
/// </summary>
/// <param name="healthStatus">The value to set for the HealthStatus 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 AutoScalingInstanceDetails WithHealthStatus(string healthStatus)
{
this.healthStatus = healthStatus;
return this;
}
// Check to see if HealthStatus property is set
internal bool IsSetHealthStatus()
{
return this.healthStatus != null;
}
/// <summary>
/// The launch configuration associated with this instance.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string LaunchConfigurationName
{
get { return this.launchConfigurationName; }
set { this.launchConfigurationName = value; }
}
/// <summary>
/// Sets the LaunchConfigurationName property
/// </summary>
/// <param name="launchConfigurationName">The value to set for the LaunchConfigurationName 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 AutoScalingInstanceDetails WithLaunchConfigurationName(string launchConfigurationName)
{
this.launchConfigurationName = launchConfigurationName;
return this;
}
// Check to see if LaunchConfigurationName property is set
internal bool IsSetLaunchConfigurationName()
{
return this.launchConfigurationName != null;
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Caliburn.Micro;
using csCommon.csMapCustomControls.CircularMenu;
using csCommon.Types.DataServer.PoI;
using csShared;
using csShared.Interfaces;
using DataServer;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.FeatureService.Symbols;
using ESRI.ArcGIS.Client.Geometry;
using ESRI.ArcGIS.Client.Projection;
using PointCollection = ESRI.ArcGIS.Client.Geometry.PointCollection;
namespace MSA.Plugins.SketchPlugin
{
[Export(typeof (IPlugin))]
public class SketchPlugin : PropertyChangedBase, IPlugin
{
private PoI selectedPoiType;
public SaveService SketchService;
private Draw draw;
private CircularMenuItem circularMenuItem;
// private MenuItem config; // Never used.
private NotificationEventArgs drawingNotification;
private ColorCircularMenuItem fillColor;
private bool hideFromSettings;
private bool isRunning;
private ColorCircularMenuItem lineColor;
private IPluginScreen screen;
private ISettingsScreen settings;
private CircularMenuItem sketchMenuItem;
public FloatingElement Element { get; set; }
public Draw Draw
{
get { return draw; }
set
{
draw = value;
NotifyOfPropertyChange(() => Draw);
}
}
public bool CanStop
{
get { return true; }
}
public ISettingsScreen Settings
{
get { return settings; }
set
{
settings = value;
NotifyOfPropertyChange(() => Settings);
}
}
public IPluginScreen Screen
{
get { return screen; }
set
{
screen = value;
NotifyOfPropertyChange(() => Screen);
}
}
public bool HideFromSettings
{
get { return hideFromSettings; }
set
{
hideFromSettings = value;
NotifyOfPropertyChange(() => HideFromSettings);
}
}
public int Priority
{
get { return 1; }
}
public string Icon
{
get { return @"/csCommon;component/Resources/Icons/PenWhite.png"; }
}
public bool IsRunning
{
get { return isRunning; }
set
{
isRunning = value;
NotifyOfPropertyChange(() => IsRunning);
}
}
public AppStateSettings AppState { get; set; }
public string Name
{
get { return "SketchPlugin"; }
}
public void Init()
{
}
public void Start()
{
IsRunning = true;
SketchService = CreateService();
circularMenuItem = new CircularMenuItem {Title = "Start Sketch"};
circularMenuItem.Selected += circularMenuItem_Selected;
circularMenuItem.Id = Guid.NewGuid().ToString();
circularMenuItem.Icon = "pack://application:,,,/csCommon;component/Resources/Icons/Pen.png";
AppState.AddCircularMenu(circularMenuItem);
circularMenuItem.OpenChanged += (e, f) =>
{
if (circularMenuItem.IsOpen)
{
CreateService();
SketchService.Layer.Visible = true;
SketchService.Layer.Opacity = 1;
}
else
{
if (SketchService != null)
{
SketchService.Layer.Opacity = 0;
}
if (Draw != null && Draw.IsEnabled) Draw.IsEnabled = false;
DisableSelections();
}
};
UpdateMenu();
Execute.OnUIThread(() => AppState.DataServer.Services.Add(SketchService));
}
public void Pause()
{
IsRunning = false;
}
public void Stop()
{
IsRunning = false;
AppState.RemoveCircularMenu(circularMenuItem.Id);
}
private void DisableSelections()
{
sketchMenuItem.Fill = Brushes.White;
}
private void UpdateMenu()
{
circularMenuItem.Items.Clear();
lineColor = ColorCircularMenuItem.CreateColorMenu("Line", 5);
lineColor.Color = Colors.Black;
circularMenuItem.Items.Add(lineColor);
fillColor = ColorCircularMenuItem.CreateColorMenu("Fill", 6);
fillColor.Color = Colors.Transparent;
//circularMenuItem.Items.Add(fillColor);
sketchMenuItem = new CircularMenuItem
{
Title = "Draw",
Id = "Draw",
CanCheck = true,
Fill = Brushes.White,
Icon = "pack://application:,,,/csCommon;component/Resources/Icons/freehand.png"
};
Draw = new Draw(AppState.ViewDef.MapControl)
{
DrawMode = DrawMode.Freehand,
LineSymbol = new SimpleLineSymbol {Color = Brushes.Black, Width = 3}
};
Draw.DrawBegin += MyDrawObject_DrawBegin;
Draw.DrawComplete += MyDrawObjectDrawComplete;
sketchMenuItem.Selected += (s, f) =>
{
selectedPoiType = new PoI
{
Service = SketchService,
DrawingMode = DrawingModes.Polyline,
StrokeColor = lineColor.Color,
FillColor = Colors.Transparent,
StrokeWidth = 3,
};
Draw.LineSymbol = new SimpleLineSymbol {Color = new SolidColorBrush(lineColor.Color), Width = 3};
//sketchMenuItem.Fill = AppState.AccentBrush;
Draw.IsEnabled = true;
drawingNotification = new NotificationEventArgs
{
Id = Guid.NewGuid(),
Style = NotificationStyle.Popup,
Duration = TimeSpan.FromHours(1),
Header = "Drawing activated",
Foreground = Brushes.White,
Background = AppState.AccentBrush,
Image = new BitmapImage(new Uri("pack://application:,,,/csCommon;component/Resources/Icons/Pen.png"))
};
AppState.TriggerNotification(drawingNotification);
};
var clear = new CircularMenuItem
{
Title = "Clear",
Id = "Clear",
CanCheck = true,
Position = 3,
Icon = "pack://application:,,,/csCommon;component/Resources/Icons/appbar.delete.png"
};
clear.Selected += (s, f) => { while (SketchService.PoIs.Any()) SketchService.PoIs.RemoveAt(0); };
circularMenuItem.Items.Add(sketchMenuItem);
circularMenuItem.Items.Add(clear);
}
private void MyDrawObjectDrawComplete(object sender, DrawEventArgs e)
{
AppState.TriggerDeleteNotification(drawingNotification);
Draw.IsEnabled = false;
var wm = new WebMercator();
PoI newPoi = selectedPoiType.GetInstance();
newPoi.Points = new ObservableCollection<Point>();
newPoi.Style = new PoIStyle {StrokeColor = lineColor.Color, StrokeWidth = 3, CanDelete = true};
//Logger.Stat("Drawing.Completed." + ((Custom) ? "Custom." + e.DrawMode : "Template." + ActiveMode.Name));
switch (e.DrawMode)
{
case DrawMode.Freehand:
case DrawMode.Polyline:
newPoi.DrawingMode = DrawingModes.Polyline;
//var polygon = e.Geometry is Polygon
// ? e.Geometry as Polygon
// : new Polygon();
if (e.Geometry is Polyline)
{
var source = e.Geometry as Polyline;
foreach (PointCollection path in source.Paths)
{
foreach (MapPoint po in path)
{
var r = wm.ToGeographic(po) as MapPoint;
if (r == null) continue;
newPoi.Points.Add(new Point(r.X, r.Y));
newPoi.Position = new Position(r.X, r.Y);
}
}
}
newPoi.UpdateEffectiveStyle();
SketchService.PoIs.Add(newPoi);
break;
case DrawMode.Circle:
case DrawMode.Polygon:
if (e.Geometry is Polygon)
{
var source = e.Geometry as Polygon;
foreach (var path in source.Rings)
{
foreach (var r in path.Select(wm.ToGeographic).OfType<MapPoint>())
{
newPoi.Points.Add(new Point(r.X, r.Y));
newPoi.Position = new Position(r.X, r.Y);
}
}
}
newPoi.UpdateEffectiveStyle();
SketchService.PoIs.Add(newPoi);
break;
}
selectedPoiType = null;
DisableSelections();
//UpdateMenu();
//ActiveLayer.Graphics.Add(g);
}
private void MyDrawObject_DrawBegin(object sender, EventArgs e)
{
}
private void circularMenuItem_Selected(object sender, MenuItemEventArgs e)
{
}
public SaveService CreateService()
{
AppState.ViewDef.FolderIcons[@"Layers\Sketch Layer"] = "pack://application:,,,/csCommon;component/Resources/Icons/sketch.png";
var ss = new SaveService
{
IsLocal = true,
Name = "Sketch " + AppState.Imb.Status.Name,
Id = Guid.NewGuid(),
IsFileBased = false,
StaticService = false,
IsVisible = false,
RelativeFolder = "Sketch Layer"
};
ss.Init(Mode.client, AppState.DataServer);
ss.Folder = Directory.GetCurrentDirectory() + @"\PoiLayers\Sketch Layer";
ss.InitPoiService();
ss.SettingsList = new ContentList
{
Service = ss,
ContentType = typeof (ServiceSettings),
Id = "settings",
IsRessetable = false
};
ss.SettingsList.Add(new ServiceSettings());
ss.AllContent.Add(ss.SettingsList);
ss.Settings.OpenTab = false;
ss.Settings.TabBarVisible = false;
ss.Settings.Icon = "layer.png";
ss.AutoStart = true;
//var result = new PoI
//{
// ContentId = "Brug",
// Style = new PoIStyle
// {
// DrawingMode = DrawingModes.Point,
// FillColor = Colors.Red,
// IconWidth = 30,
// IconHeight = 30,
// TitleMode = TitleModes.Bottom
// }
//};
//result.AddMetaInfo("name", "name");
////result.AddMetaInfo("height", "height", MetaTypes.number);
////result.AddMetaInfo("width", "width", MetaTypes.number);
////result.AddMetaInfo("description", "description");
////result.AddMetaInfo("image", "image", MetaTypes.image);
//ss.PoITypes.Add(result);
return ss;
}
}
}
| |
// form_NewMessage.cs
//
// Copyright (c) 2013 Brent Knowles (http://www.brentknowles.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.
//
// Review documentation at http://www.yourothermind.com for updated implementation notes, license updates
// or other general information/
//
// Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW
// Full source code: https://github.com/BrentKnowles/YourOtherMind
//###
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CoreUtilities
{
public class form_NewMessage : Form
{
public form_NewMessage()
{
InitializeComponent();
labelMessage.Dock = DockStyle.Fill;
//labelMessage.AutoEllipsis = true;
labelMessage.BringToFront();
}
int dwidth = 400;
int dheight = 200;
/// <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()
{
this.bOk = new System.Windows.Forms.Button();
this.labelMessage = new System.Windows.Forms.Label();
this.footer = new System.Windows.Forms.Panel();
this.bNo = new System.Windows.Forms.Button();
this.bCancel = new System.Windows.Forms.Button();
this.header = new System.Windows.Forms.Panel();
this.captionLabel = new System.Windows.Forms.Label();
this.picImage = new System.Windows.Forms.PictureBox();
this.userinput = new System.Windows.Forms.TextBox();
this.panelWebHelp = new System.Windows.Forms.Panel();
this.linkLabelWebHelp = new System.Windows.Forms.LinkLabel();
this.label1 = new System.Windows.Forms.Label();
this.panelHelpHelp = new System.Windows.Forms.Panel();
this.linkLabelHelpFile = new System.Windows.Forms.LinkLabel();
this.label2 = new System.Windows.Forms.Label();
this.footer.SuspendLayout();
this.header.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picImage)).BeginInit();
this.panelWebHelp.SuspendLayout();
this.panelHelpHelp.SuspendLayout();
this.SuspendLayout();
//
// bOk
//
this.bOk.DialogResult = System.Windows.Forms.DialogResult.OK;
this.bOk.Location = new System.Drawing.Point(240, 6);
this.bOk.Name = "bOk";
this.bOk.Size = new System.Drawing.Size(75, 23);
this.bOk.TabIndex = 0;
this.bOk.Text = "OK";
this.bOk.UseVisualStyleBackColor = true;
this.bOk.Visible = false;
this.bOk.Dock = DockStyle.Left;
//
// labelMessage
//
this.labelMessage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.labelMessage.BackColor = System.Drawing.Color.Transparent;
this.labelMessage.Location = new System.Drawing.Point(66, 34);
this.labelMessage.Name = "labelMessage";
this.labelMessage.Size = new System.Drawing.Size(220, 50);
this.labelMessage.TabIndex = 1;
this.labelMessage.Text = "label1";
this.labelMessage.MouseLeave += new System.EventHandler(this.labelMessage_MouseLeave);
this.labelMessage.MouseMove += new System.Windows.Forms.MouseEventHandler(this.labelMessage_MouseMove);
this.labelMessage.Click += new System.EventHandler(this.labelMessage_Click);
this.labelMessage.MouseDown += new System.Windows.Forms.MouseEventHandler(this.labelMessage_MouseDown);
this.labelMessage.MouseUp += new System.Windows.Forms.MouseEventHandler(this.labelMessage_MouseUp);
//
// footer
//
this.footer.BackColor = System.Drawing.Color.Transparent;
this.footer.Controls.Add(this.bNo);
this.footer.Controls.Add(this.bCancel);
this.footer.Controls.Add(this.bOk);
this.footer.Dock = System.Windows.Forms.DockStyle.Bottom;
this.footer.Location = new System.Drawing.Point(0, 86);
this.footer.Name = "footer";
this.footer.Size = new System.Drawing.Size(327, 32);
this.footer.TabIndex = 2;
this.footer.MouseMove += new System.Windows.Forms.MouseEventHandler(this.labelMessage_MouseUp);
this.footer.MouseDown += new System.Windows.Forms.MouseEventHandler(this.labelMessage_MouseDown);
this.footer.MouseUp += new System.Windows.Forms.MouseEventHandler(this.labelMessage_MouseUp);
//
// bNo
//
this.bNo.DialogResult = System.Windows.Forms.DialogResult.No;
this.bNo.Location = new System.Drawing.Point(76, 6);
this.bNo.Name = "bNo";
this.bNo.Size = new System.Drawing.Size(75, 23);
this.bNo.TabIndex = 2;
this.bNo.Text = "No";
this.bNo.UseVisualStyleBackColor = true;
this.bNo.Visible = false;
this.bNo.Dock = DockStyle.Right;
//
// bCancel
//
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(157, 6);
this.bCancel.Name = "bCancel";
this.bCancel.Size = new System.Drawing.Size(75, 23);
this.bCancel.TabIndex = 1;
this.bCancel.Text = "Cancel";
this.bCancel.UseVisualStyleBackColor = true;
this.bCancel.Visible = false;
//
// header
//
this.header.BackColor = System.Drawing.Color.Transparent;
this.header.Controls.Add(this.captionLabel);
this.header.Dock = System.Windows.Forms.DockStyle.Top;
this.header.Location = new System.Drawing.Point(0, 0);
this.header.Name = "header";
this.header.Size = new System.Drawing.Size(327, 31);
this.header.TabIndex = 3;
this.header.MouseMove += new System.Windows.Forms.MouseEventHandler(this.labelMessage_MouseMove);
this.header.MouseDown += new System.Windows.Forms.MouseEventHandler(this.labelMessage_MouseDown);
this.header.MouseUp += new System.Windows.Forms.MouseEventHandler(this.labelMessage_MouseUp);
//
// captionLabel
//
this.captionLabel.AutoSize = true;
this.captionLabel.Location = new System.Drawing.Point(10, 5);
this.captionLabel.Name = "captionLabel";
this.captionLabel.Size = new System.Drawing.Size(35, 13);
this.captionLabel.TabIndex = 0;
this.captionLabel.Text = "label1";
//
// picImage
//
this.picImage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.picImage.Location = new System.Drawing.Point(12, 34);
this.picImage.Name = "picImage";
this.picImage.Size = new System.Drawing.Size(48, 48);
this.picImage.TabIndex = 4;
this.picImage.TabStop = false;
this.picImage.Visible = false;
//
// userinput
//
this.userinput.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.userinput.Location = new System.Drawing.Point(69, 54);
this.userinput.Name = "userinput";
this.userinput.Size = new System.Drawing.Size(246, 20);
this.userinput.TabIndex = 5;
this.userinput.Visible = false;
//
// panelWebHelp
//
this.panelWebHelp.Controls.Add(this.linkLabelWebHelp);
this.panelWebHelp.Controls.Add(this.label1);
this.panelWebHelp.Location = new System.Drawing.Point(69, 49);
this.panelWebHelp.Name = "panelWebHelp";
this.panelWebHelp.Size = new System.Drawing.Size(246, 25);
this.panelWebHelp.TabIndex = 6;
this.panelWebHelp.Visible = false;
//
// linkLabelWebHelp
//
this.linkLabelWebHelp.AutoSize = true;
this.linkLabelWebHelp.Location = new System.Drawing.Point(68, 5);
this.linkLabelWebHelp.Name = "linkLabelWebHelp";
this.linkLabelWebHelp.Size = new System.Drawing.Size(55, 13);
this.linkLabelWebHelp.TabIndex = 1;
this.linkLabelWebHelp.TabStop = true;
this.linkLabelWebHelp.Text = "linkLabel1";
this.linkLabelWebHelp.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelWebHelp_LinkClicked);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(4, 5);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(58, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Web Help:";
//
// panelHelpHelp
//
this.panelHelpHelp.Controls.Add(this.linkLabelHelpFile);
this.panelHelpHelp.Controls.Add(this.label2);
this.panelHelpHelp.Location = new System.Drawing.Point(69, 49);
this.panelHelpHelp.Name = "panelHelpHelp";
this.panelHelpHelp.Size = new System.Drawing.Size(283, 22);
this.panelHelpHelp.TabIndex = 7;
this.panelHelpHelp.Visible = false;
//
// linkLabelHelpFile
//
this.linkLabelHelpFile.AutoSize = true;
this.linkLabelHelpFile.Location = new System.Drawing.Point(68, 5);
this.linkLabelHelpFile.Name = "linkLabelHelpFile";
this.linkLabelHelpFile.Size = new System.Drawing.Size(55, 13);
this.linkLabelHelpFile.TabIndex = 1;
this.linkLabelHelpFile.TabStop = true;
this.linkLabelHelpFile.Text = "linkLabel1";
this.linkLabelHelpFile.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelHelpFile_LinkClicked);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(4, 5);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(51, 13);
this.label2.TabIndex = 0;
this.label2.Text = "Help File:";
//
// NewMessageForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(dwidth, dheight);
this.ControlBox = false;
this.Controls.Add(this.panelHelpHelp);
this.Controls.Add(this.panelWebHelp);
this.Controls.Add(this.userinput);
this.Controls.Add(this.picImage);
this.Controls.Add(this.header);
this.Controls.Add(this.footer);
this.Controls.Add(this.labelMessage);
this.Name = "NewMessageForm";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "NewMessage";
this.footer.ResumeLayout(false);
this.header.ResumeLayout(false);
this.header.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.picImage)).EndInit();
this.panelWebHelp.ResumeLayout(false);
this.panelWebHelp.PerformLayout();
this.panelHelpHelp.ResumeLayout(false);
this.panelHelpHelp.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
this.AutoScroll = true;
}
#endregion
private System.Windows.Forms.Button bOk;
private System.Windows.Forms.Label labelMessage;
private System.Windows.Forms.Panel footer;
private System.Windows.Forms.Panel header;
private System.Windows.Forms.Label captionLabel;
public System.Windows.Forms.PictureBox picImage;
private System.Windows.Forms.Button bCancel;
private System.Windows.Forms.Button bNo;
public System.Windows.Forms.TextBox userinput;
private System.Windows.Forms.Panel panelWebHelp;
private System.Windows.Forms.LinkLabel linkLabelWebHelp;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Panel panelHelpHelp;
private System.Windows.Forms.LinkLabel linkLabelHelpFile;
private System.Windows.Forms.Label label2;
//////////////////////////////////////////////////////////////////////
//
// Methods
//
//////////////////////////////////////////////////////////////////////
/// <summary>
///
/// </summary>
/// <param name="captionFont"></param>
/// <param name="textFont"></param>
public void SetupFonts(Font captionFont, Font textFont)
{
if (captionFont != null && textFont != null)
{
labelMessage.Font = new Font(textFont, FontStyle.Regular);
captionLabel.Font = new Font(captionFont, FontStyle.Bold);
label1.Font =new Font(textFont, FontStyle.Regular);
label2.Font = new Font(textFont, FontStyle.Regular);
linkLabelHelpFile.Font = new Font(textFont, FontStyle.Regular);
linkLabelWebHelp.Font = new Font(textFont, FontStyle.Regular);
}
}
/// <summary>
/// sets the form to display help information
/// </summary>
public void SetupForHelpMode(string sWeblink, string sHelplink, string sHelpfile)
{
if (sWeblink != "")
{
panelWebHelp.Visible = true;
panelWebHelp.Dock = DockStyle.Bottom;
linkLabelWebHelp.Text = sWeblink;
}
/* Ju7ly 2010 - couldn't get this to work proerply so I removed
if (sHelplink != "" && sHelplink != null && sHelplink != "")
{
panelHelpHelp.Visible = true;
panelHelpHelp.Dock = DockStyle.Bottom;
linkLabelHelpFile.Text = sHelplink;
linkLabelHelpFile.Tag = sHelpfile;
}*/
labelMessage.Dock = DockStyle.Top;
labelMessage.BringToFront();
}
/// <summary>
///
/// </summary>
/// <param name="backColor">Note: If there is an image this will be useless</param>
/// <param name="captionColor">Set to transparent if there is a background</param>
/// <param name="textColor">Set to transprent if there is a background</param>
public void SetupColors(Color backColor, Color captionColor, Color textColor,
Color captionBackColor, Color textBackColor)
{
try
{
//labelMessage.BackColor = ;//Color.Transparent;
panelWebHelp.BackColor = textBackColor;
panelHelpHelp.BackColor = textBackColor;
labelMessage.BackColor = textBackColor;
captionLabel.BackColor = captionBackColor;
}
catch (Exception)
{
lg.Instance.Line("NewMessage.SetupColors",CoreUtilities.ProblemType.EXCEPTION,"unable to set label back to transparent");
labelMessage.BackColor = this.TransparencyKey;
captionLabel.BackColor = captionBackColor;
}
// if we choose not to be transparent we probably want the
// panel to be an actual heading panel like a normal
// message box
if (captionBackColor != Color.Transparent)
{
int nHeight = (int) (captionLabel.Font.Height * 1.5);
captionLabel.AutoSize = false;
captionLabel.Dock = DockStyle.Top;
captionLabel.Height = nHeight;
}
this.BackColor = backColor;
captionLabel.ForeColor = captionColor;
labelMessage.ForeColor = textColor;
}
/// <summary>
///
/// </summary>
/// <param name="sCaption"></param>
/// <param name="sText"></param>
public void SetupStrings(string sCaption, string sText)
{
captionLabel.Text = sCaption;
labelMessage.Text = sText;
}
/// <summary>
/// Called for each button to set the parameters correctly
/// </summary>
/// <param name="button"></param>
/// <returns></returns>
private Button setupButton(Button button, Color buttonColor, DockStyle docking)
{
button.Visible = true;
button.FlatStyle = FlatStyle.Flat;
button.FlatAppearance.BorderSize = 0;
button.BackColor = buttonColor;
button.Dock = docking;
// button.Margin = new Padding(20);
// button.Padding = new Padding(10); Nope
footer.Padding = new Padding(5);
// footer.Margin = new Padding(50);
return button;
}
/// <summary>
///
/// </summary>
private void setupYesNo(Color buttonColor)
{
bOk = setupButton(bOk, buttonColor, DockStyle.None);
bNo = setupButton(bNo, buttonColor, DockStyle.Right);
bNo.SendToBack(); // to make it align to the right
bOk.Text = "Yes";
// bCancel.Text = "No";
bOk.DialogResult = DialogResult.Yes;
// bCancel.DialogResult = DialogResult.No;
// manually ensure that bOK is spaced far enough away from bCancel
bOk.Dock=DockStyle.Left;
//bOk.Left = bNo.Left - 5;// -(bOk.Width); OK, Feb 2013 - we commented this out, using the Docking + Margin to accomplish spacing
bOk.Height = bNo.Height;
bOk.Top = bNo.Top;
bNo.TabIndex = 0;
bOk.TabIndex = 1;
this.AcceptButton = bNo;
}
/// <summary>
///
/// </summary>
/// <param name="buttonColor"></param>
public void setupYesNoCancel(Color buttonColor)
{
bCancel = setupButton(bCancel, buttonColor, DockStyle.Right);
bOk = setupButton(bOk, buttonColor, DockStyle.None);
bNo = setupButton(bNo, buttonColor, DockStyle.None);
bOk.Text = "Yes";
bOk.Dock = DockStyle.Left;
bOk.DialogResult = DialogResult.Yes;
bCancel.SendToBack(); // to make it align to the right
bNo.Dock = DockStyle.None;
bNo.Left = bCancel.Left - 5;// -(bOk.Width);
bNo.Height = bCancel.Height;
bNo.Top = bCancel.Top;
bOk.Left = bNo.Left - bNo.Width - 2;// -(bOk.Width);
bOk.Height = bNo.Height;
bOk.Top = bNo.Top;
bCancel.TabIndex = 0;
bNo.TabIndex = 1;
bOk.TabIndex = 2;
this.AcceptButton = bCancel;
}
/// <summary>
/// Sets
/// </summary>
/// <param name="buttons"></param>
/// <param name="bOkDefault">if true the OK button will be the default button</param>
public void SetupForButtons(MessageBoxButtons buttons, Color buttonColor, bool bOkDefault)
{
switch (buttons)
{
case MessageBoxButtons.OK:
{
this.AcceptButton = bOk;
bOk = setupButton(bOk, buttonColor, DockStyle.Right);
}
break;
case MessageBoxButtons.OKCancel:
{
bOk = setupButton(bOk, buttonColor, DockStyle.Left);
bCancel = setupButton(bCancel, buttonColor, DockStyle.Right);
bCancel.SendToBack(); // to make it align to the right
// manually ensure that bOK is spaced far enough away from bCancel
bOk.Left = bCancel.Left - 5;// -(bOk.Width);
bOk.Height = bCancel.Height;
bOk.Top = bCancel.Top;
bCancel.TabIndex = 0;
bOk.TabIndex = 1;
this.AcceptButton = bCancel;
}
break;
case MessageBoxButtons.YesNo:
{
setupYesNo(buttonColor);
} break;
case MessageBoxButtons.YesNoCancel:
{
setupYesNoCancel(buttonColor);
} break;
case MessageBoxButtons.RetryCancel:
{
setupYesNo(buttonColor);
bOk.Text = "Retry";
bOk.DialogResult = DialogResult.Retry;
bNo.Text = "Cancel";
bNo.DialogResult = DialogResult.Cancel;
} break;
case MessageBoxButtons.AbortRetryIgnore:
{
setupYesNoCancel(buttonColor);
bOk.Text = "Abort";
bOk.DialogResult = DialogResult.Abort;
bNo.Text = "Retry";
bNo.DialogResult = DialogResult.Retry;
bCancel.Text = "Ignore";
bCancel.DialogResult = DialogResult.Cancel;
} break;
default: MessageBox.Show(buttons.ToString() + " is unhandled in NewMessage"); break;
}
if (bOkDefault == true)
{
this.AcceptButton = bOk;
}
}
private void labelMessage_Click(object sender, EventArgs e)
{
}
/// <summary>
/// we hook up all components to the mouse move/mouse down so that moving works naturally
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelMessage_MouseDown(object sender, MouseEventArgs e)
{
base.OnMouseDown(e);
}
private void labelMessage_MouseLeave(object sender, EventArgs e)
{
}
private void labelMessage_MouseMove(object sender, MouseEventArgs e)
{
base.OnMouseMove(e);
}
private void labelMessage_MouseUp(object sender, MouseEventArgs e)
{
base.OnMouseUp(e);
}
private void linkLabelWebHelp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
General.OpenDocument(linkLabelWebHelp.Text, "");
}
private void linkLabelHelpFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (linkLabelHelpFile.Tag != null)
{
string sHelpFile = linkLabelHelpFile.Tag.ToString();
Help.ShowHelp(this, sHelpFile, HelpNavigator.Topic, linkLabelHelpFile.Text);
}
}
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009, 2010 Oracle and/or its affiliates. All rights reserved.
*
*/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using BerkeleyDB.Internal;
namespace BerkeleyDB {
/// <summary>
/// A class representing a SecondaryHashDatabase. The Hash format is an
/// extensible, dynamic hashing scheme.
/// </summary>
public class SecondaryHashDatabase : SecondaryDatabase {
private HashFunctionDelegate hashHandler;
private EntryComparisonDelegate compareHandler;
private EntryComparisonDelegate dupCompareHandler;
private BDB_CompareDelegate doCompareRef;
private BDB_HashDelegate doHashRef;
private BDB_CompareDelegate doDupCompareRef;
#region Constructors
internal SecondaryHashDatabase(DatabaseEnvironment env, uint flags) : base(env, flags) { }
private void Config(SecondaryHashDatabaseConfig cfg) {
base.Config(cfg);
db.set_flags(cfg.flags);
if (cfg.HashFunction != null)
HashFunction = cfg.HashFunction;
if (cfg.DuplicateCompare != null)
DupCompare = cfg.DuplicateCompare;
if (cfg.fillFactorIsSet)
db.set_h_ffactor(cfg.FillFactor);
if (cfg.nelemIsSet)
db.set_h_nelem(cfg.TableSize);
if (cfg.Compare != null)
Compare = cfg.Compare;
}
/// <summary>
/// Instantiate a new SecondaryHashDatabase object, open the
/// database represented by <paramref name="Filename"/> and associate
/// the database with the
/// <see cref="SecondaryDatabaseConfig.Primary">primary index</see>.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="Filename"/> is null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe.
/// </para>
/// <para>
/// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation
/// will be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <returns>A new, open database object</returns>
public static SecondaryHashDatabase Open(
string Filename, SecondaryHashDatabaseConfig cfg) {
return Open(Filename, null, cfg, null);
}
/// <summary>
/// Instantiate a new SecondaryHashDatabase object, open the
/// database represented by <paramref name="Filename"/> and associate
/// the database with the
/// <see cref="SecondaryDatabaseConfig.Primary">primary index</see>.
/// </summary>
/// <remarks>
/// <para>
/// If both <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/> are null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe. If
/// <paramref name="Filename"/> is null and
/// <paramref name="DatabaseName"/> is non-null, the database can be
/// opened by other threads of control and will be replicated to client
/// sites in any replication group.
/// </para>
/// <para>
/// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation
/// will be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="DatabaseName">
/// This parameter allows applications to have multiple databases in a
/// single file. Although no DatabaseName needs to be specified, it is
/// an error to attempt to open a second database in a file that was not
/// initially created using a database name.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <returns>A new, open database object</returns>
public static SecondaryHashDatabase Open(string Filename,
string DatabaseName, SecondaryHashDatabaseConfig cfg) {
return Open(Filename, DatabaseName, cfg, null);
}
/// <summary>
/// Instantiate a new SecondaryHashDatabase object, open the
/// database represented by <paramref name="Filename"/> and associate
/// the database with the
/// <see cref="SecondaryDatabaseConfig.Primary">primary index</see>.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="Filename"/> is null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe.
/// </para>
/// <para>
/// If <paramref name="txn"/> is null, but
/// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will
/// be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open. Also note that the
/// transaction must be committed before the object is closed.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>A new, open database object</returns>
public static SecondaryHashDatabase Open(string Filename,
SecondaryHashDatabaseConfig cfg, Transaction txn) {
return Open(Filename, null, cfg, txn);
}
/// <summary>
/// Instantiate a new SecondaryHashDatabase object, open the
/// database represented by <paramref name="Filename"/> and associate
/// the database with the
/// <see cref="SecondaryDatabaseConfig.Primary">primary index</see>.
/// </summary>
/// <remarks>
/// <para>
/// If both <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/> are null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe. If
/// <paramref name="Filename"/> is null and
/// <paramref name="DatabaseName"/> is non-null, the database can be
/// opened by other threads of control and will be replicated to client
/// sites in any replication group.
/// </para>
/// <para>
/// If <paramref name="txn"/> is null, but
/// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will
/// be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open. Also note that the
/// transaction must be committed before the object is closed.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="DatabaseName">
/// This parameter allows applications to have multiple databases in a
/// single file. Although no DatabaseName needs to be specified, it is
/// an error to attempt to open a second database in a file that was not
/// initially created using a database name.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>A new, open database object</returns>
public static SecondaryHashDatabase Open(
string Filename, string DatabaseName,
SecondaryHashDatabaseConfig cfg, Transaction txn) {
SecondaryHashDatabase ret = new SecondaryHashDatabase(cfg.Env, 0);
ret.Config(cfg);
ret.db.open(Transaction.getDB_TXN(txn), Filename,
DatabaseName, cfg.DbType.getDBTYPE(), cfg.openFlags, 0);
ret.isOpen = true;
ret.doAssocRef =
new BDB_AssociateDelegate(SecondaryDatabase.doAssociate);
cfg.Primary.db.associate(Transaction.getDB_TXN(null),
ret.db, ret.doAssocRef, cfg.assocFlags);
if (cfg.ForeignKeyDatabase != null) {
if (cfg.OnForeignKeyDelete == ForeignKeyDeleteAction.NULLIFY)
ret.doNullifyRef =
new BDB_AssociateForeignDelegate(doNullify);
else
ret.doNullifyRef = null;
cfg.ForeignKeyDatabase.db.associate_foreign(
ret.db, ret.doNullifyRef, cfg.foreignFlags);
}
return ret;
}
#endregion Constructors
#region Callbacks
private static int doDupCompare(
IntPtr dbp, IntPtr dbt1p, IntPtr dbt2p) {
DB db = new DB(dbp, false);
DBT dbt1 = new DBT(dbt1p, false);
DBT dbt2 = new DBT(dbt2p, false);
SecondaryHashDatabase tmp = (SecondaryHashDatabase)db.api_internal;
return tmp.DupCompare(
DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2));
}
private static uint doHash(IntPtr dbp, IntPtr datap, uint len) {
DB db = new DB(dbp, false);
byte[] t_data = new byte[len];
Marshal.Copy(datap, t_data, 0, (int)len);
SecondaryHashDatabase tmp = (SecondaryHashDatabase)db.api_internal;
return tmp.HashFunction(t_data);
}
private static int doCompare(IntPtr dbp, IntPtr dbtp1, IntPtr dbtp2) {
DB db = new DB(dbp, false);
DBT dbt1 = new DBT(dbtp1, false);
DBT dbt2 = new DBT(dbtp2, false);
SecondaryHashDatabase tmp = (SecondaryHashDatabase)db.api_internal;
return tmp.Compare(
DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2));
}
#endregion Callbacks
#region Properties
/// <summary>
/// The secondary Hash key comparison function. The comparison function
/// is called whenever it is necessary to compare a key specified by the
/// application with a key currently stored in the tree.
/// </summary>
public EntryComparisonDelegate Compare {
get { return compareHandler; }
private set {
if (value == null)
db.set_h_compare(null);
else if (compareHandler == null) {
if (doCompareRef == null)
doCompareRef = new BDB_CompareDelegate(doCompare);
db.set_h_compare(doCompareRef);
}
compareHandler = value;
}
}
/// <summary>
/// The duplicate data item comparison function.
/// </summary>
public EntryComparisonDelegate DupCompare {
get { return dupCompareHandler; }
private set {
/* Cannot be called after open. */
if (value == null)
db.set_dup_compare(null);
else if (dupCompareHandler == null) {
if (doDupCompareRef == null)
doDupCompareRef = new BDB_CompareDelegate(doDupCompare);
db.set_dup_compare(doDupCompareRef);
}
dupCompareHandler = value;
}
}
/// <summary>
/// Whether the insertion of duplicate data items in the database is
/// permitted, and whether duplicates items are sorted.
/// </summary>
public DuplicatesPolicy Duplicates {
get {
uint flags = 0;
db.get_flags(ref flags);
if ((flags & DbConstants.DB_DUPSORT) != 0)
return DuplicatesPolicy.SORTED;
else if ((flags & DbConstants.DB_DUP) != 0)
return DuplicatesPolicy.UNSORTED;
else
return DuplicatesPolicy.NONE;
}
}
/// <summary>
/// The desired density within the hash table.
/// </summary>
public uint FillFactor {
get {
uint ret = 0;
db.get_h_ffactor(ref ret);
return ret;
}
}
/// <summary>
/// A user-defined hash function; if no hash function is specified, a
/// default hash function is used.
/// </summary>
public HashFunctionDelegate HashFunction {
get { return hashHandler; }
private set {
if (value == null)
db.set_h_hash(null);
else if (hashHandler == null) {
if (doHashRef == null)
doHashRef = new BDB_HashDelegate(doHash);
db.set_h_hash(doHashRef);
}
hashHandler = value;
}
}
/// <summary>
/// An estimate of the final size of the hash table.
/// </summary>
public uint TableSize {
get {
uint ret = 0;
db.get_h_nelem(ref ret);
return ret;
}
}
#endregion Properties
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.EventUserModel
{
using System.Collections;
using NPOI.HSSF.Record;
using NPOI.Util;
/// <summary>
/// A stream based way to Get at complete records, with
/// as low a memory footprint as possible.
/// This handles Reading from a RecordInputStream, turning
/// the data into full records, Processing continue records
/// etc.
/// Most users should use HSSFEventFactory
/// HSSFListener and have new records pushed to
/// them, but this does allow for a "pull" style of coding.
/// </summary>
public class HSSFRecordStream
{
private RecordInputStream in1;
/** Have we run out of records on the stream? */
private bool hitEOS = false;
/** Have we returned all the records there are? */
private bool complete = false;
/**
* Sometimes we end up with a bunch of
* records. When we do, these should
* be returned before the next normal
* record Processing occurs (i.e. before
* we Check for continue records and
* return rec)
*/
private ArrayList bonusRecords = null;
/**
* The next record to return, which may need to have its
* continue records passed to it before we do
*/
private Record rec = null;
/**
* The most recent record that we gave to the user
*/
private Record lastRec = null;
/**
* The most recent DrawingRecord seen
*/
private DrawingRecord lastDrawingRecord = new DrawingRecord();
public HSSFRecordStream(RecordInputStream inp)
{
this.in1 = inp;
}
/// <summary>
/// Returns the next (complete) record from the
/// stream, or null if there are no more.
/// </summary>
/// <returns></returns>
public Record NextRecord()
{
Record r = null;
// Loop Until we Get something
while (r == null && !complete)
{
// Are there any bonus records that we need to
// return?
r = GetBonusRecord();
// If not, ask for the next real record
if (r == null)
{
r = GetNextRecord();
}
}
// All done
return r;
}
/// <summary>
/// If there are any "bonus" records, that should
/// be returned before Processing new ones,
/// grabs the next and returns it.
/// If not, returns null;
/// </summary>
/// <returns></returns>
private Record GetBonusRecord()
{
if (bonusRecords != null)
{
Record r = (Record)bonusRecords[0];
bonusRecords.RemoveAt(0);
if (bonusRecords.Count == 0)
{
bonusRecords = null;
}
return r;
}
return null;
}
/// <summary>
/// Returns the next available record, or null if
/// this pass didn't return a record that's
/// suitable for returning (eg was a continue record).
/// </summary>
/// <returns></returns>
private Record GetNextRecord()
{
Record toReturn = null;
if (in1.HasNextRecord)
{
// Grab our next record
in1.NextRecord();
short sid = in1.Sid;
//
// for some reasons we have to make the workbook to be at least 4096 bytes
// but if we have such workbook we Fill the end of it with zeros (many zeros)
//
// it Is not good:
// if the Length( all zero records ) % 4 = 1
// e.g.: any zero record would be Readed as 4 bytes at once ( 2 - id and 2 - size ).
// And the last 1 byte will be Readed WRONG ( the id must be 2 bytes )
//
// So we should better to Check if the sid Is zero and not to Read more data
// The zero sid shows us that rest of the stream data Is a fake to make workbook
// certain size
//
if (sid == 0)
return null;
// If we had a last record, and this one
// Isn't a continue record, then pass
// it on to the listener
if ((rec != null) && (sid != ContinueRecord.sid))
{
// This last record ought to be returned
toReturn = rec;
}
// If this record Isn't a continue record,
// then build it up
if (sid != ContinueRecord.sid)
{
//Console.WriteLine("creating "+sid);
Record[] recs = RecordFactory.CreateRecord(in1);
// We know that the multiple record situations
// don't contain continue records, so just
// pass those on to the listener now
if (recs.Length > 1)
{
bonusRecords = new ArrayList(recs.Length - 1);
for (int k = 0; k < (recs.Length - 1); k++)
{
bonusRecords.Add(recs[k]);
}
}
// Regardless of the number we Created, always hold
// onto the last record to be Processed on the next
// loop, in case it has any continue records
rec = recs[recs.Length - 1];
// Don't return it just yet though, as we probably have
// a record from the last round to return
}
else
{
// Normally, ContinueRecords are handled internally
// However, in a few cases, there Is a gap between a record at
// its Continue, so we have to handle them specially
// This logic Is much like in RecordFactory.CreateRecords()
Record[] recs = RecordFactory.CreateRecord(in1);
ContinueRecord crec = (ContinueRecord)recs[0];
if ((lastRec is ObjRecord) || (lastRec is TextObjectRecord))
{
// You can have Obj records between a DrawingRecord
// and its continue!
lastDrawingRecord.ProcessContinueRecord(crec.Data);
// Trigger them on the drawing record, now it's complete
rec = lastDrawingRecord;
}
else if ((lastRec is DrawingGroupRecord))
{
((DrawingGroupRecord)lastRec).ProcessContinueRecord(crec.Data);
// Trigger them on the drawing record, now it's complete
rec = lastRec;
}
else
{
if (rec is UnknownRecord)
{
;//silently skip records we don't know about
}
else
{
throw new RecordFormatException("Records should handle ContinueRecord internally. Should not see this exception");
}
}
}
// Update our tracking of the last record
lastRec = rec;
if (rec is DrawingRecord)
{
lastDrawingRecord = (DrawingRecord)rec;
}
}
else
{
// No more records
hitEOS = true;
}
// If we've hit the end-of-stream, then
// finish off the last record and be done
if (hitEOS)
{
complete = true;
// Return the last record if there was
// one, otherwise null
if (rec != null)
{
toReturn = rec;
rec = null;
}
}
return toReturn;
}
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Graphics\Testing\Tcl\polyConn.tcl
// output file is AVpolyConn.cs
/// <summary>
/// The testing class derived from AVpolyConn
/// </summary>
public class AVpolyConnClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVpolyConn(String [] argv)
{
//Prefix Content is: ""
// Create the RenderWindow, Renderer and both Actors[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
// read data[]
//[]
pl3d = new vtkMultiBlockPLOT3DReader();
pl3d.SetXYZFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combxyz.bin");
pl3d.SetQFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combq.bin");
pl3d.SetScalarFunctionNumber((int)100);
pl3d.SetVectorFunctionNumber((int)202);
pl3d.Update();
// planes to connect[]
plane1 = new vtkStructuredGridGeometryFilter();
plane1.SetInputData((vtkDataSet)pl3d.GetOutput().GetBlock(0));
plane1.SetExtent((int)20,(int)20,(int)0,(int)100,(int)0,(int)100);
conn = new vtkPolyDataConnectivityFilter();
conn.SetInputConnection((vtkAlgorithmOutput)plane1.GetOutputPort());
conn.ScalarConnectivityOn();
conn.SetScalarRange((double)0.19,(double)0.25);
plane1Map = vtkPolyDataMapper.New();
plane1Map.SetInputConnection((vtkAlgorithmOutput)conn.GetOutputPort());
plane1Map.SetScalarRange((double)((vtkDataSet)pl3d.GetOutput().GetBlock(0)).GetScalarRange()[0],
(double)((vtkDataSet)pl3d.GetOutput().GetBlock(0)).GetScalarRange()[1]);
plane1Actor = new vtkActor();
plane1Actor.SetMapper((vtkMapper)plane1Map);
plane1Actor.GetProperty().SetOpacity((double)0.999);
// outline[]
outline = new vtkStructuredGridOutlineFilter();
outline.SetInputData((vtkDataSet)pl3d.GetOutput().GetBlock(0));
outlineMapper = vtkPolyDataMapper.New();
outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort());
outlineActor = new vtkActor();
outlineActor.SetMapper((vtkMapper)outlineMapper);
outlineProp = outlineActor.GetProperty();
outlineProp.SetColor((double)0,(double)0,(double)0);
// Add the actors to the renderer, set the background and size[]
//[]
ren1.AddActor((vtkProp)outlineActor);
ren1.AddActor((vtkProp)plane1Actor);
ren1.SetBackground((double)1,(double)1,(double)1);
renWin.SetSize((int)300,(int)300);
cam1 = new vtkCamera();
cam1.SetClippingRange((double)14.29,(double)63.53);
cam1.SetFocalPoint((double)8.58522,(double)1.58266,(double)30.6486);
cam1.SetPosition((double)37.6808,(double)-20.1298,(double)35.4016);
cam1.SetViewAngle((double)30);
cam1.SetViewUp((double)-0.0566235,(double)0.140504,(double)0.98846);
ren1.SetActiveCamera((vtkCamera)cam1);
iren.Initialize();
// render the image[]
//[]
// prevent the tk window from showing up then start the event loop[]
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkMultiBlockPLOT3DReader pl3d;
static vtkStructuredGridGeometryFilter plane1;
static vtkPolyDataConnectivityFilter conn;
static vtkPolyDataMapper plane1Map;
static vtkActor plane1Actor;
static vtkStructuredGridOutlineFilter outline;
static vtkPolyDataMapper outlineMapper;
static vtkActor outlineActor;
static vtkProperty outlineProp;
static vtkCamera cam1;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkMultiBlockPLOT3DReader Getpl3d()
{
return pl3d;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setpl3d(vtkMultiBlockPLOT3DReader toSet)
{
pl3d = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStructuredGridGeometryFilter Getplane1()
{
return plane1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setplane1(vtkStructuredGridGeometryFilter toSet)
{
plane1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataConnectivityFilter Getconn()
{
return conn;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setconn(vtkPolyDataConnectivityFilter toSet)
{
conn = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Getplane1Map()
{
return plane1Map;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setplane1Map(vtkPolyDataMapper toSet)
{
plane1Map = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Getplane1Actor()
{
return plane1Actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setplane1Actor(vtkActor toSet)
{
plane1Actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStructuredGridOutlineFilter Getoutline()
{
return outline;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setoutline(vtkStructuredGridOutlineFilter toSet)
{
outline = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetoutlineMapper()
{
return outlineMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineMapper(vtkPolyDataMapper toSet)
{
outlineMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetoutlineActor()
{
return outlineActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineActor(vtkActor toSet)
{
outlineActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkProperty GetoutlineProp()
{
return outlineProp;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineProp(vtkProperty toSet)
{
outlineProp = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcam1()
{
return cam1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcam1(vtkCamera toSet)
{
cam1 = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(pl3d!= null){pl3d.Dispose();}
if(plane1!= null){plane1.Dispose();}
if(conn!= null){conn.Dispose();}
if(plane1Map!= null){plane1Map.Dispose();}
if(plane1Actor!= null){plane1Actor.Dispose();}
if(outline!= null){outline.Dispose();}
if(outlineMapper!= null){outlineMapper.Dispose();}
if(outlineActor!= null){outlineActor.Dispose();}
if(outlineProp!= null){outlineProp.Dispose();}
if(cam1!= null){cam1.Dispose();}
}
}
//--- end of script --//
| |
/*
* Copyright 2011 The Poderosa Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* $Id: MultiSelectTreeView.cs,v 1.2 2011/11/30 23:21:29 kzmi Exp $
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;
namespace Poderosa.SFTP {
/// <summary>
/// TreeView with multi-select functionality
/// </summary>
/// <remarks>
/// <para>SelectedNode property doesn't work.</para>
/// </remarks>
internal class MultiSelectTreeView : TreeView {
private readonly List<TreeNode> _selectedNodes = new List<TreeNode>();
public event TreeViewEventHandler SingleNodeSelected;
public event EventHandler SelectedNodesChanged;
public new TreeNode SelectedNode {
get {
throw new InvalidOperationException();
}
set {
throw new InvalidOperationException();
}
}
/// <summary>
/// Gets array of the selected nodes.
/// </summary>
public TreeNode[] SelectedNodes {
get {
ReduceSelectedNodes();
return _selectedNodes.ToArray();
}
}
/// <summary>
/// Gets number of the selected nodes.
/// </summary>
public int SelectedNodeCount {
get {
ReduceSelectedNodes();
return _selectedNodes.Count;
}
}
/// <summary>
/// Select single node
/// </summary>
public void SelectNode(TreeNode node) {
ClearSelectedNodes();
AddToSelectedNodes(node);
if (SingleNodeSelected != null)
SingleNodeSelected(this, new TreeViewEventArgs(node, TreeViewAction.Unknown));
if (SelectedNodesChanged != null)
SelectedNodesChanged(this, EventArgs.Empty);
}
/// <summary>
/// Unselect all nodes
/// </summary>
public void UnselectAllNodes() {
ClearSelectedNodes();
if (SelectedNodesChanged != null)
SelectedNodesChanged(this, EventArgs.Empty);
}
/// <summary>
/// Overrides OnBeforeSelect()
/// </summary>
protected override void OnBeforeSelect(TreeViewCancelEventArgs e) {
e.Cancel = true; // default behavior is not used
if (e.Action != TreeViewAction.ByMouse && e.Action != TreeViewAction.ByKeyboard)
return;
Keys key = Control.ModifierKeys;
TreeNode selNode = e.Node;
#if DEBUG
Debug.WriteLine(String.Format("OnBeforeSelect: \"{0}\" {1}", selNode.Text, key));
#endif
if (key == Keys.Control || key == Keys.Shift) {
if (!IsSameLevelWithSelectedNodes(selNode)) {
ClearSelectedNodes();
}
}
if (key == Keys.Control && _selectedNodes.Count > 0) {
if (_selectedNodes.Contains(selNode)) {
RemoveFromSelectedNodes(selNode);
if (SelectedNodesChanged != null)
SelectedNodesChanged(this, EventArgs.Empty);
}
else {
AddToSelectedNodes(selNode);
if (SelectedNodesChanged != null)
SelectedNodesChanged(this, EventArgs.Empty);
}
}
else if (key == Keys.Shift && _selectedNodes.Count > 0) {
TreeNode firstNode = _selectedNodes[0];
Debug.Assert(Object.ReferenceEquals(firstNode.Parent, selNode.Parent));
TreeNodeCollection collection;
if (selNode.Parent == null)
collection = this.Nodes;
else
collection = selNode.Parent.Nodes;
int firstIndex = firstNode.Index;
int lastIndex = selNode.Index;
ClearSelectedNodes();
if (firstIndex <= lastIndex) {
for (int i = firstIndex; i <= lastIndex; i++) {
TreeNode node = collection[i];
AddToSelectedNodes(node);
}
}
else {
for (int i = firstIndex; i >= lastIndex; i--) {
TreeNode node = collection[i];
AddToSelectedNodes(node);
}
}
if (SelectedNodesChanged != null)
SelectedNodesChanged(this, EventArgs.Empty);
}
else {
ClearSelectedNodes();
AddToSelectedNodes(selNode);
if (key != Keys.Control && key != Keys.Shift) {
if (SingleNodeSelected != null)
SingleNodeSelected(this, new TreeViewEventArgs(selNode, e.Action));
}
if (SelectedNodesChanged != null)
SelectedNodesChanged(this, EventArgs.Empty);
}
#if DEBUG
StringBuilder s = new StringBuilder();
s.Append("Selected: ");
foreach (TreeNode node in _selectedNodes) {
s.Append('"').Append(node.Text).Append('"').Append(", ");
}
Debug.WriteLine(s.ToString());
TreeNode singleSel = base.SelectedNode;
Debug.WriteLine("SelectedNode: " + (singleSel == null ? "(null)" : singleSel.Text));
#endif
}
private void ClearSelectedNodes() {
ReduceSelectedNodes();
foreach (TreeNode node in _selectedNodes) {
SetUnselectedVisual(node);
}
_selectedNodes.Clear();
}
private void ReduceSelectedNodes() {
for (int i = 0; i < _selectedNodes.Count; ) {
if (_selectedNodes[i].TreeView == null)
_selectedNodes.RemoveAt(i);
else
i++;
}
}
private bool IsSameLevelWithSelectedNodes(TreeNode node) {
TreeNode parent = node.Parent;
foreach (TreeNode tn in _selectedNodes) {
if (!Object.ReferenceEquals(tn.Parent, parent)) {
return false;
}
}
return true;
}
private void AddToSelectedNodes(TreeNode node) {
_selectedNodes.Add(node);
SetSelectedVisual(node);
}
private void RemoveFromSelectedNodes(TreeNode node) {
_selectedNodes.Remove(node);
SetUnselectedVisual(node);
}
private void SetSelectedVisual(TreeNode node) {
node.BackColor = SystemColors.Highlight;
node.ForeColor = SystemColors.HighlightText;
}
private void SetUnselectedVisual(TreeNode node) {
node.BackColor = this.BackColor;
node.ForeColor = this.ForeColor;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Searchservice
{
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for DataSources.
/// </summary>
public static partial class DataSourcesExtensions
{
/// <summary>
/// Creates a new Azure Search datasource or updates a datasource if it already
/// exists.
/// <see href="https://msdn.microsoft.com/library/azure/dn946900.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to create or update.
/// </param>
/// <param name='dataSource'>
/// The definition of the datasource to create or update.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static DataSource CreateOrUpdate(this IDataSources operations, string dataSourceName, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return operations.CreateOrUpdateAsync(dataSourceName, dataSource, searchRequestOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Azure Search datasource or updates a datasource if it already
/// exists.
/// <see href="https://msdn.microsoft.com/library/azure/dn946900.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to create or update.
/// </param>
/// <param name='dataSource'>
/// The definition of the datasource to create or update.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataSource> CreateOrUpdateAsync(this IDataSources operations, string dataSourceName, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(dataSourceName, dataSource, searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an Azure Search datasource.
/// <see href="https://msdn.microsoft.com/library/azure/dn946881.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to delete.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static void Delete(this IDataSources operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
operations.DeleteAsync(dataSourceName, searchRequestOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an Azure Search datasource.
/// <see href="https://msdn.microsoft.com/library/azure/dn946881.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to delete.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IDataSources operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(dataSourceName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Retrieves a datasource definition from Azure Search.
/// <see href="https://msdn.microsoft.com/library/azure/dn946893.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to retrieve.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static DataSource Get(this IDataSources operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return operations.GetAsync(dataSourceName, searchRequestOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves a datasource definition from Azure Search.
/// <see href="https://msdn.microsoft.com/library/azure/dn946893.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to retrieve.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataSource> GetAsync(this IDataSources operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(dataSourceName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all datasources available for an Azure Search service.
/// <see href="https://msdn.microsoft.com/library/azure/dn946878.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static DataSourceListResult List(this IDataSources operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return operations.ListAsync(searchRequestOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all datasources available for an Azure Search service.
/// <see href="https://msdn.microsoft.com/library/azure/dn946878.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataSourceListResult> ListAsync(this IDataSources operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new Azure Search datasource.
/// <see href="https://msdn.microsoft.com/library/azure/dn946876.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSource'>
/// The definition of the datasource to create.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static DataSource Create(this IDataSources operations, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return operations.CreateAsync(dataSource, searchRequestOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Azure Search datasource.
/// <see href="https://msdn.microsoft.com/library/azure/dn946876.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSource'>
/// The definition of the datasource to create.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataSource> CreateAsync(this IDataSources operations, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(dataSource, searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
//
// System.Web.HttpCookie.cs
//
// Author:
// Chris Toshok (toshok@novell.com)
//
//
// Copyright (C) 2005-2009 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.Text;
using System.Collections.Specialized;
using System.Security.Permissions;
namespace System.Web
{
[Flags]
internal enum CookieFlags : byte {
Secure = 1,
HttpOnly = 2
}
#if !MOBILE
// CAS - no InheritanceDemand here as the class is sealed
[AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
#endif
#if TARGET_J2EE
// Cookies must be serializable to be saved in the session for J2EE portal
[Serializable]
#endif
public sealed class HttpCookie {
string path = "/";
string domain;
DateTime expires = DateTime.MinValue;
string name;
CookieFlags flags = 0;
NameValueCollection values;
[Obsolete]
internal HttpCookie (string name, string value, string path, DateTime expires)
{
this.name = name;
this.values = new CookieNVC();
this.Value = value;
this.path = path;
this.expires = expires;
}
public HttpCookie (string name)
{
this.name = name;
values = new CookieNVC();
Value = "";
}
public HttpCookie (string name, string value)
: this (name)
{
Value = value;
}
internal string GetCookieHeaderValue ()
{
StringBuilder builder = new StringBuilder ();
builder.Append (name);
builder.Append ("=");
builder.Append (Value);
if (domain != null) {
builder.Append ("; domain=");
builder.Append (domain);
}
if (path != null) {
builder.Append ("; path=");
builder.Append (path);
}
if (expires != DateTime.MinValue) {
builder.Append ("; expires=");
builder.Append (expires.ToUniversalTime().ToString("r"));
}
if ((flags & CookieFlags.Secure) != 0) {
builder.Append ("; secure");
}
if ((flags & CookieFlags.HttpOnly) != 0){
builder.Append ("; HttpOnly");
}
return builder.ToString ();
}
public string Domain {
get {
return domain;
}
set {
domain = value;
}
}
public DateTime Expires {
get {
return expires;
}
set {
expires = value;
}
}
public bool HasKeys {
get {
return values.HasKeys();
}
}
public string this [ string key ] {
get {
return values [ key ];
}
set {
values [ key ] = value;
}
}
public string Name {
get {
return name;
}
set {
name = value;
}
}
public string Path {
get {
return path;
}
set {
path = value;
}
}
public bool Secure {
get {
return (flags & CookieFlags.Secure) == CookieFlags.Secure;
}
set {
if (value)
flags |= CookieFlags.Secure;
else
flags &= ~CookieFlags.Secure;
}
}
public string Value {
get {
return HttpUtility.UrlDecode(values.ToString ());
}
set {
values.Clear ();
if (value != null && value != "") {
string [] components = value.Split ('&');
foreach (string kv in components){
int pos = kv.IndexOf ('=');
if (pos == -1){
values.Add (null, kv);
} else {
string key = kv.Substring (0, pos);
string val = kv.Substring (pos+1);
values.Add (key, val);
}
}
}
}
}
public NameValueCollection Values {
get {
return values;
}
}
public bool HttpOnly {
get {
return (flags & CookieFlags.HttpOnly) == CookieFlags.HttpOnly;
}
set {
if (value)
flags |= CookieFlags.HttpOnly;
else
flags &= ~CookieFlags.HttpOnly;
}
}
/*
* simple utility class that just overrides ToString
* to get the desired behavior for
* HttpCookie.Values
*/
[Serializable]
sealed class CookieNVC : NameValueCollection
{
public CookieNVC ()
: base (StringComparer.OrdinalIgnoreCase)
{
}
public override string ToString ()
{
StringBuilder builder = new StringBuilder ("");
bool first_key = true;
foreach (string key in Keys) {
if (!first_key)
builder.Append ("&");
string[] vals = GetValues (key);
if(vals == null)
vals = new string[1] {String.Empty};
bool first_val = true;
foreach (string v in vals) {
if (!first_val)
builder.Append ("&");
if (key != null && key.Length > 0) {
builder.Append (HttpUtility.UrlEncode(key));
builder.Append ("=");
}
if(v != null && v.Length > 0)
builder.Append (HttpUtility.UrlEncode(v));
first_val = false;
}
first_key = false;
}
return builder.ToString();
}
/* MS's implementation has the interesting quirk that if you do:
* cookie.Values[null] = "foo"
* it clears out the rest of the values.
*/
public override void Set (string name, string value)
{
if (this.IsReadOnly)
throw new NotSupportedException ("Collection is read-only");
if (name == null) {
Clear();
name = string.Empty;
}
// if (value == null)
// value = string.Empty;
base.Set (name, value);
}
}
}
}
| |
using Newtonsoft.Json;
using SendGrid;
using SendGrid.Helpers.Mail; // If you are using the Mail Helper
using System;
var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
var client = new SendGridClient(apiKey);
////////////////////////////////////////////////////////
// Retrieve all blocks
// GET /suppression/blocks
string queryParams = @"{
'end_time': 1,
'limit': 1,
'offset': 1,
'start_time': 1
}";
var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/blocks", queryParams: queryParams);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Delete blocks
// DELETE /suppression/blocks
string data = @"{
'delete_all': false,
'emails': [
'example1@example.com',
'example2@example.com'
]
}";
Object json = JsonConvert.DeserializeObject<Object>(data);
data = json.ToString();
var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/blocks", requestBody: data);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Retrieve a specific block
// GET /suppression/blocks/{email}
var email = "test_url_param";
var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/blocks/" + email);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Delete a specific block
// DELETE /suppression/blocks/{email}
var email = "test_url_param";
var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/blocks/" + email);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Retrieve all bounces
// GET /suppression/bounces
string queryParams = @"{
'end_time': 1,
'start_time': 1
}";
var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/bounces", queryParams: queryParams);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Delete bounces
// DELETE /suppression/bounces
string data = @"{
'delete_all': true,
'emails': [
'example@example.com',
'example2@example.com'
]
}";
Object json = JsonConvert.DeserializeObject<Object>(data);
data = json.ToString();
var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/bounces", requestBody: data);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Retrieve a Bounce
// GET /suppression/bounces/{email}
var email = "test_url_param";
var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/bounces/" + email);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Delete a bounce
// DELETE /suppression/bounces/{email}
string queryParams = @"{
'email_address': 'example@example.com'
}";
var email = "test_url_param";
var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/bounces/" + email, queryParams: queryParams);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Retrieve all invalid emails
// GET /suppression/invalid_emails
string queryParams = @"{
'end_time': 1,
'limit': 1,
'offset': 1,
'start_time': 1
}";
var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/invalid_emails", queryParams: queryParams);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Delete invalid emails
// DELETE /suppression/invalid_emails
string data = @"{
'delete_all': false,
'emails': [
'example1@example.com',
'example2@example.com'
]
}";
Object json = JsonConvert.DeserializeObject<Object>(data);
data = json.ToString();
var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/invalid_emails", requestBody: data);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Retrieve a specific invalid email
// GET /suppression/invalid_emails/{email}
var email = "test_url_param";
var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/invalid_emails/" + email);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Delete a specific invalid email
// DELETE /suppression/invalid_emails/{email}
var email = "test_url_param";
var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/invalid_emails/" + email);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Retrieve a specific spam report
// GET /suppression/spam_report/{email}
var email = "test_url_param";
var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/spam_report/" + email);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Delete a specific spam report
// DELETE /suppression/spam_report/{email}
var email = "test_url_param";
var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/spam_reports/" + email);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Retrieve all spam reports
// GET /suppression/spam_reports
string queryParams = @"{
'end_time': 1,
'limit': 1,
'offset': 1,
'start_time': 1
}";
var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/spam_reports", queryParams: queryParams);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Delete spam reports
// DELETE /suppression/spam_reports
string data = @"{
'delete_all': false,
'emails': [
'example1@example.com',
'example2@example.com'
]
}";
Object json = JsonConvert.DeserializeObject<Object>(data);
data = json.ToString();
var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/spam_reports", requestBody: data);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
////////////////////////////////////////////////////////
// Retrieve all global suppressions
// GET /suppression/unsubscribes
string queryParams = @"{
'end_time': 1,
'limit': 1,
'offset': 1,
'start_time': 1
}";
var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/unsubscribes", queryParams: queryParams);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
| |
//
// Copyright (c) 2004-2021 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.Targets.Wrappers
{
using System;
using System.ComponentModel;
using System.Threading;
using NLog.Common;
using NLog.Internal;
/// <summary>
/// Provides asynchronous, buffered execution of target writes.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/AsyncWrapper-target">Documentation on NLog Wiki</seealso>
/// <remarks>
/// <p>
/// Asynchronous target wrapper allows the logger code to execute more quickly, by queueing
/// messages and processing them in a separate thread. You should wrap targets
/// that spend a non-trivial amount of time in their Write() method with asynchronous
/// target to speed up logging.
/// </p>
/// <p>
/// Because asynchronous logging is quite a common scenario, NLog supports a
/// shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to
/// the <targets/> element in the configuration file.
/// </p>
/// <code lang="XML">
/// <![CDATA[
/// <targets async="true">
/// ... your targets go here ...
/// </targets>
/// ]]></code>
/// </remarks>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/AsyncWrapper/NLog.config" />
/// <p>
/// The above examples assume just one target and a single rule. See below for
/// a programmatic configuration that's equivalent to the above config file:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/AsyncWrapper/Wrapping File/Example.cs" />
/// </example>
[Target("AsyncWrapper", IsWrapper = true)]
public class AsyncTargetWrapper : WrapperTargetBase
{
private readonly object _writeLockObject = new object();
private readonly object _timerLockObject = new object();
private Timer _lazyWriterTimer;
private readonly ReusableAsyncLogEventList _reusableAsyncLogEventList = new ReusableAsyncLogEventList(200);
private event EventHandler<LogEventDroppedEventArgs> _logEventDroppedEvent;
private event EventHandler<LogEventQueueGrowEventArgs> _eventQueueGrowEvent;
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
public AsyncTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="name">Name of the target.</param>
/// <param name="wrappedTarget">The wrapped target.</param>
public AsyncTargetWrapper(string name, Target wrappedTarget)
: this(wrappedTarget)
{
Name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public AsyncTargetWrapper(Target wrappedTarget)
: this(wrappedTarget, 10000, AsyncTargetWrapperOverflowAction.Discard)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="queueLimit">Maximum number of requests in the queue.</param>
/// <param name="overflowAction">The action to be taken when the queue overflows.</param>
public AsyncTargetWrapper(Target wrappedTarget, int queueLimit, AsyncTargetWrapperOverflowAction overflowAction)
{
#if NETSTANDARD2_0
// NetStandard20 includes many optimizations for ConcurrentQueue:
// - See: https://blogs.msdn.microsoft.com/dotnet/2017/06/07/performance-improvements-in-net-core/
// Net40 ConcurrencyQueue can seem to leak, because it doesn't clear properly on dequeue
// - See: https://blogs.msdn.microsoft.com/pfxteam/2012/05/08/concurrentqueuet-holding-on-to-a-few-dequeued-elements/
_requestQueue = new ConcurrentRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard);
#else
_requestQueue = new AsyncRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard);
#endif
TimeToSleepBetweenBatches = 1;
BatchSize = 200;
FullBatchSizeWriteLimit = 5;
WrappedTarget = wrappedTarget;
QueueLimit = queueLimit;
OverflowAction = overflowAction;
}
/// <summary>
/// Gets or sets the number of log events that should be processed in a batch
/// by the lazy writer thread.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(200)]
public int BatchSize { get; set; }
/// <summary>
/// Gets or sets the time in milliseconds to sleep between batches. (1 or less means trigger on new activity)
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(1)]
public int TimeToSleepBetweenBatches { get; set; }
/// <summary>
/// Raise event when Target cannot store LogEvent.
/// Event arg contains lost LogEvents
/// </summary>
public event EventHandler<LogEventDroppedEventArgs> LogEventDropped
{
add
{
if (_logEventDroppedEvent == null && _requestQueue != null )
{
_requestQueue.LogEventDropped += OnRequestQueueDropItem;
}
_logEventDroppedEvent += value;
}
remove
{
_logEventDroppedEvent -= value;
if (_logEventDroppedEvent == null && _requestQueue != null)
{
_requestQueue.LogEventDropped -= OnRequestQueueDropItem;
}
}
}
/// <summary>
/// Raises when event queue grow.
/// Queue can grow when <see cref="OverflowAction"/> was set to <see cref="AsyncTargetWrapperOverflowAction.Grow"/>
/// </summary>
public event EventHandler<LogEventQueueGrowEventArgs> EventQueueGrow
{
add
{
if (_eventQueueGrowEvent == null && _requestQueue != null)
{
_requestQueue.LogEventQueueGrow += OnRequestQueueGrow;
}
_eventQueueGrowEvent += value;
}
remove
{
_eventQueueGrowEvent -= value;
if (_eventQueueGrowEvent == null && _requestQueue != null)
{
_requestQueue.LogEventQueueGrow -= OnRequestQueueGrow;
}
}
}
/// <summary>
/// Gets or sets the action to be taken when the lazy writer thread request queue count
/// exceeds the set limit.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue("Discard")]
public AsyncTargetWrapperOverflowAction OverflowAction
{
get => _requestQueue.OnOverflow;
set => _requestQueue.OnOverflow = value;
}
/// <summary>
/// Gets or sets the limit on the number of requests in the lazy writer thread request queue.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(10000)]
public int QueueLimit
{
get => _requestQueue.RequestLimit;
set => _requestQueue.RequestLimit = value;
}
/// <summary>
/// Gets or sets the limit of full <see cref="BatchSize"/>s to write before yielding into <see cref="TimeToSleepBetweenBatches"/>
/// Performance is better when writing many small batches, than writing a single large batch
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(5)]
public int FullBatchSizeWriteLimit { get; set; }
/// <summary>
/// Gets or sets whether to use the locking queue, instead of a lock-free concurrent queue
/// The locking queue is less concurrent when many logger threads, but reduces memory allocation
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(false)]
public bool ForceLockingQueue { get => _forceLockingQueue ?? false; set => _forceLockingQueue = value; }
private bool? _forceLockingQueue;
/// <summary>
/// Gets the queue of lazy writer thread requests.
/// </summary>
AsyncRequestQueueBase _requestQueue;
/// <summary>
/// Schedules a flush of pending events in the queue (if any), followed by flushing the WrappedTarget.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
if (_flushEventsInQueueDelegate == null)
_flushEventsInQueueDelegate = new AsyncHelpersTask(FlushEventsInQueue);
AsyncHelpers.StartAsyncTask(_flushEventsInQueueDelegate.Value, asyncContinuation);
}
private AsyncHelpersTask? _flushEventsInQueueDelegate;
/// <summary>
/// Initializes the target by starting the lazy writer timer.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
if (!OptimizeBufferReuse && WrappedTarget != null && WrappedTarget.OptimizeBufferReuse)
{
OptimizeBufferReuse = GetType() == typeof(AsyncTargetWrapper); // Class not sealed, reduce breaking changes
if (!OptimizeBufferReuse && !ForceLockingQueue)
{
ForceLockingQueue = true; // Avoid too much allocation, when wrapping a legacy target
}
}
if (!ForceLockingQueue && OverflowAction == AsyncTargetWrapperOverflowAction.Block && BatchSize * 1.5m > QueueLimit)
{
ForceLockingQueue = true; // ConcurrentQueue does not perform well if constantly hitting QueueLimit
}
#if NET4_5 || NET4_0
if (_forceLockingQueue.HasValue && _forceLockingQueue.Value != (_requestQueue is AsyncRequestQueue))
{
_requestQueue = ForceLockingQueue ? (AsyncRequestQueueBase)new AsyncRequestQueue(QueueLimit, OverflowAction) : new ConcurrentRequestQueue(QueueLimit, OverflowAction);
}
#endif
if (BatchSize > QueueLimit && TimeToSleepBetweenBatches <= 1)
{
BatchSize = QueueLimit; // Avoid too much throttling
}
_requestQueue.Clear();
InternalLogger.Trace("AsyncWrapper(Name={0}): Start Timer", Name);
_lazyWriterTimer = new Timer(ProcessPendingEvents, null, Timeout.Infinite, Timeout.Infinite);
StartLazyWriterTimer();
}
/// <summary>
/// Shuts down the lazy writer timer.
/// </summary>
protected override void CloseTarget()
{
StopLazyWriterThread();
if (Monitor.TryEnter(_writeLockObject, 500))
{
try
{
WriteEventsInQueue(int.MaxValue, "Closing Target");
}
finally
{
Monitor.Exit(_writeLockObject);
}
}
if (OverflowAction == AsyncTargetWrapperOverflowAction.Block)
{
_requestQueue.Clear(); // Try to eject any threads, that are blocked in the RequestQueue
}
base.CloseTarget();
}
/// <summary>
/// Starts the lazy writer thread which periodically writes
/// queued log messages.
/// </summary>
protected virtual void StartLazyWriterTimer()
{
lock (_timerLockObject)
{
if (_lazyWriterTimer != null)
{
if (TimeToSleepBetweenBatches <= 1)
{
InternalLogger.Trace("AsyncWrapper(Name={0}): Throttled timer scheduled", Name);
_lazyWriterTimer.Change(1, Timeout.Infinite);
}
else
{
_lazyWriterTimer.Change(TimeToSleepBetweenBatches, Timeout.Infinite);
}
}
}
}
/// <summary>
/// Attempts to start an instant timer-worker-thread which can write
/// queued log messages.
/// </summary>
/// <returns>Returns true when scheduled a timer-worker-thread</returns>
protected virtual bool StartInstantWriterTimer()
{
return StartTimerUnlessWriterActive(true);
}
private bool StartTimerUnlessWriterActive(bool instant)
{
bool lockTaken = false;
try
{
lockTaken = Monitor.TryEnter(_writeLockObject);
if (lockTaken)
{
// Lock taken means no other timer-worker-thread is trying to write, schedule timer now
if (instant)
{
lock (_timerLockObject)
{
if (_lazyWriterTimer != null)
{
// Not optimal to schedule timer-worker-thread while holding lock,
// as the newly scheduled timer-worker-thread will hammer into the writeLockObject
_lazyWriterTimer.Change(0, Timeout.Infinite);
return true;
}
}
}
else
{
StartLazyWriterTimer();
return true;
}
}
}
finally
{
// If not able to take lock, then it means timer-worker-thread is already active,
// and timer-worker-thread will check RequestQueue after leaving writeLockObject
if (lockTaken)
Monitor.Exit(_writeLockObject);
}
return false;
}
/// <summary>
/// Stops the lazy writer thread.
/// </summary>
protected virtual void StopLazyWriterThread()
{
lock (_timerLockObject)
{
var currentTimer = _lazyWriterTimer;
if (currentTimer != null)
{
_lazyWriterTimer = null;
currentTimer.WaitForDispose(TimeSpan.FromSeconds(1));
}
}
}
/// <summary>
/// Adds the log event to asynchronous queue to be processed by
/// the lazy writer thread.
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <remarks>
/// The <see cref="Target.PrecalculateVolatileLayouts"/> is called
/// to ensure that the log event can be processed in another thread.
/// </remarks>
protected override void Write(AsyncLogEventInfo logEvent)
{
PrecalculateVolatileLayouts(logEvent.LogEvent);
bool queueWasEmpty = _requestQueue.Enqueue(logEvent);
if (queueWasEmpty)
{
if (TimeToSleepBetweenBatches == 0)
StartInstantWriterTimer();
else if (TimeToSleepBetweenBatches <= 1)
StartTimerUnlessWriterActive(false);
}
}
/// <summary>
/// Write to queue without locking <see cref="Target.SyncRoot"/>
/// </summary>
/// <param name="logEvent"></param>
protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent)
{
try
{
Write(logEvent);
}
catch (Exception exception)
{
if (ExceptionMustBeRethrown(exception))
{
throw;
}
logEvent.Continuation(exception);
}
}
private void ProcessPendingEvents(object state)
{
if (_lazyWriterTimer == null)
return;
bool wroteFullBatchSize = false;
try
{
lock (_writeLockObject)
{
int count = WriteEventsInQueue(BatchSize, "Timer");
if (count == BatchSize)
wroteFullBatchSize = true;
if (wroteFullBatchSize && TimeToSleepBetweenBatches <= 1)
StartInstantWriterTimer(); // Found full batch, fast schedule to take next batch (within lock to avoid pile up)
}
}
catch (Exception exception)
{
wroteFullBatchSize = false; // Something went wrong, lets throttle retry
InternalLogger.Error(exception, "AsyncWrapper(Name={0}): Error in lazy writer timer procedure.", Name);
#if DEBUG
if (exception.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
#endif
}
finally
{
if (TimeToSleepBetweenBatches <= 1)
{
if (!wroteFullBatchSize && !_requestQueue.IsEmpty)
{
// If queue was not empty, then more might have arrived while writing the first batch
// Do not use instant timer, so we can process in larger batches (faster)
StartTimerUnlessWriterActive(false);
}
}
else
{
StartLazyWriterTimer();
}
}
}
private void FlushEventsInQueue(object state)
{
try
{
var asyncContinuation = state as AsyncContinuation;
lock (_writeLockObject)
{
WriteEventsInQueue(int.MaxValue, "Flush Async");
if (asyncContinuation != null)
base.FlushAsync(asyncContinuation);
}
if (TimeToSleepBetweenBatches <= 1 && !_requestQueue.IsEmpty)
StartTimerUnlessWriterActive(false);
}
catch (Exception exception)
{
InternalLogger.Error(exception, "AsyncWrapper(Name={0}): Error in flush procedure.", Name);
#if DEBUG
if (exception.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
#endif
}
}
private int WriteEventsInQueue(int batchSize, string reason)
{
if (WrappedTarget == null)
{
InternalLogger.Error("AsyncWrapper(Name={0}): WrappedTarget is NULL", Name);
return 0;
}
int count = 0;
for (int i = 0; i < FullBatchSizeWriteLimit; ++i)
{
if (!OptimizeBufferReuse || batchSize == int.MaxValue)
{
var logEvents = _requestQueue.DequeueBatch(batchSize);
if (logEvents.Length > 0)
{
if (reason != null)
InternalLogger.Trace("AsyncWrapper(Name={0}): Writing {1} events ({2})", Name, logEvents.Length, reason);
WrappedTarget.WriteAsyncLogEvents(logEvents);
}
count = logEvents.Length;
}
else
{
using (var targetList = _reusableAsyncLogEventList.Allocate())
{
var logEvents = targetList.Result;
_requestQueue.DequeueBatch(batchSize, logEvents);
if (logEvents.Count > 0)
{
if (reason != null)
InternalLogger.Trace("AsyncWrapper(Name={0}): Writing {1} events ({2})", Name, logEvents.Count, reason);
WrappedTarget.WriteAsyncLogEvents(logEvents);
}
count = logEvents.Count;
}
}
if (count < batchSize)
break;
}
return count;
}
private void OnRequestQueueDropItem(object sender, LogEventDroppedEventArgs logEventDroppedEventArgs)
{
_logEventDroppedEvent?.Invoke(this, logEventDroppedEventArgs);
}
private void OnRequestQueueGrow(object sender, LogEventQueueGrowEventArgs logEventQueueGrowEventArgs)
{
_eventQueueGrowEvent?.Invoke(this, logEventQueueGrowEventArgs);
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.MetaData.Normalized
{
using System;
//
// Don't remove "sealed" attribute unless you read comments on Equals method.
//
public sealed class MetaDataTypeDefinitionGenericInstantiation : MetaDataTypeDefinitionAbstract,
IMetaDataUnique
{
//
// State
//
internal MetaDataTypeDefinitionGeneric m_baseType;
internal SignatureType[] m_parameters;
//
// Constructor Methods
//
internal MetaDataTypeDefinitionGenericInstantiation( MetaDataAssembly owner ,
int token ) : base( owner, token )
{
m_elementType = ElementTypes.GENERICINST;
}
//--//
//
// MetaDataEquality Methods
//
public override bool Equals( object obj )
{
if(obj is MetaDataTypeDefinitionGenericInstantiation) // Since the class is sealed (no subclasses allowed), there's no need to compare using .GetType()
{
MetaDataTypeDefinitionGenericInstantiation other = (MetaDataTypeDefinitionGenericInstantiation)obj;
if(m_baseType == other.m_baseType)
{
if(ArrayUtility.ArrayEquals( m_parameters, other.m_parameters))
{
return true;
}
}
}
return false;
}
public override int GetHashCode()
{
return m_baseType.GetHashCode();
}
//
// Helper Methods
//
public override bool IsOpenType
{
get
{
for(int i = 0; i < m_parameters.Length; i++)
{
if(m_parameters[i].IsOpenType)
{
return true;
}
}
return false;
}
}
public override bool Match( MetaDataTypeDefinitionAbstract typeContext ,
MetaDataMethodAbstract methodContext ,
MetaDataTypeDefinitionAbstract type )
{
if(type is MetaDataTypeDefinitionGenericInstantiation)
{
MetaDataTypeDefinitionGenericInstantiation other = (MetaDataTypeDefinitionGenericInstantiation)type;
if(m_baseType == other.m_baseType &&
m_parameters.Length == other.m_parameters.Length )
{
for(int i = 0; i < m_parameters.Length; i++)
{
if(m_parameters[i].Match( typeContext, methodContext, other.m_parameters[i] ) == false)
{
return false;
}
}
return true;
}
}
return false;
}
public MetaDataTypeDefinitionGenericInstantiation Specialize( SignatureType[] genericParameters )
{
MetaDataTypeDefinitionGenericInstantiation tdNew = new MetaDataTypeDefinitionGenericInstantiation( m_owner, 0 );
tdNew.m_baseType = m_baseType;
tdNew.m_parameters = genericParameters;
return tdNew;
}
//
// Access Methods
//
public MetaDataTypeDefinitionGeneric GenericType
{
get
{
return m_baseType;
}
}
public SignatureType[] InstantiationParams
{
get
{
return m_parameters;
}
}
public override bool UsesTypeParameters
{
get
{
foreach(SignatureType td in m_parameters)
{
if(td.UsesTypeParameters) return true;
}
return false;
}
}
public override bool UsesMethodParameters
{
get
{
foreach(SignatureType td in m_parameters)
{
if(td.UsesMethodParameters) return true;
}
return false;
}
}
//
// Debug Methods
//
public override string FullName
{
get
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append( m_baseType.FullName );
sb.Append( "<" );
for(int i = 0; i < m_parameters.Length; i++)
{
if(i != 0) sb.Append( "," );
sb.Append( m_parameters[i].FullName );
}
sb.Append( ">" );
return sb.ToString();
}
}
public override string FullNameWithAbbreviation
{
get
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append( m_baseType.FullNameWithAbbreviation );
sb.Append( "<" );
for(int i = 0; i < m_parameters.Length; i++)
{
if(i != 0) sb.Append( "," );
sb.Append( m_parameters[i].FullNameWithAbbreviation );
}
sb.Append( ">" );
return sb.ToString();
}
}
public override string ToString()
{
return QualifiedToString( "MetaDataTypeDefinitionGenericInstantiation" );
}
public override String ToString( IMetaDataDumper context )
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
context = context.PushContext( this );
sb.Append( m_baseType.ToString( context ) );
return sb.ToString();
}
public override void Dump( IMetaDataDumper writer )
{
throw new NotNormalized( "Dump" );
}
}
}
| |
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Content.Shared.GameObjects.Components.Body.Part;
using Content.Shared.GameObjects.Components.Body.Part.Property;
using Content.Shared.GameObjects.Components.Body.Preset;
using Content.Shared.GameObjects.Components.Body.Template;
using Robust.Shared.Interfaces.GameObjects;
namespace Content.Shared.GameObjects.Components.Body
{
/// <summary>
/// Component representing a collection of <see cref="IBodyPart"/>s
/// attached to each other.
/// </summary>
public interface IBody : IComponent, IBodyPartContainer
{
/// <summary>
/// The name of the <see cref="BodyTemplatePrototype"/> used by this
/// <see cref="IBody"/>.
/// </summary>
public string? TemplateName { get; }
/// <summary>
/// The name of the <see cref="BodyPresetPrototype"/> used by this
/// <see cref="IBody"/>.
/// </summary>
public string? PresetName { get; }
// TODO BODY Part slots
// TODO BODY Sensible templates
/// <summary>
/// Mapping of <see cref="IBodyPart"/> slots in this body to their
/// <see cref="BodyPartType"/>.
/// </summary>
public Dictionary<string, BodyPartType> Slots { get; }
/// <summary>
/// Mapping of slots to the <see cref="IBodyPart"/> filling each one.
/// </summary>
public IReadOnlyDictionary<string, IBodyPart> Parts { get; }
/// <summary>
/// Mapping of slots to which other slots they connect to.
/// For example, the torso could be mapped to a list containing
/// "right arm", "left arm", "left leg", and "right leg".
/// This is mapped both ways during runtime, but in the prototype
/// it only has to be defined one-way, "torso": "left arm" will automatically
/// map "left arm" to "torso" as well.
/// </summary>
public Dictionary<string, List<string>> Connections { get; }
/// <summary>
/// Mapping of template slots to the ID of the <see cref="IBodyPart"/>
/// that should fill it. E.g. "right arm" : "BodyPart.arm.basic_human".
/// </summary>
public IReadOnlyDictionary<string, string> PartIds { get; }
/// <summary>
/// Attempts to add a part to the given slot.
/// </summary>
/// <param name="slot">The slot to add this part to.</param>
/// <param name="part">The part to add.</param>
/// <param name="force">
/// Whether or not to check for the validity of the given <see cref="part"/>.
/// Passing true does not guarantee it to be added, for example if it
/// had already been added before.
/// </param>
/// <returns>
/// true if the part was added, false otherwise even if it was already added.
/// </returns>
bool TryAddPart(string slot, IBodyPart part, bool force = false);
/// <summary>
/// Checks if there is a <see cref="IBodyPart"/> in the given slot.
/// </summary>
/// <param name="slot">The slot to look in.</param>
/// <returns>
/// true if there is a part in the given <see cref="slot"/>,
/// false otherwise.
/// </returns>
bool HasPart(string slot);
/// <summary>
/// Checks if this <see cref="IBody"/> contains the given <see cref="part"/>.
/// </summary>
/// <param name="part">The part to look for.</param>
/// <returns>
/// true if the given <see cref="part"/> is attached to the body,
/// false otherwise.
/// </returns>
bool HasPart(IBodyPart part);
/// <summary>
/// Removes the given <see cref="IBodyPart"/> reference, potentially
/// dropping other <see cref="IBodyPart">BodyParts</see> if they
/// were hanging off of it.
/// </summary>
void RemovePart(IBodyPart part);
/// <summary>
/// Removes the body part in slot <see cref="slot"/> from this body,
/// if one exists.
/// </summary>
/// <param name="slot">The slot to remove it from.</param>
/// <returns>True if the part was removed, false otherwise.</returns>
bool RemovePart(string slot);
/// <summary>
/// Removes the body part from this body, if one exists.
/// </summary>
/// <param name="part">The part to remove from this body.</param>
/// <param name="slotName">The slot that the part was in, if any.</param>
/// <returns>True if <see cref="part"/> was removed, false otherwise.</returns>
bool RemovePart(IBodyPart part, [NotNullWhen(true)] out string? slotName);
/// <summary>
/// Disconnects the given <see cref="IBodyPart"/> reference, potentially
/// dropping other <see cref="IBodyPart">BodyParts</see> if they
/// were hanging off of it.
/// </summary>
/// <param name="part">The part to drop.</param>
/// <param name="dropped">
/// All of the parts that were dropped, including <see cref="part"/>.
/// </param>
/// <returns>
/// True if the part was dropped, false otherwise.
/// </returns>
bool TryDropPart(IBodyPart part, [NotNullWhen(true)] out List<IBodyPart>? dropped);
/// <summary>
/// Recursively searches for if <see cref="part"/> is connected to
/// the center.
/// </summary>
/// <param name="part">The body part to find the center for.</param>
/// <returns>True if it is connected to the center, false otherwise.</returns>
bool ConnectedToCenter(IBodyPart part);
/// <summary>
/// Finds the central <see cref="IBodyPart"/>, if any, of this body based on
/// the <see cref="BodyTemplate"/>. For humans, this is the torso.
/// </summary>
/// <returns>The <see cref="BodyPart"/> if one exists, null otherwise.</returns>
IBodyPart? CenterPart();
/// <summary>
/// Returns whether the given part slot name exists within the current
/// <see cref="BodyTemplate"/>.
/// </summary>
/// <param name="slot">The slot to check for.</param>
/// <returns>True if the slot exists in this body, false otherwise.</returns>
bool HasSlot(string slot);
/// <summary>
/// Finds the <see cref="IBodyPart"/> in the given <see cref="slot"/> if
/// one exists.
/// </summary>
/// <param name="slot">The part slot to search in.</param>
/// <param name="result">The body part in that slot, if any.</param>
/// <returns>True if found, false otherwise.</returns>
bool TryGetPart(string slot, [NotNullWhen(true)] out IBodyPart? result);
/// <summary>
/// Finds the slotName that the given <see cref="IBodyPart"/> resides in.
/// </summary>
/// <param name="part">
/// The <see cref="IBodyPart"/> to find the slot for.
/// </param>
/// <param name="slot">The slot found, if any.</param>
/// <returns>True if a slot was found, false otherwise</returns>
bool TryGetSlot(IBodyPart part, [NotNullWhen(true)] out string? slot);
/// <summary>
/// Finds the <see cref="BodyPartType"/> in the given
/// <see cref="slot"/> if one exists.
/// </summary>
/// <param name="slot">The slot to search in.</param>
/// <param name="result">
/// The <see cref="BodyPartType"/> of that slot, if any.
/// </param>
/// <returns>True if found, false otherwise.</returns>
bool TryGetSlotType(string slot, out BodyPartType result);
/// <summary>
/// Finds the names of all slots connected to the given
/// <see cref="slot"/> for the template.
/// </summary>
/// <param name="slot">The slot to search in.</param>
/// <param name="connections">The connections found, if any.</param>
/// <returns>True if the connections are found, false otherwise.</returns>
bool TryGetSlotConnections(string slot, [NotNullWhen(true)] out List<string>? connections);
/// <summary>
/// Grabs all occupied slots connected to the given slot,
/// regardless of whether the given <see cref="slot"/> is occupied.
/// </summary>
/// <param name="slot">The slot name to find connections from.</param>
/// <param name="connections">The connected body parts, if any.</param>
/// <returns>
/// True if successful, false if the slot couldn't be found on this body.
/// </returns>
bool TryGetPartConnections(string slot, [NotNullWhen(true)] out List<IBodyPart>? connections);
/// <summary>
/// Grabs all parts connected to the given <see cref="part"/>, regardless
/// of whether the given <see cref="part"/> is occupied.
/// </summary>
/// <param name="part">The part to find connections from.</param>
/// <param name="connections">The connected body parts, if any.</param>
/// <returns>
/// True if successful, false if the part couldn't be found on this body.
/// </returns>
bool TryGetPartConnections(IBodyPart part, [NotNullWhen(true)] out List<IBodyPart>? connections);
/// <summary>
/// Finds all <see cref="IBodyPart"/>s of the given type in this body.
/// </summary>
/// <returns>A list of parts of that type.</returns>
List<IBodyPart> GetPartsOfType(BodyPartType type);
/// <summary>
/// Finds all <see cref="IBodyPart"/>s with the given property in this body.
/// </summary>
/// <type name="type">The property type to look for.</type>
/// <returns>A list of parts with that property.</returns>
List<(IBodyPart part, IBodyPartProperty property)> GetPartsWithProperty(Type type);
/// <summary>
/// Finds all <see cref="IBodyPart"/>s with the given property in this body.
/// </summary>
/// <typeparam name="T">The property type to look for.</typeparam>
/// <returns>A list of parts with that property.</returns>
List<(IBodyPart part, T property)> GetPartsWithProperty<T>() where T : class, IBodyPartProperty;
// TODO BODY Make a slot object that makes sense to the human mind, and make it serializable. Imagine the possibilities!
/// <summary>
/// Retrieves the slot at the given index.
/// </summary>
/// <param name="index">The index to look in.</param>
/// <returns>A pair of the slot name and part type occupying it.</returns>
KeyValuePair<string, BodyPartType> SlotAt(int index);
/// <summary>
/// Retrieves the part at the given index.
/// </summary>
/// <param name="index">The index to look in.</param>
/// <returns>A pair of the part name and body part occupying it.</returns>
KeyValuePair<string, IBodyPart> PartAt(int index);
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Security.Authentication;
using System.Text;
using System.Xml;
using SuperSocket.Common;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
namespace SuperSocket.SocketEngine.Configuration
{
/// <summary>
/// Server configuration
/// </summary>
public class Server : ConfigurationElementBase, IServerConfig
{
/// <summary>
/// Gets the name of the service.
/// </summary>
/// <value>
/// The name of the service.
/// </value>
[ConfigurationProperty("serviceName", IsRequired = true)]
public string ServiceName
{
get { return this["serviceName"] as string; }
}
/// <summary>
/// Gets the protocol.
/// </summary>
[ConfigurationProperty("protocol", IsRequired = false)]
public string Protocol
{
get { return this["protocol"] as string; }
}
/// <summary>
/// Gets the ip.
/// </summary>
[ConfigurationProperty("ip", IsRequired = false)]
public string Ip
{
get { return this["ip"] as string; }
}
/// <summary>
/// Gets the port.
/// </summary>
[ConfigurationProperty("port", IsRequired = true)]
public int Port
{
get { return (int)this["port"]; }
}
/// <summary>
/// Gets the mode.
/// </summary>
[ConfigurationProperty("mode", IsRequired = false, DefaultValue = "Tcp")]
public SocketMode Mode
{
get { return (SocketMode)this["mode"]; }
}
/// <summary>
/// Gets a value indicating whether this <see cref="IServerConfig"/> is disabled.
/// </summary>
/// <value>
/// <c>true</c> if disabled; otherwise, <c>false</c>.
/// </value>
[ConfigurationProperty("disabled", DefaultValue = "false")]
public bool Disabled
{
get { return (bool)this["disabled"]; }
}
/// <summary>
/// Gets a value indicating whether [enable management service].
/// </summary>
/// <value>
/// <c>true</c> if [enable management service]; otherwise, <c>false</c>.
/// </value>
[ConfigurationProperty("enableManagementService", DefaultValue = "false")]
public bool EnableManagementService
{
get { return (bool)this["enableManagementService"]; }
}
/// <summary>
/// Gets the provider.
/// </summary>
[ConfigurationProperty("provider", IsRequired = false)]
public string Provider
{
get { return (string)this["provider"]; }
}
/// <summary>
/// Gets the read time out.
/// </summary>
[ConfigurationProperty("readTimeOut", IsRequired = false, DefaultValue = 0)]
public int ReadTimeOut
{
get { return (int)this["readTimeOut"]; }
}
/// <summary>
/// Gets the send time out.
/// </summary>
[ConfigurationProperty("sendTimeOut", IsRequired = false, DefaultValue = 0)]
public int SendTimeOut
{
get { return (int)this["sendTimeOut"]; }
}
/// <summary>
/// Gets the max connection number.
/// </summary>
[ConfigurationProperty("maxConnectionNumber", IsRequired = false, DefaultValue = 100)]
public int MaxConnectionNumber
{
get { return (int)this["maxConnectionNumber"]; }
}
/// <summary>
/// Gets the size of the receive buffer.
/// </summary>
/// <value>
/// The size of the receive buffer.
/// </value>
[ConfigurationProperty("receiveBufferSize", IsRequired = false, DefaultValue = 2048)]
public int ReceiveBufferSize
{
get { return (int)this["receiveBufferSize"]; }
}
/// <summary>
/// Gets the size of the send buffer.
/// </summary>
/// <value>
/// The size of the send buffer.
/// </value>
[ConfigurationProperty("sendBufferSize", IsRequired = false, DefaultValue = 2048)]
public int SendBufferSize
{
get { return (int)this["sendBufferSize"]; }
}
/// <summary>
/// Gets a value indicating whether log command in log file.
/// </summary>
/// <value><c>true</c> if log command; otherwise, <c>false</c>.</value>
[ConfigurationProperty("logCommand", IsRequired = false, DefaultValue = false)]
public bool LogCommand
{
get { return (bool)this["logCommand"]; }
}
/// <summary>
/// Gets a value indicating whether clear idle session.
/// </summary>
/// <value><c>true</c> if clear idle session; otherwise, <c>false</c>.</value>
[ConfigurationProperty("clearIdleSession", IsRequired = false, DefaultValue = false)]
public bool ClearIdleSession
{
get { return (bool)this["clearIdleSession"]; }
}
/// <summary>
/// Gets the clear idle session interval, in seconds.
/// </summary>
/// <value>The clear idle session interval.</value>
[ConfigurationProperty("clearIdleSessionInterval", IsRequired = false, DefaultValue = 120)]
public int ClearIdleSessionInterval
{
get { return (int)this["clearIdleSessionInterval"]; }
}
/// <summary>
/// Gets the idle session timeout time length, in seconds.
/// </summary>
/// <value>The idle session time out.</value>
[ConfigurationProperty("idleSessionTimeOut", IsRequired = false, DefaultValue = 300)]
public int IdleSessionTimeOut
{
get { return (int)this["idleSessionTimeOut"]; }
}
/// <summary>
/// Gets the certificate config.
/// </summary>
/// <value>The certificate config.</value>
[ConfigurationProperty("certificate", IsRequired = false)]
public CertificateConfig CertificateConfig
{
get { return (CertificateConfig)this["certificate"]; }
}
/// <summary>
/// Gets X509Certificate configuration.
/// </summary>
/// <value>
/// X509Certificate configuration.
/// </value>
public ICertificateConfig Certificate
{
get { return CertificateConfig; }
}
/// <summary>
/// Gets the security protocol, X509 certificate.
/// </summary>
[ConfigurationProperty("security", IsRequired = false, DefaultValue = "None")]
public string Security
{
get
{
return (string)this["security"];
}
}
/// <summary>
/// Gets the max allowed length of request.
/// </summary>
/// <value>
/// The max allowed length of request.
/// </value>
[ConfigurationProperty("maxRequestLength", IsRequired = false, DefaultValue = 1024)]
public int MaxRequestLength
{
get
{
return (int)this["maxRequestLength"];
}
}
/// <summary>
/// Gets a value indicating whether [disable session snapshot]
/// </summary>
[ConfigurationProperty("disableSessionSnapshot", IsRequired = false, DefaultValue = false)]
public bool DisableSessionSnapshot
{
get
{
return (bool)this["disableSessionSnapshot"];
}
}
/// <summary>
/// Gets the interval to taking snapshot for all live sessions.
/// </summary>
[ConfigurationProperty("sessionSnapshotInterval", IsRequired = false, DefaultValue = 5)]
public int SessionSnapshotInterval
{
get
{
return (int)this["sessionSnapshotInterval"];
}
}
/// <summary>
/// Gets the connection filters used by this server instance.
/// </summary>
/// <value>
/// The connection filters's name list, seperated by comma
/// </value>
[ConfigurationProperty("connectionFilters", IsRequired = false)]
public string ConnectionFilters
{
get
{
return (string)this["connectionFilters"];
}
}
/// <summary>
/// Gets the start keep alive time, in seconds
/// </summary>
[ConfigurationProperty("keepAliveTime", IsRequired = false, DefaultValue = 600)]
public int KeepAliveTime
{
get
{
return (int)this["keepAliveTime"];
}
}
/// <summary>
/// Gets the keep alive interval, in seconds.
/// </summary>
[ConfigurationProperty("keepAliveInterval", IsRequired = false, DefaultValue = 60)]
public int KeepAliveInterval
{
get
{
return (int)this["keepAliveInterval"];
}
}
/// <summary>
/// Gets a value indicating whether [enable dynamic command](support commands written in IronPython).
/// </summary>
/// <value>
/// <c>true</c> if [dynamic command is enabled]; otherwise, <c>false</c>.
/// </value>
[ConfigurationProperty("enableDynamicCommand", IsRequired = false, DefaultValue = false)]
public bool EnableDynamicCommand
{
get
{
return (bool)this["enableDynamicCommand"];
}
}
/// <summary>
/// Gets the backlog size of socket listening.
/// </summary>
[ConfigurationProperty("listenBacklog", IsRequired = false, DefaultValue = 100)]
public int ListenBacklog
{
get
{
return (int)this["listenBacklog"];
}
}
/// <summary>
/// Gets the startup order of the server instance.
/// </summary>
[ConfigurationProperty("startupOrder", IsRequired = false, DefaultValue = 0)]
public int StartupOrder
{
get
{
return (int)this["startupOrder"];
}
}
/// <summary>
/// Gets the listeners' configuration.
/// </summary>
[ConfigurationProperty("listeners", IsRequired = false)]
public ListenerConfigCollection Listeners
{
get
{
return this["listeners"] as ListenerConfigCollection;
}
}
/// <summary>
/// Gets the listeners' configuration.
/// </summary>
IEnumerable<IListenerConfig> IServerConfig.Listeners
{
get
{
return this.Listeners;
}
}
/// <summary>
/// Gets the child config.
/// </summary>
/// <typeparam name="TConfig">The type of the config.</typeparam>
/// <param name="childConfigName">Name of the child config.</param>
/// <returns></returns>
public TConfig GetChildConfig<TConfig>(string childConfigName)
where TConfig : ConfigurationElement, new()
{
var childConfig = this.OptionElements.GetValue(childConfigName, string.Empty);
if (string.IsNullOrEmpty(childConfig))
return default(TConfig);
var checkConfig = childConfig.Replace(Environment.NewLine, string.Empty).Trim();
if (string.IsNullOrEmpty(checkConfig))
return default(TConfig);
XmlReader reader = new XmlTextReader(new StringReader(checkConfig));
var config = new TConfig();
config.Deserialize(reader);
return config;
}
}
}
| |
/*
* 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 vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSLInteger = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public partial class ScriptBaseClass
{
// LSL CONSTANTS
public static readonly LSLInteger TRUE = new LSLInteger(1);
public static readonly LSLInteger FALSE = new LSLInteger(0);
public const int STATUS_PHYSICS = 1;
public const int STATUS_ROTATE_X = 2;
public const int STATUS_ROTATE_Y = 4;
public const int STATUS_ROTATE_Z = 8;
public const int STATUS_PHANTOM = 16;
public const int STATUS_SANDBOX = 32;
public const int STATUS_BLOCK_GRAB = 64;
public const int STATUS_DIE_AT_EDGE = 128;
public const int STATUS_RETURN_AT_EDGE = 256;
public const int STATUS_CAST_SHADOWS = 512;
public const int STATUS_BLOCK_GRAB_OBJECT = 1024;
public const int AGENT = 1;
public const int AGENT_BY_LEGACY_NAME = 1;
public const int AGENT_BY_USERNAME = 0x10;
public const int NPC = 0x20;
public const int ACTIVE = 2;
public const int PASSIVE = 4;
public const int SCRIPTED = 8;
public const int OS_NPC = 0x01000000;
public const int CONTROL_FWD = 1;
public const int CONTROL_BACK = 2;
public const int CONTROL_LEFT = 4;
public const int CONTROL_RIGHT = 8;
public const int CONTROL_UP = 16;
public const int CONTROL_DOWN = 32;
public const int CONTROL_ROT_LEFT = 256;
public const int CONTROL_ROT_RIGHT = 512;
public const int CONTROL_LBUTTON = 268435456;
public const int CONTROL_ML_LBUTTON = 1073741824;
//Permissions
public const int PERMISSION_DEBIT = 2;
public const int PERMISSION_TAKE_CONTROLS = 4;
public const int PERMISSION_REMAP_CONTROLS = 8;
public const int PERMISSION_TRIGGER_ANIMATION = 16;
public const int PERMISSION_ATTACH = 32;
public const int PERMISSION_RELEASE_OWNERSHIP = 64;
public const int PERMISSION_CHANGE_LINKS = 128;
public const int PERMISSION_CHANGE_JOINTS = 256;
public const int PERMISSION_CHANGE_PERMISSIONS = 512;
public const int PERMISSION_TRACK_CAMERA = 1024;
public const int PERMISSION_CONTROL_CAMERA = 2048;
public const int AGENT_FLYING = 1;
public const int AGENT_ATTACHMENTS = 2;
public const int AGENT_SCRIPTED = 4;
public const int AGENT_MOUSELOOK = 8;
public const int AGENT_SITTING = 16;
public const int AGENT_ON_OBJECT = 32;
public const int AGENT_AWAY = 64;
public const int AGENT_WALKING = 128;
public const int AGENT_IN_AIR = 256;
public const int AGENT_TYPING = 512;
public const int AGENT_CROUCHING = 1024;
public const int AGENT_BUSY = 2048;
public const int AGENT_ALWAYS_RUN = 4096;
//Particle Systems
public const int PSYS_PART_INTERP_COLOR_MASK = 1;
public const int PSYS_PART_INTERP_SCALE_MASK = 2;
public const int PSYS_PART_BOUNCE_MASK = 4;
public const int PSYS_PART_WIND_MASK = 8;
public const int PSYS_PART_FOLLOW_SRC_MASK = 16;
public const int PSYS_PART_FOLLOW_VELOCITY_MASK = 32;
public const int PSYS_PART_TARGET_POS_MASK = 64;
public const int PSYS_PART_TARGET_LINEAR_MASK = 128;
public const int PSYS_PART_EMISSIVE_MASK = 256;
public const int PSYS_PART_RIBBON_MASK = 1024;
public const int PSYS_PART_FLAGS = 0;
public const int PSYS_PART_START_COLOR = 1;
public const int PSYS_PART_START_ALPHA = 2;
public const int PSYS_PART_END_COLOR = 3;
public const int PSYS_PART_END_ALPHA = 4;
public const int PSYS_PART_START_SCALE = 5;
public const int PSYS_PART_END_SCALE = 6;
public const int PSYS_PART_MAX_AGE = 7;
public const int PSYS_SRC_ACCEL = 8;
public const int PSYS_SRC_PATTERN = 9;
public const int PSYS_SRC_INNERANGLE = 10;
public const int PSYS_SRC_OUTERANGLE = 11;
public const int PSYS_SRC_TEXTURE = 12;
public const int PSYS_SRC_BURST_RATE = 13;
public const int PSYS_SRC_BURST_PART_COUNT = 15;
public const int PSYS_SRC_BURST_RADIUS = 16;
public const int PSYS_SRC_BURST_SPEED_MIN = 17;
public const int PSYS_SRC_BURST_SPEED_MAX = 18;
public const int PSYS_SRC_MAX_AGE = 19;
public const int PSYS_SRC_TARGET_KEY = 20;
public const int PSYS_SRC_OMEGA = 21;
public const int PSYS_SRC_ANGLE_BEGIN = 22;
public const int PSYS_SRC_ANGLE_END = 23;
public const int PSYS_PART_BLEND_FUNC_SOURCE = 24;
public const int PSYS_PART_BLEND_FUNC_DEST = 25;
public const int PSYS_PART_START_GLOW = 26;
public const int PSYS_PART_END_GLOW = 27;
public const int PSYS_PART_BF_ONE = 0;
public const int PSYS_PART_BF_ZERO = 1;
public const int PSYS_PART_BF_DEST_COLOR = 2;
public const int PSYS_PART_BF_SOURCE_COLOR = 3;
public const int PSYS_PART_BF_ONE_MINUS_DEST_COLOR = 4;
public const int PSYS_PART_BF_ONE_MINUS_SOURCE_COLOR = 5;
public const int PSYS_PART_BF_SOURCE_ALPHA = 7;
public const int PSYS_PART_BF_ONE_MINUS_SOURCE_ALPHA = 9;
public const int PSYS_SRC_PATTERN_DROP = 1;
public const int PSYS_SRC_PATTERN_EXPLODE = 2;
public const int PSYS_SRC_PATTERN_ANGLE = 4;
public const int PSYS_SRC_PATTERN_ANGLE_CONE = 8;
public const int PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY = 16;
public const int VEHICLE_TYPE_NONE = 0;
public const int VEHICLE_TYPE_SLED = 1;
public const int VEHICLE_TYPE_CAR = 2;
public const int VEHICLE_TYPE_BOAT = 3;
public const int VEHICLE_TYPE_AIRPLANE = 4;
public const int VEHICLE_TYPE_BALLOON = 5;
public const int VEHICLE_LINEAR_FRICTION_TIMESCALE = 16;
public const int VEHICLE_ANGULAR_FRICTION_TIMESCALE = 17;
public const int VEHICLE_LINEAR_MOTOR_DIRECTION = 18;
public const int VEHICLE_LINEAR_MOTOR_OFFSET = 20;
public const int VEHICLE_ANGULAR_MOTOR_DIRECTION = 19;
public const int VEHICLE_HOVER_HEIGHT = 24;
public const int VEHICLE_HOVER_EFFICIENCY = 25;
public const int VEHICLE_HOVER_TIMESCALE = 26;
public const int VEHICLE_BUOYANCY = 27;
public const int VEHICLE_LINEAR_DEFLECTION_EFFICIENCY = 28;
public const int VEHICLE_LINEAR_DEFLECTION_TIMESCALE = 29;
public const int VEHICLE_LINEAR_MOTOR_TIMESCALE = 30;
public const int VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE = 31;
public const int VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY = 32;
public const int VEHICLE_ANGULAR_DEFLECTION_TIMESCALE = 33;
public const int VEHICLE_ANGULAR_MOTOR_TIMESCALE = 34;
public const int VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE = 35;
public const int VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY = 36;
public const int VEHICLE_VERTICAL_ATTRACTION_TIMESCALE = 37;
public const int VEHICLE_BANKING_EFFICIENCY = 38;
public const int VEHICLE_BANKING_MIX = 39;
public const int VEHICLE_BANKING_TIMESCALE = 40;
public const int VEHICLE_REFERENCE_FRAME = 44;
public const int VEHICLE_RANGE_BLOCK = 45;
public const int VEHICLE_ROLL_FRAME = 46;
public const int VEHICLE_FLAG_NO_DEFLECTION_UP = 1;
public const int VEHICLE_FLAG_LIMIT_ROLL_ONLY = 2;
public const int VEHICLE_FLAG_HOVER_WATER_ONLY = 4;
public const int VEHICLE_FLAG_HOVER_TERRAIN_ONLY = 8;
public const int VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT = 16;
public const int VEHICLE_FLAG_HOVER_UP_ONLY = 32;
public const int VEHICLE_FLAG_LIMIT_MOTOR_UP = 64;
public const int VEHICLE_FLAG_MOUSELOOK_STEER = 128;
public const int VEHICLE_FLAG_MOUSELOOK_BANK = 256;
public const int VEHICLE_FLAG_CAMERA_DECOUPLED = 512;
public const int VEHICLE_FLAG_NO_X = 1024;
public const int VEHICLE_FLAG_NO_Y = 2048;
public const int VEHICLE_FLAG_NO_Z = 4096;
public const int VEHICLE_FLAG_LOCK_HOVER_HEIGHT = 8192;
public const int VEHICLE_FLAG_NO_DEFLECTION = 16392;
public const int VEHICLE_FLAG_LOCK_ROTATION = 32784;
public const int INVENTORY_ALL = -1;
public const int INVENTORY_NONE = -1;
public const int INVENTORY_TEXTURE = 0;
public const int INVENTORY_SOUND = 1;
public const int INVENTORY_LANDMARK = 3;
public const int INVENTORY_CLOTHING = 5;
public const int INVENTORY_OBJECT = 6;
public const int INVENTORY_NOTECARD = 7;
public const int INVENTORY_SCRIPT = 10;
public const int INVENTORY_BODYPART = 13;
public const int INVENTORY_ANIMATION = 20;
public const int INVENTORY_GESTURE = 21;
public const int ATTACH_CHEST = 1;
public const int ATTACH_HEAD = 2;
public const int ATTACH_LSHOULDER = 3;
public const int ATTACH_RSHOULDER = 4;
public const int ATTACH_LHAND = 5;
public const int ATTACH_RHAND = 6;
public const int ATTACH_LFOOT = 7;
public const int ATTACH_RFOOT = 8;
public const int ATTACH_BACK = 9;
public const int ATTACH_PELVIS = 10;
public const int ATTACH_MOUTH = 11;
public const int ATTACH_CHIN = 12;
public const int ATTACH_LEAR = 13;
public const int ATTACH_REAR = 14;
public const int ATTACH_LEYE = 15;
public const int ATTACH_REYE = 16;
public const int ATTACH_NOSE = 17;
public const int ATTACH_RUARM = 18;
public const int ATTACH_RLARM = 19;
public const int ATTACH_LUARM = 20;
public const int ATTACH_LLARM = 21;
public const int ATTACH_RHIP = 22;
public const int ATTACH_RULEG = 23;
public const int ATTACH_RLLEG = 24;
public const int ATTACH_LHIP = 25;
public const int ATTACH_LULEG = 26;
public const int ATTACH_LLLEG = 27;
public const int ATTACH_BELLY = 28;
public const int ATTACH_RPEC = 29;
public const int ATTACH_LPEC = 30;
public const int ATTACH_LEFT_PEC = 29; // Same value as ATTACH_RPEC, see https://jira.secondlife.com/browse/SVC-580
public const int ATTACH_RIGHT_PEC = 30; // Same value as ATTACH_LPEC, see https://jira.secondlife.com/browse/SVC-580
public const int ATTACH_HUD_CENTER_2 = 31;
public const int ATTACH_HUD_TOP_RIGHT = 32;
public const int ATTACH_HUD_TOP_CENTER = 33;
public const int ATTACH_HUD_TOP_LEFT = 34;
public const int ATTACH_HUD_CENTER_1 = 35;
public const int ATTACH_HUD_BOTTOM_LEFT = 36;
public const int ATTACH_HUD_BOTTOM = 37;
public const int ATTACH_HUD_BOTTOM_RIGHT = 38;
public const int ATTACH_NECK = 39;
public const int ATTACH_AVATAR_CENTER = 40;
#region osMessageAttachments constants
/// <summary>
/// Instructs osMessageAttachements to send the message to attachments
/// on every point.
/// </summary>
/// <remarks>
/// One might expect this to be named OS_ATTACH_ALL, but then one might
/// also expect functions designed to attach or detach or get
/// attachments to work with it too. Attaching a no-copy item to
/// many attachments could be dangerous.
/// when combined with OS_ATTACH_MSG_INVERT_POINTS, will prevent the
/// message from being sent.
/// if combined with OS_ATTACH_MSG_OBJECT_CREATOR or
/// OS_ATTACH_MSG_SCRIPT_CREATOR, could result in no message being
/// sent- this is expected behaviour.
/// </remarks>
public const int OS_ATTACH_MSG_ALL = -65535;
/// <summary>
/// Instructs osMessageAttachements to invert how the attachment points
/// list should be treated (e.g. go from inclusive operation to
/// exclusive operation).
/// </summary>
/// <remarks>
/// This might be used if you want to deliver a message to one set of
/// attachments and a different message to everything else. With
/// this flag, you only need to build one explicit list for both calls.
/// </remarks>
public const int OS_ATTACH_MSG_INVERT_POINTS = 1;
/// <summary>
/// Instructs osMessageAttachments to only send the message to
/// attachments with a CreatorID that matches the host object CreatorID
/// </summary>
/// <remarks>
/// This would be used if distributed in an object vendor/updater server.
/// </remarks>
public const int OS_ATTACH_MSG_OBJECT_CREATOR = 2;
/// <summary>
/// Instructs osMessageAttachments to only send the message to
/// attachments with a CreatorID that matches the sending script CreatorID
/// </summary>
/// <remarks>
/// This might be used if the script is distributed independently of a
/// containing object.
/// </remarks>
public const int OS_ATTACH_MSG_SCRIPT_CREATOR = 4;
#endregion
public const int LAND_LEVEL = 0;
public const int LAND_RAISE = 1;
public const int LAND_LOWER = 2;
public const int LAND_SMOOTH = 3;
public const int LAND_NOISE = 4;
public const int LAND_REVERT = 5;
public const int LAND_SMALL_BRUSH = 1;
public const int LAND_MEDIUM_BRUSH = 2;
public const int LAND_LARGE_BRUSH = 3;
//Agent Dataserver
public const int DATA_ONLINE = 1;
public const int DATA_NAME = 2;
public const int DATA_BORN = 3;
public const int DATA_RATING = 4;
public const int DATA_SIM_POS = 5;
public const int DATA_SIM_STATUS = 6;
public const int DATA_SIM_RATING = 7;
public const int DATA_PAYINFO = 8;
public const int DATA_SIM_RELEASE = 128;
public const int ANIM_ON = 1;
public const int LOOP = 2;
public const int REVERSE = 4;
public const int PING_PONG = 8;
public const int SMOOTH = 16;
public const int ROTATE = 32;
public const int SCALE = 64;
public const int ALL_SIDES = -1;
public const int LINK_SET = -1;
public const int LINK_ROOT = 1;
public const int LINK_ALL_OTHERS = -2;
public const int LINK_ALL_CHILDREN = -3;
public const int LINK_THIS = -4;
public const int CHANGED_INVENTORY = 1;
public const int CHANGED_COLOR = 2;
public const int CHANGED_SHAPE = 4;
public const int CHANGED_SCALE = 8;
public const int CHANGED_TEXTURE = 16;
public const int CHANGED_LINK = 32;
public const int CHANGED_ALLOWED_DROP = 64;
public const int CHANGED_OWNER = 128;
public const int CHANGED_REGION = 256;
public const int CHANGED_TELEPORT = 512;
public const int CHANGED_REGION_RESTART = 1024;
public const int CHANGED_REGION_START = 1024; //LL Changed the constant from CHANGED_REGION_RESTART
public const int CHANGED_MEDIA = 2048;
public const int CHANGED_ANIMATION = 16384;
public const int TYPE_INVALID = 0;
public const int TYPE_INTEGER = 1;
public const int TYPE_FLOAT = 2;
public const int TYPE_STRING = 3;
public const int TYPE_KEY = 4;
public const int TYPE_VECTOR = 5;
public const int TYPE_ROTATION = 6;
//XML RPC Remote Data Channel
public const int REMOTE_DATA_CHANNEL = 1;
public const int REMOTE_DATA_REQUEST = 2;
public const int REMOTE_DATA_REPLY = 3;
//llHTTPRequest
public const int HTTP_METHOD = 0;
public const int HTTP_MIMETYPE = 1;
public const int HTTP_BODY_MAXLENGTH = 2;
public const int HTTP_VERIFY_CERT = 3;
public const int HTTP_VERBOSE_THROTTLE = 4;
public const int HTTP_CUSTOM_HEADER = 5;
public const int HTTP_PRAGMA_NO_CACHE = 6;
// llSetContentType
public const int CONTENT_TYPE_TEXT = 0; //text/plain
public const int CONTENT_TYPE_HTML = 1; //text/html
public const int CONTENT_TYPE_XML = 2; //application/xml
public const int CONTENT_TYPE_XHTML = 3; //application/xhtml+xml
public const int CONTENT_TYPE_ATOM = 4; //application/atom+xml
public const int CONTENT_TYPE_JSON = 5; //application/json
public const int CONTENT_TYPE_LLSD = 6; //application/llsd+xml
public const int CONTENT_TYPE_FORM = 7; //application/x-www-form-urlencoded
public const int CONTENT_TYPE_RSS = 8; //application/rss+xml
public const int PRIM_MATERIAL = 2;
public const int PRIM_PHYSICS = 3;
public const int PRIM_TEMP_ON_REZ = 4;
public const int PRIM_PHANTOM = 5;
public const int PRIM_POSITION = 6;
public const int PRIM_SIZE = 7;
public const int PRIM_ROTATION = 8;
public const int PRIM_TYPE = 9;
public const int PRIM_TEXTURE = 17;
public const int PRIM_COLOR = 18;
public const int PRIM_BUMP_SHINY = 19;
public const int PRIM_FULLBRIGHT = 20;
public const int PRIM_FLEXIBLE = 21;
public const int PRIM_TEXGEN = 22;
public const int PRIM_CAST_SHADOWS = 24; // Not implemented, here for completeness sake
public const int PRIM_POINT_LIGHT = 23; // Huh?
public const int PRIM_GLOW = 25;
public const int PRIM_TEXT = 26;
public const int PRIM_NAME = 27;
public const int PRIM_DESC = 28;
public const int PRIM_ROT_LOCAL = 29;
public const int PRIM_OMEGA = 32;
public const int PRIM_POS_LOCAL = 33;
public const int PRIM_LINK_TARGET = 34;
public const int PRIM_SLICE = 35;
public const int PRIM_SPECULAR = 36;
public const int PRIM_NORMAL = 37;
public const int PRIM_ALPHA_MODE = 38;
public const int PRIM_TEXGEN_DEFAULT = 0;
public const int PRIM_TEXGEN_PLANAR = 1;
public const int PRIM_TYPE_BOX = 0;
public const int PRIM_TYPE_CYLINDER = 1;
public const int PRIM_TYPE_PRISM = 2;
public const int PRIM_TYPE_SPHERE = 3;
public const int PRIM_TYPE_TORUS = 4;
public const int PRIM_TYPE_TUBE = 5;
public const int PRIM_TYPE_RING = 6;
public const int PRIM_TYPE_SCULPT = 7;
public const int PRIM_HOLE_DEFAULT = 0;
public const int PRIM_HOLE_CIRCLE = 16;
public const int PRIM_HOLE_SQUARE = 32;
public const int PRIM_HOLE_TRIANGLE = 48;
public const int PRIM_MATERIAL_STONE = 0;
public const int PRIM_MATERIAL_METAL = 1;
public const int PRIM_MATERIAL_GLASS = 2;
public const int PRIM_MATERIAL_WOOD = 3;
public const int PRIM_MATERIAL_FLESH = 4;
public const int PRIM_MATERIAL_PLASTIC = 5;
public const int PRIM_MATERIAL_RUBBER = 6;
public const int PRIM_MATERIAL_LIGHT = 7;
public const int PRIM_SHINY_NONE = 0;
public const int PRIM_SHINY_LOW = 1;
public const int PRIM_SHINY_MEDIUM = 2;
public const int PRIM_SHINY_HIGH = 3;
public const int PRIM_BUMP_NONE = 0;
public const int PRIM_BUMP_BRIGHT = 1;
public const int PRIM_BUMP_DARK = 2;
public const int PRIM_BUMP_WOOD = 3;
public const int PRIM_BUMP_BARK = 4;
public const int PRIM_BUMP_BRICKS = 5;
public const int PRIM_BUMP_CHECKER = 6;
public const int PRIM_BUMP_CONCRETE = 7;
public const int PRIM_BUMP_TILE = 8;
public const int PRIM_BUMP_STONE = 9;
public const int PRIM_BUMP_DISKS = 10;
public const int PRIM_BUMP_GRAVEL = 11;
public const int PRIM_BUMP_BLOBS = 12;
public const int PRIM_BUMP_SIDING = 13;
public const int PRIM_BUMP_LARGETILE = 14;
public const int PRIM_BUMP_STUCCO = 15;
public const int PRIM_BUMP_SUCTION = 16;
public const int PRIM_BUMP_WEAVE = 17;
public const int PRIM_SCULPT_TYPE_SPHERE = 1;
public const int PRIM_SCULPT_TYPE_TORUS = 2;
public const int PRIM_SCULPT_TYPE_PLANE = 3;
public const int PRIM_SCULPT_TYPE_CYLINDER = 4;
public const int PRIM_SCULPT_FLAG_INVERT = 64;
public const int PRIM_SCULPT_FLAG_MIRROR = 128;
public const int PROFILE_NONE = 0;
public const int PROFILE_SCRIPT_MEMORY = 1;
public const int MASK_BASE = 0;
public const int MASK_OWNER = 1;
public const int MASK_GROUP = 2;
public const int MASK_EVERYONE = 3;
public const int MASK_NEXT = 4;
public const int PERM_TRANSFER = 8192;
public const int PERM_MODIFY = 16384;
public const int PERM_COPY = 32768;
public const int PERM_MOVE = 524288;
public const int PERM_ALL = 2147483647;
public const int PARCEL_MEDIA_COMMAND_STOP = 0;
public const int PARCEL_MEDIA_COMMAND_PAUSE = 1;
public const int PARCEL_MEDIA_COMMAND_PLAY = 2;
public const int PARCEL_MEDIA_COMMAND_LOOP = 3;
public const int PARCEL_MEDIA_COMMAND_TEXTURE = 4;
public const int PARCEL_MEDIA_COMMAND_URL = 5;
public const int PARCEL_MEDIA_COMMAND_TIME = 6;
public const int PARCEL_MEDIA_COMMAND_AGENT = 7;
public const int PARCEL_MEDIA_COMMAND_UNLOAD = 8;
public const int PARCEL_MEDIA_COMMAND_AUTO_ALIGN = 9;
public const int PARCEL_MEDIA_COMMAND_TYPE = 10;
public const int PARCEL_MEDIA_COMMAND_SIZE = 11;
public const int PARCEL_MEDIA_COMMAND_DESC = 12;
public const int PARCEL_FLAG_ALLOW_FLY = 0x1; // parcel allows flying
public const int PARCEL_FLAG_ALLOW_SCRIPTS = 0x2; // parcel allows outside scripts
public const int PARCEL_FLAG_ALLOW_LANDMARK = 0x8; // parcel allows landmarks to be created
public const int PARCEL_FLAG_ALLOW_TERRAFORM = 0x10; // parcel allows anyone to terraform the land
public const int PARCEL_FLAG_ALLOW_DAMAGE = 0x20; // parcel allows damage
public const int PARCEL_FLAG_ALLOW_CREATE_OBJECTS = 0x40; // parcel allows anyone to create objects
public const int PARCEL_FLAG_USE_ACCESS_GROUP = 0x100; // parcel limits access to a group
public const int PARCEL_FLAG_USE_ACCESS_LIST = 0x200; // parcel limits access to a list of residents
public const int PARCEL_FLAG_USE_BAN_LIST = 0x400; // parcel uses a ban list, including restricting access based on payment info
public const int PARCEL_FLAG_USE_LAND_PASS_LIST = 0x800; // parcel allows passes to be purchased
public const int PARCEL_FLAG_LOCAL_SOUND_ONLY = 0x8000; // parcel restricts spatialized sound to the parcel
public const int PARCEL_FLAG_RESTRICT_PUSHOBJECT = 0x200000; // parcel restricts llPushObject
public const int PARCEL_FLAG_ALLOW_GROUP_SCRIPTS = 0x2000000; // parcel allows scripts owned by group
public const int PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS = 0x4000000; // parcel allows group object creation
public const int PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY = 0x8000000; // parcel allows objects owned by any user to enter
public const int PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY = 0x10000000; // parcel allows with the same group to enter
public const int REGION_FLAG_ALLOW_DAMAGE = 0x1; // region is entirely damage enabled
public const int REGION_FLAG_FIXED_SUN = 0x10; // region has a fixed sun position
public const int REGION_FLAG_BLOCK_TERRAFORM = 0x40; // region terraforming disabled
public const int REGION_FLAG_SANDBOX = 0x100; // region is a sandbox
public const int REGION_FLAG_DISABLE_COLLISIONS = 0x1000; // region has disabled collisions
public const int REGION_FLAG_DISABLE_PHYSICS = 0x4000; // region has disabled physics
public const int REGION_FLAG_BLOCK_FLY = 0x80000; // region blocks flying
public const int REGION_FLAG_ALLOW_DIRECT_TELEPORT = 0x100000; // region allows direct teleports
public const int REGION_FLAG_RESTRICT_PUSHOBJECT = 0x400000; // region restricts llPushObject
//llManageEstateAccess
public const int ESTATE_ACCESS_ALLOWED_AGENT_ADD = 0;
public const int ESTATE_ACCESS_ALLOWED_AGENT_REMOVE = 1;
public const int ESTATE_ACCESS_ALLOWED_GROUP_ADD = 2;
public const int ESTATE_ACCESS_ALLOWED_GROUP_REMOVE = 3;
public const int ESTATE_ACCESS_BANNED_AGENT_ADD = 4;
public const int ESTATE_ACCESS_BANNED_AGENT_REMOVE = 5;
public static readonly LSLInteger PAY_HIDE = new LSLInteger(-1);
public static readonly LSLInteger PAY_DEFAULT = new LSLInteger(-2);
public const string NULL_KEY = "00000000-0000-0000-0000-000000000000";
public const string EOF = "\n\n\n";
public const double PI = 3.14159274f;
public const double TWO_PI = 6.28318548f;
public const double PI_BY_TWO = 1.57079637f;
public const double DEG_TO_RAD = 0.01745329238f;
public const double RAD_TO_DEG = 57.29578f;
public const double SQRT2 = 1.414213538f;
public const int STRING_TRIM_HEAD = 1;
public const int STRING_TRIM_TAIL = 2;
public const int STRING_TRIM = 3;
public const int LIST_STAT_RANGE = 0;
public const int LIST_STAT_MIN = 1;
public const int LIST_STAT_MAX = 2;
public const int LIST_STAT_MEAN = 3;
public const int LIST_STAT_MEDIAN = 4;
public const int LIST_STAT_STD_DEV = 5;
public const int LIST_STAT_SUM = 6;
public const int LIST_STAT_SUM_SQUARES = 7;
public const int LIST_STAT_NUM_COUNT = 8;
public const int LIST_STAT_GEOMETRIC_MEAN = 9;
public const int LIST_STAT_HARMONIC_MEAN = 100;
//ParcelPrim Categories
public const int PARCEL_COUNT_TOTAL = 0;
public const int PARCEL_COUNT_OWNER = 1;
public const int PARCEL_COUNT_GROUP = 2;
public const int PARCEL_COUNT_OTHER = 3;
public const int PARCEL_COUNT_SELECTED = 4;
public const int PARCEL_COUNT_TEMP = 5;
public const int DEBUG_CHANNEL = 0x7FFFFFFF;
public const int PUBLIC_CHANNEL = 0x00000000;
// Constants for llGetObjectDetails
public const int OBJECT_UNKNOWN_DETAIL = -1;
public const int OBJECT_NAME = 1;
public const int OBJECT_DESC = 2;
public const int OBJECT_POS = 3;
public const int OBJECT_ROT = 4;
public const int OBJECT_VELOCITY = 5;
public const int OBJECT_OWNER = 6;
public const int OBJECT_GROUP = 7;
public const int OBJECT_CREATOR = 8;
public const int OBJECT_RUNNING_SCRIPT_COUNT = 9;
public const int OBJECT_TOTAL_SCRIPT_COUNT = 10;
public const int OBJECT_SCRIPT_MEMORY = 11;
public const int OBJECT_SCRIPT_TIME = 12;
public const int OBJECT_PRIM_EQUIVALENCE = 13;
public const int OBJECT_SERVER_COST = 14;
public const int OBJECT_STREAMING_COST = 15;
public const int OBJECT_PHYSICS_COST = 16;
public const int OBJECT_CHARACTER_TIME = 17;
public const int OBJECT_ROOT = 18;
public const int OBJECT_ATTACHED_POINT = 19;
public const int OBJECT_PATHFINDING_TYPE = 20;
public const int OBJECT_PHYSICS = 21;
public const int OBJECT_PHANTOM = 22;
public const int OBJECT_TEMP_ON_REZ = 23;
// Pathfinding types
public const int OPT_OTHER = -1;
public const int OPT_LEGACY_LINKSET = 0;
public const int OPT_AVATAR = 1;
public const int OPT_CHARACTER = 2;
public const int OPT_WALKABLE = 3;
public const int OPT_STATIC_OBSTACLE = 4;
public const int OPT_MATERIAL_VOLUME = 5;
public const int OPT_EXCLUSION_VOLUME = 6;
// for llGetAgentList
public const int AGENT_LIST_PARCEL = 1;
public const int AGENT_LIST_PARCEL_OWNER = 2;
public const int AGENT_LIST_REGION = 4;
// Can not be public const?
public static readonly vector ZERO_VECTOR = new vector(0.0, 0.0, 0.0);
public static readonly rotation ZERO_ROTATION = new rotation(0.0, 0.0, 0.0, 1.0);
// constants for llSetCameraParams
public const int CAMERA_PITCH = 0;
public const int CAMERA_FOCUS_OFFSET = 1;
public const int CAMERA_FOCUS_OFFSET_X = 2;
public const int CAMERA_FOCUS_OFFSET_Y = 3;
public const int CAMERA_FOCUS_OFFSET_Z = 4;
public const int CAMERA_POSITION_LAG = 5;
public const int CAMERA_FOCUS_LAG = 6;
public const int CAMERA_DISTANCE = 7;
public const int CAMERA_BEHINDNESS_ANGLE = 8;
public const int CAMERA_BEHINDNESS_LAG = 9;
public const int CAMERA_POSITION_THRESHOLD = 10;
public const int CAMERA_FOCUS_THRESHOLD = 11;
public const int CAMERA_ACTIVE = 12;
public const int CAMERA_POSITION = 13;
public const int CAMERA_POSITION_X = 14;
public const int CAMERA_POSITION_Y = 15;
public const int CAMERA_POSITION_Z = 16;
public const int CAMERA_FOCUS = 17;
public const int CAMERA_FOCUS_X = 18;
public const int CAMERA_FOCUS_Y = 19;
public const int CAMERA_FOCUS_Z = 20;
public const int CAMERA_POSITION_LOCKED = 21;
public const int CAMERA_FOCUS_LOCKED = 22;
// constants for llGetParcelDetails
public const int PARCEL_DETAILS_NAME = 0;
public const int PARCEL_DETAILS_DESC = 1;
public const int PARCEL_DETAILS_OWNER = 2;
public const int PARCEL_DETAILS_GROUP = 3;
public const int PARCEL_DETAILS_AREA = 4;
public const int PARCEL_DETAILS_ID = 5;
public const int PARCEL_DETAILS_SEE_AVATARS = 6; // not implemented
//osSetParcelDetails
public const int PARCEL_DETAILS_CLAIMDATE = 10;
// constants for llSetClickAction
public const int CLICK_ACTION_NONE = 0;
public const int CLICK_ACTION_TOUCH = 0;
public const int CLICK_ACTION_SIT = 1;
public const int CLICK_ACTION_BUY = 2;
public const int CLICK_ACTION_PAY = 3;
public const int CLICK_ACTION_OPEN = 4;
public const int CLICK_ACTION_PLAY = 5;
public const int CLICK_ACTION_OPEN_MEDIA = 6;
public const int CLICK_ACTION_ZOOM = 7;
// constants for the llDetectedTouch* functions
public const int TOUCH_INVALID_FACE = -1;
public static readonly vector TOUCH_INVALID_TEXCOORD = new vector(-1.0, -1.0, 0.0);
public static readonly vector TOUCH_INVALID_VECTOR = ZERO_VECTOR;
// constants for llGetPrimMediaParams/llSetPrimMediaParams
public const int PRIM_MEDIA_ALT_IMAGE_ENABLE = 0;
public const int PRIM_MEDIA_CONTROLS = 1;
public const int PRIM_MEDIA_CURRENT_URL = 2;
public const int PRIM_MEDIA_HOME_URL = 3;
public const int PRIM_MEDIA_AUTO_LOOP = 4;
public const int PRIM_MEDIA_AUTO_PLAY = 5;
public const int PRIM_MEDIA_AUTO_SCALE = 6;
public const int PRIM_MEDIA_AUTO_ZOOM = 7;
public const int PRIM_MEDIA_FIRST_CLICK_INTERACT = 8;
public const int PRIM_MEDIA_WIDTH_PIXELS = 9;
public const int PRIM_MEDIA_HEIGHT_PIXELS = 10;
public const int PRIM_MEDIA_WHITELIST_ENABLE = 11;
public const int PRIM_MEDIA_WHITELIST = 12;
public const int PRIM_MEDIA_PERMS_INTERACT = 13;
public const int PRIM_MEDIA_PERMS_CONTROL = 14;
public const int PRIM_MEDIA_CONTROLS_STANDARD = 0;
public const int PRIM_MEDIA_CONTROLS_MINI = 1;
public const int PRIM_MEDIA_PERM_NONE = 0;
public const int PRIM_MEDIA_PERM_OWNER = 1;
public const int PRIM_MEDIA_PERM_GROUP = 2;
public const int PRIM_MEDIA_PERM_ANYONE = 4;
public const int PRIM_PHYSICS_SHAPE_TYPE = 30;
public const int PRIM_PHYSICS_SHAPE_PRIM = 0;
public const int PRIM_PHYSICS_SHAPE_CONVEX = 2;
public const int PRIM_PHYSICS_SHAPE_NONE = 1;
public const int PRIM_PHYSICS_MATERIAL = 31;
public const int DENSITY = 1;
public const int FRICTION = 2;
public const int RESTITUTION = 4;
public const int GRAVITY_MULTIPLIER = 8;
// extra constants for llSetPrimMediaParams
public static readonly LSLInteger LSL_STATUS_OK = new LSLInteger(0);
public static readonly LSLInteger LSL_STATUS_MALFORMED_PARAMS = new LSLInteger(1000);
public static readonly LSLInteger LSL_STATUS_TYPE_MISMATCH = new LSLInteger(1001);
public static readonly LSLInteger LSL_STATUS_BOUNDS_ERROR = new LSLInteger(1002);
public static readonly LSLInteger LSL_STATUS_NOT_FOUND = new LSLInteger(1003);
public static readonly LSLInteger LSL_STATUS_NOT_SUPPORTED = new LSLInteger(1004);
public static readonly LSLInteger LSL_STATUS_INTERNAL_ERROR = new LSLInteger(1999);
public static readonly LSLInteger LSL_STATUS_WHITELIST_FAILED = new LSLInteger(2001);
// Constants for default textures
public const string TEXTURE_BLANK = "5748decc-f629-461c-9a36-a35a221fe21f";
public const string TEXTURE_DEFAULT = "89556747-24cb-43ed-920b-47caed15465f";
public const string TEXTURE_PLYWOOD = "89556747-24cb-43ed-920b-47caed15465f";
public const string TEXTURE_TRANSPARENT = "8dcd4a48-2d37-4909-9f78-f7a9eb4ef903";
public const string TEXTURE_MEDIA = "8b5fec65-8d8d-9dc5-cda8-8fdf2716e361";
// Constants for osGetRegionStats
public const int STATS_TIME_DILATION = 0;
public const int STATS_SIM_FPS = 1;
public const int STATS_PHYSICS_FPS = 2;
public const int STATS_AGENT_UPDATES = 3;
public const int STATS_ROOT_AGENTS = 4;
public const int STATS_CHILD_AGENTS = 5;
public const int STATS_TOTAL_PRIMS = 6;
public const int STATS_ACTIVE_PRIMS = 7;
public const int STATS_FRAME_MS = 8;
public const int STATS_NET_MS = 9;
public const int STATS_PHYSICS_MS = 10;
public const int STATS_IMAGE_MS = 11;
public const int STATS_OTHER_MS = 12;
public const int STATS_IN_PACKETS_PER_SECOND = 13;
public const int STATS_OUT_PACKETS_PER_SECOND = 14;
public const int STATS_UNACKED_BYTES = 15;
public const int STATS_AGENT_MS = 16;
public const int STATS_PENDING_DOWNLOADS = 17;
public const int STATS_PENDING_UPLOADS = 18;
public const int STATS_ACTIVE_SCRIPTS = 19;
public const int STATS_SCRIPT_LPS = 20;
// Constants for osNpc* functions
public const int OS_NPC_FLY = 0;
public const int OS_NPC_NO_FLY = 1;
public const int OS_NPC_LAND_AT_TARGET = 2;
public const int OS_NPC_RUNNING = 4;
public const int OS_NPC_SIT_NOW = 0;
public const int OS_NPC_CREATOR_OWNED = 0x1;
public const int OS_NPC_NOT_OWNED = 0x2;
public const int OS_NPC_SENSE_AS_AGENT = 0x4;
public const string URL_REQUEST_GRANTED = "URL_REQUEST_GRANTED";
public const string URL_REQUEST_DENIED = "URL_REQUEST_DENIED";
public static readonly LSLInteger RC_REJECT_TYPES = 0;
public static readonly LSLInteger RC_DETECT_PHANTOM = 1;
public static readonly LSLInteger RC_DATA_FLAGS = 2;
public static readonly LSLInteger RC_MAX_HITS = 3;
public static readonly LSLInteger RC_REJECT_AGENTS = 1;
public static readonly LSLInteger RC_REJECT_PHYSICAL = 2;
public static readonly LSLInteger RC_REJECT_NONPHYSICAL = 4;
public static readonly LSLInteger RC_REJECT_LAND = 8;
public static readonly LSLInteger RC_GET_NORMAL = 1;
public static readonly LSLInteger RC_GET_ROOT_KEY = 2;
public static readonly LSLInteger RC_GET_LINK_NUM = 4;
public static readonly LSLInteger RCERR_UNKNOWN = -1;
public static readonly LSLInteger RCERR_SIM_PERF_LOW = -2;
public static readonly LSLInteger RCERR_CAST_TIME_EXCEEDED = 3;
public const int KFM_MODE = 1;
public const int KFM_LOOP = 1;
public const int KFM_REVERSE = 3;
public const int KFM_FORWARD = 0;
public const int KFM_PING_PONG = 2;
public const int KFM_DATA = 2;
public const int KFM_TRANSLATION = 2;
public const int KFM_ROTATION = 1;
public const int KFM_COMMAND = 0;
public const int KFM_CMD_PLAY = 0;
public const int KFM_CMD_STOP = 1;
public const int KFM_CMD_PAUSE = 2;
/// <summary>
/// process name parameter as regex
/// </summary>
public const int OS_LISTEN_REGEX_NAME = 0x1;
/// <summary>
/// process message parameter as regex
/// </summary>
public const int OS_LISTEN_REGEX_MESSAGE = 0x2;
}
}
| |
// 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 OLEDB.Test.ModuleCore;
using System.IO;
using System.Text;
using XmlCoreTest.Common;
using Xunit;
namespace System.Xml.Tests
{
//[TestCase(Name = "XmlWriterSettings: NamespaceHandling")]
public partial class TCNamespaceHandling
{
private static NamespaceHandling[] s_nlHandlingMembers = { NamespaceHandling.Default, NamespaceHandling.OmitDuplicates };
private StringWriter _strWriter = null;
private XmlWriter CreateMemWriter(XmlWriterUtils utils, XmlWriterSettings settings)
{
XmlWriterSettings wSettings = settings.Clone();
wSettings.CloseOutput = false;
wSettings.OmitXmlDeclaration = true;
wSettings.CheckCharacters = false;
XmlWriter w = null;
switch (utils.WriterType)
{
case WriterType.UTF8Writer:
wSettings.Encoding = Encoding.UTF8;
if (_strWriter != null) _strWriter.Dispose();
_strWriter = new StringWriter();
w = WriterHelper.Create(_strWriter, wSettings, overrideAsync: true, async: utils.Async);
break;
case WriterType.UnicodeWriter:
wSettings.Encoding = Encoding.Unicode;
if (_strWriter != null) _strWriter.Dispose();
_strWriter = new StringWriter();
w = WriterHelper.Create(_strWriter, wSettings, overrideAsync: true, async: utils.Async);
break;
case WriterType.WrappedWriter:
if (_strWriter != null) _strWriter.Dispose();
_strWriter = new StringWriter();
XmlWriter ww = WriterHelper.Create(_strWriter, wSettings, overrideAsync: true, async: utils.Async);
w = WriterHelper.Create(ww, wSettings, overrideAsync: true, async: utils.Async);
break;
case WriterType.CharCheckingWriter:
if (_strWriter != null) _strWriter.Dispose();
_strWriter = new StringWriter();
XmlWriter cw = WriterHelper.Create(_strWriter, wSettings, overrideAsync: true, async: utils.Async);
XmlWriterSettings cws = settings.Clone();
cws.CheckCharacters = true;
w = WriterHelper.Create(cw, cws, overrideAsync: true, async: utils.Async);
break;
default:
throw new Exception("Unknown writer type");
}
return w;
}
private void VerifyOutput(string expected)
{
string actual = _strWriter.ToString();
if (actual != expected)
{
CError.WriteLineIgnore("Expected: " + expected);
CError.WriteLineIgnore("Actual: " + actual);
CError.Compare(false, "Expected and actual output differ!");
}
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting)]
public void NS_Handling_1(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
CError.Compare(wSettings.NamespaceHandling, NamespaceHandling.Default, "Incorrect default value for XmlWriterSettings.NamespaceHandling");
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
CError.Compare(w.Settings.NamespaceHandling, NamespaceHandling.Default, "Incorrect default value for XmlWriter.Settings.NamespaceHandling");
}
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_2(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
CError.Compare(w != null, "XmlWriter creation failed");
CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment");
}
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting)]
public void NS_Handling_2a(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = NamespaceHandling.Default | NamespaceHandling.OmitDuplicates;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
CError.Compare(w.Settings.NamespaceHandling, NamespaceHandling.OmitDuplicates, "Invalid NamespaceHandling assignment");
}
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_3(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = NamespaceHandling.OmitDuplicates;
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
wSettings.NamespaceHandling = NamespaceHandling.Default;
CError.Compare(w != null, "XmlWriter creation failed");
CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment");
}
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_3a(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
try
{
wSettings.NamespaceHandling = (NamespaceHandling)(-1);
CError.Compare(false, "Failed");
}
catch (ArgumentOutOfRangeException)
{
try
{
wSettings.NamespaceHandling = (NamespaceHandling)(999);
CError.Compare(false, "Failed2");
}
catch (ArgumentOutOfRangeException) { }
}
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
CError.Compare(w != null, "XmlWriter creation failed");
CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment");
}
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uri\" /></p:foo></root>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uri\" /></p:foo></root>", "<root><p:foo xmlns:p=\"uri\"><a /></p:foo></root>")]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><foo xmlns=\"uri\"><a xmlns=\"uri\" /></foo></root>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><foo xmlns=\"uri\"><a xmlns=\"uri\" /></foo></root>", "<root><foo xmlns=\"uri\"><a /></foo></root>")]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uriOther\" /></p:foo></root>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uriOther\" /></p:foo></root>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><p:foo xmlns:p=\"uri\"><a xmlns:pOther=\"uri\" /></p:foo></root>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><p:foo xmlns:p=\"uri\"><a xmlns:pOther=\"uri\" /></p:foo></root>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root xmlns:p=\"uri\"><p:foo><p:a xmlns:p=\"uri\" /></p:foo></root>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root xmlns:p=\"uri\"><p:foo><p:a xmlns:p=\"uri\" /></p:foo></root>", "<root xmlns:p=\"uri\"><p:foo><p:a /></p:foo></root>")]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root xmlns:p=\"uri\"><p:foo><a xmlns:p=\"uri\" /></p:foo></root>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root xmlns:p=\"uri\"><p:foo><a xmlns:p=\"uri\" /></p:foo></root>", "<root xmlns:p=\"uri\"><p:foo><a /></p:foo></root>")]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><p xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" /></root>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><p xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" /></root>", "<root><p /></root>")]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<a xmlns=\"p1\"><b xmlns=\"p2\"><c xmlns=\"p1\" /></b><d xmlns=\"\"><e xmlns=\"p1\"><f xmlns=\"\" /></e></d></a>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<a xmlns=\"p1\"><b xmlns=\"p2\"><c xmlns=\"p1\" /></b><d xmlns=\"\"><e xmlns=\"p1\"><f xmlns=\"\" /></e></d></a>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root> <elem1 xmlns=\"urn:namespace\" att1=\"foo\" /></root>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root> <elem1 xmlns=\"urn:namespace\" att1=\"foo\" /></root>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<a xmlns:p=\"p1\"><b xmlns:a=\"p1\"><c xmlns:b=\"p1\" /></b></a>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<a xmlns:p=\"p1\"><b xmlns:a=\"p1\"><c xmlns:b=\"p1\" /></b></a>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p3\" /></b></a>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p3\" /></b></a>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p1\" /></b></a>", null)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p1\" /></b></a>", null)]
public void NS_Handling_3b(XmlWriterUtils utils, NamespaceHandling nsHandling, string xml, string exp)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlReader r = ReaderHelper.Create(new StringReader(xml)))
{
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteNode(r, false);
w.Dispose();
VerifyOutput(exp == null ? xml : exp);
}
}
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_4a(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter ww = CreateMemWriter(utils, wSettings))
{
XmlWriterSettings ws = wSettings.Clone();
ws.NamespaceHandling = NamespaceHandling.Default;
ws.CheckCharacters = true;
using (XmlWriter w = WriterHelper.Create(ww, ws, overrideAsync: true, async: utils.Async))
{
CError.Compare(w != null, "XmlWriter creation failed");
CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment");
}
}
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_4b(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter ww = CreateMemWriter(utils, wSettings))
{
XmlWriterSettings ws = wSettings.Clone();
ws.NamespaceHandling = NamespaceHandling.OmitDuplicates;
ws.CheckCharacters = true;
using (XmlWriter w = WriterHelper.Create(ww, ws, overrideAsync: true, async: utils.Async))
{
CError.Compare(w != null, "XmlWriter creation failed");
CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment");
}
}
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_5(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("root", "uri");
w.WriteStartAttribute("xmlns", "p", "http://www.w3.org/2000/xmlns/");
w.WriteString("uri");
w.WriteEndElement();
}
VerifyOutput("<root xmlns:p=\"uri\" xmlns=\"uri\" />");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_6(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement(null, "e", "ns");
w.WriteAttributeString(null, "attr", "ns", "val");
w.WriteElementString(null, "el", "ns", "val");
}
VerifyOutput("<e p1:attr=\"val\" xmlns:p1=\"ns\" xmlns=\"ns\"><p1:el>val</p1:el></e>");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_7(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement(String.Empty, "e", "ns");
w.WriteAttributeString(String.Empty, "attr", "ns", "val");
w.WriteElementString(String.Empty, "el", "ns", "val");
}
VerifyOutput("<e p1:attr=\"val\" xmlns:p1=\"ns\" xmlns=\"ns\"><el>val</el></e>");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_8(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("a", "e", "ns");
w.WriteAttributeString("a", "attr", "ns", "val");
w.WriteElementString("a", "el", "ns", "val");
}
VerifyOutput("<a:e a:attr=\"val\" xmlns:a=\"ns\"><a:el>val</a:el></a:e>");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_9(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("e", "ns");
w.WriteAttributeString("attr", "ns", "val");
w.WriteElementString("el", "ns", "val");
}
VerifyOutput("<e p1:attr=\"val\" xmlns:p1=\"ns\" xmlns=\"ns\"><p1:el>val</p1:el></e>");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_10(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement(null, "e", null);
w.WriteAttributeString(null, "attr", null, "val");
w.WriteElementString(null, "el", null, "val");
}
VerifyOutput("<e attr=\"val\"><el>val</el></e>");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_11(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement(String.Empty, "e", String.Empty);
w.WriteAttributeString(String.Empty, "attr", String.Empty, "val");
w.WriteElementString(String.Empty, "el", String.Empty, "val");
}
VerifyOutput("<e attr=\"val\"><el>val</el></e>");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_12(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("e");
w.WriteAttributeString("attr", "val");
w.WriteElementString("el", "val");
}
VerifyOutput("<e attr=\"val\"><el>val</el></e>");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_16(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("a", "foo", "b");
CError.Compare(w.LookupPrefix("foo"), null, "FailedEl");
w.WriteAttributeString("a", "foo", "b");
CError.Compare(w.LookupPrefix("foo"), "p1", "FailedAttr");
w.WriteElementString("e", "foo", "b");
CError.Compare(w.LookupPrefix("foo"), "p1", "FailedEl");
}
VerifyOutput("<a:foo p1:a=\"b\" xmlns:p1=\"foo\" xmlns:a=\"b\"><p1:e>b</p1:e></a:foo>");
return;
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_17(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteDocType("a", null, null, "<!ATTLIST Root a CDATA #IMPLIED>");
w.WriteStartElement("Root");
for (int i = 0; i < 1000; i++)
{
w.WriteAttributeString("a", "n" + i, "val");
}
try
{
w.WriteAttributeString("a", "n" + 999, "val");
CError.Compare(false, "Failed");
}
catch (XmlException e) { CError.WriteLine(e); return; }
}
Assert.True(false);
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)]
public void NS_Handling_17a(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteDocType("a", null, null, "<!ATTLIST Root a CDATA #IMPLIED>");
w.WriteStartElement("Root");
for (int i = 0; i < 10; i++)
{
if (isAttr)
w.WriteAttributeString("p", "a" + i, "n", "val");
else
w.WriteElementString("p", "a" + i, "n", "val");
}
}
string exp = isAttr ?
"<!DOCTYPE a [<!ATTLIST Root a CDATA #IMPLIED>]><Root p:a0=\"val\" p:a1=\"val\" p:a2=\"val\" p:a3=\"val\" p:a4=\"val\" p:a5=\"val\" p:a6=\"val\" p:a7=\"val\" p:a8=\"val\" p:a9=\"val\" xmlns:p=\"n\" />" :
"<!DOCTYPE a [<!ATTLIST Root a CDATA #IMPLIED>]><Root><p:a0 xmlns:p=\"n\">val</p:a0><p:a1 xmlns:p=\"n\">val</p:a1><p:a2 xmlns:p=\"n\">val</p:a2><p:a3 xmlns:p=\"n\">val</p:a3><p:a4 xmlns:p=\"n\">val</p:a4><p:a5 xmlns:p=\"n\">val</p:a5><p:a6 xmlns:p=\"n\">val</p:a6><p:a7 xmlns:p=\"n\">val</p:a7><p:a8 xmlns:p=\"n\">val</p:a8><p:a9 xmlns:p=\"n\">val</p:a9></Root>";
VerifyOutput(exp);
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)]
public void NS_Handling_17b(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("Root");
for (int i = 0; i < 5; i++)
{
if (isAttr)
w.WriteAttributeString("p", "a" + i, "xmlns", "val");
else
w.WriteElementString("p", "a" + i, "xmlns", "val");
}
}
string exp = isAttr ?
"<Root p:a0=\"val\" p:a1=\"val\" p:a2=\"val\" p:a3=\"val\" p:a4=\"val\" xmlns:p=\"xmlns\" />" :
"<Root><p:a0 xmlns:p=\"xmlns\">val</p:a0><p:a1 xmlns:p=\"xmlns\">val</p:a1><p:a2 xmlns:p=\"xmlns\">val</p:a2><p:a3 xmlns:p=\"xmlns\">val</p:a3><p:a4 xmlns:p=\"xmlns\">val</p:a4></Root>";
VerifyOutput(exp);
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)]
public void NS_Handling_17c(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
XmlWriter w = CreateMemWriter(utils, wSettings);
w.WriteStartElement("Root");
for (int i = 0; i < 5; i++)
{
if (isAttr)
w.WriteAttributeString("p" + i, "a", "n" + i, "val" + i);
else
w.WriteElementString("p" + i, "a", "n" + i, "val" + i);
}
try
{
if (isAttr)
{
w.WriteAttributeString("p", "a", "n" + 4, "val");
CError.Compare(false, "Failed");
}
else
w.WriteElementString("p", "a", "n" + 4, "val");
}
catch (XmlException) { }
finally
{
w.Dispose();
string exp = isAttr ?
"<Root p0:a=\"val0\" p1:a=\"val1\" p2:a=\"val2\" p3:a=\"val3\" p4:a=\"val4\"" :
"<Root><p0:a xmlns:p0=\"n0\">val0</p0:a><p1:a xmlns:p1=\"n1\">val1</p1:a><p2:a xmlns:p2=\"n2\">val2</p2:a><p3:a xmlns:p3=\"n3\">val3</p3:a><p4:a xmlns:p4=\"n4\">val4</p4:a><p:a xmlns:p=\"n4\">val</p:a></Root>";
VerifyOutput(exp);
}
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)]
public void NS_Handling_17d(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("Root");
for (int i = 0; i < 5; i++)
{
if (isAttr)
{
w.WriteAttributeString("xml", "a" + i, "http://www.w3.org/XML/1998/namespace", "val");
w.WriteAttributeString("xmlns", "a" + i, "http://www.w3.org/2000/xmlns/", "val");
}
else
{
w.WriteElementString("xml", "a" + i, "http://www.w3.org/XML/1998/namespace", "val");
}
}
}
string exp = isAttr ?
"<Root xml:a0=\"val\" xmlns:a0=\"val\" xml:a1=\"val\" xmlns:a1=\"val\" xml:a2=\"val\" xmlns:a2=\"val\" xml:a3=\"val\" xmlns:a3=\"val\" xml:a4=\"val\" xmlns:a4=\"val\" />" :
"<Root><xml:a0>val</xml:a0><xml:a1>val</xml:a1><xml:a2>val</xml:a2><xml:a3>val</xml:a3><xml:a4>val</xml:a4></Root>";
VerifyOutput(exp);
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)]
public void NS_Handling_17e(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("Root");
for (int i = 0; i < 5; i++)
{
if (isAttr)
w.WriteAttributeString("a" + i, "http://www.w3.org/XML/1998/namespace", "val");
else
w.WriteElementString("a" + i, "http://www.w3.org/XML/1998/namespace", "val");
}
}
string exp = isAttr ?
"<Root xml:a0=\"val\" xml:a1=\"val\" xml:a2=\"val\" xml:a3=\"val\" xml:a4=\"val\" />" :
"<Root><xml:a0>val</xml:a0><xml:a1>val</xml:a1><xml:a2>val</xml:a2><xml:a3>val</xml:a3><xml:a4>val</xml:a4></Root>";
VerifyOutput(exp);
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_18(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("test");
w.WriteAttributeString("p", "a1", "ns1", "v");
w.WriteStartElement("base");
w.WriteAttributeString("a2", "ns1", "v");
w.WriteAttributeString("p", "a3", "ns2", "v");
w.WriteElementString("p", "e", "ns2", "v");
w.WriteEndElement();
w.WriteEndElement();
}
string exp = "<test p:a1=\"v\" xmlns:p=\"ns1\"><base p:a2=\"v\" p4:a3=\"v\" xmlns:p4=\"ns2\"><p:e xmlns:p=\"ns2\">v</p:e></base></test>";
VerifyOutput(exp);
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_19(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("Root");
w.WriteAttributeString("xmlns", "xml", null, "http://www.w3.org/XML/1998/namespace");
w.WriteAttributeString("xmlns", "space", null, "preserve");
w.WriteAttributeString("xmlns", "lang", null, "chs");
w.WriteElementString("xml", "lang", null, "jpn");
w.WriteElementString("xml", "space", null, "default");
w.WriteElementString("xml", "xml", null, "http://www.w3.org/XML/1998/namespace");
w.WriteEndElement();
}
string exp = (nsHandling == NamespaceHandling.OmitDuplicates) ?
"<Root xmlns:space=\"preserve\" xmlns:lang=\"chs\"><xml:lang>jpn</xml:lang><xml:space>default</xml:space><xml:xml>http://www.w3.org/XML/1998/namespace</xml:xml></Root>" :
"<Root xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" xmlns:space=\"preserve\" xmlns:lang=\"chs\"><xml:lang>jpn</xml:lang><xml:space>default</xml:space><xml:xml>http://www.w3.org/XML/1998/namespace</xml:xml></Root>";
VerifyOutput(exp);
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "xml", true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "xml", true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "xml", false)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "xml", false)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xml", "space", true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xml", "space", true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "space", false)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "space", false)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "lang", true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "lang", true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "lang", false)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "lang", false)]
public void NS_Handling_19a(XmlWriterUtils utils, NamespaceHandling nsHandling, string prefix, string name, bool isAttr)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
XmlWriter w = CreateMemWriter(utils, wSettings);
w.WriteStartElement("Root");
try
{
if (isAttr)
w.WriteAttributeString(prefix, name, null, null);
else
w.WriteElementString(prefix, name, null, null);
CError.Compare(false, "error");
}
catch (ArgumentException e) { CError.WriteLine(e); CError.Compare(w.WriteState, WriteState.Error, "state"); }
finally
{
w.Dispose();
CError.Compare(w.WriteState, WriteState.Closed, "state");
}
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)]
public void NS_Handling_19b(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("Root");
try
{
if (isAttr)
w.WriteAttributeString("xmlns", "xml", null, null);
else
w.WriteElementString("xmlns", "xml", null, null);
}
catch (ArgumentException e) { CError.WriteLine(e.Message); }
}
string exp = isAttr ? "<Root" : "<Root><xmlns:xml";
VerifyOutput(exp);
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_20(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("d", "Data", "http://example.org/data");
w.WriteStartElement("g", "GoodStuff", "http://example.org/data/good");
w.WriteAttributeString("hello", "world");
w.WriteEndElement();
w.WriteStartElement("BadStuff", "http://example.org/data/bad");
w.WriteAttributeString("hello", "world");
w.WriteEndElement();
w.WriteEndElement();
}
VerifyOutput("<d:Data xmlns:d=\"http://example.org/data\"><g:GoodStuff hello=\"world\" xmlns:g=\"http://example.org/data/good\" /><BadStuff hello=\"world\" xmlns=\"http://example.org/data/bad\" /></d:Data>");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_21(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
string strraw = "abc";
char[] buffer = strraw.ToCharArray();
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("root");
w.WriteStartAttribute("xml", "lang", null);
w.WriteRaw(buffer, 0, 0);
w.WriteRaw(buffer, 1, 1);
w.WriteRaw(buffer, 0, 2);
w.WriteEndElement();
}
VerifyOutput("<root xml:lang=\"bab\" />");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_22(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("root");
w.WriteStartAttribute("xml", "lang", null);
w.WriteBinHex(buffer, 0, 0);
w.WriteBinHex(buffer, 1, 1);
w.WriteBinHex(buffer, 0, 2);
w.WriteEndElement();
}
VerifyOutput("<root xml:lang=\"626162\" />");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_23(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("root");
w.WriteStartAttribute("a", "b", null);
w.WriteBase64(buffer, 0, 0);
w.WriteBase64(buffer, 1, 1);
w.WriteBase64(buffer, 0, 2);
w.WriteEndElement();
}
VerifyOutput("<root b=\"YmFi\" />");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_24(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
XmlWriter w = CreateMemWriter(utils, wSettings);
byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
w.WriteStartElement("A");
w.WriteAttributeString("xmlns", "p", null, "ns1");
w.WriteStartElement("B");
w.WriteAttributeString("xmlns", "p", null, "ns1"); // will be omitted
try
{
w.WriteAttributeString("xmlns", "p", null, "ns1");
CError.Compare(false, "error");
}
catch (XmlException e) { CError.WriteLine(e); }
finally
{
w.Dispose();
VerifyOutput(nsHandling == NamespaceHandling.OmitDuplicates ? "<A xmlns:p=\"ns1\"><B" : "<A xmlns:p=\"ns1\"><B xmlns:p=\"ns1\"");
}
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_25(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
string xml = "<employees xmlns:email=\"http://www.w3c.org/some-spec-3.2\">" +
"<employee><name>Bob Worker</name><address xmlns=\"http://postal.ie/spec-1.0\"><street>Nassau Street</street>" +
"<city>Dublin 3</city><country>Ireland</country></address><email:address>bob.worker@hisjob.ie</email:address>" +
"</employee></employees>";
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlReader r = ReaderHelper.Create(new StringReader(xml)))
{
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteNode(r, false);
}
}
VerifyOutput(xml);
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_25a(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
string xml = "<root><elem1 xmlns=\"urn:URN1\" xmlns:ns1=\"urn:URN2\"><ns1:childElem1><grandChild1 /></ns1:childElem1><childElem2><grandChild2 /></childElem2></elem1></root>";
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlReader r = ReaderHelper.Create(new StringReader(xml)))
{
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteNode(r, false);
}
}
VerifyOutput(xml);
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_26(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("p", "e", "uri1");
w.WriteAttributeString("p", "e", "uri1", "val");
w.WriteAttributeString("p", "e", "uri2", "val");
w.WriteElementString("p", "e", "uri1", "val");
w.WriteElementString("p", "e", "uri2", "val");
}
VerifyOutput("<p:e p:e=\"val\" p1:e=\"val\" xmlns:p1=\"uri2\" xmlns:p=\"uri1\"><p:e>val</p:e><p:e xmlns:p=\"uri2\">val</p:e></p:e>");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_27(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("p1", "e", "uri");
w.WriteAttributeString("p1", "e", "uri", "val");
w.WriteAttributeString("p2", "e2", "uri", "val");
w.WriteElementString("p1", "e", "uri", "val");
w.WriteElementString("p2", "e", "uri", "val");
}
VerifyOutput("<p1:e p1:e=\"val\" p2:e2=\"val\" xmlns:p2=\"uri\" xmlns:p1=\"uri\"><p1:e>val</p1:e><p2:e>val</p2:e></p1:e>");
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_29(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
string xml = "<!DOCTYPE root [ <!ELEMENT root ANY > <!ELEMENT ns1:elem1 ANY >" +
"<!ATTLIST ns1:elem1 xmlns CDATA #FIXED \"urn:URN2\"> <!ATTLIST ns1:elem1 xmlns:ns1 CDATA #FIXED \"urn:URN1\">" +
"<!ELEMENT childElem1 ANY > <!ATTLIST childElem1 childElem1Att1 CDATA #FIXED \"attributeValue\">]>" +
"<root> <ns1:elem1 xmlns:ns1=\"urn:URN1\" xmlns=\"urn:URN2\"> text node in elem1 <![CDATA[<doc> content </doc>]]>" +
"<childElem1 childElem1Att1=\"attributeValue\"> <?PI in childElem1 ?> </childElem1> <!-- Comment in elem1 --> & </ns1:elem1></root>";
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = DtdProcessing.Parse;
using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs))
{
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteNode(r, false);
}
}
VerifyOutput(xml);
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_30(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
string xml = "<!DOCTYPE doc " +
"[<!ELEMENT doc ANY>" +
"<!ELEMENT test1 (#PCDATA)>" +
"<!ELEMENT test2 ANY>" +
"<!ELEMENT test3 (#PCDATA)>" +
"<!ENTITY e1 \"&e2;\">" +
"<!ENTITY e2 \"xmlns:p='x'\">" +
"<!ATTLIST test3 a1 CDATA #IMPLIED>" +
"<!ATTLIST test3 a2 CDATA #IMPLIED>" +
"]>" +
"<doc xmlns:p='&e2;'>" +
" &e2;" +
" <test1 xmlns:p='&e2;'>AA&e2;AA</test1>" +
" <test2 xmlns:p='&e1;'>BB&e1;BB</test2>" +
" <test3 a1=\"&e2;\" a2=\"&e1;\">World</test3>" +
"</doc>";
string exp = (nsHandling == NamespaceHandling.OmitDuplicates) ?
"<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns:p='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns:p='x'\"> xmlns:p='x' <test1>AAxmlns:p='x'AA</test1> <test2>BBxmlns:p='x'BB</test2> <test3 a1=\"xmlns:p='x'\" a2=\"xmlns:p='x'\">World</test3></doc>" :
"<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns:p='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns:p='x'\"> xmlns:p='x' <test1 xmlns:p=\"xmlns:p='x'\">AAxmlns:p='x'AA</test1> <test2 xmlns:p=\"xmlns:p='x'\">BBxmlns:p='x'BB</test2> <test3 a1=\"xmlns:p='x'\" a2=\"xmlns:p='x'\">World</test3></doc>";
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = DtdProcessing.Parse;
using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs))
{
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteNode(r, false);
}
}
VerifyOutput(exp);
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_30a(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
string xml = "<!DOCTYPE doc " +
"[<!ELEMENT doc ANY>" +
"<!ELEMENT test1 (#PCDATA)>" +
"<!ELEMENT test2 ANY>" +
"<!ELEMENT test3 (#PCDATA)>" +
"<!ENTITY e1 \"&e2;\">" +
"<!ENTITY e2 \"xmlns='x'\">" +
"<!ATTLIST test3 a1 CDATA #IMPLIED>" +
"<!ATTLIST test3 a2 CDATA #IMPLIED>" +
"]>" +
"<doc xmlns:p='&e2;'>" +
" &e2;" +
" <test1 xmlns:p='&e2;'>AA&e2;AA</test1>" +
" <test2 xmlns:p='&e1;'>BB&e1;BB</test2>" +
" <test3 a1=\"&e2;\" a2=\"&e1;\">World</test3>" +
"</doc>";
string exp = (nsHandling == NamespaceHandling.OmitDuplicates) ?
"<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns='x'\"> xmlns='x' <test1>AAxmlns='x'AA</test1> <test2>BBxmlns='x'BB</test2> <test3 a1=\"xmlns='x'\" a2=\"xmlns='x'\">World</test3></doc>" :
"<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns='x'\"> xmlns='x' <test1 xmlns:p=\"xmlns='x'\">AAxmlns='x'AA</test1> <test2 xmlns:p=\"xmlns='x'\">BBxmlns='x'BB</test2> <test3 a1=\"xmlns='x'\" a2=\"xmlns='x'\">World</test3></doc>";
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = DtdProcessing.Parse;
using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs))
{
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteNode(r, false);
}
}
VerifyOutput(exp);
return;
}
[Theory]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)]
[XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)]
public void NS_Handling_31(XmlWriterUtils utils, NamespaceHandling nsHandling)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.NamespaceHandling = nsHandling;
using (XmlWriter w = CreateMemWriter(utils, wSettings))
{
w.WriteStartElement("test");
w.WriteAttributeString("p", "a1", "ns1", "v");
w.WriteStartElement("base");
w.WriteAttributeString("a2", "ns1", "v");
w.WriteAttributeString("p", "a3", "ns2", "v");
w.WriteEndElement();
w.WriteEndElement();
}
VerifyOutput("<test p:a1=\"v\" xmlns:p=\"ns1\"><base p:a2=\"v\" p4:a3=\"v\" xmlns:p4=\"ns2\" /></test>");
return;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class AverageTests : EnumerableTests
{
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > int.MinValue
select x;
Assert.Equal(q.Average(), q.Average());
}
[Fact]
public void SameResultsRepeatCallsNullableLongQuery()
{
var q = from x in new long?[] { int.MaxValue, 0, 255, 127, 128, 1, 33, 99, null, int.MinValue }
select x;
Assert.Equal(q.Average(), q.Average());
}
public static IEnumerable<object[]> NullableFloat_TestData()
{
yield return new object[] { new float?[0], null };
yield return new object[] { new float?[] { float.MinValue }, float.MinValue };
yield return new object[] { new float?[] { 0f, 0f, 0f, 0f, 0f }, 0f };
yield return new object[] { new float?[] { 5.5f, 0, null, null, null, 15.5f, 40.5f, null, null, -23.5f }, 7.6f };
yield return new object[] { new float?[] { null, null, null, null, 45f }, 45f };
yield return new object[] { new float?[] { null, null, null, null, null }, null };
}
[Theory]
[MemberData(nameof(NullableFloat_TestData))]
public void NullableFoat(float?[] source, float? expected)
{
Assert.Equal(expected, source.Average());
Assert.Equal(expected, source.Average(x => x));
}
[Theory, MemberData(nameof(NullableFloat_TestData))]
public void NullableFoatRunOnce(float?[] source, float? expected)
{
Assert.Equal(expected, source.RunOnce().Average());
Assert.Equal(expected, source.RunOnce().Average(x => x));
}
[Fact]
public void NullableFloat_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<float?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<float?>)null).Average(i => i));
}
[Fact]
public void NullableFloat_NullSelector_ThrowsArgumentNullException()
{
Func<float?, float?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float?>().Average(selector));
}
[Fact]
public void NullableFloat_WithSelector()
{
var source = new []
{
new { name = "Tim", num = (float?)5.5f },
new { name = "John", num = (float?)15.5f },
new { name = "Bob", num = default(float?) }
};
float? expected = 10.5f;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void Int_EmptySource_ThrowsInvalidOperationException()
{
int[] source = new int[0];
Assert.Throws<InvalidOperationException>(() => source.Average());
Assert.Throws<InvalidOperationException>(() => source.Average(i => i));
}
[Fact]
public void Int_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Average(i => i));
}
[Fact]
public void Int_NullSelector_ThrowsArgumentNullException()
{
Func<int, int> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int>().Average(selector));
}
public static IEnumerable<object[]> Int_TestData()
{
yield return new object[] { new int[] { 5 }, 5 };
yield return new object[] { new int[] { 0, 0, 0, 0, 0 }, 0 };
yield return new object[] { new int[] { 5, -10, 15, 40, 28 }, 15.6 };
}
[Theory]
[MemberData(nameof(Int_TestData))]
public void Int(int[] source, double expected)
{
Assert.Equal(expected, source.Average());
Assert.Equal(expected, source.Average(x => x));
}
[Theory, MemberData(nameof(Int_TestData))]
public void IntRunOnce(int[] source, double expected)
{
Assert.Equal(expected, source.RunOnce().Average());
Assert.Equal(expected, source.RunOnce().Average(x => x));
}
[Fact]
public void Int_WithSelector()
{
var source = new []
{
new { name="Tim", num = 10 },
new { name="John", num = -10 },
new { name="Bob", num = 15 }
};
double expected = 5;
Assert.Equal(expected, source.Average(e => e.num));
}
public static IEnumerable<object[]> NullableInt_TestData()
{
yield return new object[] { new int?[0], null };
yield return new object[] { new int?[] { -5 }, -5.0 };
yield return new object[] { new int?[] { 0, 0, 0, 0, 0 }, 0.0 };
yield return new object[] { new int?[] { 5, -10, null, null, null, 15, 40, 28, null, null }, 15.6 };
yield return new object[] { new int?[] { null, null, null, null, 50 }, 50.0 };
yield return new object[] { new int?[] { null, null, null, null, null }, null };
}
[Theory]
[MemberData(nameof(NullableInt_TestData))]
public void NullableInt(int?[] source, double? expected)
{
Assert.Equal(expected, source.Average());
Assert.Equal(expected, source.Average(x => x));
}
[Fact]
public void NullableInt_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int?>)null).Average(i => i));
}
[Fact]
public void NullableInt_NullSelector_ThrowsArgumentNullException()
{
Func<int?, int?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int?>().Average(selector));
}
[Fact]
public void NullableInt_WithSelector()
{
var source = new []
{
new { name = "Tim", num = (int?)10 },
new { name = "John", num = default(int?) },
new { name = "Bob", num = (int?)10 }
};
double? expected = 10;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void Long_EmptySource_ThrowsInvalidOperationException()
{
long[] source = new long[0];
Assert.Throws<InvalidOperationException>(() => source.Average());
Assert.Throws<InvalidOperationException>(() => source.Average(i => i));
}
[Fact]
public void Long_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<long>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<long>)null).Average(i => i));
}
[Fact]
public void Long_NullSelector_ThrowsArgumentNullException()
{
Func<long, long> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long>().Average(selector));
}
public static IEnumerable<object[]> Long_TestData()
{
yield return new object[] { new long[] { long.MaxValue }, long.MaxValue };
yield return new object[] { new long[] { 0, 0, 0, 0, 0 }, 0 };
yield return new object[] { new long[] { 5, -10, 15, 40, 28 }, 15.6 };
}
[Theory]
[MemberData(nameof(Long_TestData))]
public void Long(long[] source, double expected)
{
Assert.Equal(expected, source.Average());
Assert.Equal(expected, source.Average(x => x));
}
[Fact]
public void Long_FromSelector()
{
var source = new []
{
new { name = "Tim", num = 40L },
new { name = "John", num = 50L },
new { name = "Bob", num = 60L }
};
double expected = 50;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void Long_SumTooLarge_ThrowsOverflowException()
{
long[] source = new long[] { long.MaxValue, long.MaxValue };
Assert.Throws<OverflowException>(() => source.Average());
}
public static IEnumerable<object[]> NullableLong_TestData()
{
yield return new object[] { new long?[0], null };
yield return new object[] { new long?[] { long.MaxValue }, (double)long.MaxValue };
yield return new object[] { new long?[] { 0, 0, 0, 0, 0 }, 0.0 };
yield return new object[] { new long?[] { 5, -10, null, null, null, 15, 40, 28, null, null }, 15.6 };
yield return new object[] { new long?[] { null, null, null, null, 50 }, 50.0 };
yield return new object[] { new long?[] { null, null, null, null, null }, null };
}
[Theory]
[MemberData(nameof(NullableLong_TestData))]
public void NullableLong(long?[] source, double? expected)
{
Assert.Equal(expected, source.Average());
Assert.Equal(expected, source.Average(x => x));
}
[Fact]
public void NullableLong_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<long?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<long?>)null).Average(i => i));
}
[Fact]
public void NullableLong_NullSelector_ThrowsArgumentNullException()
{
Func<long?, long?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long?>().Average(selector));
}
[Fact]
public void NullableLong_WithSelector()
{
var source = new []
{
new { name = "Tim", num = (long?)40L },
new { name = "John", num = default(long?) },
new { name = "Bob", num = (long?)30L }
};
double? expected = 35;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void Double_EmptySource_ThrowsInvalidOperationException()
{
double[] source = new double[0];
Assert.Throws<InvalidOperationException>(() => source.Average());
Assert.Throws<InvalidOperationException>(() => source.Average(i => i));
}
[Fact]
public void Double_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<double>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<double>)null).Average(i => i));
}
[Fact]
public void Double_NullSelector_ThrowsArgumentNullException()
{
Func<double, double> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double>().Average(selector));
}
public static IEnumerable<object[]> Double_TestData()
{
yield return new object[] { new double[] { double.MaxValue }, double.MaxValue };
yield return new object[] { new double[] { 0.0, 0.0, 0.0, 0.0, 0.0 }, 0 };
yield return new object[] { new double[] { 5.5, -10, 15.5, 40.5, 28.5 }, 16 };
yield return new object[] { new double[] { 5.58, double.NaN, 30, 4.55, 19.38 }, double.NaN };
}
[Theory]
[MemberData(nameof(Double_TestData))]
public void Average_Double(double[] source, double expected)
{
Assert.Equal(expected, source.Average());
Assert.Equal(expected, source.Average(x => x));
}
[Fact]
public void Double_WithSelector()
{
var source = new []
{
new { name = "Tim", num = 5.5},
new { name = "John", num = 15.5},
new { name = "Bob", num = 3.0}
};
double expected = 8.0;
Assert.Equal(expected, source.Average(e => e.num));
}
public static IEnumerable<object[]> NullableDouble_TestData()
{
yield return new object[] { new double?[0], null };
yield return new object[] { new double?[] { double.MinValue }, double.MinValue };
yield return new object[] { new double?[] { 0, 0, 0, 0, 0 }, 0.0 };
yield return new object[] { new double?[] { 5.5, 0, null, null, null, 15.5, 40.5, null, null, -23.5 }, 7.6 };
yield return new object[] { new double?[] { null, null, null, null, 45 }, 45.0 };
yield return new object[] { new double?[] { -23.5, 0, double.NaN, 54.3, 0.56 }, double.NaN };
yield return new object[] { new double?[] { null, null, null, null, null }, null };
}
[Theory]
[MemberData(nameof(NullableDouble_TestData))]
public void NullableDouble(double?[] source, double? expected)
{
Assert.Equal(expected, source.Average());
Assert.Equal(expected, source.Average(x => x));
}
[Fact]
public void NullableDouble_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<double?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<double?>)null).Average(i => i));
}
[Fact]
public void NullableDouble_NullSelector_ThrowsArgumentNullException()
{
Func<double?, double?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double?>().Average(selector));
}
[Fact]
public void NullableDouble_WithSelector()
{
var source = new[]
{
new{ name = "Tim", num = (double?)5.5 },
new{ name = "John", num = (double?)15.5 },
new{ name = "Bob", num = default(double?) }
};
double? expected = 10.5;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void Decimal_EmptySource_ThrowsInvalidOperationException()
{
decimal[] source = new decimal[0];
Assert.Throws<InvalidOperationException>(() => source.Average());
Assert.Throws<InvalidOperationException>(() => source.Average(i => i));
}
[Fact]
public void Decimal_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal>)null).Average(i => i));
}
[Fact]
public void Decimal_NullSelector_ThrowsArgumentNullException()
{
Func<decimal, decimal> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal>().Average(selector));
}
public static IEnumerable<object[]> Decimal_TestData()
{
yield return new object[] { new decimal[] { decimal.MaxValue }, decimal.MaxValue };
yield return new object[] { new decimal[] { 0.0m, 0.0m, 0.0m, 0.0m, 0.0m }, 0 };
yield return new object[] { new decimal[] { 5.5m, -10m, 15.5m, 40.5m, 28.5m }, 16 };
}
[Theory]
[MemberData(nameof(Decimal_TestData))]
public void Decimal(decimal[] source, decimal expected)
{
Assert.Equal(expected, source.Average());
Assert.Equal(expected, source.Average(x => x));
}
[Fact]
public void Decimal_WithSelector()
{
var source = new[]
{
new{ name = "Tim", num = 5.5m},
new{ name = "John", num = 15.5m},
new{ name = "Bob", num = 3.0m}
};
decimal expected = 8.0m;
Assert.Equal(expected, source.Average(e => e.num));
}
public static IEnumerable<object[]> NullableDecimal_TestData()
{
yield return new object[] { new decimal?[0], null };
yield return new object[] { new decimal?[] { decimal.MinValue }, decimal.MinValue };
yield return new object[] { new decimal?[] { 0m, 0m, 0m, 0m, 0m }, 0m };
yield return new object[] { new decimal?[] { 5.5m, 0, null, null, null, 15.5m, 40.5m, null, null, -23.5m }, 7.6m };
yield return new object[] { new decimal?[] { null, null, null, null, 45m }, 45m };
yield return new object[] { new decimal?[] { null, null, null, null, null }, null };
}
[Theory]
[MemberData(nameof(NullableDecimal_TestData))]
public void NullableDecimal(decimal?[] source, decimal? expected)
{
Assert.Equal(expected, source.Average());
Assert.Equal(expected, source.Average(x => x));
}
[Fact]
public void NullableDecimal_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal?>)null).Average(i => i));
}
[Fact]
public void NullableDecimal_NullSelector_ThrowsArgumentNullException()
{
Func<decimal?, decimal?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal?>().Average(selector));
}
[Fact]
public void NullableDecimal_WithSelector()
{
var source = new[]
{
new{ name = "Tim", num = (decimal?)5.5m},
new{ name = "John", num = (decimal?)15.5m},
new{ name = "Bob", num = (decimal?)null}
};
decimal? expected = 10.5m;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void NullableDecimal_SumTooLarge_ThrowsOverflowException()
{
decimal?[] source = new decimal?[] { decimal.MaxValue, decimal.MaxValue };
Assert.Throws<OverflowException>(() => source.Average());
}
[Fact]
public void Float_EmptySource_ThrowsInvalidOperationException()
{
float[] source = new float[0];
Assert.Throws<InvalidOperationException>(() => source.Average());
Assert.Throws<InvalidOperationException>(() => source.Average(i => i));
}
[Fact]
public void Float_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<float>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<float>)null).Average(i => i));
}
[Fact]
public void Float_NullSelector_ThrowsArgumentNullException()
{
Func<float, float> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float>().Average(selector));
}
public static IEnumerable<object[]> Float_TestData()
{
yield return new object[] { new float[] { float.MaxValue }, float.MaxValue };
yield return new object[] { new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, 0f };
yield return new object[] { new float[] { 5.5f, -10f, 15.5f, 40.5f, 28.5f }, 16f };
}
[Theory]
[MemberData(nameof(Float_TestData))]
public void Float(float[] source, float expected)
{
Assert.Equal(expected, source.Average());
Assert.Equal(expected, source.Average(x => x));
}
[Fact]
public void Float_WithSelector()
{
var source = new[]
{
new{ name = "Tim", num = 5.5f},
new{ name = "John", num = 15.5f},
new{ name = "Bob", num = 3.0f}
};
float expected = 8.0f;
Assert.Equal(expected, source.Average(e => e.num));
}
}
}
| |
using AppStudio.Uwp;
using AppStudio.Uwp.Actions;
using AppStudio.Uwp.Converters;
using AppStudio.Uwp.DataSync;
using AppStudio.Uwp.Navigation;
using System;
using System.Collections.Generic;
using Windows.ApplicationModel.Resources;
using Windows.UI.Xaml.Media.Imaging;
namespace DotNetSpainConference.ViewModels
{
public class ItemViewModel : ObservableBase, INavigable, ISyncItem<ItemViewModel>
{
public string Id { get; set; }
public object OrderBy { get; set; }
public object GroupBy { get; set; }
private string _pageTitle;
public string PageTitle
{
get { return _pageTitle; }
set { SetProperty(ref _pageTitle, value); }
}
private string _header;
public string Header
{
get { return _header; }
set { SetProperty(ref _header, value); }
}
private string _title;
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
private string _subTitle;
public string SubTitle
{
get { return _subTitle; }
set { SetProperty(ref _subTitle, value); }
}
private string _description;
public string Description
{
get { return _description; }
set { SetProperty(ref _description, value); }
}
private string _imageUrl;
public string ImageUrl
{
get { return _imageUrl; }
set { SetProperty(ref _imageUrl, value); }
}
private string _content;
public string Content
{
get { return _content; }
set { SetProperty(ref _content, value); }
}
private string _footer;
public string Footer
{
get { return _footer; }
set { SetProperty(ref _footer, value); }
}
private string _aside;
public string Aside
{
get { return _aside; }
set { SetProperty(ref _aside, value); }
}
private string _source;
public string Source
{
get { return _source; }
set { SetProperty(ref _source, value); }
}
private IEnumerable<string> SearchFields
{
get
{
yield return Title;
yield return SubTitle;
yield return Description;
yield return Content;
}
}
public NavigationInfo NavigationInfo { get; set; }
public List<ActionInfo> Actions { get; set; }
public bool HasActions
{
get
{
return Actions != null && Actions.Count > 0;
}
}
public bool NeedSync(ItemViewModel other)
{
return this.Id == other.Id && (this.PageTitle != other.PageTitle || this.Title != other.Title || this.SubTitle != other.SubTitle || this.Description != other.Description || this.ImageUrl != other.ImageUrl || this.Content != other.Content);
}
public void Sync(ItemViewModel other)
{
this.PageTitle = other.PageTitle;
this.Title = other.Title;
this.SubTitle = other.SubTitle;
this.Description = other.Description;
this.ImageUrl = other.ImageUrl;
this.Content = other.Content;
this.Aside = other.Aside;
this.GroupBy = other.GroupBy;
this.Source = other.Source;
}
public bool Equals(ItemViewModel other)
{
if (ReferenceEquals(this, other)) return true;
if (ReferenceEquals(null, other)) return false;
return this.Id == other.Id;
}
public override bool Equals(object obj)
{
return Equals(obj as ItemViewModel);
}
public override int GetHashCode()
{
if (string.IsNullOrEmpty(this.Id))
{
return 0;
}
return this.Id.GetHashCode();
}
public override string ToString()
{
var resourceLoader = new ResourceLoader();
string toStringResult = string.Empty;
if (!string.IsNullOrEmpty(Title))
{
toStringResult += resourceLoader.GetString("NarrationTitle") + ". ";
toStringResult += Title + ". ";
}
if (!string.IsNullOrEmpty(SubTitle))
{
toStringResult += resourceLoader.GetString("NarrationSubTitle") + ". ";
toStringResult += SubTitle;
}
return toStringResult;
}
public bool ContainsString(string stringText)
{
if (!string.IsNullOrEmpty(stringText))
{
foreach (string searchField in SearchFields)
{
if (!string.IsNullOrEmpty(searchField) && searchField.ToLowerInvariant().Contains(stringText.ToLowerInvariant()))
{
return true;
}
}
return false;
}
else
{
return true;
}
}
public static string LoadSafeUrl(string imageUrl)
{
if (string.IsNullOrEmpty(imageUrl))
{
return StringToSizeConverter.DefaultEmpty;
}
try
{
if (!imageUrl.StartsWith("http") && !imageUrl.StartsWith("ms-appx:"))
{
imageUrl = string.Concat("ms-appx://", imageUrl);
}
}
catch (Exception) { }
return imageUrl;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
namespace Microsoft.Azure.Management.DataLake.Store
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// AccountOperations operations.
/// </summary>
internal partial class AccountOperations : IServiceOperations<DataLakeStoreAccountManagementClient>, IAccountOperations
{
/// <summary>
/// Tests the existence of the specified Data Lake Store firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account from which to test the firewall
/// rule's existence.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule to test for existence.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> FirewallRuleExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (firewallRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "firewallRuleName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("firewallRuleName", firewallRuleName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetFirewallRule", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/firewallRules/{firewallRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName));
_url = _url.Replace("{firewallRuleName}", Uri.EscapeDataString(firewallRuleName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
if(_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("ResourceNotFound", StringComparison.OrdinalIgnoreCase))
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = true;
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Tests whether the specified Data Lake Store account exists.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to test existence of.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> ExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
if (_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("ResourceNotFound", StringComparison.OrdinalIgnoreCase))
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = true;
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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.
//
// Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused.
//
using System;
using System.Diagnostics;
using System.Globalization;
namespace System.Text
{
// Encodes text into and out of UTF-32. UTF-32 is a way of writing
// Unicode characters with a single storage unit (32 bits) per character,
//
// The UTF-32 byte order mark is simply the Unicode byte order mark
// (0x00FEFF) written in UTF-32 (0x0000FEFF or 0xFFFE0000). The byte order
// mark is used mostly to distinguish UTF-32 text from other encodings, and doesn't
// switch the byte orderings.
public sealed class UTF32Encoding : Encoding
{
/*
words bits UTF-32 representation
----- ---- -----------------------------------
1 16 00000000 00000000 xxxxxxxx xxxxxxxx
2 21 00000000 000xxxxx hhhhhhll llllllll
----- ---- -----------------------------------
Surrogate:
Real Unicode value = (HighSurrogate - 0xD800) * 0x400 + (LowSurrogate - 0xDC00) + 0x10000
*/
// Used by Encoding.UTF32/BigEndianUTF32 for lazy initialization
// The initialization code will not be run until a static member of the class is referenced
internal static readonly UTF32Encoding s_default = new UTF32Encoding(bigEndian: false, byteOrderMark: true);
internal static readonly UTF32Encoding s_bigEndianDefault = new UTF32Encoding(bigEndian: true, byteOrderMark: true);
private static readonly byte[] s_bigEndianPreamble = new byte[4] { 0x00, 0x00, 0xFE, 0xFF };
private static readonly byte[] s_littleEndianPreamble = new byte[4] { 0xFF, 0xFE, 0x00, 0x00 };
private bool _emitUTF32ByteOrderMark = false;
private bool _isThrowException = false;
private bool _bigEndian = false;
public UTF32Encoding() : this(false, true, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark) :
this(bigEndian, byteOrderMark, false)
{
}
public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters) :
base(bigEndian ? 12001 : 12000)
{
_bigEndian = bigEndian;
_emitUTF32ByteOrderMark = byteOrderMark;
_isThrowException = throwOnInvalidCharacters;
// Encoding constructor already did this, but it'll be wrong if we're throwing exceptions
if (_isThrowException)
SetDefaultFallbacks();
}
internal override void SetDefaultFallbacks()
{
// For UTF-X encodings, we use a replacement fallback with an empty string
if (_isThrowException)
{
this.encoderFallback = EncoderFallback.ExceptionFallback;
this.decoderFallback = DecoderFallback.ExceptionFallback;
}
else
{
this.encoderFallback = new EncoderReplacementFallback("\xFFFD");
this.decoderFallback = new DecoderReplacementFallback("\xFFFD");
}
}
// The following methods are copied from EncodingNLS.cs.
// Unfortunately EncodingNLS.cs is internal and we're public, so we have to re-implement them here.
// These should be kept in sync for the following classes:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// Returns the number of bytes required to encode a range of characters in
// a character array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetByteCount(char[] chars, int index, int count)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException("chars", SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer);
// If no input, return 0, avoid fixed empty array problem
if (count == 0)
return 0;
// Just call the pointer version
fixed (char* pChars = chars)
return GetByteCount(pChars + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetByteCount(String s)
{
// Validate input
if (s==null)
throw new ArgumentNullException("s");
fixed (char* pChars = s)
return GetByteCount(pChars, s.Length, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
// Validate Parameters
if (chars == null)
throw new ArgumentNullException("chars", SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
// Call it with empty encoder
return GetByteCount(chars, count, null);
}
// Parent method is safe.
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
public override unsafe int GetBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
if (s == null || bytes == null)
throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (s.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
int byteCount = bytes.Length - byteIndex;
// Fix our input array if 0 length because fixed doesn't like 0 length arrays
if (bytes.Length == 0)
bytes = new byte[1];
fixed (char* pChars = s) fixed (byte* pBytes = &bytes[0])
return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. An exception occurs if the byte array is not large
// enough to hold the complete encoding of the characters. The
// GetByteCount method can be used to determine the exact number of
// bytes that will be produced for a given range of characters.
// Alternatively, the GetMaxByteCount method can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
// If nothing to encode return 0, avoid fixed problem
if (charCount == 0)
return 0;
// Just call pointer version
int byteCount = bytes.Length - byteIndex;
// Fix our input array if 0 length because fixed doesn't like 0 length arrays
if (bytes.Length == 0)
bytes = new byte[1];
fixed (char* pChars = chars) fixed (byte* pBytes = &bytes[0])
// Remember that byteCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
return GetBytes(chars, charCount, bytes, byteCount, null);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
// If no input just return 0, fixed doesn't like 0 length arrays.
if (count == 0)
return 0;
// Just call pointer version
fixed (byte* pBytes = bytes)
return GetCharCount(pBytes + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
return GetCharCount(bytes, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if ( bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index);
// If no input, return 0 & avoid fixed problem
if (byteCount == 0)
return 0;
// Just call pointer version
int charCount = chars.Length - charIndex;
// Fix our input array if 0 length because fixed doesn't like 0 length arrays
if (chars.Length == 0)
chars = new char[1];
fixed (byte* pBytes = bytes) fixed (char* pChars = &chars[0])
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
return GetChars(bytes, byteCount, chars, charCount, null);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe String GetString(byte[] bytes, int index, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
// Avoid problems with empty input buffer
if (count == 0) return String.Empty;
fixed (byte* pBytes = bytes)
return String.CreateStringFromEncoding(
pBytes + index, count, this);
}
//
// End of standard methods copied from EncodingNLS.cs
//
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
Debug.Assert(chars != null, "[UTF32Encoding.GetByteCount]chars!=null");
Debug.Assert(count >= 0, "[UTF32Encoding.GetByteCount]count >=0");
char* end = chars + count;
char* charStart = chars;
int byteCount = 0;
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
char* charsForFallback;
if (encoder != null)
{
highSurrogate = encoder._charLeftOver;
fallbackBuffer = encoder.FallbackBuffer;
// We mustn't have left over fallback data when counting
if (fallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, end, encoder, false);
char ch;
TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < end)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Do we need a low surrogate?
if (highSurrogate != '\0')
{
//
// In previous char, we encounter a high surrogate, so we are expecting a low surrogate here.
//
if (Char.IsLowSurrogate(ch))
{
// They're all legal
highSurrogate = '\0';
//
// One surrogate pair will be translated into 4 bytes UTF32.
//
byteCount += 4;
continue;
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
Debug.Assert(chars > charStart,
"[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate");
chars--;
// Do the fallback
charsForFallback = chars;
fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback);
chars = charsForFallback;
// We're going to fallback the old high surrogate.
highSurrogate = '\0';
continue;
}
// Do we have another high surrogate?
if (Char.IsHighSurrogate(ch))
{
//
// We'll have a high surrogate to check next time.
//
highSurrogate = ch;
continue;
}
// Check for illegal characters
if (Char.IsLowSurrogate(ch))
{
// We have a leading low surrogate, do the fallback
charsForFallback = chars;
fallbackBuffer.InternalFallback(ch, ref charsForFallback);
chars = charsForFallback;
// Try again with fallback buffer
continue;
}
// We get to add the character (4 bytes UTF32)
byteCount += 4;
}
// May have to do our last surrogate
if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
{
// We have to do the fallback for the lonely high surrogate
charsForFallback = chars;
fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback);
chars = charsForFallback;
highSurrogate = (char)0;
goto TryAgain;
}
// Check for overflows.
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GetByteCountOverflow);
// Shouldn't have anything in fallback buffer for GetByteCount
// (don't have to check _throwOnOverflow for count)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end");
// Return our count
return byteCount;
}
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
Debug.Assert(chars != null, "[UTF32Encoding.GetBytes]chars!=null");
Debug.Assert(bytes != null, "[UTF32Encoding.GetBytes]bytes!=null");
Debug.Assert(byteCount >= 0, "[UTF32Encoding.GetBytes]byteCount >=0");
Debug.Assert(charCount >= 0, "[UTF32Encoding.GetBytes]charCount >=0");
char* charStart = chars;
char* charEnd = chars + charCount;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
EncoderFallbackBuffer fallbackBuffer = null;
char* charsForFallback;
if (encoder != null)
{
highSurrogate = encoder._charLeftOver;
fallbackBuffer = encoder.FallbackBuffer;
// We mustn't have left over fallback data when not converting
if (encoder._throwOnOverflow && fallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
char ch;
TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Do we need a low surrogate?
if (highSurrogate != '\0')
{
//
// In previous char, we encountered a high surrogate, so we are expecting a low surrogate here.
//
if (Char.IsLowSurrogate(ch))
{
// Is it a legal one?
uint iTemp = GetSurrogate(highSurrogate, ch);
highSurrogate = '\0';
//
// One surrogate pair will be translated into 4 bytes UTF32.
//
if (bytes + 3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
{
fallbackBuffer.MovePrevious(); // Aren't using these 2 fallback chars
fallbackBuffer.MovePrevious();
}
else
{
// If we don't have enough room, then either we should've advanced a while
// or we should have bytes==byteStart and throw below
Debug.Assert(chars > charStart + 1 || bytes == byteStart,
"[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
chars -= 2; // Aren't using those 2 chars
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
highSurrogate = (char)0; // Nothing left over (we backed up to start of pair if supplimentary)
break;
}
if (_bigEndian)
{
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
*(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
*(bytes++) = (byte)(iTemp); // Implies & 0xFF
}
else
{
*(bytes++) = (byte)(iTemp); // Implies & 0xFF
*(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
*(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
*(bytes++) = (byte)(0x00);
}
continue;
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
Debug.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate");
chars--;
// Do the fallback
charsForFallback = chars;
fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback);
chars = charsForFallback;
// We're going to fallback the old high surrogate.
highSurrogate = '\0';
continue;
}
// Do we have another high surrogate?, if so remember it
if (Char.IsHighSurrogate(ch))
{
//
// We'll have a high surrogate to check next time.
//
highSurrogate = ch;
continue;
}
// Check for illegal characters (low surrogate)
if (Char.IsLowSurrogate(ch))
{
// We have a leading low surrogate, do the fallback
charsForFallback = chars;
fallbackBuffer.InternalFallback(ch, ref charsForFallback);
chars = charsForFallback;
// Try again with fallback buffer
continue;
}
// We get to add the character, yippee.
if (bytes + 3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
fallbackBuffer.MovePrevious(); // Aren't using this fallback char
else
{
// Must've advanced already
Debug.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character");
chars--; // Aren't using this char
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
break; // Didn't throw, stop
}
if (_bigEndian)
{
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
*(bytes++) = (byte)(ch); // Implies & 0xFF
}
else
{
*(bytes++) = (byte)(ch); // Implies & 0xFF
*(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
*(bytes++) = (byte)(0x00);
*(bytes++) = (byte)(0x00);
}
}
// May have to do our last surrogate
if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
{
// We have to do the fallback for the lonely high surrogate
charsForFallback = chars;
fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback);
chars = charsForFallback;
highSurrogate = (char)0;
goto TryAgain;
}
// Fix our encoder if we have one
Debug.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush),
"[UTF32Encoding.GetBytes]Expected encoder to be flushed.");
if (encoder != null)
{
// Remember our left over surrogate (or 0 if flushing)
encoder._charLeftOver = highSurrogate;
// Need # chars used
encoder._charsUsed = (int)(chars - charStart);
}
// return the new length
return (int)(bytes - byteStart);
}
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
Debug.Assert(bytes != null, "[UTF32Encoding.GetCharCount]bytes!=null");
Debug.Assert(count >= 0, "[UTF32Encoding.GetCharCount]count >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// None so far!
int charCount = 0;
byte* end = bytes + count;
byte* byteStart = bytes;
// Set up decoder
int readCount = 0;
uint iChar = 0;
// For fallback we may need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
// See if there's anything in our decoder
if (decoder != null)
{
readCount = decoder.readByteCount;
iChar = (uint)decoder.iChar;
fallbackBuffer = decoder.FallbackBuffer;
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check _throwOnOverflow for chars or count)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start");
}
else
{
fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(byteStart, null);
// Loop through our input, 4 characters at a time!
while (bytes < end && charCount >= 0)
{
// Get our next character
if (_bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
iChar += *(bytes++);
}
else
{
// Scoot right and add it to the top
iChar >>= 8;
iChar += (uint)(*(bytes++)) << 24;
}
readCount++;
// See if we have all the bytes yet
if (readCount < 4)
continue;
// Have the bytes
readCount = 0;
// See if its valid to encode
if (iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
if (_bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
}
else
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
}
charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
// Ignore the illegal character
iChar = 0;
continue;
}
// Ok, we have something we can add to our output
if (iChar >= 0x10000)
{
// Surrogates take 2
charCount++;
}
// Add the rest of the surrogate or our normal character
charCount++;
// iChar is back to 0
iChar = 0;
}
// See if we have something left over that has to be decoded
if (readCount > 0 && (decoder == null || decoder.MustFlush))
{
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
if (_bigEndian)
{
while (readCount > 0)
{
fallbackBytes[--readCount] = unchecked((byte)iChar);
iChar >>= 8;
}
}
else
{
while (readCount > 0)
{
fallbackBytes[--readCount] = unchecked((byte)(iChar >> 24));
iChar <<= 8;
}
}
charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
}
// Check for overflows.
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GetByteCountOverflow);
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check _throwOnOverflow for chars or count)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end");
// Return our count
return charCount;
}
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
Debug.Assert(chars != null, "[UTF32Encoding.GetChars]chars!=null");
Debug.Assert(bytes != null, "[UTF32Encoding.GetChars]bytes!=null");
Debug.Assert(byteCount >= 0, "[UTF32Encoding.GetChars]byteCount >=0");
Debug.Assert(charCount >= 0, "[UTF32Encoding.GetChars]charCount >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// None so far!
char* charStart = chars;
char* charEnd = chars + charCount;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
// See if there's anything in our decoder (but don't clear it yet)
int readCount = 0;
uint iChar = 0;
// For fallback we may need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
char* charsForFallback;
// See if there's anything in our decoder
if (decoder != null)
{
readCount = decoder.readByteCount;
iChar = (uint)decoder.iChar;
fallbackBuffer = baseDecoder.FallbackBuffer;
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check _throwOnOverflow for chars)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at start");
}
else
{
fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
}
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(bytes, chars + charCount);
// Loop through our input, 4 characters at a time!
while (bytes < byteEnd)
{
// Get our next character
if (_bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
iChar += *(bytes++);
}
else
{
// Scoot right and add it to the top
iChar >>= 8;
iChar += (uint)(*(bytes++)) << 24;
}
readCount++;
// See if we have all the bytes yet
if (readCount < 4)
continue;
// Have the bytes
readCount = 0;
// See if its valid to encode
if (iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
if (_bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
}
else
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
}
// Chars won't be updated unless this works.
charsForFallback = chars;
bool fallbackResult = fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref charsForFallback);
chars = charsForFallback;
if (!fallbackResult)
{
// Couldn't fallback, throw or wait til next time
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)");
bytes -= 4; // get back to where we were
iChar = 0; // Remembering nothing
fallbackBuffer.InternalReset();
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
// Ignore the illegal character
iChar = 0;
continue;
}
// Ok, we have something we can add to our output
if (iChar >= 0x10000)
{
// Surrogates take 2
if (chars >= charEnd - 1)
{
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)");
bytes -= 4; // get back to where we were
iChar = 0; // Remembering nothing
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
*(chars++) = GetHighSurrogate(iChar);
iChar = GetLowSurrogate(iChar);
}
// Bounds check for normal character
else if (chars >= charEnd)
{
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)");
bytes -= 4; // get back to where we were
iChar = 0; // Remembering nothing
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
break; // Stop here, didn't throw
}
// Add the rest of the surrogate or our normal character
*(chars++) = (char)iChar;
// iChar is back to 0
iChar = 0;
}
// See if we have something left over that has to be decoded
if (readCount > 0 && (decoder == null || decoder.MustFlush))
{
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
int tempCount = readCount;
if (_bigEndian)
{
while (tempCount > 0)
{
fallbackBytes[--tempCount] = unchecked((byte)iChar);
iChar >>= 8;
}
}
else
{
while (tempCount > 0)
{
fallbackBytes[--tempCount] = unchecked((byte)(iChar >> 24));
iChar <<= 8;
}
}
charsForFallback = chars;
bool fallbackResult = fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref charsForFallback);
chars = charsForFallback;
if (!fallbackResult)
{
// Couldn't fallback.
fallbackBuffer.InternalReset();
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
// Stop here, didn't throw, backed up, so still nothing in buffer
}
else
{
// Don't clear our decoder unless we could fall it back.
// If we caught the if above, then we're a convert() and will catch this next time.
readCount = 0;
iChar = 0;
}
}
// Remember any left over stuff, clearing buffer as well for MustFlush
if (decoder != null)
{
decoder.iChar = (int)iChar;
decoder.readByteCount = readCount;
decoder._bytesUsed = (int)(bytes - byteStart);
}
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check _throwOnOverflow for chars)
Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at end");
// Return our count
return (int)(chars - charStart);
}
private uint GetSurrogate(char cHigh, char cLow)
{
return (((uint)cHigh - 0xD800) * 0x400) + ((uint)cLow - 0xDC00) + 0x10000;
}
private char GetHighSurrogate(uint iChar)
{
return (char)((iChar - 0x10000) / 0x400 + 0xD800);
}
private char GetLowSurrogate(uint iChar)
{
return (char)((iChar - 0x10000) % 0x400 + 0xDC00);
}
public override Decoder GetDecoder()
{
return new UTF32Decoder(this);
}
public override Encoder GetEncoder()
{
return new EncoderNLS(this);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount),
SR.ArgumentOutOfRange_NeedNonNegNum);
// Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// 4 bytes per char
byteCount *= 4;
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow);
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(byteCount),
SR.ArgumentOutOfRange_NeedNonNegNum);
// A supplementary character becomes 2 surrogate characters, so 4 input bytes becomes 2 chars,
// plus we may have 1 surrogate char left over if the decoder has 3 bytes in it already for a non-bmp char.
// Have to add another one because 1/2 == 0, but 3 bytes left over could be 2 char surrogate pair
int charCount = (byteCount / 2) + 2;
// Also consider fallback because our input bytes could be out of range of unicode.
// Since fallback would fallback 4 bytes at a time, we'll only fall back 1/2 of MaxCharCount.
if (DecoderFallback.MaxCharCount > 2)
{
// Multiply time fallback size
charCount *= DecoderFallback.MaxCharCount;
// We were already figuring 2 chars per 4 bytes, but fallback will be different #
charCount /= 2;
}
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow);
return (int)charCount;
}
public override byte[] GetPreamble()
{
if (_emitUTF32ByteOrderMark)
{
// Allocate new array to prevent users from modifying it.
if (_bigEndian)
{
return new byte[4] { 0x00, 0x00, 0xFE, 0xFF };
}
else
{
return new byte[4] { 0xFF, 0xFE, 0x00, 0x00 }; // 00 00 FE FF
}
}
else
return Array.Empty<byte>();
}
public override ReadOnlySpan<byte> Preamble =>
GetType() != typeof(UTF32Encoding) ? GetPreamble() : // in case a derived UTF32Encoding overrode GetPreamble
_emitUTF32ByteOrderMark ? (_bigEndian ? s_bigEndianPreamble : s_littleEndianPreamble) :
Array.Empty<byte>();
public override bool Equals(Object value)
{
UTF32Encoding that = value as UTF32Encoding;
if (that != null)
{
return (_emitUTF32ByteOrderMark == that._emitUTF32ByteOrderMark) &&
(_bigEndian == that._bigEndian) &&
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
}
return (false);
}
public override int GetHashCode()
{
//Not great distribution, but this is relatively unlikely to be used as the key in a hashtable.
return this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() +
CodePage + (_emitUTF32ByteOrderMark ? 4 : 0) + (_bigEndian ? 8 : 0);
}
private sealed class UTF32Decoder : DecoderNLS
{
// Need a place to store any extra bytes we may have picked up
internal int iChar = 0;
internal int readByteCount = 0;
public UTF32Decoder(UTF32Encoding encoding) : base(encoding)
{
// base calls reset
}
public override void Reset()
{
this.iChar = 0;
this.readByteCount = 0;
if (_fallbackBuffer != null)
_fallbackBuffer.Reset();
}
// Anything left in our decoder?
internal override bool HasState
{
get
{
// ReadByteCount is our flag. (iChar==0 doesn't mean much).
return (this.readByteCount != 0);
}
}
}
}
}
| |
//-------------------------------------------------------------------------
// <copyright file="SparkViewFactoryTester.cs">
// Copyright 2008-2010 Louis DeJardin - http://whereslou.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.
// </copyright>
// <author>Louis DeJardin</author>
// <author>Gauthier Segay</author>
// <author>Jacob Proffitt</author>
// <author>John Gietzen</author>
//-------------------------------------------------------------------------
using System.Linq;
namespace Spark.Tests
{
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using Rhino.Mocks;
using Spark.Compiler;
using Spark.FileSystem;
using Spark.Tests.Models;
using Spark.Tests.Stubs;
[TestFixture, Category("SparkViewEngine")]
public class SparkViewFactoryTester
{
private MockRepository mocks;
private StubViewFactory factory;
private SparkViewEngine engine;
private StringBuilder sb;
private SparkSettings settings;
[SetUp]
public void Init()
{
settings = new SparkSettings().SetPageBaseType("Spark.Tests.Stubs.StubSparkView");
engine = new SparkViewEngine(settings) { ViewFolder = new FileSystemViewFolder("Spark.Tests.Views") };
factory = new StubViewFactory { Engine = engine };
sb = new StringBuilder();
mocks = new MockRepository();
}
StubViewContext MakeViewContext(string viewName, string masterName)
{
return new StubViewContext { ControllerName = "Home", ViewName = viewName, MasterName = masterName, Output = sb };
}
StubViewContext MakeViewContext(string viewName, string masterName, StubViewData data)
{
return new StubViewContext { ControllerName = "Home", ViewName = viewName, MasterName = masterName, Output = sb, Data = data };
}
[Test]
public void RenderPlainView()
{
mocks.ReplayAll();
factory.RenderView(MakeViewContext("Index", null));
mocks.VerifyAll();
}
[Test]
public void ForEachTest()
{
mocks.ReplayAll();
factory.RenderView(MakeViewContext("foreach", null));
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content.Contains(@"<li class=""odd"">1: foo</li>"));
Assert.That(content.Contains(@"<li class=""even"">2: bar</li>"));
Assert.That(content.Contains(@"<li class=""odd"">3: baaz</li>"));
}
[Test]
public void GlobalSetTest()
{
mocks.ReplayAll();
factory.RenderView(MakeViewContext("globalset", null));
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content.Contains("<p>default: Global set test</p>"));
Assert.That(content.Contains("<p>7==7</p>"));
}
[Test]
public void MasterTest()
{
mocks.ReplayAll();
factory.RenderView(MakeViewContext("childview", "layout"));
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content.Contains("<title>Standalone Index View</title>"));
Assert.That(content.Contains("<h1>Standalone Index View</h1>"));
Assert.That(content.Contains("<p>no header by default</p>"));
Assert.That(content.Contains("<p>no footer by default</p>"));
}
[Test]
public void CaptureNamedContent()
{
mocks.ReplayAll();
factory.RenderView(MakeViewContext("namedcontent", "layout"));
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content.Contains("<p>main content</p>"));
Assert.That(content.Contains("<p>this is the header</p>"));
Assert.That(content.Contains("<p>footer part one</p>"));
Assert.That(content.Contains("<p>footer part two</p>"));
}
[Test]
public void UsingPartialFile()
{
mocks.ReplayAll();
factory.RenderView(MakeViewContext("usingpartial", null));
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content.Contains("<li>Partial where x=\"zero\"</li>"));
Assert.That(content.Contains("<li>Partial where x=\"one\"</li>"));
Assert.That(content.Contains("<li>Partial where x=\"two\"</li>"));
Assert.That(content.Contains("<li>Partial where x=\"three\"</li>"));
Assert.That(content.Contains("<li>Partial where x=\"four\"</li>"));
}
[Test]
public void UsingPartialWithRenderElement()
{
mocks.ReplayAll();
factory.RenderView(MakeViewContext("usingpartial-render-element", null));
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content.Contains("<li>Partial where x=\"zero\"</li>"));
Assert.That(content.Contains("<li>Partial where x=\"one\"</li>"));
Assert.That(content.Contains("<li>Partial where x=\"two\"</li>"));
Assert.That(content.Contains("<li>Partial where x=\"three\"</li>"));
Assert.That(content.Contains("<li>Partial where x=\"four\"</li>"));
}
[Test]
public void UsingPartialFileImplicit()
{
mocks.ReplayAll();
factory.RenderView(MakeViewContext("usingpartialimplicit", null));
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content.Contains("<li class=\"odd\">one</li>"));
Assert.That(content.Contains("<li class=\"even\">two</li>"));
}
[Test]
public void UsingNamespace()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("usingnamespace", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content.Contains("<p>Foo</p>"));
Assert.That(content.Contains("<p>Bar</p>"));
Assert.That(content.Contains("<p>Hello</p>"));
}
[Test]
public void IfElseElements()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("ifelement", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(!content.Contains("<if"));
Assert.That(!content.Contains("<else"));
Assert.That(content.Contains("<p>argis5</p>"));
Assert.That(!content.Contains("<p>argis6</p>"));
Assert.That(content.Contains("<p>argisstill5</p>"));
Assert.That(!content.Contains("<p>argisnotstill5</p>"));
Assert.That(!content.Contains("<p>argisnow6</p>"));
Assert.That(content.Contains("<p>argisstillnot6</p>"));
}
[Test]
public void IfElseAttributes()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("ifattribute", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(!content.Contains("<if"));
Assert.That(!content.Contains("<else"));
Assert.That(content.Contains("<p>argis5</p>"));
Assert.That(!content.Contains("<p>argis6</p>"));
Assert.That(content.Contains("<p>argisstill5</p>"));
Assert.That(!content.Contains("<p>argisnotstill5</p>"));
Assert.That(!content.Contains("<p>argisnow6</p>"));
Assert.That(content.Contains("<p>argisstillnot6</p>"));
}
[Test]
public void UnlessElements()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("unlesselement", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(!content.Contains("<unless"));
Assert.That(content.Contains("<p>argisnot6</p>"));
Assert.That(!content.Contains("<p>argis5</p>"));
}
[Test]
public void UnlessAttributes()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("unlessattribute", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(!content.Contains("<unless"));
Assert.That(content.Contains("<p>argisnot6</p>"));
Assert.That(!content.Contains("<p>argis5</p>"));
}
[Test]
public void ChainingElseIfElement()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("elseifelement", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>Hi Bob!</p>",
"<p>Administrator James</p>",
"<p>Test user.</p>",
"<p>Anonymous user.</p>"));
}
[Test]
public void ChainingElseIfElement2()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("elseifelement2", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>Hi Bob!</p>",
"<p>Administrator James</p>",
"<p>Test user.</p>",
"<p>Anonymous user.</p>"));
}
[Test]
public void ChainingElseIfAttribute()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("elseifattribute", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>Hi Bob!</p>",
"<p>Administrator James</p>",
"<p>Test user.</p>",
"<p>Anonymous user.</p>"));
}
[Test]
public void EachAttribute()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("eachattribute", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<td>Bob</td>",
"<td>James</td>",
"<td>SpecialName</td>",
"<td>Anonymous</td>"));
}
[Test]
public void EachAttributeWhitespace()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("eachattribute-whitespace", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
var content = sb.ToString();
var expected =
@"<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul>
</ul>
<p>
1,2,3,
</p>
<p>
</p>
<p>
<span>1</span>
<span>2</span>
<span>3</span>
</p>
<p>
?: <img src=""1.jpg""/><img src=""2.jpg""/><img src=""3.jpg""/>
</p>
<p><img src=""1.jpg""/><img src=""2.jpg""/><img src=""3.jpg""/></p>
<p>
<span>abc</span>
</p>
<p>
</p>
<p>
abc
</p>
<p>
</p>
<p>
<div>abc</div>
</p>
<p>
<div>def</div>
</p>
";
// Ignore differences in line-ending style.
content = content.Replace("\r\n", "\n").Replace("\r", "\n");
expected = expected.Replace("\r\n", "\n").Replace("\r", "\n");
Assert.That(content, Is.EqualTo(expected));
}
[Test]
public void MarkupBasedMacros()
{
var data = new StubViewData
{
{"username", "Bob"},
{"comments", new[] {
new Comment {Text = "Alpha"},
new Comment {Text = "Beta"},
new Comment {Text = "Gamma"}
}}
};
mocks.ReplayAll();
var viewContext = MakeViewContext("macros", null, data);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>Bob</p>", "<p>Alpha</p>",
"<p>Bob</p>", "<p>Beta</p>",
"<p>Bob</p>", "<p>Gamma</p>",
"<span class=\"yadda\">Rating: 5</span>"));
}
[Test]
public void TestForEachIndex()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("foreachindex", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>0: Alpha</p>",
"<p>1: Beta</p>",
"<p>2: Gamma</p>",
"<p>3: Delta</p>",
"<li ", "class='even'>Alpha</li>",
"<li ", "class='odd'>Beta</li>",
"<li ", "class='even'>Gamma</li>",
"<li ", "class='odd'>Delta</li>"
));
}
[Test]
public void ForEachMoreAutoVariable()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("foreach-moreautovariables", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString().Replace(" ", "").Replace("\t", "").Replace("\r\n", "");
Assert.That(content, Contains.InOrder(
"<tr><td>one</td><td>0</td><td>4</td><td>True</td><td>False</td><td>False</td><td>True</td></tr>",
"<tr><td>two</td><td>1</td><td>4</td><td>False</td><td>False</td><td>True</td><td>False</td></tr>",
"<tr><td>three</td><td>2</td><td>4</td><td>False</td><td>False</td><td>False</td><td>True</td></tr>",
"<tr><td>four</td><td>3</td><td>4</td><td>False</td><td>True</td><td>True</td><td>False</td></tr>"));
}
[Test]
public void ConditionalTestElement()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("testelement", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>out-1</p>",
"<p>out-2</p>",
"<p>out-3</p>",
"<p>out-4</p>",
"<p>out-5</p>",
"<p>out-6</p>"));
Assert.IsFalse(content.Contains("fail"));
}
[Test]
public void ConditionalTestElementNested()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("testelementnested", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString().Replace(" ", "").Replace("\r", "").Replace("\n", "");
Assert.AreEqual("<p>a</p><p>b</p><p>c</p><p>d</p><p>e</p><p>f</p>", content);
}
[Test]
public void PartialFilesCanHaveSpecialElements()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("partialspecialelements", null, new StubViewData { { "foo", "alpha" } });
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"Hi there, alpha.",
"Hi there, alpha."));
}
[Test]
public void StatementTerminatingStrings()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("statement-terminating-strings", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString().Replace(" ", "").Replace("\r", "").Replace("\n", "");
Assert.AreEqual("<p>a:1</p><p>b:2</p><p>c:3%></p><p>d:<%4%></p><p>e:5%></p><p>f:<%6%></p>", content);
}
[Test]
public void ExpressionHasVerbatimStrings()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("expression-has-verbatim-strings", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString().Replace(" ", "").Replace("\r", "").Replace("\n", "");
Assert.AreEqual("<p>a\\\"b</p><p>c\\\"}d</p>", content);
}
[Test]
public void RelativeApplicationPaths()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("relativeapplicationpaths", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<img src=\"/TestApp/content/images/etc.png\"/>",
"<script src=\"/TestApp/content/js/etc.js\"></script>",
"<p class=\"~/blah.css\"></p>"));
}
[Test]
public void UseAssembly()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("useassembly", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>SortByCategory</p>"));
}
[Test]
public void AddViewDataMoreThanOnce()
{
mocks.ReplayAll();
var viewData = new StubViewData { { "comment", new Comment { Text = "Hello world" } } };
var viewContext = MakeViewContext("addviewdatamorethanonce", null, viewData);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<div>Hello world</div>",
"<div>\r\n Again: Hello world\r\n</div>"));
}
[Test]
public void AddViewDataDifferentTypes()
{
mocks.ReplayAll();
var viewData = new StubViewData { { "comment", new Comment { Text = "Hello world" } } };
var viewContext = MakeViewContext("addviewdatadifferenttypes", null, viewData);
Assert.That(() => factory.RenderView(viewContext), Throws.TypeOf<CompilerException>());
mocks.VerifyAll();
}
[Test]
public void RenderPartialWithContainedContent()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("render-partial-with-contained-content", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"xbox",
"xtop",
"xb1",
"xb2",
"xb3",
"xb4",
"xboxcontent",
"Hello World",
"xbottom",
"xb4",
"xb3",
"xb2",
"xb1"));
}
[Test]
public void RenderPartialWithSegmentContent()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("render-partial-with-segment-content", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"xbox",
"xtop",
"xb1",
"xb2",
"xb3",
"xb4",
"xboxcontent",
"title=\"My Tooltip\"",
"<h3>This is a test</h3>",
"Hello World",
"xbottom",
"xb4",
"xb3",
"xb2",
"xb1"));
}
[Test]
public void RenderPartialWithSectionAsHtml5ContentByDefault()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("render-partial-section-or-ignore", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"xbox",
"xtop",
"xb1",
"xb2",
"xb3",
"xb4",
"xboxcontent",
"<section name=\"top\">",
"<h3>This is a test</h3>",
"</section>",
"<section name=\"tooltip\">",
"My Tooltip",
"</section>",
"<p>Hello World</p>",
"xbottom",
"xb4",
"xb3",
"xb2",
"xb1"));
}
[Test]
public void RenderPartialWithSectionAsSegmentContentFromSettings()
{
settings.SetParseSectionTagAsSegment(true);
mocks.ReplayAll();
var viewContext = MakeViewContext("render-partial-section-or-ignore", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"xbox",
"xtop",
"xb1",
"xb2",
"xb3",
"xb4",
"xboxcontent",
"title=\"My Tooltip\"",
"<h3>This is a test</h3>",
"Hello World",
"xbottom",
"xb4",
"xb3",
"xb2",
"xb1"));
}
[Test]
public void RenderlPartialWithDotInName()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("render-dotted-partial", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>",
"this.is.some.text:",
"test456",
"</p>"
));
Assert.IsFalse(content.Contains("<PartialWith.Dot"));
}
[Test]
public void CaptureContentAsVariable()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("capture-content-as-variable", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"new-var-new-def-set-var"));
}
[Test]
public void CaptureContentBeforeAndAfter()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("capture-content-before-and-after", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>beforedataafter</p>"));
}
[Test]
public void ConstAndReadonlyGlobals()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("const-and-readonly-globals", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString().Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", "");
Assert.AreEqual("<ol><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li></ol>", content);
}
[Test]
public void PrefixContentNotation()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("prefix-content-notation", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString().Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace(" ", "");
Assert.That(content.Contains("onetwothree"));
}
[Test]
public void DynamicAttributes()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("dynamic-attributes", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<div>",
@"<elt1 a1=""1"" a3=""3""></elt1>",
@"<elt2 a1=""1"" a3=""3""></elt2>",
@"<elt3 a1=""1"" a2="""" a3=""3""></elt3>",
@"<elt4 a1=""1"" a2=""2"" a3=""3""></elt4>",
@"<elt5 a1=""1"" a2="" beta"" a3=""3""></elt5>",
@"<elt6 a1=""1"" a2=""alpha beta"" a3=""3""></elt6>",
@"<elt7 a1=""1"" a2=""alpha"" a3=""3""></elt7>",
@"<elt8 a1=""1"" a3=""3""></elt8>",
@"<elt9 a1=""1"" a2="" beta"" a3=""3""></elt9>",
@"<elt10 a1=""1"" a2=""alpha beta"" a3=""3""></elt10>",
@"<elt11 a1=""1"" a3=""3""></elt11>",
@"<elt12 a1=""1"" a2=""onetwo"" a3=""3""></elt12>",
"</div>"
));
}
[Test]
public void XMLDeclAndProcessingInstruction()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("xmldecl-and-processing-instruction", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>",
"<?php yadda yadda yadda ?>"
));
}
[Test]
public void ForEachAutovariablesUsedInline()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("foreach-autovariables-used-inline", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<li", "class=", "selected", "blah", "</li>",
"blah", "blah"));
}
[Test]
public void AlternateViewdataSyntax()
{
mocks.ReplayAll();
var viewData = new StubViewData<IList<string>> { { "my-data", "alpha" } };
viewData.Model = new[] { "beta", "gamma", "delta" };
var viewContext = MakeViewContext("alternate-viewdata-syntax", null, viewData);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>", "alpha", "</p>",
"<p>", "beta", "</p>",
"<p>", "gamma", "</p>",
"<p>", "delta", "</p>"
));
}
[Test]
public void DefaultValuesDontCollideWithExistingLocals()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("DefaultValuesDontCollideWithExistingLocals", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.IsFalse(content.Contains("default"));
Assert.That(content, Contains.InOrder("ok1", "ok2"));
Assert.IsFalse(content.Contains("fail"));
}
[Test]
public void DefaultValuesDontReplaceGlobals()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("DefaultValuesDontReplaceGlobals", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.IsFalse(content.Contains("default"));
Assert.That(content, Contains.InOrder("ok1", "ok2"));
Assert.IsFalse(content.Contains("fail"));
}
[Test]
public void DefaultValuesDontReplaceViewData()
{
mocks.ReplayAll();
var viewData = new StubViewData { { "x1", 5 }, { "x2", 5 } };
var viewContext = MakeViewContext("DefaultValuesDontReplaceViewData", null, viewData);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.IsFalse(content.Contains("default"));
Assert.That(content, Contains.InOrder("ok1", "ok2"));
Assert.IsFalse(content.Contains("fail"));
}
[Test]
public void DefaultValuesActAsLocal()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("DefaultValuesActAsLocal", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.IsFalse(content.Contains("default"));
Assert.That(content, Contains.InOrder("ok1", "ok2"));
Assert.IsFalse(content.Contains("fail"));
}
[Test]
public void DefaultValuesStandInForNullViewData()
{
mocks.ReplayAll();
var viewData = new StubViewData();
var viewContext = MakeViewContext("DefaultValuesStandInForNullViewData", null, viewData);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.IsFalse(content.Contains("default"));
Assert.That(content, Contains.InOrder("ok1", "ok2"));
Assert.IsFalse(content.Contains("fail"));
}
[Test]
public void NullExceptionHandledAutomatically()
{
mocks.ReplayAll();
var viewData = new StubViewData();
var viewContext = MakeViewContext("NullExceptionHandledAutomatically", null, viewData);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.IsFalse(content.Contains("default"));
Assert.That(content, Contains.InOrder(
"<p>name kaboom *${user.Name}*</p>",
"<p>name silently **</p>",
"<p>name fixed *fred*</p>"));
}
[Test]
public void CodeCommentsCanHaveQuotes()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("CodeCommentsCanHaveQuotes", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.IsFalse(content.Contains("broken"));
Assert.That(content, Contains.InOrder("one", "two", "three", "four", "five"));
}
[Test]
public void ConditionalAttributeDelimitedBySpaces()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("ConditionalAttributeDelimitedBySpaces", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.IsFalse(content.Contains("broken"));
Assert.That(content, Contains.InOrder(
"<h1 class=\"one three\"></h1>",
"<h2></h2>",
"<h3 class=\" two three\"></h3>",
"<h4 class=\"one three\"></h4>",
"<h5 class=\"one two\"></h5>",
"<h6></h6>",
"<h7 class=\"one&two<three\"></h7>"));
}
[Test]
public void OnceAttribute()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("OnceAttribute", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"foo1",
"bar0",
"quux2",
"a1"));
Assert.IsFalse(content.Contains("foo2"));
Assert.IsFalse(content.Contains("foo3"));
Assert.IsFalse(content.Contains("bar1"));
Assert.IsFalse(content.Contains("bar3"));
Assert.IsFalse(content.Contains("a2"));
}
[Test]
public void EachAttributeWorksOnSpecialNodes()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("EachAttributeWorksOnSpecialNodes", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>name-0-alpha</p>",
"<p>name-1-beta</p>",
"<p>name-2-gamma</p>",
"<span>one</span>",
"<span>two</span>",
"<span>three</span>"));
}
[Test]
public void IfAttributeWorksOnSpecialNodes()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("IfAttributeWorksOnSpecialNodes", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>name-0-alpha</p>",
"<p>name-2-gamma</p>",
"<span>one</span>",
"<span>three</span>"));
Assert.IsFalse(content.Contains("beta"));
Assert.IsFalse(content.Contains("two"));
}
[Test]
public void UnlessAttributeWorksOnSpecialNodes()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("UnlessAttributeWorksOnSpecialNodes", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>name-0-alpha</p>",
"<p>name-2-gamma</p>",
"<span>one</span>",
"<span>three</span>"));
Assert.IsFalse(content.Contains("beta"));
Assert.IsFalse(content.Contains("two"));
}
[Test]
public void OnceAttributeWorksOnSpecialNodes()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("OnceAttributeWorksOnSpecialNodes", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>name-0-alpha</p>",
"<span>foo1</span>",
"<span>bar0</span>",
"<span>quux2</span>"));
Assert.IsFalse(content.Contains("name-1"));
Assert.IsFalse(content.Contains("name-2"));
Assert.IsFalse(content.Contains("foo2"));
Assert.IsFalse(content.Contains("foo3"));
Assert.IsFalse(content.Contains("bar1"));
Assert.IsFalse(content.Contains("bar3"));
}
[Test]
public void LateBoundEvalResolvesViewData()
{
mocks.ReplayAll();
var viewData = new StubViewData()
{
{"alpha", "<strong>hi</strong>"},
{"beta", "yadda"}
};
var viewContext = MakeViewContext("LateBoundEvalResolvesViewData", null, viewData);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p><strong>hi</strong></p>",
"<p><strong>hi</strong></p>",
"yadda",
"<p>42</p>"));
}
[Test]
public void PartialInMacroMayUseDefaultElement()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("PartialInMacroMayUseDefaultElement", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>3hello</p>",
"<p>2hello.</p>",
"<p>1hello..</p>",
"<p>0hello...</p>"));
}
[Test]
public void RecursivePartialsThrowCompilerException()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("RecursivePartialsThrowCompilerException", null);
Assert.That(() =>
factory.RenderView(viewContext),
Throws.TypeOf<CompilerException>());
}
[Test]
public void NestedPartialsCanBackRenderUpAndReRenderDown()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("NestedPartialsCanBackRenderUpAndReRenderDown", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
var stripped = content.Replace(" ", "").Replace("\t", "").Replace("\r\n", "");
Assert.That(stripped, Is.EqualTo(
"[001][101]" +
"[201][102]" +
"[201][104][202]" +
"[106][002][107]" +
"[201][109][202]" +
"[111][202]" +
"[112][003]"));
}
[Test]
public void SegmentRenderingFallbackMayRenderSegment()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("SegmentRenderingFallbackMayRenderSegment", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
var stripped = content.Replace(" ", "").Replace("\t", "").Replace("\r\n", "");
Assert.That(stripped, Is.EqualTo(
"[001]" +
"[101][102]" +
"[002][004]" +
"[103][104]" +
"[005]"));
}
[Test]
public void Markdown()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("markdown", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<pre><code>", "code block on the first line", "</code></pre>",
"<p>", "Regular text.", "</p>",
"<pre><code>", "code block indented by spaces", "</code></pre>",
"<p>", "Regular text.", "</p>",
"<pre><code>", "the lines in this block",
"all contain trailing spaces", "</code></pre>",
"<p>", "Regular Text.", "</p>",
"<pre><code>", "code block on the last line", "</code></pre>"));
}
[Test]
public void Ignore()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("ignore", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<div>",
"Regular text ${This.isnt.code < 0}",
"<var dummy=\"This isn't a variable\" />",
"</div>"));
Assert.IsFalse(content.Contains("<ignore>"));
Assert.IsFalse(content.Contains("</ignore>"));
}
[Test]
public void Escape()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("escape", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<div>",
"${Encoded.Escaped.with.a.dollar < 0}",
"${Encoded.Escaped.with.a.backslash < 0}",
"${Encoded.Escaped.with.a.backtick < 0}",
"</div>"));
Assert.That(content, Contains.InOrder(
"<div>",
"!{Unencoded.Escaped.with.a.dollar < 0}",
"!{Unencoded.Escaped.with.a.backslash < 0}",
"!{Unencoded.Escaped.with.a.backtick < 0}",
"</div>"));
Assert.That(content, Contains.InOrder(
"<div>",
"$!{Encoded.Silent.Nulls.Escaped.with.a.dollar < 0}",
"$!{Encoded.Silent.Nulls.Escaped.with.a.backslash < 0}",
"$!{Encoded.Silent.Nulls.Escaped.with.a.backtick < 0}",
"</div>"));
}
[Test]
public void PreserveSingleQuotes()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("preserveSingleQuotes", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Is.EqualTo(@"<img attr='something; other=""value1, value2""'/>"));
}
[Test]
public void PreserveDoubleQuotes()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("preserveDoubleQuotes", null);
factory.RenderView(viewContext);
mocks.VerifyAll();
string content = sb.ToString();
Assert.That(content, Is.EqualTo(@"<img attr=""something; other='value1, value2'""/>"));
}
[Test]
public void ShadeFileRenders()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("ShadeFileRenders", null);
factory.RenderView(viewContext, Constants.DotShade);
mocks.VerifyAll();
var content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<html>",
"<head>",
"<title>",
"offset test",
"</title>",
"<body>",
"<div class=\"container\">",
"<h1 id=\"top\">",
"offset test",
"</h1>",
"</div>",
"</body>",
"</html>"));
}
[Test]
public void ShadeEvaluatesExpressions()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("ShadeEvaluatesExpressions", null);
factory.RenderView(viewContext, Constants.DotShade);
mocks.VerifyAll();
var content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>",
"<span>",
"8",
"</span>",
"<span>",
"2", " and ", "7",
"</span>",
"</p>"));
}
[Test]
public void ShadeSupportsAttributesAndMayTreatSomeElementsAsSpecialNodes()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("ShadeSupportsAttributesAndMayTreatSomeElementsAsSpecialNodes", null);
factory.RenderView(viewContext, Constants.DotShade);
mocks.VerifyAll();
var content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<ul class=\"nav\">",
"<li>Welcome</li>",
"<li>to</li>",
"<li>the</li>",
"<li>Machine</li>",
"</ul>",
"<p>",
"<span>4</span>",
"</p>"));
}
[Test]
public void ShadeCodeMayBeDashOrAtBraced()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("ShadeCodeMayBeDashOrAtBraced", null);
factory.RenderView(viewContext, Constants.DotShade);
mocks.VerifyAll();
var content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<ul>",
"<li>emocleW</li>",
"<li>ot</li>",
"<li>eht</li>",
"<li>enihcaM</li>",
"</ul>"));
}
[Test]
public void ShadeTextMayContainExpressions()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("ShadeTextMayContainExpressions", null);
factory.RenderView(viewContext, Constants.DotShade);
mocks.VerifyAll();
var content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>",
"<span>8</span>",
"<span>2 and 7</span>",
"</p>"));
}
[Test]
public void TextOrientedAttributesApplyToVarAndSet()
{
mocks.ReplayAll();
((SparkSettings)engine.Settings).AttributeBehaviour = AttributeBehaviour.TextOriented;
var viewContext = MakeViewContext("TextOrientedAttributesApplyToVarAndSet", null);
factory.RenderView(viewContext, Constants.DotSpark);
mocks.VerifyAll();
var content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>String:HelloWorld</p>",
"<p>Int32:42</p>"));
}
[Test]
public void TextOrientedAttributesApplyToUseFile()
{
mocks.ReplayAll();
((SparkSettings)engine.Settings).AttributeBehaviour = AttributeBehaviour.TextOriented;
var viewContext = MakeViewContext("TextOrientedAttributesApplyToUseFile", null);
factory.RenderView(viewContext, Constants.DotSpark);
mocks.VerifyAll();
var content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<span>Hello</span>",
"<span>Hello World!</span>",
"<span>42</span>"));
}
[Test]
public void TextOrientedAttributesApplyToDefault()
{
mocks.ReplayAll();
((SparkSettings)engine.Settings).AttributeBehaviour = AttributeBehaviour.TextOriented;
var viewContext = MakeViewContext("TextOrientedAttributesApplyToDefault", null);
factory.RenderView(viewContext, Constants.DotSpark);
mocks.VerifyAll();
var content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>String:World</p>",
"<p>String:Hello World!</p>",
"<p>Int32:42</p>"));
}
[Test]
public void TextOrientedAttributesApplyToGlobal()
{
mocks.ReplayAll();
((SparkSettings)engine.Settings).AttributeBehaviour = AttributeBehaviour.TextOriented;
var viewContext = MakeViewContext("TextOrientedAttributesApplyToGlobal", null);
factory.RenderView(viewContext, Constants.DotSpark);
mocks.VerifyAll();
var content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<p>String:World</p>",
"<p>String:Hello World!</p>",
"<p>Int32:42</p>"));
}
[Test]
public void ShadeElementsMayStackOnOneLine()
{
mocks.ReplayAll();
var viewContext = MakeViewContext("ShadeElementsMayStackOnOneLine", null);
factory.RenderView(viewContext, Constants.DotShade);
mocks.VerifyAll();
var content = sb.ToString();
Assert.That(content, Contains.InOrder(
"<html>",
"<head>",
"<title>",
"offset test",
"</title>",
"<body>",
"<div class=\"container\">",
"<h1 id=\"top\">",
"offset test",
"</h1>",
"</div>",
"</body>",
"</html>"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall;
using FlatRedBall.Input;
using FlatRedBall.Gui;
using FlatRedBall.Math.Splines;
using Microsoft.Xna.Framework;
using ToolTemplate.Entities;
using ToolTemplate.Gui;
using Microsoft.Xna.Framework.Graphics;
using Keys = Microsoft.Xna.Framework.Input.Keys;
using EditorObjects;
using EditorObjects.Undo.PropertyComparers;
using SplineEditor.States;
using SplineEditor.Commands;
using SplineEditor.ViewModels;
namespace ToolTemplate
{
public class EditorLogic
{
#region Fields
private ReactiveHud mReactiveHud = new ReactiveHud();
AllObjectsToolbarViewModel allObjectsToolbarViewModel;
Spline mCurrentSpline;
SplinePoint mCurrentSplinePoint;
Spline mSplineOver;
SplinePoint mSplinePointOver;
SplinePoint mGrabbedSplinePoint;
int mHandleIndexOver0Base = -1;
float mXGrabOffset;
float mYGrabOffset;
bool mSwitchedCurrentOnLastPush;
#endregion
#region Properties
public Spline CurrentSpline
{
get
{
Spline toReturn = null;
bool found = false;
if (mCurrentSplinePoint != null)
{
foreach (var spline in EditorData.SplineList)
{
if (spline.Contains(mCurrentSplinePoint))
{
toReturn = spline;
found = true;
break;
}
}
}
if (!found)
{
toReturn = mCurrentSpline;
}
return toReturn;
}
set
{
if (mCurrentSpline != null)
{
mCurrentSpline.PointColor = Color.DarkGray;
mCurrentSpline.PathColor = Color.DarkMagenta;
mCurrentSplinePoint = null;
}
mCurrentSpline = value;
if (mCurrentSpline != null)
{
// I don't know why we forced visible here, it should
// just stay whatever it was before:
//mCurrentSpline.Visible = true;
mCurrentSpline.PointColor = Color.White;
mCurrentSpline.PathColor = Color.Red;
mCurrentSpline.CalculateVelocities();
mCurrentSpline.CalculateAccelerations();
mCurrentSpline.CalculateDistanceTimeRelationships(.05f);
// Before highlighting the object let's make sure that the list is showing it
// Update: Doing this actually refreshes the list and this can screw selection and
// collapse state. It's annoying, and I don't think we need it:
//GuiData.SplineListDisplay.UpdateToList();
mCurrentSpline.Visible = true;
}
GuiData.UpdateToSpline(mCurrentSpline);
UpdateDeselectedSplineVisibility();
if (mCurrentSpline == null ||
(CurrentSplinePoint != null && !mCurrentSpline.Contains(mCurrentSplinePoint)))
{
CurrentSplinePoint = null;
}
}
}
public SplinePoint CurrentSplinePoint
{
get
{
return mCurrentSplinePoint;
}
set
{
mCurrentSplinePoint = value;
GuiData.UpdateToSplinePoint(mCurrentSplinePoint);
}
}
bool showDeselectedSplines;
public bool ShowDeselectedSplines
{
get
{
return showDeselectedSplines;
}
set
{
showDeselectedSplines = value;
UpdateDeselectedSplineVisibility();
}
}
#endregion
#region Methods
#region Constructor
public EditorLogic()
{
}
#endregion
#region Public Methods
public void Update()
{
UpdateSplines();
MouseSplineActivity();
mReactiveHud.Update();
AppCommands.Self.Preview.SplineCrawlerActivity();
KeyboardShortcutActivity();
}
internal AllObjectsToolbarViewModel GetAllObjectsToolbarViewModel()
{
if(allObjectsToolbarViewModel == null)
{
CreateAllObjectsToolbarViewModel();
}
return allObjectsToolbarViewModel;
}
private void CreateAllObjectsToolbarViewModel()
{
allObjectsToolbarViewModel = new AllObjectsToolbarViewModel();
this.ShowDeselectedSplines = allObjectsToolbarViewModel.ShowDeselectedSplines;
allObjectsToolbarViewModel.PropertyChanged += AllObjectsToolbarViewModel_PropertyChanged;
}
private void AllObjectsToolbarViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if(e.PropertyName == nameof(allObjectsToolbarViewModel.ShowDeselectedSplines))
{
ShowDeselectedSplines = allObjectsToolbarViewModel.ShowDeselectedSplines;
}
}
#endregion
#region Private Methods
private void GetSplineAndSplinePointOver()
{
mSplinePointOver = null;
mSplineOver = null;
mHandleIndexOver0Base = -1;
#region First see if the cursor is over the current Spline
if (mCurrentSpline != null)
{
if (mReactiveHud.SplinePointSelectionMarker.HasCursorOver(GuiManager.Cursor, out mHandleIndexOver0Base))
{
mSplineOver = AppState.Self.CurrentSpline;
mSplinePointOver = AppState.Self.CurrentSplinePoint;
}
else
{
SplinePoint splinePointOver = GetSplinePointOver(mCurrentSpline);
if (splinePointOver != null)
{
mSplinePointOver = splinePointOver;
mSplineOver = mCurrentSpline;
return;
}
}
}
#endregion
#region If not, try the other Splines
for (int i = 0; i < EditorData.SplineList.Count; i++)
{
Spline spline = EditorData.SplineList[i];
if (spline.Visible)
{
SplinePoint splinePointOver = GetSplinePointOver(spline);
if (splinePointOver != null)
{
mSplineOver = spline;
mSplinePointOver = splinePointOver;
break;
}
}
}
#endregion
}
private SplinePoint GetSplinePointOver(Spline spline)
{
foreach (SplinePoint splinePoint in spline)
{
float splinePointRadius = AppState.Self.Preview.SplinePointRadius / Camera.Main.PixelsPerUnitAt(splinePoint.Position.Z);
float cursorWorldX = GuiManager.Cursor.WorldXAt(splinePoint.Position.Z);
float cursorWorldY = GuiManager.Cursor.WorldYAt(splinePoint.Position.Z);
if (
(splinePoint.Position -
new Vector3(cursorWorldX, cursorWorldY, splinePoint.Position.Z)).Length() < splinePointRadius)
{
return splinePoint;
}
}
return null;
}
private void UpdateDeselectedSplineVisibility()
{
foreach(var spline in EditorData.SplineList)
{
if(spline != mCurrentSpline)
{
spline.Visible = showDeselectedSplines;
}
}
}
private void KeyboardShortcutActivity()
{
if (InputManager.ReceivingInput == null)
{
EditorObjects.CameraMethods.KeyboardCameraControl(SpriteManager.Camera);
}
#region CTRL+C copy current Spline
if (InputManager.InputReceiver == null && InputManager.Keyboard.ControlCPushed() && CurrentSpline != null)
{
Spline newSpline = CurrentSpline.Clone() as Spline;
EditorData.SplineList.Add(newSpline);
EditorData.InitializeSplineAfterCreation(newSpline);
AppCommands.Self.Gui.RefreshTreeView();
}
#endregion
#region SPACE - create spline crawler
if (InputManager.Keyboard.KeyPushed(Keys.Space) &&
!InputManager.IsKeyConsumedByInputReceiver(Keys.Space))
{
AppCommands.Self.Preview.CreateSplineCrawler();
}
#endregion
}
private void MouseGrabbingActivity()
{
Cursor cursor = GuiManager.Cursor;
if (cursor.PrimaryPush && GuiManager.Cursor.WindowOver == null)
{
mCurrentSplinePoint = null;
if (mReactiveHud.SplineMover.IsMouseOver == false)
{
mSwitchedCurrentOnLastPush = mCurrentSpline != mSplineOver;
CurrentSpline = mSplineOver;
// Make sure we set the CurrentSplinePoint after setting the CurrentSpline so that
// the GUI for the CurrentSpline is already set.
CurrentSplinePoint = mSplinePointOver;
mGrabbedSplinePoint = mSplinePointOver;
if (mGrabbedSplinePoint != null)
{
float cursorX = cursor.WorldXAt(mGrabbedSplinePoint.Position.Z);
float cursorY = cursor.WorldYAt(mGrabbedSplinePoint.Position.Z);
mXGrabOffset = mGrabbedSplinePoint.Position.X - cursorX;
mYGrabOffset = mGrabbedSplinePoint.Position.Y - cursorY;
}
}
// else if over the spline mover, let the current spline point stay at null
}
if (cursor.PrimaryDown && mGrabbedSplinePoint != null)
{
if (mHandleIndexOver0Base != -1)
{
float cursorX = cursor.WorldXAt(mGrabbedSplinePoint.Position.Z);
float cursorY = cursor.WorldYAt(mGrabbedSplinePoint.Position.Z);
float differenceX = cursorX - mGrabbedSplinePoint.Position.X;
float differenceY = cursorY - mGrabbedSplinePoint.Position.Y;
differenceX *= 2;
differenceY *= 2;
if (mHandleIndexOver0Base == 0)
{
// Index 0 goes negative, index 1 goes positive
differenceX *= -1;
differenceY *= -1;
}
mGrabbedSplinePoint.Velocity.X = differenceX;
mGrabbedSplinePoint.Velocity.Y = differenceY;
}
else if (!mSwitchedCurrentOnLastPush)
{
mGrabbedSplinePoint.Position = new Vector3(
cursor.WorldXAt(mGrabbedSplinePoint.Position.Z) + mXGrabOffset,
cursor.WorldYAt(mGrabbedSplinePoint.Position.Z) + mYGrabOffset,
mGrabbedSplinePoint.Position.Z);
}
}
if (cursor.PrimaryClick)
{
mGrabbedSplinePoint = null;
GuiData.PropertyGrid.Refresh();
}
}
private void MouseSplineActivity()
{
if (GuiManager.Cursor.IsInWindow())
{
if (GuiManager.Cursor.PrimaryDown == false)
{
GetSplineAndSplinePointOver();
}
MouseGrabbingActivity();
}
}
private void UpdateSplines()
{
if (mCurrentSpline != null)
{
mCurrentSpline.CalculateVelocities();
mCurrentSpline.CalculateAccelerations();
mCurrentSpline.Sort();
}
foreach (Spline spline in EditorData.SplineList)
{
spline.PointFrequency = .15f;
spline.UpdateShapes();
}
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Orleans.Concurrency;
using Orleans.Runtime;
namespace Orleans
{
/// <summary>
/// Interface for Membership Table.
/// </summary>
public interface IMembershipTable
{
/// <summary>
/// Initializes the membership table, will be called before all other methods
/// </summary>
/// <param name="tryInitTableVersion">whether an attempt will be made to init the underlying table</param>
Task InitializeMembershipTable(bool tryInitTableVersion);
/// <summary>
/// Deletes all table entries of the given clusterId
/// </summary>
Task DeleteMembershipTableEntries(string clusterId);
/// <summary>
/// Delete all dead silo entries older than <paramref name="beforeDate"/>
/// </summary>
Task CleanupDefunctSiloEntries(DateTimeOffset beforeDate);
/// <summary>
/// Atomically reads the Membership Table information about a given silo.
/// The returned MembershipTableData includes one MembershipEntry entry for a given silo and the
/// TableVersion for this table. The MembershipEntry and the TableVersion have to be read atomically.
/// </summary>
/// <param name="key">The address of the silo whose membership information needs to be read.</param>
/// <returns>The membership information for a given silo: MembershipTableData consisting one MembershipEntry entry and
/// TableVersion, read atomically.</returns>
Task<MembershipTableData> ReadRow(SiloAddress key);
/// <summary>
/// Atomically reads the full content of the Membership Table.
/// The returned MembershipTableData includes all MembershipEntry entry for all silos in the table and the
/// TableVersion for this table. The MembershipEntries and the TableVersion have to be read atomically.
/// </summary>
/// <returns>The membership information for a given table: MembershipTableData consisting multiple MembershipEntry entries and
/// TableVersion, all read atomically.</returns>
Task<MembershipTableData> ReadAll();
/// <summary>
/// Atomically tries to insert (add) a new MembershipEntry for one silo and also update the TableVersion.
/// If operation succeeds, the following changes would be made to the table:
/// 1) New MembershipEntry will be added to the table.
/// 2) The newly added MembershipEntry will also be added with the new unique automatically generated eTag.
/// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version.
/// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag.
/// All those changes to the table, insert of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects.
/// The operation should fail in each of the following conditions:
/// 1) A MembershipEntry for a given silo already exist in the table
/// 2) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table.
/// </summary>
/// <param name="entry">MembershipEntry to be inserted.</param>
/// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param>
/// <returns>True if the insert operation succeeded and false otherwise.</returns>
Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion);
/// <summary>
/// Atomically tries to update the MembershipEntry for one silo and also update the TableVersion.
/// If operation succeeds, the following changes would be made to the table:
/// 1) The MembershipEntry for this silo will be updated to the new MembershipEntry (the old entry will be fully substituted by the new entry)
/// 2) The eTag for the updated MembershipEntry will also be eTag with the new unique automatically generated eTag.
/// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version.
/// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag.
/// All those changes to the table, update of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects.
/// The operation should fail in each of the following conditions:
/// 1) A MembershipEntry for a given silo does not exist in the table
/// 2) A MembershipEntry for a given silo exist in the table but its etag in the table does not match the provided etag.
/// 3) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table.
/// </summary>
/// <param name="entry">MembershipEntry to be updated.</param>
/// <param name="etag">The etag for the given MembershipEntry.</param>
/// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param>
/// <returns>True if the update operation succeeded and false otherwise.</returns>
Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion);
/// <summary>
/// Updates the IAmAlive part (column) of the MembershipEntry for this silo.
/// This operation should only update the IAmAlive column and not change other columns.
/// This operation is a "dirty write" or "in place update" and is performed without etag validation.
/// With regards to eTags update:
/// This operation may automatically update the eTag associated with the given silo row, but it does not have to. It can also leave the etag not changed ("dirty write").
/// With regards to TableVersion:
/// this operation should not change the TableVersion of the table. It should leave it untouched.
/// There is no scenario where this operation could fail due to table semantical reasons. It can only fail due to network problems or table unavailability.
/// </summary>
/// <param name="entry"></param>
/// <returns>Task representing the successful execution of this operation. </returns>
Task UpdateIAmAlive(MembershipEntry entry);
}
/// <summary>
/// Membership table interface for system target based implementation.
/// </summary>
[Unordered]
public interface IMembershipTableSystemTarget : IMembershipTable, ISystemTarget
{
}
[Serializable]
[Immutable]
public class TableVersion
{
/// <summary>
/// The version part of this TableVersion. Monotonically increasing number.
/// </summary>
public int Version { get; private set; }
/// <summary>
/// The etag of this TableVersion, used for validation of table update operations.
/// </summary>
public string VersionEtag { get; private set; }
public TableVersion(int version, string eTag)
{
Version = version;
VersionEtag = eTag;
}
public TableVersion Next()
{
return new TableVersion(Version + 1, VersionEtag);
}
public override string ToString()
{
return string.Format("<{0}, {1}>", Version, VersionEtag);
}
}
[Serializable]
public class MembershipTableData
{
public IReadOnlyList<Tuple<MembershipEntry, string>> Members { get; private set; }
public TableVersion Version { get; private set; }
public MembershipTableData(List<Tuple<MembershipEntry, string>> list, TableVersion version)
{
// put deads at the end, just for logging.
list.Sort(
(x, y) =>
{
if (x.Item1.Status == SiloStatus.Dead) return 1; // put Deads at the end
if (y.Item1.Status == SiloStatus.Dead) return -1; // put Deads at the end
return String.Compare(x.Item1.SiloName, y.Item1.SiloName, StringComparison.Ordinal);
});
Members = list.AsReadOnly();
Version = version;
}
public MembershipTableData(Tuple<MembershipEntry, string> tuple, TableVersion version)
{
Members = (new List<Tuple<MembershipEntry, string>> { tuple }).AsReadOnly();
Version = version;
}
public MembershipTableData(TableVersion version)
{
Members = (new List<Tuple<MembershipEntry, string>>()).AsReadOnly();
Version = version;
}
public Tuple<MembershipEntry, string> Get(SiloAddress silo)
{
return Members.First(tuple => tuple.Item1.SiloAddress.Equals(silo));
}
public bool Contains(SiloAddress silo)
{
return Members.Any(tuple => tuple.Item1.SiloAddress.Equals(silo));
}
public override string ToString()
{
int active = Members.Count(e => e.Item1.Status == SiloStatus.Active);
int dead = Members.Count(e => e.Item1.Status == SiloStatus.Dead);
int created = Members.Count(e => e.Item1.Status == SiloStatus.Created);
int joining = Members.Count(e => e.Item1.Status == SiloStatus.Joining);
int shuttingDown = Members.Count(e => e.Item1.Status == SiloStatus.ShuttingDown);
int stopping = Members.Count(e => e.Item1.Status == SiloStatus.Stopping);
string otherCounts = String.Format("{0}{1}{2}{3}",
created > 0 ? (", " + created + " are Created") : "",
joining > 0 ? (", " + joining + " are Joining") : "",
shuttingDown > 0 ? (", " + shuttingDown + " are ShuttingDown") : "",
stopping > 0 ? (", " + stopping + " are Stopping") : "");
return string.Format("{0} silos, {1} are Active, {2} are Dead{3}, Version={4}. All silos: {5}",
Members.Count,
active,
dead,
otherCounts,
Version,
Utils.EnumerableToString(Members, tuple => tuple.Item1.ToFullString()));
}
// return a copy of the table removing all dead appereances of dead nodes, except for the last one.
public MembershipTableData WithoutDuplicateDeads()
{
var dead = new Dictionary<IPEndPoint, Tuple<MembershipEntry, string>>();
// pick only latest Dead for each instance
foreach (var next in Members.Where(item => item.Item1.Status == SiloStatus.Dead))
{
var ipEndPoint = next.Item1.SiloAddress.Endpoint;
Tuple<MembershipEntry, string> prev;
if (!dead.TryGetValue(ipEndPoint, out prev))
{
dead[ipEndPoint] = next;
}
else
{
// later dead.
if (next.Item1.SiloAddress.Generation.CompareTo(prev.Item1.SiloAddress.Generation) > 0)
dead[ipEndPoint] = next;
}
}
//now add back non-dead
List<Tuple<MembershipEntry, string>> all = dead.Values.ToList();
all.AddRange(Members.Where(item => item.Item1.Status != SiloStatus.Dead));
return new MembershipTableData(all, Version);
}
internal Dictionary<SiloAddress, SiloStatus> GetSiloStatuses(Func<SiloStatus, bool> filter, bool includeMyself, SiloAddress myAddress)
{
var result = new Dictionary<SiloAddress, SiloStatus>();
foreach (var memberEntry in this.Members)
{
var entry = memberEntry.Item1;
if (!includeMyself && entry.SiloAddress.Equals(myAddress)) continue;
if (filter(entry.Status)) result[entry.SiloAddress] = entry.Status;
}
return result;
}
}
[Serializable]
public class MembershipEntry
{
/// <summary>
/// The silo unique identity (ip:port:epoch). Used mainly by the Membership Protocol.
/// </summary>
public SiloAddress SiloAddress { get; set; }
/// <summary>
/// The silo status. Managed by the Membership Protocol.
/// </summary>
public SiloStatus Status { get; set; }
/// <summary>
/// The list of silos that suspect this silo. Managed by the Membership Protocol.
/// </summary>
public List<Tuple<SiloAddress, DateTime>> SuspectTimes { get; set; }
/// <summary>
/// Silo to clients TCP port. Set on silo startup.
/// </summary>
public int ProxyPort { get; set; }
/// <summary>
/// The DNS host name of the silo. Equals to Dns.GetHostName(). Set on silo startup.
/// </summary>
public string HostName { get; set; }
/// <summary>
/// the name of the specific silo instance within a cluster.
/// If running in Azure - the name of this role instance. Set on silo startup.
/// </summary>
public string SiloName { get; set; }
public string RoleName { get; set; } // Optional - only for Azure role
public int UpdateZone { get; set; } // Optional - only for Azure role
public int FaultZone { get; set; } // Optional - only for Azure role
/// <summary>
/// Time this silo was started. For diagnostics and troubleshooting only.
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// the last time this silo reported that it is alive. For diagnostics and troubleshooting only.
/// </summary>
public DateTime IAmAliveTime { get; set; }
public void AddSuspector(SiloAddress suspectingSilo, DateTime suspectingTime)
{
if (SuspectTimes == null)
SuspectTimes = new List<Tuple<SiloAddress, DateTime>>();
var suspector = new Tuple<SiloAddress, DateTime>(suspectingSilo, suspectingTime);
SuspectTimes.Add(suspector);
}
internal MembershipEntry Copy()
{
return new MembershipEntry
{
SiloAddress = this.SiloAddress,
Status = this.Status,
HostName = this.HostName,
ProxyPort = this.ProxyPort,
RoleName = this.RoleName,
SiloName = this.SiloName,
UpdateZone = this.UpdateZone,
FaultZone = this.FaultZone,
SuspectTimes = this.SuspectTimes is null ? null : new List<Tuple<SiloAddress, DateTime>>(this.SuspectTimes),
StartTime = this.StartTime,
IAmAliveTime = this.IAmAliveTime,
};
}
internal MembershipEntry WithStatus(SiloStatus status)
{
var updated = this.Copy();
updated.Status = status;
return updated;
}
internal ImmutableList<Tuple<SiloAddress, DateTime>> GetFreshVotes(DateTime now, TimeSpan expiration)
{
if (this.SuspectTimes == null)
return ImmutableList<Tuple<SiloAddress, DateTime>>.Empty;
var result = ImmutableList.CreateBuilder<Tuple<SiloAddress, DateTime>>();
foreach (var voter in this.SuspectTimes)
{
// If now is smaller than otherVoterTime, than assume the otherVoterTime is fresh.
// This could happen if clocks are not synchronized and the other voter clock is ahead of mine.
var otherVoterTime = voter.Item2;
if (now < otherVoterTime || now.Subtract(otherVoterTime) < expiration)
{
result.Add(voter);
}
}
return result.ToImmutable();
}
public override string ToString()
{
return string.Format("SiloAddress={0} SiloName={1} Status={2}", SiloAddress.ToLongString(), SiloName, Status);
}
internal string ToFullString(bool full = false)
{
if (!full)
return ToString();
List<SiloAddress> suspecters = SuspectTimes == null
? null
: SuspectTimes.Select(tuple => tuple.Item1).ToList();
List<DateTime> timestamps = SuspectTimes == null
? null
: SuspectTimes.Select(tuple => tuple.Item2).ToList();
return string.Format("[SiloAddress={0} SiloName={1} Status={2} HostName={3} ProxyPort={4} " +
"RoleName={5} UpdateZone={6} FaultZone={7} StartTime = {8} IAmAliveTime = {9} {10} {11}]",
SiloAddress.ToLongString(),
SiloName,
Status,
HostName,
ProxyPort,
RoleName,
UpdateZone,
FaultZone,
LogFormatter.PrintDate(StartTime),
LogFormatter.PrintDate(IAmAliveTime),
suspecters == null
? ""
: "Suspecters = " + Utils.EnumerableToString(suspecters, sa => sa.ToLongString()),
timestamps == null
? ""
: "SuspectTimes = " + Utils.EnumerableToString(timestamps, LogFormatter.PrintDate)
);
}
}
}
| |
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
namespace SixLabors.Fonts.Unicode
{
/// <summary>
/// Unicode Joining Groups
/// <see href="https://www.unicode.org/versions/Unicode13.0.0/ch09.pdf"/>.
/// </summary>
public enum JoiningGroup
{
/// <summary>
/// African_Feh
/// </summary>
AfricanFeh,
/// <summary>
/// African_Noon
/// </summary>
AfricanNoon,
/// <summary>
/// African_Qaf
/// </summary>
AfricanQaf,
/// <summary>
/// Ain
/// </summary>
Ain,
/// <summary>
/// Alaph
/// </summary>
Alaph,
/// <summary>
/// Alef
/// </summary>
Alef,
/// <summary>
/// Beh
/// </summary>
Beh,
/// <summary>
/// Beth
/// </summary>
Beth,
/// <summary>
/// Burushaski_Yeh_Barree
/// </summary>
BurushaskiYehBarree,
/// <summary>
/// Dal
/// </summary>
Dal,
/// <summary>
/// Dalath_Rish
/// </summary>
DalathRish,
/// <summary>
/// E
/// </summary>
E,
/// <summary>
/// Farsi_Yeh
/// </summary>
FarsiYeh,
/// <summary>
/// Fe
/// </summary>
Fe,
/// <summary>
/// Feh
/// </summary>
Feh,
/// <summary>
/// Final_Semkath
/// </summary>
FinalSemkath,
/// <summary>
/// Gaf
/// </summary>
Gaf,
/// <summary>
/// Gamal
/// </summary>
Gamal,
/// <summary>
/// Hah
/// </summary>
Hah,
/// <summary>
/// Hanifi_Rohingya_Kinna_Ya
/// </summary>
HanifiRohingyaKinnaYa,
/// <summary>
/// Hanifi_Rohingya_Pa
/// </summary>
HanifiRohingyaPa,
/// <summary>
/// He
/// </summary>
He,
/// <summary>
/// Heh
/// </summary>
Heh,
/// <summary>
/// Heh_Goal
/// </summary>
HehGoal,
/// <summary>
/// Heth
/// </summary>
Heth,
/// <summary>
/// Kaf
/// </summary>
Kaf,
/// <summary>
/// Kaph
/// </summary>
Kaph,
/// <summary>
/// Khaph
/// </summary>
Khaph,
/// <summary>
/// Knotted_Heh
/// </summary>
KnottedHeh,
/// <summary>
/// Lam
/// </summary>
Lam,
/// <summary>
/// Lamadh
/// </summary>
Lamadh,
/// <summary>
/// Malayalam_Bha
/// </summary>
MalayalamBha,
/// <summary>
/// Malayalam_Ja
/// </summary>
MalayalamJa,
/// <summary>
/// Malayalam_Lla
/// </summary>
MalayalamLla,
/// <summary>
/// Malayalam_Llla
/// </summary>
MalayalamLlla,
/// <summary>
/// Malayalam_Nga
/// </summary>
MalayalamNga,
/// <summary>
/// Malayalam_Nna
/// </summary>
MalayalamNna,
/// <summary>
/// Malayalam_Nnna
/// </summary>
MalayalamNnna,
/// <summary>
/// Malayalam_Nya
/// </summary>
MalayalamNya,
/// <summary>
/// Malayalam_Ra
/// </summary>
MalayalamRa,
/// <summary>
/// Malayalam_Ssa
/// </summary>
MalayalamSsa,
/// <summary>
/// Malayalam_Tta
/// </summary>
MalayalamTta,
/// <summary>
/// Manichaean_Aleph
/// </summary>
ManichaeanAleph,
/// <summary>
/// Manichaean_Ayin
/// </summary>
ManichaeanAyin,
/// <summary>
/// Manichaean_Beth
/// </summary>
ManichaeanBeth,
/// <summary>
/// Manichaean_Daleth
/// </summary>
ManichaeanDaleth,
/// <summary>
/// Manichaean_Dhamedh
/// </summary>
ManichaeanDhamedh,
/// <summary>
/// Manichaean_Five
/// </summary>
ManichaeanFive,
/// <summary>
/// Manichaean_Gimel
/// </summary>
ManichaeanGimel,
/// <summary>
/// Manichaean_Heth
/// </summary>
ManichaeanHeth,
/// <summary>
/// Manichaean_Hundred
/// </summary>
ManichaeanHundred,
/// <summary>
/// Manichaean_Kaph
/// </summary>
ManichaeanKaph,
/// <summary>
/// Manichaean_Lamedh
/// </summary>
ManichaeanLamedh,
/// <summary>
/// Manichaean_Mem
/// </summary>
ManichaeanMem,
/// <summary>
/// Manichaean_Nun
/// </summary>
ManichaeanNun,
/// <summary>
/// Manichaean_One
/// </summary>
ManichaeanOne,
/// <summary>
/// Manichaean_Pe
/// </summary>
ManichaeanPe,
/// <summary>
/// Manichaean_Qoph
/// </summary>
ManichaeanQoph,
/// <summary>
/// Manichaean_Resh
/// </summary>
ManichaeanResh,
/// <summary>
/// Manichaean_Sadhe
/// </summary>
ManichaeanSadhe,
/// <summary>
/// Manichaean_Samekh
/// </summary>
ManichaeanSamekh,
/// <summary>
/// Manichaean_Taw
/// </summary>
ManichaeanTaw,
/// <summary>
/// Manichaean_Ten
/// </summary>
ManichaeanTen,
/// <summary>
/// Manichaean_Teth
/// </summary>
ManichaeanTeth,
/// <summary>
/// Manichaean_Thamedh
/// </summary>
ManichaeanThamedh,
/// <summary>
/// Manichaean_Twenty
/// </summary>
ManichaeanTwenty,
/// <summary>
/// Manichaean_Waw
/// </summary>
ManichaeanWaw,
/// <summary>
/// Manichaean_Yodh
/// </summary>
ManichaeanYodh,
/// <summary>
/// Manichaean_Zayin
/// </summary>
ManichaeanZayin,
/// <summary>
/// Meem
/// </summary>
Meem,
/// <summary>
/// Mim
/// </summary>
Mim,
/// <summary>
/// No_Joining_Group
/// </summary>
NoJoiningGroup,
/// <summary>
/// Noon
/// </summary>
Noon,
/// <summary>
/// Nun
/// </summary>
Nun,
/// <summary>
/// Nya
/// </summary>
Nya,
/// <summary>
/// Pe
/// </summary>
Pe,
/// <summary>
/// Qaf
/// </summary>
Qaf,
/// <summary>
/// Qaph
/// </summary>
Qaph,
/// <summary>
/// Reh
/// </summary>
Reh,
/// <summary>
/// Reversed_Pe
/// </summary>
ReversedPe,
/// <summary>
/// Rohingya_Yeh
/// </summary>
RohingyaYeh,
/// <summary>
/// Sad
/// </summary>
Sad,
/// <summary>
/// Sadhe
/// </summary>
Sadhe,
/// <summary>
/// Seen
/// </summary>
Seen,
/// <summary>
/// Semkath
/// </summary>
Semkath,
/// <summary>
/// Shin
/// </summary>
Shin,
/// <summary>
/// Straight_Waw
/// </summary>
StraightWaw,
/// <summary>
/// Swash_Kaf
/// </summary>
SwashKaf,
/// <summary>
/// Syriac_Waw
/// </summary>
SyriacWaw,
/// <summary>
/// Tah
/// </summary>
Tah,
/// <summary>
/// Taw
/// </summary>
Taw,
/// <summary>
/// Teh_Marbuta
/// </summary>
TehMarbuta,
/// <summary>
/// Hamza_On_Heh_Goal
/// </summary>
TehMarbutaGoal,
/// <summary>
/// Teth
/// </summary>
Teth,
/// <summary>
/// Thin_Yeh
/// </summary>
ThinYeh,
/// <summary>
/// Vertical_Tail
/// </summary>
VerticalTail,
/// <summary>
/// Waw
/// </summary>
Waw,
/// <summary>
/// Yeh
/// </summary>
Yeh,
/// <summary>
/// Yeh_Barree
/// </summary>
YehBarree,
/// <summary>
/// Yeh_With_Tail
/// </summary>
YehWithTail,
/// <summary>
/// Yudh
/// </summary>
Yudh,
/// <summary>
/// Yudh_He
/// </summary>
YudhHe,
/// <summary>
/// Zain
/// </summary>
Zain,
/// <summary>
/// Zhain
/// </summary>
Zhain
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// TraceLogging: used when implementing a custom TraceLoggingTypeInfo.
/// An instance of this type is provided to the TypeInfo.WriteMetadata method.
/// </summary>
internal class TraceLoggingMetadataCollector
{
private readonly Impl impl;
private readonly FieldMetadata currentGroup;
private int bufferedArrayFieldCount = int.MinValue;
/// <summary>
/// Creates a root-level collector.
/// </summary>
internal TraceLoggingMetadataCollector()
{
this.impl = new Impl();
}
/// <summary>
/// Creates a collector for a group.
/// </summary>
/// <param name="other">Parent collector</param>
/// <param name="group">The field that starts the group</param>
private TraceLoggingMetadataCollector(
TraceLoggingMetadataCollector other,
FieldMetadata group)
{
this.impl = other.impl;
this.currentGroup = group;
}
/// <summary>
/// The field tags to be used for the next field.
/// This will be reset to None each time a field is written.
/// </summary>
internal EventFieldTags Tags
{
get;
set;
}
internal int ScratchSize
{
get { return this.impl.scratchSize; }
}
internal int DataCount
{
get { return this.impl.dataCount; }
}
internal int PinCount
{
get { return this.impl.pinCount; }
}
private bool BeginningBufferedArray
{
get { return this.bufferedArrayFieldCount == 0; }
}
/// <summary>
/// Call this method to add a group to the event and to return
/// a new metadata collector that can be used to add fields to the
/// group. After all of the fields in the group have been written,
/// switch back to the original metadata collector to add fields
/// outside of the group.
/// Special-case: if name is null, no group is created, and AddGroup
/// returns the original metadata collector. This is useful when
/// adding the top-level group for an event.
/// Note: do not use the original metadata collector while the group's
/// metadata collector is in use, and do not use the group's metadata
/// collector after switching back to the original.
/// </summary>
/// <param name="name">
/// The name of the group. If name is null, the call to AddGroup is a
/// no-op (collector.AddGroup(null) returns collector).
/// </param>
/// <returns>
/// A new metadata collector that can be used to add fields to the group.
/// </returns>
public TraceLoggingMetadataCollector AddGroup(string name)
{
TraceLoggingMetadataCollector result = this;
if (name != null || // Normal.
this.BeginningBufferedArray) // Error, FieldMetadata's constructor will throw the appropriate exception.
{
var newGroup = new FieldMetadata(
name,
TraceLoggingDataType.Struct,
this.Tags,
this.BeginningBufferedArray);
this.AddField(newGroup);
result = new TraceLoggingMetadataCollector(this, newGroup);
}
return result;
}
/// <summary>
/// Adds a scalar field to an event.
/// </summary>
/// <param name="name">
/// The name to use for the added field. This value must not be null.
/// </param>
/// <param name="type">
/// The type code for the added field. This must be a fixed-size type
/// (e.g. string types are not supported).
/// </param>
public void AddScalar(string name, TraceLoggingDataType type)
{
int size;
switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask))
{
case TraceLoggingDataType.Int8:
case TraceLoggingDataType.UInt8:
case TraceLoggingDataType.Char8:
size = 1;
break;
case TraceLoggingDataType.Int16:
case TraceLoggingDataType.UInt16:
case TraceLoggingDataType.Char16:
size = 2;
break;
case TraceLoggingDataType.Int32:
case TraceLoggingDataType.UInt32:
case TraceLoggingDataType.HexInt32:
case TraceLoggingDataType.Float:
case TraceLoggingDataType.Boolean32:
size = 4;
break;
case TraceLoggingDataType.Int64:
case TraceLoggingDataType.UInt64:
case TraceLoggingDataType.HexInt64:
case TraceLoggingDataType.Double:
case TraceLoggingDataType.FileTime:
size = 8;
break;
case TraceLoggingDataType.Guid:
case TraceLoggingDataType.SystemTime:
size = 16;
break;
default:
throw new ArgumentOutOfRangeException("type");
}
this.impl.AddScalar(size);
this.AddField(new FieldMetadata(name, type, this.Tags, this.BeginningBufferedArray));
}
/// <summary>
/// Adds a binary-format field to an event.
/// Compatible with core types: Binary, CountedUtf16String, CountedMbcsString.
/// Compatible with dataCollector methods: AddBinary(string), AddArray(Any8bitType[]).
/// </summary>
/// <param name="name">
/// The name to use for the added field. This value must not be null.
/// </param>
/// <param name="type">
/// The type code for the added field. This must be a Binary or CountedString type.
/// </param>
public void AddBinary(string name, TraceLoggingDataType type)
{
switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask))
{
case TraceLoggingDataType.Binary:
case TraceLoggingDataType.CountedMbcsString:
case TraceLoggingDataType.CountedUtf16String:
break;
default:
throw new ArgumentOutOfRangeException("type");
}
this.impl.AddScalar(2);
this.impl.AddNonscalar();
this.AddField(new FieldMetadata(name, type, this.Tags, this.BeginningBufferedArray));
}
/// <summary>
/// Adds an array field to an event.
/// </summary>
/// <param name="name">
/// The name to use for the added field. This value must not be null.
/// </param>
/// <param name="type">
/// The type code for the added field. This must be a fixed-size type
/// or a string type. In the case of a string type, this adds an array
/// of characters, not an array of strings.
/// </param>
public void AddArray(string name, TraceLoggingDataType type)
{
switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask))
{
case TraceLoggingDataType.Utf16String:
case TraceLoggingDataType.MbcsString:
case TraceLoggingDataType.Int8:
case TraceLoggingDataType.UInt8:
case TraceLoggingDataType.Int16:
case TraceLoggingDataType.UInt16:
case TraceLoggingDataType.Int32:
case TraceLoggingDataType.UInt32:
case TraceLoggingDataType.Int64:
case TraceLoggingDataType.UInt64:
case TraceLoggingDataType.Float:
case TraceLoggingDataType.Double:
case TraceLoggingDataType.Boolean32:
case TraceLoggingDataType.Guid:
case TraceLoggingDataType.FileTime:
case TraceLoggingDataType.HexInt32:
case TraceLoggingDataType.HexInt64:
case TraceLoggingDataType.Char16:
case TraceLoggingDataType.Char8:
break;
default:
throw new ArgumentOutOfRangeException("type");
}
if (this.BeginningBufferedArray)
{
throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedNestedArraysEnums"));
}
this.impl.AddScalar(2);
this.impl.AddNonscalar();
this.AddField(new FieldMetadata(name, type, this.Tags, true));
}
public void BeginBufferedArray()
{
if (this.bufferedArrayFieldCount >= 0)
{
throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedNestedArraysEnums"));
}
this.bufferedArrayFieldCount = 0;
this.impl.BeginBuffered();
}
public void EndBufferedArray()
{
if (this.bufferedArrayFieldCount != 1)
{
throw new InvalidOperationException(Resources.GetResourceString("EventSource_IncorrentlyAuthoredTypeInfo"));
}
this.bufferedArrayFieldCount = int.MinValue;
this.impl.EndBuffered();
}
/// <summary>
/// Adds a custom-serialized field to an event.
/// </summary>
/// <param name="name">
/// The name to use for the added field. This value must not be null.
/// </param>
/// <param name="type">The encoding type for the field.</param>
/// <param name="metadata">Additional information needed to decode the field, if any.</param>
public void AddCustom(string name, TraceLoggingDataType type, byte[] metadata)
{
if (this.BeginningBufferedArray)
{
throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedCustomSerializedData"));
}
this.impl.AddScalar(2);
this.impl.AddNonscalar();
this.AddField(new FieldMetadata(
name,
type,
this.Tags,
metadata));
}
internal byte[] GetMetadata()
{
var size = this.impl.Encode(null);
var metadata = new byte[size];
this.impl.Encode(metadata);
return metadata;
}
private void AddField(FieldMetadata fieldMetadata)
{
this.Tags = EventFieldTags.None;
this.bufferedArrayFieldCount++;
this.impl.fields.Add(fieldMetadata);
if (this.currentGroup != null)
{
this.currentGroup.IncrementStructFieldCount();
}
}
private class Impl
{
internal readonly List<FieldMetadata> fields = new List<FieldMetadata>();
internal short scratchSize;
internal sbyte dataCount;
internal sbyte pinCount;
private int bufferNesting;
private bool scalar;
public void AddScalar(int size)
{
if (this.bufferNesting == 0)
{
if (!this.scalar)
{
this.dataCount = checked((sbyte)(this.dataCount + 1));
}
this.scalar = true;
this.scratchSize = checked((short)(this.scratchSize + size));
}
}
public void AddNonscalar()
{
if (this.bufferNesting == 0)
{
this.scalar = false;
this.pinCount = checked((sbyte)(this.pinCount + 1));
this.dataCount = checked((sbyte)(this.dataCount + 1));
}
}
public void BeginBuffered()
{
if (this.bufferNesting == 0)
{
this.AddNonscalar();
}
this.bufferNesting++;
}
public void EndBuffered()
{
this.bufferNesting--;
}
public int Encode(byte[] metadata)
{
int size = 0;
foreach (var field in this.fields)
{
field.Encode(ref size, metadata);
}
return size;
}
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Xamarin.Forms;
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Sensus.UI.Inputs;
namespace Sensus.UI
{
public class ScriptInputsPage : ContentPage
{
public ScriptInputsPage(InputGroup inputGroup, List<InputGroup> previousInputGroups)
{
Title = "Inputs";
ListView inputsList = new ListView(ListViewCachingStrategy.RecycleElement);
inputsList.ItemTemplate = new DataTemplate(typeof(TextCell));
inputsList.ItemTemplate.SetBinding(TextCell.TextProperty, nameof(Input.Caption));
inputsList.ItemsSource = inputGroup.Inputs;
inputsList.ItemTapped += async (o, e) =>
{
if (inputsList.SelectedItem == null)
{
return;
}
Input selectedInput = inputsList.SelectedItem as Input;
int selectedIndex = inputGroup.Inputs.IndexOf(selectedInput);
List<string> actions = new List<string>();
if (selectedIndex > 0)
{
actions.Add("Move Up");
}
if (selectedIndex < inputGroup.Inputs.Count - 1)
{
actions.Add("Move Down");
}
actions.Add("Edit");
if (previousInputGroups != null && previousInputGroups.Select(previousInputGroup => previousInputGroup.Inputs.Count).Sum() > 0)
{
actions.Add("Add Display Condition");
}
if (selectedInput.DisplayConditions.Count > 0)
{
actions.AddRange(new string[] { "View Display Conditions" });
}
actions.Add("Delete");
string selectedAction = await DisplayActionSheet(selectedInput.Name, "Cancel", null, actions.ToArray());
if (selectedAction == "Move Up")
{
inputGroup.Inputs.Move(selectedIndex, selectedIndex - 1);
}
else if (selectedAction == "Move Down")
{
inputGroup.Inputs.Move(selectedIndex, selectedIndex + 1);
}
else if (selectedAction == "Edit")
{
ScriptInputPage inputPage = new ScriptInputPage(selectedInput);
await Navigation.PushAsync(inputPage);
inputsList.SelectedItem = null;
}
else if (selectedAction == "Add Display Condition")
{
string abortMessage = "Condition is not complete. Abort?";
SensusServiceHelper.Get().PromptForInputsAsync("Display Condition", new Input[]
{
new ItemPickerPageInput("Input:", previousInputGroups.SelectMany(previousInputGroup => previousInputGroup.Inputs.Cast<object>()).ToList()),
new ItemPickerPageInput("Condition:", Enum.GetValues(typeof(InputValueCondition)).Cast<object>().ToList()),
new ItemPickerPageInput("Conjunctive/Disjunctive:", new object[] { "Conjunctive", "Disjunctive" }.ToList())
},
null,
true,
null,
null,
abortMessage,
null,
false,
inputs =>
{
if (inputs == null)
{
return;
}
if (inputs.All(input => input.Valid))
{
Input conditionInput = ((inputs[0] as ItemPickerPageInput).Value as IEnumerable<object>).First() as Input;
InputValueCondition condition = (InputValueCondition)((inputs[1] as ItemPickerPageInput).Value as IEnumerable<object>).First();
bool conjunctive = ((inputs[2] as ItemPickerPageInput).Value as IEnumerable<object>).First().Equals("Conjunctive");
if (condition == InputValueCondition.IsComplete)
{
selectedInput.DisplayConditions.Add(new InputDisplayCondition(conditionInput, condition, null, conjunctive));
}
else
{
Regex uppercaseSplitter = new Regex(@"
(?<=[A-Z])(?=[A-Z][a-z]) |
(?<=[^A-Z])(?=[A-Z]) |
(?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace);
// show the user a required copy of the condition input and prompt for the condition value
Input conditionInputCopy = conditionInput.Copy(false);
conditionInputCopy.DisplayConditions.Clear();
conditionInputCopy.LabelText = "Value that " + conditionInputCopy.Name + " " + uppercaseSplitter.Replace(condition.ToString(), " ").ToLower() + ":";
conditionInputCopy.Required = true;
// ensure that the copied input cannot define a variable
if (conditionInputCopy is IVariableDefiningInput)
{
(conditionInputCopy as IVariableDefiningInput).DefinedVariable = null;
}
SensusServiceHelper.Get().PromptForInputAsync("Display Condition",
conditionInputCopy,
null,
true,
"OK",
null,
abortMessage,
null,
false,
input =>
{
if (input?.Valid ?? false)
{
selectedInput.DisplayConditions.Add(new InputDisplayCondition(conditionInput, condition, input.Value, conjunctive));
}
});
}
}
});
}
else if (selectedAction == "View Display Conditions")
{
await Navigation.PushAsync(new ViewTextLinesPage("Display Conditions", selectedInput.DisplayConditions.Select(displayCondition => displayCondition.ToString()).ToList(), null, () =>
{
selectedInput.DisplayConditions.Clear();
}));
}
else if (selectedAction == "Delete")
{
if (await DisplayAlert("Delete " + selectedInput.Name + "?", "This action cannot be undone.", "Delete", "Cancel"))
{
inputGroup.Inputs.Remove(selectedInput);
inputsList.SelectedItem = null; // manually reset, since it isn't done automatically.
}
}
};
ToolbarItems.Add(new ToolbarItem(null, "plus.png", async () =>
{
List<Input> inputs = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Input)))
.Select(t => Activator.CreateInstance(t))
.Cast<Input>()
.OrderBy(i => i.Name)
.ToList();
string cancelButtonName = "Cancel";
string selected = await DisplayActionSheet("Select Input Type", cancelButtonName, null, inputs.Select((input, index) => (index + 1) + ") " + input.Name).ToArray());
if (!string.IsNullOrWhiteSpace(selected) && selected != cancelButtonName)
{
Input input = inputs[int.Parse(selected.Substring(0, selected.IndexOf(")"))) - 1];
if (input is VoiceInput && inputGroup.Inputs.Count > 0 || !(input is VoiceInput) && inputGroup.Inputs.Any(i => i is VoiceInput))
{
await SensusServiceHelper.Get().FlashNotificationAsync("Voice inputs must reside in groups by themselves.");
}
else
{
inputGroup.Inputs.Add(input);
await Navigation.PushAsync(new ScriptInputPage(input));
}
}
}));
Content = inputsList;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------
//------------------------------------------------------------
using System.IO;
using System.Collections;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Collections.Generic;
namespace System.Xml
{
internal abstract class XmlBaseWriter : XmlDictionaryWriter
{
private XmlNodeWriter _writer;
private NamespaceManager _nsMgr;
private Element[] _elements;
private int _depth;
private string _attributeLocalName;
private string _attributeValue;
private bool _isXmlAttribute;
private bool _isXmlnsAttribute;
private WriteState _writeState;
private DocumentState _documentState;
private byte[] _trailBytes;
private int _trailByteCount;
private XmlStreamNodeWriter _nodeWriter;
private bool _inList;
private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/";
private const string xmlNamespace = "http://www.w3.org/XML/1998/namespace";
private static string[] s_prefixes = { "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" };
protected XmlBaseWriter()
{
_nsMgr = new NamespaceManager();
_writeState = WriteState.Start;
_documentState = DocumentState.None;
}
protected void SetOutput(XmlStreamNodeWriter writer)
{
_inList = false;
_writer = writer;
_nodeWriter = writer;
_writeState = WriteState.Start;
_documentState = DocumentState.None;
_nsMgr.Clear();
if (_depth != 0)
{
_elements = null;
_depth = 0;
}
_attributeLocalName = null;
_attributeValue = null;
}
public override void Flush()
{
if (IsClosed)
ThrowClosed();
_writer.Flush();
}
public override void Close()
{
if (IsClosed)
return;
try
{
FinishDocument();
AutoComplete(WriteState.Closed);
_writer.Flush();
}
finally
{
_nsMgr.Close();
if (_depth != 0)
{
_elements = null;
_depth = 0;
}
_attributeValue = null;
_attributeLocalName = null;
_nodeWriter.Close();
}
}
protected bool IsClosed
{
get { return _writeState == WriteState.Closed; }
}
protected void ThrowClosed()
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlWriterClosed)));
}
public override string XmlLang
{
get
{
return _nsMgr.XmlLang;
}
}
public override XmlSpace XmlSpace
{
get
{
return _nsMgr.XmlSpace;
}
}
public override WriteState WriteState
{
get
{
return _writeState;
}
}
public override void WriteXmlnsAttribute(string prefix, string ns)
{
if (IsClosed)
ThrowClosed();
if (ns == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns");
if (_writeState != WriteState.Element)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteXmlnsAttribute", WriteState.ToString())));
if (prefix == null)
{
prefix = _nsMgr.LookupPrefix(ns);
if (prefix == null)
{
GeneratePrefix(ns, null);
}
}
else
{
_nsMgr.AddNamespaceIfNotDeclared(prefix, ns, null);
}
}
public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
{
if (IsClosed)
ThrowClosed();
if (ns == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns");
if (_writeState != WriteState.Element)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteXmlnsAttribute", WriteState.ToString())));
if (prefix == null)
{
prefix = _nsMgr.LookupPrefix(ns.Value);
if (prefix == null)
{
GeneratePrefix(ns.Value, ns);
}
}
else
{
_nsMgr.AddNamespaceIfNotDeclared(prefix, ns.Value, ns);
}
}
private void StartAttribute(ref string prefix, string localName, string ns, XmlDictionaryString xNs)
{
if (IsClosed)
ThrowClosed();
if (_writeState == WriteState.Attribute)
WriteEndAttribute();
if (localName == null || (localName.Length == 0 && prefix != "xmlns"))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName"));
if (_writeState != WriteState.Element)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteStartAttribute", WriteState.ToString())));
if (prefix == null)
{
if (ns == xmlnsNamespace && localName != "xmlns")
prefix = "xmlns";
else if (ns == xmlNamespace)
prefix = "xml";
else
prefix = string.Empty;
}
// Normalize a (prefix,localName) of (null, "xmlns") to ("xmlns", string.Empty).
if (prefix.Length == 0 && localName == "xmlns")
{
prefix = "xmlns";
localName = string.Empty;
}
_isXmlnsAttribute = false;
_isXmlAttribute = false;
if (prefix == "xml")
{
if (ns != null && ns != xmlNamespace)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlPrefixBoundToNamespace, "xml", xmlNamespace, ns), "ns"));
_isXmlAttribute = true;
_attributeValue = string.Empty;
_attributeLocalName = localName;
}
else if (prefix == "xmlns")
{
if (ns != null && ns != xmlnsNamespace)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlPrefixBoundToNamespace, "xmlns", xmlnsNamespace, ns), "ns"));
_isXmlnsAttribute = true;
_attributeValue = string.Empty;
_attributeLocalName = localName;
}
else if (ns == null)
{
// A null namespace means the namespace of the given prefix.
if (prefix.Length == 0)
{
// An empty prefix on an attribute means no namespace (not the default namespace)
ns = string.Empty;
}
else
{
ns = _nsMgr.LookupNamespace(prefix);
if (ns == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlUndefinedPrefix, prefix), "prefix"));
}
}
else if (ns.Length == 0)
{
// An empty namespace means no namespace; prefix must be empty
if (prefix.Length != 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlEmptyNamespaceRequiresNullPrefix), "prefix"));
}
else if (prefix.Length == 0)
{
// No prefix specified - try to find a prefix corresponding to the given namespace
prefix = _nsMgr.LookupAttributePrefix(ns);
// If we didn't find anything with the right namespace, generate one.
if (prefix == null)
{
// Watch for special values
if (ns.Length == xmlnsNamespace.Length && ns == xmlnsNamespace)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlSpecificBindingNamespace, "xmlns", ns)));
if (ns.Length == xmlNamespace.Length && ns == xmlNamespace)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlSpecificBindingNamespace, "xml", ns)));
prefix = GeneratePrefix(ns, xNs);
}
}
else
{
_nsMgr.AddNamespaceIfNotDeclared(prefix, ns, xNs);
}
_writeState = WriteState.Attribute;
}
public override void WriteStartAttribute(string prefix, string localName, string namespaceUri)
{
StartAttribute(ref prefix, localName, namespaceUri, null);
if (!_isXmlnsAttribute)
{
_writer.WriteStartAttribute(prefix, localName);
}
}
public override void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
StartAttribute(ref prefix, (localName != null ? localName.Value : null), (namespaceUri != null ? namespaceUri.Value : null), namespaceUri);
if (!_isXmlnsAttribute)
{
_writer.WriteStartAttribute(prefix, localName);
}
}
public override void WriteEndAttribute()
{
if (IsClosed)
ThrowClosed();
if (_writeState != WriteState.Attribute)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteEndAttribute", WriteState.ToString())));
FlushBase64();
try
{
if (_isXmlAttribute)
{
if (_attributeLocalName == "lang")
{
_nsMgr.AddLangAttribute(_attributeValue);
}
else if (_attributeLocalName == "space")
{
if (_attributeValue == "preserve")
{
_nsMgr.AddSpaceAttribute(XmlSpace.Preserve);
}
else if (_attributeValue == "default")
{
_nsMgr.AddSpaceAttribute(XmlSpace.Default);
}
else
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlInvalidXmlSpace, _attributeValue)));
}
}
else
{
// XmlTextWriter specifically allows for other localNames
}
_isXmlAttribute = false;
_attributeLocalName = null;
_attributeValue = null;
}
if (_isXmlnsAttribute)
{
_nsMgr.AddNamespaceIfNotDeclared(_attributeLocalName, _attributeValue, null);
_isXmlnsAttribute = false;
_attributeLocalName = null;
_attributeValue = null;
}
else
{
_writer.WriteEndAttribute();
}
}
finally
{
_writeState = WriteState.Element;
}
}
public override void WriteComment(string text)
{
if (IsClosed)
ThrowClosed();
if (_writeState == WriteState.Attribute)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteComment", WriteState.ToString())));
if (text == null)
{
text = string.Empty;
}
else if (text.IndexOf("--", StringComparison.Ordinal) != -1 || (text.Length > 0 && text[text.Length - 1] == '-'))
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlInvalidCommentChars), "text"));
}
StartComment();
FlushBase64();
_writer.WriteComment(text);
EndComment();
}
public override void WriteFullEndElement()
{
if (IsClosed)
ThrowClosed();
if (_writeState == WriteState.Attribute)
WriteEndAttribute();
if (_writeState != WriteState.Element && _writeState != WriteState.Content)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteFullEndElement", WriteState.ToString())));
AutoComplete(WriteState.Content);
WriteEndElement();
}
public override void WriteCData(string text)
{
if (IsClosed)
ThrowClosed();
if (_writeState == WriteState.Attribute)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteCData", WriteState.ToString())));
if (text == null)
text = string.Empty;
if (text.Length > 0)
{
StartContent();
FlushBase64();
_writer.WriteCData(text);
EndContent();
}
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.XmlMethodNotSupported, "WriteDocType")));
}
private void StartElement(ref string prefix, string localName, string ns, XmlDictionaryString xNs)
{
if (IsClosed)
ThrowClosed();
if (_documentState == DocumentState.Epilog)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlOnlyOneRoot)));
if (localName == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName"));
if (localName.Length == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.InvalidLocalNameEmpty), "localName"));
if (_writeState == WriteState.Attribute)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteStartElement", WriteState.ToString())));
FlushBase64();
AutoComplete(WriteState.Element);
Element element = EnterScope();
if (ns == null)
{
if (prefix == null)
prefix = string.Empty;
ns = _nsMgr.LookupNamespace(prefix);
if (ns == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlUndefinedPrefix, prefix), "prefix"));
}
else if (prefix == null)
{
prefix = _nsMgr.LookupPrefix(ns);
if (prefix == null)
{
prefix = string.Empty;
_nsMgr.AddNamespace(string.Empty, ns, xNs);
}
}
else
{
_nsMgr.AddNamespaceIfNotDeclared(prefix, ns, xNs);
}
element.Prefix = prefix;
element.LocalName = localName;
}
public override void WriteStartElement(string prefix, string localName, string namespaceUri)
{
StartElement(ref prefix, localName, namespaceUri, null);
_writer.WriteStartElement(prefix, localName);
}
public override void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
StartElement(ref prefix, (localName != null ? localName.Value : null), (namespaceUri != null ? namespaceUri.Value : null), namespaceUri);
_writer.WriteStartElement(prefix, localName);
}
public override void WriteEndElement()
{
if (IsClosed)
ThrowClosed();
if (_depth == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidDepth, "WriteEndElement", _depth.ToString(CultureInfo.InvariantCulture))));
if (_writeState == WriteState.Attribute)
WriteEndAttribute();
FlushBase64();
if (_writeState == WriteState.Element)
{
_nsMgr.DeclareNamespaces(_writer);
_writer.WriteEndStartElement(true);
}
else
{
Element element = _elements[_depth];
_writer.WriteEndElement(element.Prefix, element.LocalName);
}
ExitScope();
_writeState = WriteState.Content;
}
private Element EnterScope()
{
_nsMgr.EnterScope();
_depth++;
if (_elements == null)
{
_elements = new Element[4];
}
else if (_elements.Length == _depth)
{
Element[] newElementNodes = new Element[_depth * 2];
Array.Copy(_elements, newElementNodes, _depth);
_elements = newElementNodes;
}
Element element = _elements[_depth];
if (element == null)
{
element = new Element();
_elements[_depth] = element;
}
return element;
}
private void ExitScope()
{
_elements[_depth].Clear();
_depth--;
if (_depth == 0 && _documentState == DocumentState.Document)
_documentState = DocumentState.Epilog;
_nsMgr.ExitScope();
}
protected void FlushElement()
{
if (_writeState == WriteState.Element)
{
AutoComplete(WriteState.Content);
}
}
protected void StartComment()
{
FlushElement();
}
protected void EndComment()
{
}
protected void StartContent()
{
FlushElement();
if (_depth == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlIllegalOutsideRoot)));
}
protected void StartContent(char ch)
{
FlushElement();
if (_depth == 0)
VerifyWhitespace(ch);
}
protected void StartContent(string s)
{
FlushElement();
if (_depth == 0)
VerifyWhitespace(s);
}
protected void StartContent(char[] chars, int offset, int count)
{
FlushElement();
if (_depth == 0)
VerifyWhitespace(chars, offset, count);
}
private void VerifyWhitespace(char ch)
{
if (!IsWhitespace(ch))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlIllegalOutsideRoot)));
}
private void VerifyWhitespace(string s)
{
for (int i = 0; i < s.Length; i++)
if (!IsWhitespace(s[i]))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlIllegalOutsideRoot)));
}
private void VerifyWhitespace(char[] chars, int offset, int count)
{
for (int i = 0; i < count; i++)
if (!IsWhitespace(chars[offset + i]))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlIllegalOutsideRoot)));
}
private bool IsWhitespace(char ch)
{
return (ch == ' ' || ch == '\n' || ch == '\r' || ch == 't');
}
protected void EndContent()
{
}
private void AutoComplete(WriteState writeState)
{
if (_writeState == WriteState.Element)
{
EndStartElement();
}
_writeState = writeState;
}
private void EndStartElement()
{
_nsMgr.DeclareNamespaces(_writer);
_writer.WriteEndStartElement(false);
}
public override string LookupPrefix(string ns)
{
if (ns == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns"));
if (IsClosed)
ThrowClosed();
return _nsMgr.LookupPrefix(ns);
}
internal string LookupNamespace(string prefix)
{
if (prefix == null)
return null;
return _nsMgr.LookupNamespace(prefix);
}
private string GetQualifiedNamePrefix(string namespaceUri, XmlDictionaryString xNs)
{
string prefix = _nsMgr.LookupPrefix(namespaceUri);
if (prefix == null)
{
if (_writeState != WriteState.Attribute)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlNamespaceNotFound, namespaceUri), "namespaceUri"));
prefix = GeneratePrefix(namespaceUri, xNs);
}
return prefix;
}
public override void WriteQualifiedName(string localName, string namespaceUri)
{
if (IsClosed)
ThrowClosed();
if (localName == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName"));
if (localName.Length == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.InvalidLocalNameEmpty), "localName"));
if (namespaceUri == null)
namespaceUri = string.Empty;
string prefix = GetQualifiedNamePrefix(namespaceUri, null);
if (prefix.Length != 0)
{
WriteString(prefix);
WriteString(":");
}
WriteString(localName);
}
public override void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (IsClosed)
ThrowClosed();
if (localName == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName"));
if (localName.Value.Length == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.InvalidLocalNameEmpty), "localName"));
if (namespaceUri == null)
namespaceUri = XmlDictionaryString.Empty;
string prefix = GetQualifiedNamePrefix(namespaceUri.Value, namespaceUri);
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(string.Concat(prefix, ":", namespaceUri.Value));
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteQualifiedName(prefix, localName);
EndContent();
}
}
public override void WriteStartDocument()
{
if (IsClosed)
ThrowClosed();
if (_writeState != WriteState.Start)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteStartDocument", WriteState.ToString())));
_writeState = WriteState.Prolog;
_documentState = DocumentState.Document;
_writer.WriteDeclaration();
}
public override void WriteStartDocument(bool standalone)
{
if (IsClosed)
ThrowClosed();
WriteStartDocument();
}
public override void WriteProcessingInstruction(string name, string text)
{
if (IsClosed)
ThrowClosed();
if (name != "xml")
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlProcessingInstructionNotSupported), "name"));
if (_writeState != WriteState.Start)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidDeclaration)));
// The only thing the text can legitimately contain is version, encoding, and standalone.
// We only support version 1.0, we can only write whatever encoding we were supplied,
// and we don't support DTDs, so whatever values are supplied in the text argument are irrelevant.
_writer.WriteDeclaration();
}
private void FinishDocument()
{
if (_writeState == WriteState.Attribute)
{
WriteEndAttribute();
}
while (_depth > 0)
{
WriteEndElement();
}
}
public override void WriteEndDocument()
{
if (IsClosed)
ThrowClosed();
if (_writeState == WriteState.Start || _writeState == WriteState.Prolog)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlNoRootElement)));
FinishDocument();
_writeState = WriteState.Start;
_documentState = DocumentState.End;
}
protected int NamespaceBoundary
{
get
{
return _nsMgr.NamespaceBoundary;
}
set
{
_nsMgr.NamespaceBoundary = value;
}
}
public override void WriteEntityRef(string name)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.XmlMethodNotSupported, "WriteEntityRef")));
}
public override void WriteName(string name)
{
if (IsClosed)
ThrowClosed();
WriteString(name);
}
public override void WriteNmToken(string name)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.XmlMethodNotSupported, "WriteNmToken")));
}
public override void WriteWhitespace(string whitespace)
{
if (IsClosed)
ThrowClosed();
if (whitespace == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("whitespace");
for (int i = 0; i < whitespace.Length; ++i)
{
char c = whitespace[i];
if (c != ' ' &&
c != '\t' &&
c != '\n' &&
c != '\r')
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlOnlyWhitespace), "whitespace"));
}
WriteString(whitespace);
}
public override void WriteString(string value)
{
if (IsClosed)
ThrowClosed();
if (value == null)
value = string.Empty;
if (value.Length > 0 || _inList)
{
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(value);
if (!_isXmlnsAttribute)
{
StartContent(value);
_writer.WriteEscapedText(value);
EndContent();
}
}
}
public override void WriteString(XmlDictionaryString value)
{
if (IsClosed)
ThrowClosed();
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
if (value.Value.Length > 0)
{
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(value.Value);
if (!_isXmlnsAttribute)
{
StartContent(value.Value);
_writer.WriteEscapedText(value);
EndContent();
}
}
}
public override void WriteChars(char[] chars, int offset, int count)
{
if (IsClosed)
ThrowClosed();
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars"));
// Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.Format(SR.ValueMustBeNonNegative)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.ValueMustBeNonNegative)));
if (count > chars.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
if (count > 0)
{
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(new string(chars, offset, count));
if (!_isXmlnsAttribute)
{
StartContent(chars, offset, count);
_writer.WriteEscapedText(chars, offset, count);
EndContent();
}
}
}
public override void WriteRaw(string value)
{
if (IsClosed)
ThrowClosed();
if (value == null)
value = string.Empty;
if (value.Length > 0)
{
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(value);
if (!_isXmlnsAttribute)
{
StartContent(value);
_writer.WriteText(value);
EndContent();
}
}
}
public override void WriteRaw(char[] chars, int offset, int count)
{
if (IsClosed)
ThrowClosed();
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars"));
// Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.Format(SR.ValueMustBeNonNegative)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.ValueMustBeNonNegative)));
if (count > chars.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
if (count > 0)
{
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(new string(chars, offset, count));
if (!_isXmlnsAttribute)
{
StartContent(chars, offset, count);
_writer.WriteText(chars, offset, count);
EndContent();
}
}
}
public override void WriteCharEntity(char ch)
{
if (IsClosed)
ThrowClosed();
if (ch >= 0xd800 && ch <= 0xdfff)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlMissingLowSurrogate), "ch"));
if (_attributeValue != null)
WriteAttributeText(ch.ToString());
if (!_isXmlnsAttribute)
{
StartContent(ch);
FlushBase64();
_writer.WriteCharEntity(ch);
EndContent();
}
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
if (IsClosed)
ThrowClosed();
SurrogateChar ch = new SurrogateChar(lowChar, highChar);
if (_attributeValue != null)
{
char[] chars = new char[2] { highChar, lowChar };
WriteAttributeText(new string(chars));
}
if (!_isXmlnsAttribute)
{
StartContent();
FlushBase64();
_writer.WriteCharEntity(ch.Char);
EndContent();
}
}
public override void WriteValue(object value)
{
if (IsClosed)
ThrowClosed();
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
else if (value is object[])
{
WriteValue((object[])value);
}
else if (value is Array)
{
WriteValue((Array)value);
}
else
{
WritePrimitiveValue(value);
}
}
protected void WritePrimitiveValue(object value)
{
if (IsClosed)
ThrowClosed();
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
if (value is ulong)
{
WriteValue((ulong)value);
}
else if (value is string)
{
WriteValue((string)value);
}
else if (value is int)
{
WriteValue((int)value);
}
else if (value is long)
{
WriteValue((long)value);
}
else if (value is bool)
{
WriteValue((bool)value);
}
else if (value is double)
{
WriteValue((double)value);
}
else if (value is DateTime)
{
WriteValue((DateTime)value);
}
else if (value is float)
{
WriteValue((float)value);
}
else if (value is decimal)
{
WriteValue((decimal)value);
}
else if (value is XmlDictionaryString)
{
WriteValue((XmlDictionaryString)value);
}
else if (value is UniqueId)
{
WriteValue((UniqueId)value);
}
else if (value is Guid)
{
WriteValue((Guid)value);
}
else if (value is TimeSpan)
{
WriteValue((TimeSpan)value);
}
else if (value.GetType().IsArray)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlNestedArraysNotSupported), "value"));
}
else
{
base.WriteValue(value);
}
}
public override void WriteValue(string value)
{
if (IsClosed)
ThrowClosed();
WriteString(value);
}
public override void WriteValue(int value)
{
if (IsClosed)
ThrowClosed();
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(XmlConverter.ToString(value));
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteInt32Text(value);
EndContent();
}
}
public override void WriteValue(long value)
{
if (IsClosed)
ThrowClosed();
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(XmlConverter.ToString(value));
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteInt64Text(value);
EndContent();
}
}
private void WriteValue(ulong value)
{
if (IsClosed)
ThrowClosed();
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(XmlConverter.ToString(value));
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteUInt64Text(value);
EndContent();
}
}
public override void WriteValue(bool value)
{
if (IsClosed)
ThrowClosed();
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(XmlConverter.ToString(value));
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteBoolText(value);
EndContent();
}
}
public override void WriteValue(decimal value)
{
if (IsClosed)
ThrowClosed();
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(XmlConverter.ToString(value));
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteDecimalText(value);
EndContent();
}
}
public override void WriteValue(float value)
{
if (IsClosed)
ThrowClosed();
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(XmlConverter.ToString(value));
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteFloatText(value);
EndContent();
}
}
public override void WriteValue(double value)
{
if (IsClosed)
ThrowClosed();
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(XmlConverter.ToString(value));
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteDoubleText(value);
EndContent();
}
}
public override void WriteValue(XmlDictionaryString value)
{
WriteString(value);
}
public void WriteValue(DateTime value)
{
if (IsClosed)
ThrowClosed();
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(XmlConverter.ToString(value));
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteDateTimeText(value);
EndContent();
}
}
public override void WriteValue(UniqueId value)
{
if (IsClosed)
ThrowClosed();
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(XmlConverter.ToString(value));
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteUniqueIdText(value);
EndContent();
}
}
public override void WriteValue(Guid value)
{
if (IsClosed)
ThrowClosed();
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(XmlConverter.ToString(value));
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteGuidText(value);
EndContent();
}
}
public override void WriteValue(TimeSpan value)
{
if (IsClosed)
ThrowClosed();
FlushBase64();
if (_attributeValue != null)
WriteAttributeText(XmlConverter.ToString(value));
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteTimeSpanText(value);
EndContent();
}
}
public override void WriteBase64(byte[] buffer, int offset, int count)
{
if (IsClosed)
ThrowClosed();
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer"));
// Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.Format(SR.ValueMustBeNonNegative)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.ValueMustBeNonNegative)));
if (count > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
if (count > 0)
{
if (_trailByteCount > 0)
{
while (_trailByteCount < 3 && count > 0)
{
_trailBytes[_trailByteCount++] = buffer[offset++];
count--;
}
}
int totalByteCount = _trailByteCount + count;
int actualByteCount = totalByteCount - (totalByteCount % 3);
if (_trailBytes == null)
{
_trailBytes = new byte[3];
}
if (actualByteCount >= 3)
{
if (_attributeValue != null)
{
WriteAttributeText(XmlConverter.Base64Encoding.GetString(_trailBytes, 0, _trailByteCount));
WriteAttributeText(XmlConverter.Base64Encoding.GetString(buffer, offset, actualByteCount - _trailByteCount));
}
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteBase64Text(_trailBytes, _trailByteCount, buffer, offset, actualByteCount - _trailByteCount);
EndContent();
}
_trailByteCount = (totalByteCount - actualByteCount);
if (_trailByteCount > 0)
{
int trailOffset = offset + count - _trailByteCount;
for (int i = 0; i < _trailByteCount; i++)
_trailBytes[i] = buffer[trailOffset++];
}
}
else
{
Buffer.BlockCopy(buffer, offset, _trailBytes, _trailByteCount, count);
_trailByteCount += count;
}
}
}
public override bool CanCanonicalize
{
get
{
return false;
}
}
public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public override void EndCanonicalization()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
private void FlushBase64()
{
if (_trailByteCount > 0)
{
FlushTrailBytes();
}
}
private void FlushTrailBytes()
{
if (_attributeValue != null)
WriteAttributeText(XmlConverter.Base64Encoding.GetString(_trailBytes, 0, _trailByteCount));
if (!_isXmlnsAttribute)
{
StartContent();
_writer.WriteBase64Text(_trailBytes, _trailByteCount, _trailBytes, 0, 0);
EndContent();
}
_trailByteCount = 0;
}
private void WriteValue(object[] array)
{
FlushBase64();
StartContent();
_writer.WriteStartListText();
_inList = true;
for (int i = 0; i < array.Length; i++)
{
if (i != 0)
{
_writer.WriteListSeparator();
}
WritePrimitiveValue(array[i]);
}
_inList = false;
_writer.WriteEndListText();
EndContent();
}
private void WriteValue(Array array)
{
FlushBase64();
StartContent();
_writer.WriteStartListText();
_inList = true;
for (int i = 0; i < array.Length; i++)
{
if (i != 0)
{
_writer.WriteListSeparator();
}
WritePrimitiveValue(array.GetValue(i));
}
_inList = false;
_writer.WriteEndListText();
EndContent();
}
protected void StartArray(int count)
{
FlushBase64();
if (_documentState == DocumentState.Epilog)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlOnlyOneRoot)));
if (_documentState == DocumentState.Document && count > 1 && _depth == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlOnlyOneRoot)));
if (_writeState == WriteState.Attribute)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteStartElement", WriteState.ToString())));
AutoComplete(WriteState.Content);
}
protected void EndArray()
{
}
private string GeneratePrefix(string ns, XmlDictionaryString xNs)
{
if (_writeState != WriteState.Element && _writeState != WriteState.Attribute)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidPrefixState, WriteState.ToString())));
string prefix = _nsMgr.AddNamespace(ns, xNs);
if (prefix != null)
return prefix;
while (true)
{
int prefixId = _elements[_depth].PrefixId++;
prefix = string.Concat("d", _depth.ToString(CultureInfo.InvariantCulture), "p", prefixId.ToString(CultureInfo.InvariantCulture));
if (_nsMgr.LookupNamespace(prefix) == null)
{
_nsMgr.AddNamespace(prefix, ns, xNs);
return prefix;
}
}
}
private void WriteAttributeText(string value)
{
if (_attributeValue.Length == 0)
_attributeValue = value;
else
_attributeValue += value;
}
private class Element
{
private string _prefix;
private string _localName;
private int _prefixId;
public string Prefix
{
get
{
return _prefix;
}
set
{
_prefix = value;
}
}
public string LocalName
{
get
{
return _localName;
}
set
{
_localName = value;
}
}
public int PrefixId
{
get
{
return _prefixId;
}
set
{
_prefixId = value;
}
}
public void Clear()
{
_prefix = null;
_localName = null;
_prefixId = 0;
}
}
private enum DocumentState : byte
{
None, // Not inside StartDocument/EndDocument - Allows multiple root elemnts
Document, // Inside StartDocument/EndDocument
Epilog, // EndDocument must be called
End // Nothing further to write
}
private class NamespaceManager
{
private Namespace[] _namespaces;
private Namespace _lastNameSpace;
private int _nsCount;
private int _depth;
private XmlAttribute[] _attributes;
private int _attributeCount;
private XmlSpace _space;
private string _lang;
private int _namespaceBoundary;
private int _nsTop;
private Namespace _defaultNamespace;
public NamespaceManager()
{
_defaultNamespace = new Namespace();
_defaultNamespace.Depth = 0;
_defaultNamespace.Prefix = string.Empty;
_defaultNamespace.Uri = string.Empty;
_defaultNamespace.UriDictionaryString = null;
}
public string XmlLang
{
get
{
return _lang;
}
}
public XmlSpace XmlSpace
{
get
{
return _space;
}
}
public void Clear()
{
if (_namespaces == null)
{
_namespaces = new Namespace[4];
_namespaces[0] = _defaultNamespace;
}
_nsCount = 1;
_nsTop = 0;
_depth = 0;
_attributeCount = 0;
_space = XmlSpace.None;
_lang = null;
_lastNameSpace = null;
_namespaceBoundary = 0;
}
public int NamespaceBoundary
{
get
{
return _namespaceBoundary;
}
set
{
int i;
for (i = 0; i < _nsCount; i++)
if (_namespaces[i].Depth >= value)
break;
_nsTop = i;
_namespaceBoundary = value;
_lastNameSpace = null;
}
}
public void Close()
{
if (_depth == 0)
{
if (_namespaces != null && _namespaces.Length > 32)
_namespaces = null;
if (_attributes != null && _attributes.Length > 4)
_attributes = null;
}
else
{
_namespaces = null;
_attributes = null;
}
_lang = null;
}
public void DeclareNamespaces(XmlNodeWriter writer)
{
int i = _nsCount;
while (i > 0)
{
Namespace nameSpace = _namespaces[i - 1];
if (nameSpace.Depth != _depth)
break;
i--;
}
while (i < _nsCount)
{
Namespace nameSpace = _namespaces[i];
if (nameSpace.UriDictionaryString != null)
writer.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.UriDictionaryString);
else
writer.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.Uri);
i++;
}
}
public void EnterScope()
{
_depth++;
}
public void ExitScope()
{
while (_nsCount > 0)
{
Namespace nameSpace = _namespaces[_nsCount - 1];
if (nameSpace.Depth != _depth)
break;
if (_lastNameSpace == nameSpace)
_lastNameSpace = null;
nameSpace.Clear();
_nsCount--;
}
while (_attributeCount > 0)
{
XmlAttribute attribute = _attributes[_attributeCount - 1];
if (attribute.Depth != _depth)
break;
_space = attribute.XmlSpace;
_lang = attribute.XmlLang;
attribute.Clear();
_attributeCount--;
}
_depth--;
}
public void AddLangAttribute(string lang)
{
AddAttribute();
_lang = lang;
}
public void AddSpaceAttribute(XmlSpace space)
{
AddAttribute();
_space = space;
}
private void AddAttribute()
{
if (_attributes == null)
{
_attributes = new XmlAttribute[1];
}
else if (_attributes.Length == _attributeCount)
{
XmlAttribute[] newAttributes = new XmlAttribute[_attributeCount * 2];
Array.Copy(_attributes, newAttributes, _attributeCount);
_attributes = newAttributes;
}
XmlAttribute attribute = _attributes[_attributeCount];
if (attribute == null)
{
attribute = new XmlAttribute();
_attributes[_attributeCount] = attribute;
}
attribute.XmlLang = _lang;
attribute.XmlSpace = _space;
attribute.Depth = _depth;
_attributeCount++;
}
public string AddNamespace(string uri, XmlDictionaryString uriDictionaryString)
{
if (uri.Length == 0)
{
// Empty namespace can only be bound to the empty prefix
AddNamespaceIfNotDeclared(string.Empty, uri, uriDictionaryString);
return string.Empty;
}
else
{
for (int i = 0; i < s_prefixes.Length; i++)
{
string prefix = s_prefixes[i];
bool declared = false;
for (int j = _nsCount - 1; j >= _nsTop; j--)
{
Namespace nameSpace = _namespaces[j];
if (nameSpace.Prefix == prefix)
{
declared = true;
break;
}
}
if (!declared)
{
AddNamespace(prefix, uri, uriDictionaryString);
return prefix;
}
}
}
return null;
}
public void AddNamespaceIfNotDeclared(string prefix, string uri, XmlDictionaryString uriDictionaryString)
{
if (LookupNamespace(prefix) != uri)
{
AddNamespace(prefix, uri, uriDictionaryString);
}
}
public void AddNamespace(string prefix, string uri, XmlDictionaryString uriDictionaryString)
{
if (prefix.Length >= 3)
{
// Upper and lower case letter differ by a bit.
if ((prefix[0] & ~32) == 'X' && (prefix[1] & ~32) == 'M' && (prefix[2] & ~32) == 'L')
{
if (prefix == "xml" && uri == xmlNamespace)
return;
if (prefix == "xmlns" && uri == xmlnsNamespace)
return;
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlReservedPrefix), "prefix"));
}
}
Namespace nameSpace;
for (int i = _nsCount - 1; i >= 0; i--)
{
nameSpace = _namespaces[i];
if (nameSpace.Depth != _depth)
break;
if (nameSpace.Prefix == prefix)
{
if (nameSpace.Uri == uri)
return;
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlPrefixBoundToNamespace, prefix, nameSpace.Uri, uri), "prefix"));
}
}
if (prefix.Length != 0 && uri.Length == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlEmptyNamespaceRequiresNullPrefix), "prefix"));
if (uri.Length == xmlnsNamespace.Length && uri == xmlnsNamespace)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlSpecificBindingNamespace, "xmlns", uri)));
// The addressing namespace and the xmlNamespace are the same length, so add a quick check to try to disambiguate
if (uri.Length == xmlNamespace.Length && uri[18] == 'X' && uri == xmlNamespace)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlSpecificBindingNamespace, "xml", uri)));
if (_namespaces.Length == _nsCount)
{
Namespace[] newNamespaces = new Namespace[_nsCount * 2];
Array.Copy(_namespaces, newNamespaces, _nsCount);
_namespaces = newNamespaces;
}
nameSpace = _namespaces[_nsCount];
if (nameSpace == null)
{
nameSpace = new Namespace();
_namespaces[_nsCount] = nameSpace;
}
nameSpace.Depth = _depth;
nameSpace.Prefix = prefix;
nameSpace.Uri = uri;
nameSpace.UriDictionaryString = uriDictionaryString;
_nsCount++;
_lastNameSpace = null;
}
public string LookupPrefix(string ns)
{
if (_lastNameSpace != null && _lastNameSpace.Uri == ns)
return _lastNameSpace.Prefix;
int nsCount = _nsCount;
for (int i = nsCount - 1; i >= _nsTop; i--)
{
Namespace nameSpace = _namespaces[i];
if (object.ReferenceEquals(nameSpace.Uri, ns))
{
string prefix = nameSpace.Prefix;
// Make sure that the prefix refers to the namespace in scope
bool declared = false;
for (int j = i + 1; j < nsCount; j++)
{
if (_namespaces[j].Prefix == prefix)
{
declared = true;
break;
}
}
if (!declared)
{
_lastNameSpace = nameSpace;
return prefix;
}
}
}
for (int i = nsCount - 1; i >= _nsTop; i--)
{
Namespace nameSpace = _namespaces[i];
if (nameSpace.Uri == ns)
{
string prefix = nameSpace.Prefix;
// Make sure that the prefix refers to the namespace in scope
bool declared = false;
for (int j = i + 1; j < nsCount; j++)
{
if (_namespaces[j].Prefix == prefix)
{
declared = true;
break;
}
}
if (!declared)
{
_lastNameSpace = nameSpace;
return prefix;
}
}
}
if (ns.Length == 0)
{
// Make sure the default binding is still valid
bool emptyPrefixUnassigned = true;
for (int i = nsCount - 1; i >= _nsTop; i--)
{
if (_namespaces[i].Prefix.Length == 0)
{
emptyPrefixUnassigned = false;
break;
}
}
if (emptyPrefixUnassigned)
return string.Empty;
}
if (ns == xmlnsNamespace)
return "xmlns";
if (ns == xmlNamespace)
return "xml";
return null;
}
public string LookupAttributePrefix(string ns)
{
if (_lastNameSpace != null && _lastNameSpace.Uri == ns && _lastNameSpace.Prefix.Length != 0)
return _lastNameSpace.Prefix;
int nsCount = _nsCount;
for (int i = nsCount - 1; i >= _nsTop; i--)
{
Namespace nameSpace = _namespaces[i];
if (object.ReferenceEquals(nameSpace.Uri, ns))
{
string prefix = nameSpace.Prefix;
if (prefix.Length != 0)
{
// Make sure that the prefix refers to the namespace in scope
bool declared = false;
for (int j = i + 1; j < nsCount; j++)
{
if (_namespaces[j].Prefix == prefix)
{
declared = true;
break;
}
}
if (!declared)
{
_lastNameSpace = nameSpace;
return prefix;
}
}
}
}
for (int i = nsCount - 1; i >= _nsTop; i--)
{
Namespace nameSpace = _namespaces[i];
if (nameSpace.Uri == ns)
{
string prefix = nameSpace.Prefix;
if (prefix.Length != 0)
{
// Make sure that the prefix refers to the namespace in scope
bool declared = false;
for (int j = i + 1; j < nsCount; j++)
{
if (_namespaces[j].Prefix == prefix)
{
declared = true;
break;
}
}
if (!declared)
{
_lastNameSpace = nameSpace;
return prefix;
}
}
}
}
if (ns.Length == 0)
return string.Empty;
return null;
}
public string LookupNamespace(string prefix)
{
int nsCount = _nsCount;
if (prefix.Length == 0)
{
for (int i = nsCount - 1; i >= _nsTop; i--)
{
Namespace nameSpace = _namespaces[i];
if (nameSpace.Prefix.Length == 0)
return nameSpace.Uri;
}
return string.Empty;
}
if (prefix.Length == 1)
{
char prefixChar = prefix[0];
for (int i = nsCount - 1; i >= _nsTop; i--)
{
Namespace nameSpace = _namespaces[i];
if (nameSpace.PrefixChar == prefixChar)
return nameSpace.Uri;
}
return null;
}
for (int i = nsCount - 1; i >= _nsTop; i--)
{
Namespace nameSpace = _namespaces[i];
if (nameSpace.Prefix == prefix)
return nameSpace.Uri;
}
if (prefix == "xmlns")
return xmlnsNamespace;
if (prefix == "xml")
return xmlNamespace;
return null;
}
private class XmlAttribute
{
private XmlSpace _space;
private string _lang;
private int _depth;
public XmlAttribute()
{
}
public int Depth
{
get
{
return _depth;
}
set
{
_depth = value;
}
}
public string XmlLang
{
get
{
return _lang;
}
set
{
_lang = value;
}
}
public XmlSpace XmlSpace
{
get
{
return _space;
}
set
{
_space = value;
}
}
public void Clear()
{
_lang = null;
}
}
private class Namespace
{
private string _prefix;
private string _ns;
private XmlDictionaryString _xNs;
private int _depth;
private char _prefixChar;
public Namespace()
{
}
public void Clear()
{
_prefix = null;
_prefixChar = (char)0;
_ns = null;
_xNs = null;
_depth = 0;
}
public int Depth
{
get
{
return _depth;
}
set
{
_depth = value;
}
}
public char PrefixChar
{
get
{
return _prefixChar;
}
}
public string Prefix
{
get
{
return _prefix;
}
set
{
if (value.Length == 1)
_prefixChar = value[0];
else
_prefixChar = (char)0;
_prefix = value;
}
}
public string Uri
{
get
{
return _ns;
}
set
{
_ns = value;
}
}
public XmlDictionaryString UriDictionaryString
{
get
{
return _xNs;
}
set
{
_xNs = value;
}
}
}
}
}
}
| |
// 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.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicIndexerAccessExpression_DynamicArgument()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
var x = /*<bind>*/c[d]/*</bind>*/;
}
public int this[int i] => 0;
}
";
string expectedOperationTree = @"
IDynamicIndexerAccessExpression (OperationKind.DynamicIndexerAccessExpression, Type: dynamic) (Syntax: 'c[d]')
Expression:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(1):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicIndexerAccessExpression_MultipleApplicableSymbols()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
var x = /*<bind>*/c[d]/*</bind>*/;
}
public int this[int i] => 0;
public int this[long i] => 0;
}
";
string expectedOperationTree = @"
IDynamicIndexerAccessExpression (OperationKind.DynamicIndexerAccessExpression, Type: dynamic) (Syntax: 'c[d]')
Expression:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(1):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicIndexerAccessExpression_MultipleArgumentsAndApplicableSymbols()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
char ch = 'c';
var x = /*<bind>*/c[d, ch]/*</bind>*/;
}
public int this[int i, char ch] => 0;
public int this[long i, char ch] => 0;
}
";
string expectedOperationTree = @"
IDynamicIndexerAccessExpression (OperationKind.DynamicIndexerAccessExpression, Type: dynamic) (Syntax: 'c[d, ch]')
Expression:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(2):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ILocalReferenceExpression: ch (OperationKind.LocalReferenceExpression, Type: System.Char) (Syntax: 'ch')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicIndexerAccessExpression_ArgumentNames()
{
string source = @"
class C
{
void M(C c, dynamic d, dynamic e)
{
var x = /*<bind>*/c[i: d, ch: e]/*</bind>*/;
}
public int this[int i, char ch] => 0;
public int this[long i, char ch] => 0;
}
";
string expectedOperationTree = @"
IDynamicIndexerAccessExpression (OperationKind.DynamicIndexerAccessExpression, Type: dynamic) (Syntax: 'c[i: d, ch: e]')
Expression:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(2):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
IParameterReferenceExpression: e (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'e')
ArgumentNames(2):
""i""
""ch""
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicIndexerAccessExpression_ArgumentRefKinds()
{
string source = @"
class C
{
void M(C c, dynamic d, dynamic e)
{
var x = /*<bind>*/c[i: d, ch: ref e]/*</bind>*/;
}
public int this[int i, ref dynamic ch] => 0;
}
";
string expectedOperationTree = @"
IDynamicIndexerAccessExpression (OperationKind.DynamicIndexerAccessExpression, Type: dynamic) (Syntax: 'c[i: d, ch: ref e]')
Expression:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(2):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
IParameterReferenceExpression: e (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'e')
ArgumentNames(2):
""i""
""ch""
ArgumentRefKinds(2):
None
Ref
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0631: ref and out are not valid in this context
// public int this[int i, ref dynamic ch] => 0;
Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicIndexerAccessExpression_WithDynamicReceiver()
{
string source = @"
class C
{
void M(dynamic d, int i)
{
var x = /*<bind>*/d[i]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicIndexerAccessExpression (OperationKind.DynamicIndexerAccessExpression, Type: dynamic) (Syntax: 'd[i]')
Expression:
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
Arguments(1):
IParameterReferenceExpression: i (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'i')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicIndexerAccessExpression_WithDynamicMemberReceiver()
{
string source = @"
class C
{
void M(dynamic c, int i)
{
var x = /*<bind>*/c.M2[i]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicIndexerAccessExpression (OperationKind.DynamicIndexerAccessExpression, Type: dynamic) (Syntax: 'c.M2[i]')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: dynamic) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'c')
Arguments(1):
IParameterReferenceExpression: i (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'i')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicIndexerAccessExpression_WithDynamicTypedMemberReceiver()
{
string source = @"
class C
{
dynamic M2 = null;
void M(C c, int i)
{
var x = /*<bind>*/c.M2[i]/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicIndexerAccessExpression (OperationKind.DynamicIndexerAccessExpression, Type: dynamic) (Syntax: 'c.M2[i]')
Expression:
IFieldReferenceExpression: dynamic C.M2 (OperationKind.FieldReferenceExpression, Type: dynamic) (Syntax: 'c.M2')
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(1):
IParameterReferenceExpression: i (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'i')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicIndexerAccessExpression_AllFields()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
int i = 0;
var x = /*<bind>*/c[ref i, c: d]/*</bind>*/;
}
public int this[ref int i, char c] => 0;
public int this[ref int i, long c] => 0;
}
";
string expectedOperationTree = @"
IDynamicIndexerAccessExpression (OperationKind.DynamicIndexerAccessExpression, Type: dynamic) (Syntax: 'c[ref i, c: d]')
Expression:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(2):
ILocalReferenceExpression: i (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'i')
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ArgumentNames(2):
""null""
""c""
ArgumentRefKinds(2):
Ref
None
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0631: ref and out are not valid in this context
// public int this[ref int i, char c] => 0;
Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(10, 21),
// CS0631: ref and out are not valid in this context
// public int this[ref int i, long c] => 0;
Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(11, 21)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicIndexerAccessExpression_ErrorBadDynamicMethodArgLambda()
{
string source = @"
using System;
class C
{
public void M(C c)
{
dynamic y = null;
var x = /*<bind>*/c[delegate { }, y]/*</bind>*/;
}
public int this[Action a, Action y] => 0;
}
";
string expectedOperationTree = @"
IDynamicIndexerAccessExpression (OperationKind.DynamicIndexerAccessExpression, Type: dynamic, IsInvalid) (Syntax: 'c[delegate { }, y]')
Expression:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(2):
IAnonymousFunctionExpression (Symbol: lambda expression) (OperationKind.AnonymousFunctionExpression, Type: null, IsInvalid) (Syntax: 'delegate { }')
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: '{ }')
IReturnStatement (OperationKind.ReturnStatement, IsInvalid, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
ILocalReferenceExpression: y (OperationKind.LocalReferenceExpression, Type: dynamic) (Syntax: 'y')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
// var x = /*<bind>*/c[delegate { }, y]/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }").WithLocation(9, 29)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicIndexerAccessExpression_OverloadResolutionFailure()
{
string source = @"
using System;
class C
{
void M(C c, dynamic d)
{
var x = /*<bind>*/c[d]/*</bind>*/;
}
public int this[int i, int j] => 0;
public int this[int i, int j, int k] => 0;
}
";
string expectedOperationTree = @"
IInvalidExpression (OperationKind.InvalidExpression, Type: System.Int32, IsInvalid) (Syntax: 'c[d]')
Children(2):
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C, IsInvalid) (Syntax: 'c')
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic, IsInvalid) (Syntax: 'd')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1501: No overload for method 'this' takes 1 arguments
// var x = /*<bind>*/c[d]/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadArgCount, "c[d]").WithArguments("this", "1").WithLocation(8, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ITN.Felicity.Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace System.Globalization
{
internal partial class CultureData
{
// ICU constants
const int ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY = 100; // max size of keyword or value
const int ICU_ULOC_FULLNAME_CAPACITY = 157; // max size of locale name
const string ICU_COLLATION_KEYWORD = "@collation=";
/// <summary>
/// This method uses the sRealName field (which is initialized by the constructor before this is called) to
/// initialize the rest of the state of CultureData based on the underlying OS globalization library.
/// </summary>
[SecuritySafeCritical]
private unsafe bool InitCultureData()
{
Contract.Assert(this.sRealName != null);
string alternateSortName = string.Empty;
string realNameBuffer = this.sRealName;
// Basic validation
if (realNameBuffer.Contains("@"))
{
return false; // don't allow ICU variants to come in directly
}
// Replace _ (alternate sort) with @collation= for ICU
int index = realNameBuffer.IndexOf('_');
if (index > 0)
{
if (index >= (realNameBuffer.Length - 1) // must have characters after _
|| realNameBuffer.Substring(index + 1).Contains("_")) // only one _ allowed
{
return false; // fail
}
alternateSortName = realNameBuffer.Substring(index + 1);
realNameBuffer = realNameBuffer.Substring(0, index) + ICU_COLLATION_KEYWORD + alternateSortName;
}
// Get the locale name from ICU
if (!GetLocaleName(realNameBuffer, out this.sWindowsName))
{
return false; // fail
}
// Replace the ICU collation keyword with an _
index = this.sWindowsName.IndexOf(ICU_COLLATION_KEYWORD, StringComparison.Ordinal);
if (index >= 0)
{
this.sName = this.sWindowsName.Substring(0, index) + "_" + alternateSortName;
}
else
{
this.sName = this.sWindowsName;
}
this.sRealName = this.sName;
this.sSpecificCulture = this.sRealName; // we don't attempt to find a non-neutral locale if a neutral is passed in (unlike win32)
this.iLanguage = this.ILANGUAGE;
if (this.iLanguage == 0)
{
this.iLanguage = LOCALE_CUSTOM_UNSPECIFIED;
}
this.bNeutral = (this.SISO3166CTRYNAME.Length == 0);
// Remove the sort from sName unless custom culture
if (!this.bNeutral)
{
if (!IsCustomCultureId(this.iLanguage))
{
this.sName = this.sWindowsName.Substring(0, index);
}
}
return true;
}
[SecuritySafeCritical]
internal static bool GetLocaleName(string localeName, out string windowsName)
{
// Get the locale name from ICU
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
if (!Interop.GlobalizationInterop.GetLocaleName(localeName, sb, sb.Capacity))
{
StringBuilderCache.Release(sb);
windowsName = null;
return false; // fail
}
// Success - use the locale name returned which may be different than realNameBuffer (casing)
windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls
return true;
}
[SecuritySafeCritical]
internal static bool GetDefaultLocaleName(out string windowsName)
{
// Get the default (system) locale name from ICU
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
if (!Interop.GlobalizationInterop.GetDefaultLocaleName(sb, sb.Capacity))
{
StringBuilderCache.Release(sb);
windowsName = null;
return false; // fail
}
// Success - use the locale name returned which may be different than realNameBuffer (casing)
windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls
return true;
}
private string GetLocaleInfo(LocaleStringData type)
{
Contract.Assert(this.sWindowsName != null, "[CultureData.GetLocaleInfo] Expected this.sWindowsName to be populated already");
return GetLocaleInfo(this.sWindowsName, type);
}
// For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
// "windows" name, which can be specific for downlevel (< windows 7) os's.
[SecuritySafeCritical]
private string GetLocaleInfo(string localeName, LocaleStringData type)
{
Contract.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null");
switch (type)
{
case LocaleStringData.NegativeInfinitySymbol:
// not an equivalent in ICU; prefix the PositiveInfinitySymbol with NegativeSign
return GetLocaleInfo(localeName, LocaleStringData.NegativeSign) +
GetLocaleInfo(localeName, LocaleStringData.PositiveInfinitySymbol);
}
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
bool result = Interop.GlobalizationInterop.GetLocaleInfoString(localeName, (uint)type, sb, sb.Capacity);
if (!result)
{
// Failed, just use empty string
StringBuilderCache.Release(sb);
Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed");
return String.Empty;
}
return StringBuilderCache.GetStringAndRelease(sb);
}
[SecuritySafeCritical]
private int GetLocaleInfo(LocaleNumberData type)
{
Contract.Assert(this.sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected this.sWindowsName to be populated already");
switch (type)
{
case LocaleNumberData.CalendarType:
// returning 0 will cause the first supported calendar to be returned, which is the preferred calendar
return 0;
}
int value = 0;
bool result = Interop.GlobalizationInterop.GetLocaleInfoInt(this.sWindowsName, (uint)type, ref value);
if (!result)
{
// Failed, just use 0
Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed");
}
return value;
}
[SecuritySafeCritical]
private int[] GetLocaleInfo(LocaleGroupingData type)
{
Contract.Assert(this.sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected this.sWindowsName to be populated already");
int primaryGroupingSize = 0;
int secondaryGroupingSize = 0;
bool result = Interop.GlobalizationInterop.GetLocaleInfoGroupingSizes(this.sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize);
if (!result)
{
Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed");
}
if (secondaryGroupingSize == 0)
{
return new int[] { primaryGroupingSize };
}
return new int[] { primaryGroupingSize, secondaryGroupingSize };
}
private string GetTimeFormatString()
{
return GetTimeFormatString(false);
}
[SecuritySafeCritical]
private string GetTimeFormatString(bool shortFormat)
{
Contract.Assert(this.sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected this.sWindowsName to be populated already");
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
bool result = Interop.GlobalizationInterop.GetLocaleTimeFormat(this.sWindowsName, shortFormat, sb, sb.Capacity);
if (!result)
{
// Failed, just use empty string
StringBuilderCache.Release(sb);
Contract.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
return String.Empty;
}
return ConvertIcuTimeFormatString(StringBuilderCache.GetStringAndRelease(sb));
}
private int GetFirstDayOfWeek()
{
return this.GetLocaleInfo(LocaleNumberData.FirstDayOfWeek);
}
private String[] GetTimeFormats()
{
string format = GetTimeFormatString(false);
return new string[] { format };
}
private String[] GetShortTimeFormats()
{
string format = GetTimeFormatString(true);
return new string[] { format };
}
private static CultureData GetCultureDataFromRegionName(String regionName)
{
// no support to lookup by region name, other than the hard-coded list in CultureData
return null;
}
private static string GetLanguageDisplayName(string cultureName)
{
return new CultureInfo(cultureName).m_cultureData.GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName);
}
private static string GetRegionDisplayName(string isoCountryCode)
{
// use the fallback which is to return NativeName
return null;
}
private static CultureInfo GetUserDefaultCulture()
{
return CultureInfo.GetUserDefaultCulture();
}
private static string ConvertIcuTimeFormatString(string icuFormatString)
{
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
bool amPmAdded = false;
for (int i = 0; i < icuFormatString.Length; i++)
{
switch(icuFormatString[i])
{
case ':':
case '.':
case 'H':
case 'h':
case 'm':
case 's':
sb.Append(icuFormatString[i]);
break;
case ' ':
case '\u00A0':
// Convert nonbreaking spaces into regular spaces
sb.Append(' ');
break;
case 'a': // AM/PM
if (!amPmAdded)
{
amPmAdded = true;
sb.Append("tt");
}
break;
}
}
return StringBuilderCache.GetStringAndRelease(sb);
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using ZXing.Common;
namespace ZXing.Datamatrix.Internal
{
/// <summary>
/// <author>bbrown@google.com (Brian Brown)</author>
/// </summary>
sealed class BitMatrixParser
{
private readonly BitMatrix mappingBitMatrix;
private readonly BitMatrix readMappingMatrix;
private readonly Version version;
/// <summary>
/// <param name="bitMatrix"><see cref="BitMatrix" />to parse</param>
/// <exception cref="FormatException">if dimension is < 8 or > 144 or not 0 mod 2</exception>
/// </summary>
internal BitMatrixParser(BitMatrix bitMatrix)
{
int dimension = bitMatrix.Height;
if (dimension < 8 || dimension > 144 || (dimension & 0x01) != 0)
{
return;
}
version = readVersion(bitMatrix);
if (version != null)
{
mappingBitMatrix = extractDataRegion(bitMatrix);
readMappingMatrix = new BitMatrix(mappingBitMatrix.Width, mappingBitMatrix.Height);
}
}
public Version Version
{
get { return version; }
}
/// <summary>
/// <p>Creates the version object based on the dimension of the original bit matrix from
/// the datamatrix code.</p>
///
/// <p>See ISO 16022:2006 Table 7 - ECC 200 symbol attributes</p>
///
/// <param name="bitMatrix">Original <see cref="BitMatrix" />including alignment patterns</param>
/// <returns><see cref="Version" />encapsulating the Data Matrix Code's "version"</returns>
/// <exception cref="FormatException">if the dimensions of the mapping matrix are not valid</exception>
/// Data Matrix dimensions.
/// </summary>
internal static Version readVersion(BitMatrix bitMatrix)
{
int numRows = bitMatrix.Height;
int numColumns = bitMatrix.Width;
return Version.getVersionForDimensions(numRows, numColumns);
}
/// <summary>
/// <p>Reads the bits in the <see cref="BitMatrix" />representing the mapping matrix (No alignment patterns)
/// in the correct order in order to reconstitute the codewords bytes contained within the
/// Data Matrix Code.</p>
///
/// <returns>bytes encoded within the Data Matrix Code</returns>
/// <exception cref="FormatException">if the exact number of bytes expected is not read</exception>
/// </summary>
internal byte[] readCodewords()
{
byte[] result = new byte[version.getTotalCodewords()];
int resultOffset = 0;
int row = 4;
int column = 0;
int numRows = mappingBitMatrix.Height;
int numColumns = mappingBitMatrix.Width;
bool corner1Read = false;
bool corner2Read = false;
bool corner3Read = false;
bool corner4Read = false;
// Read all of the codewords
do
{
// Check the four corner cases
if ((row == numRows) && (column == 0) && !corner1Read)
{
result[resultOffset++] = (byte)readCorner1(numRows, numColumns);
row -= 2;
column += 2;
corner1Read = true;
}
else if ((row == numRows - 2) && (column == 0) && ((numColumns & 0x03) != 0) && !corner2Read)
{
result[resultOffset++] = (byte)readCorner2(numRows, numColumns);
row -= 2;
column += 2;
corner2Read = true;
}
else if ((row == numRows + 4) && (column == 2) && ((numColumns & 0x07) == 0) && !corner3Read)
{
result[resultOffset++] = (byte)readCorner3(numRows, numColumns);
row -= 2;
column += 2;
corner3Read = true;
}
else if ((row == numRows - 2) && (column == 0) && ((numColumns & 0x07) == 4) && !corner4Read)
{
result[resultOffset++] = (byte)readCorner4(numRows, numColumns);
row -= 2;
column += 2;
corner4Read = true;
}
else
{
// Sweep upward diagonally to the right
do
{
if ((row < numRows) && (column >= 0) && !readMappingMatrix[column, row])
{
result[resultOffset++] = (byte)readUtah(row, column, numRows, numColumns);
}
row -= 2;
column += 2;
} while ((row >= 0) && (column < numColumns));
row += 1;
column += 3;
// Sweep downward diagonally to the left
do
{
if ((row >= 0) && (column < numColumns) && !readMappingMatrix[column, row])
{
result[resultOffset++] = (byte)readUtah(row, column, numRows, numColumns);
}
row += 2;
column -= 2;
} while ((row < numRows) && (column >= 0));
row += 3;
column += 1;
}
} while ((row < numRows) || (column < numColumns));
if (resultOffset != version.getTotalCodewords())
{
return null;
}
return result;
}
/// <summary>
/// <p>Reads a bit of the mapping matrix accounting for boundary wrapping.</p>
///
/// <param name="row">Row to read in the mapping matrix</param>
/// <param name="column">Column to read in the mapping matrix</param>
/// <param name="numRows">Number of rows in the mapping matrix</param>
/// <param name="numColumns">Number of columns in the mapping matrix</param>
/// <returns>value of the given bit in the mapping matrix</returns>
/// </summary>
private bool readModule(int row, int column, int numRows, int numColumns)
{
// Adjust the row and column indices based on boundary wrapping
if (row < 0)
{
row += numRows;
column += 4 - ((numRows + 4) & 0x07);
}
if (column < 0)
{
column += numColumns;
row += 4 - ((numColumns + 4) & 0x07);
}
if (row >= numRows)
{
row -= numRows;
}
readMappingMatrix[column, row] = true;
return mappingBitMatrix[column, row];
}
/// <summary>
/// <p>Reads the 8 bits of the standard Utah-shaped pattern.</p>
///
/// <p>See ISO 16022:2006, 5.8.1 Figure 6</p>
///
/// <param name="row">Current row in the mapping matrix, anchored at the 8th bit (LSB) of the pattern</param>
/// <param name="column">Current column in the mapping matrix, anchored at the 8th bit (LSB) of the pattern</param>
/// <param name="numRows">Number of rows in the mapping matrix</param>
/// <param name="numColumns">Number of columns in the mapping matrix</param>
/// <returns>byte from the utah shape</returns>
/// </summary>
private int readUtah(int row, int column, int numRows, int numColumns)
{
int currentByte = 0;
if (readModule(row - 2, column - 2, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row - 2, column - 1, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row - 1, column - 2, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row - 1, column - 1, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row - 1, column, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row, column - 2, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row, column - 1, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(row, column, numRows, numColumns))
{
currentByte |= 1;
}
return currentByte;
}
/// <summary>
/// <p>Reads the 8 bits of the special corner condition 1.</p>
///
/// <p>See ISO 16022:2006, Figure F.3</p>
///
/// <param name="numRows">Number of rows in the mapping matrix</param>
/// <param name="numColumns">Number of columns in the mapping matrix</param>
/// <returns>byte from the Corner condition 1</returns>
/// </summary>
private int readCorner1(int numRows, int numColumns)
{
int currentByte = 0;
if (readModule(numRows - 1, 0, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, 1, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, 2, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 2, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 1, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 1, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(2, numColumns - 1, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(3, numColumns - 1, numRows, numColumns))
{
currentByte |= 1;
}
return currentByte;
}
/// <summary>
/// <p>Reads the 8 bits of the special corner condition 2.</p>
///
/// <p>See ISO 16022:2006, Figure F.4</p>
///
/// <param name="numRows">Number of rows in the mapping matrix</param>
/// <param name="numColumns">Number of columns in the mapping matrix</param>
/// <returns>byte from the Corner condition 2</returns>
/// </summary>
private int readCorner2(int numRows, int numColumns)
{
int currentByte = 0;
if (readModule(numRows - 3, 0, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 2, 0, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, 0, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 4, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 3, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 2, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 1, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 1, numRows, numColumns))
{
currentByte |= 1;
}
return currentByte;
}
/// <summary>
/// <p>Reads the 8 bits of the special corner condition 3.</p>
///
/// <p>See ISO 16022:2006, Figure F.5</p>
///
/// <param name="numRows">Number of rows in the mapping matrix</param>
/// <param name="numColumns">Number of columns in the mapping matrix</param>
/// <returns>byte from the Corner condition 3</returns>
/// </summary>
private int readCorner3(int numRows, int numColumns)
{
int currentByte = 0;
if (readModule(numRows - 1, 0, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, numColumns - 1, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 3, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 2, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 1, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 3, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 2, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 1, numRows, numColumns))
{
currentByte |= 1;
}
return currentByte;
}
/// <summary>
/// <p>Reads the 8 bits of the special corner condition 4.</p>
///
/// <p>See ISO 16022:2006, Figure F.6</p>
///
/// <param name="numRows">Number of rows in the mapping matrix</param>
/// <param name="numColumns">Number of columns in the mapping matrix</param>
/// <returns>byte from the Corner condition 4</returns>
/// </summary>
private int readCorner4(int numRows, int numColumns)
{
int currentByte = 0;
if (readModule(numRows - 3, 0, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 2, 0, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, 0, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 2, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 1, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 1, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(2, numColumns - 1, numRows, numColumns))
{
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(3, numColumns - 1, numRows, numColumns))
{
currentByte |= 1;
}
return currentByte;
}
/// <summary>
/// <p>Extracts the data region from a <see cref="BitMatrix" />that contains
/// alignment patterns.</p>
///
/// <param name="bitMatrix">Original <see cref="BitMatrix" />with alignment patterns</param>
/// <returns>BitMatrix that has the alignment patterns removed</returns>
/// </summary>
private BitMatrix extractDataRegion(BitMatrix bitMatrix)
{
int symbolSizeRows = version.getSymbolSizeRows();
int symbolSizeColumns = version.getSymbolSizeColumns();
if (bitMatrix.Height != symbolSizeRows)
{
throw new ArgumentException("Dimension of bitMatrix must match the version size");
}
int dataRegionSizeRows = version.getDataRegionSizeRows();
int dataRegionSizeColumns = version.getDataRegionSizeColumns();
int numDataRegionsRow = symbolSizeRows / dataRegionSizeRows;
int numDataRegionsColumn = symbolSizeColumns / dataRegionSizeColumns;
int sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows;
int sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns;
BitMatrix bitMatrixWithoutAlignment = new BitMatrix(sizeDataRegionColumn, sizeDataRegionRow);
for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow)
{
int dataRegionRowOffset = dataRegionRow * dataRegionSizeRows;
for (int dataRegionColumn = 0; dataRegionColumn < numDataRegionsColumn; ++dataRegionColumn)
{
int dataRegionColumnOffset = dataRegionColumn * dataRegionSizeColumns;
for (int i = 0; i < dataRegionSizeRows; ++i)
{
int readRowOffset = dataRegionRow * (dataRegionSizeRows + 2) + 1 + i;
int writeRowOffset = dataRegionRowOffset + i;
for (int j = 0; j < dataRegionSizeColumns; ++j)
{
int readColumnOffset = dataRegionColumn * (dataRegionSizeColumns + 2) + 1 + j;
if (bitMatrix[readColumnOffset, readRowOffset])
{
int writeColumnOffset = dataRegionColumnOffset + j;
bitMatrixWithoutAlignment[writeColumnOffset, writeRowOffset] = true;
}
}
}
}
}
return bitMatrixWithoutAlignment;
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: DocContent
// ObjectType: DocContent
// CSLAType: EditableChild
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using DocStore.Business.Security;
namespace DocStore.Business
{
/// <summary>
/// Document files (editable child object).<br/>
/// This is a generated <see cref="DocContent"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="Doc"/> collection.
/// </remarks>
[Serializable]
public partial class DocContent : BusinessBase<DocContent>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="DocContentID"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> DocContentIDProperty = RegisterProperty<int>(p => p.DocContentID, "Doc Content ID");
/// <summary>
/// Gets the Doc Content ID.
/// </summary>
/// <value>The Doc Content ID.</value>
public int DocContentID
{
get { return GetProperty(DocContentIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Version"/> property.
/// </summary>
public static readonly PropertyInfo<short> VersionProperty = RegisterProperty<short>(p => p.Version, "Version");
/// <summary>
/// Gets or sets the Version.
/// </summary>
/// <value>The Version.</value>
public short Version
{
get { return GetProperty(VersionProperty); }
set { SetProperty(VersionProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="FileContent"/> property.
/// </summary>
public static readonly PropertyInfo<byte[]> FileContentProperty = RegisterProperty<byte[]>(p => p.FileContent, "File Content");
/// <summary>
/// Gets or sets the File Content.
/// </summary>
/// <value>The File Content.</value>
public byte[] FileContent
{
get { return GetProperty(FileContentProperty); }
set { SetProperty(FileContentProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="FileSize"/> property.
/// </summary>
public static readonly PropertyInfo<int> FileSizeProperty = RegisterProperty<int>(p => p.FileSize, "File Size");
/// <summary>
/// Gets or sets the File Size.
/// </summary>
/// <value>The File Size.</value>
public int FileSize
{
get { return GetProperty(FileSizeProperty); }
set { SetProperty(FileSizeProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="FileType"/> property.
/// </summary>
public static readonly PropertyInfo<string> FileTypeProperty = RegisterProperty<string>(p => p.FileType, "File Type");
/// <summary>
/// Gets or sets the File Type.
/// </summary>
/// <value>The File Type.</value>
public string FileType
{
get { return GetProperty(FileTypeProperty); }
set { SetProperty(FileTypeProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CheckInDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CheckInDateProperty = RegisterProperty<SmartDate>(p => p.CheckInDate, "Check In Date");
/// <summary>
/// Check-in date
/// </summary>
/// <value>The Check In Date.</value>
public string CheckInDate
{
get { return GetPropertyConvert<SmartDate, string>(CheckInDateProperty); }
set { SetPropertyConvert<SmartDate, string>(CheckInDateProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CheckInUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> CheckInUserIDProperty = RegisterProperty<int>(p => p.CheckInUserID, "Check In User ID");
/// <summary>
/// Check-in user ID
/// </summary>
/// <value>The Check In User ID.</value>
public int CheckInUserID
{
get { return GetProperty(CheckInUserIDProperty); }
set
{
SetProperty(CheckInUserIDProperty, value);
OnPropertyChanged("CheckInUserName");
}
}
/// <summary>
/// Maintains metadata about <see cref="CheckInComment"/> property.
/// </summary>
public static readonly PropertyInfo<string> CheckInCommentProperty = RegisterProperty<string>(p => p.CheckInComment, "Check In Comment");
/// <summary>
/// Check-in comment
/// </summary>
/// <value>The Check In Comment.</value>
public string CheckInComment
{
get { return GetProperty(CheckInCommentProperty); }
set { SetProperty(CheckInCommentProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CheckOutDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CheckOutDateProperty = RegisterProperty<SmartDate>(p => p.CheckOutDate, "Check Out Date");
/// <summary>
/// Check-out date
/// </summary>
/// <value>The Check Out Date.</value>
public string CheckOutDate
{
get { return GetPropertyConvert<SmartDate, string>(CheckOutDateProperty); }
set { SetPropertyConvert<SmartDate, string>(CheckOutDateProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CheckOutUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> CheckOutUserIDProperty = RegisterProperty<int?>(p => p.CheckOutUserID, "Check Out User ID");
/// <summary>
/// Check-out user ID
/// </summary>
/// <value>The Check Out User ID.</value>
public int? CheckOutUserID
{
get { return GetProperty(CheckOutUserIDProperty); }
set
{
SetProperty(CheckOutUserIDProperty, value);
OnPropertyChanged("CheckOutUserName");
}
}
/// <summary>
/// Maintains metadata about <see cref="RowVersion"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version");
/// <summary>
/// Gets the Row Version.
/// </summary>
/// <value>The Row Version.</value>
public byte[] RowVersion
{
get { return GetProperty(RowVersionProperty); }
}
/// <summary>
/// Gets the Check In User Name.
/// </summary>
/// <value>The Check In User Name.</value>
public string CheckInUserName
{
get
{
var result = string.Empty;
if (Admin.UserNVL.GetUserNVL().ContainsKey(CheckInUserID))
result = Admin.UserNVL.GetUserNVL().GetItemByKey(CheckInUserID).Value;
return result;
}
}
/// <summary>
/// Gets the Check Out User Name.
/// </summary>
/// <value>The Check Out User Name.</value>
public string CheckOutUserName
{
get
{
var result = string.Empty;
if (CheckOutUserID.HasValue && Admin.UserNVL.GetUserNVL().ContainsKey(CheckOutUserID.Value))
result = Admin.UserNVL.GetUserNVL().GetItemByKey(CheckOutUserID.Value).Value;
return result;
}
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="DocContent"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="DocContent"/> object.</returns>
internal static DocContent NewDocContent()
{
return DataPortal.CreateChild<DocContent>();
}
/// <summary>
/// Factory method. Loads a <see cref="DocContent"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="DocContent"/> object.</returns>
internal static DocContent GetDocContent(SafeDataReader dr)
{
DocContent obj = new DocContent();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="DocContent"/> object.
/// </summary>
/// <param name="callback">The completion callback method.</param>
internal static void NewDocContent(EventHandler<DataPortalResult<DocContent>> callback)
{
DataPortal.BeginCreate<DocContent>(callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DocContent"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public DocContent()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="DocContent"/> object properties.
/// </summary>
[RunLocal]
protected override void Child_Create()
{
LoadProperty(DocContentIDProperty, System.Threading.Interlocked.Decrement(ref _lastId));
LoadProperty(VersionProperty, (short)1);
LoadProperty(FileContentProperty, new byte[0]);
LoadProperty(FileSizeProperty, 0);
LoadProperty(FileTypeProperty, "");
LoadProperty(CheckInDateProperty, new SmartDate(DateTime.Now));
LoadProperty(CheckInUserIDProperty, UserInformation.UserId);
LoadProperty(CheckInCommentProperty, "Main content");
LoadProperty(CheckOutDateProperty, null);
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="DocContent"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(DocContentIDProperty, dr.GetInt32("DocContentID"));
LoadProperty(VersionProperty, dr.GetInt16("Version"));
LoadProperty(FileSizeProperty, dr.GetInt32("FileSize"));
LoadProperty(FileTypeProperty, dr.GetString("FileType"));
LoadProperty(CheckInDateProperty, dr.GetSmartDate("CheckInDate", true));
LoadProperty(CheckInUserIDProperty, dr.GetInt32("CheckInUserID"));
LoadProperty(CheckInCommentProperty, dr.GetString("CheckInComment"));
LoadProperty(CheckOutDateProperty, dr.IsDBNull("CheckOutDate") ? null : dr.GetSmartDate("CheckOutDate", true));
LoadProperty(CheckOutUserIDProperty, (int?)dr.GetValue("CheckOutUserID"));
LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]);
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="DocContent"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
private void Child_Insert(Doc parent)
{
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("AddDocContent", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocID", parent.DocID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@DocContentID", ReadProperty(DocContentIDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@FileSize", ReadProperty(FileSizeProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@FileType", ReadProperty(FileTypeProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@CheckInDate", ReadProperty(CheckInDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@CheckInUserID", ReadProperty(CheckInUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@CheckInComment", ReadProperty(CheckInCommentProperty)).DbType = DbType.String;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(DocContentIDProperty, (int) cmd.Parameters["@DocContentID"].Value);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="DocContent"/> object.
/// </summary>
private void Child_Update()
{
if (!IsDirty)
return;
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("UpdateDocContent", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocContentID", ReadProperty(DocContentIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@CheckOutDate", ReadProperty(CheckOutDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@CheckOutUserID", ReadProperty(CheckOutUserIDProperty) == null ? (object)DBNull.Value : ReadProperty(CheckOutUserIDProperty).Value).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace Microsoft.VisualStudio.Pug
{
/// <summary>
/// Represents a range in a text buffer or a string. Specified start and end of text.
/// End is exclusive, i.e. Length = End - Start. Implements IComparable that compares
/// range start positions.
/// </summary>
[DebuggerDisplay("[{Start}...{End}], Length = {Length}")]
internal class TextRange : IExpandableTextRange, ICloneable, IComparable
{
private static TextRange _emptyRange = new TextRange(0, 0);
private int _start;
private int _end;
/// <summary>
/// Returns an empty, invalid range.
/// </summary>
public static TextRange EmptyRange => _emptyRange;
/// <summary>
/// Creates text range starting at position 0
/// and length of 1
/// </summary>
public TextRange()
: this(0)
{
}
/// <summary>
/// Creates text range starting at given position
/// and length of 1.
/// </summary>
/// <param name="position">Start position</param>
public TextRange(int position)
{
this._start = position;
this._end = position < Int32.MaxValue ? position + 1 : position;
}
/// <summary>
/// Creates text range based on start and end positions.
/// End is exclusive, Length = End - Start
/// <param name="start">Range start</param>
/// <param name="length">Range length</param>
/// </summary>
public TextRange(int start, int length)
{
if (length < 0)
{
throw new ArgumentException("Length must not be negative");
}
this._start = start;
this._end = start + length;
}
/// <summary>
/// Creates text range based on another text range
/// </summary>
/// <param name="range">Text range to use as position source</param>
public TextRange(ITextRange range)
: this(range.Start, range.Length)
{
}
/// <summary>
/// Resets text range to (0, 0)
/// </summary>
public void Empty()
{
this._start = 0;
this._end = 0;
}
/// <summary>
/// Creates text range based on start and end positions.
/// End is exclusive, Length = End - Start
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
public static TextRange FromBounds(int start, int end)
{
return new TextRange(start, end - start);
}
/// <summary>
/// Finds out of range intersects another range
/// </summary>
/// <param name="start">Start of another range</param>
/// <param name="length">Length of another range</param>
/// <returns>True if ranges intersect</returns>
public virtual bool Intersect(int start, int length)
{
return TextRange.Intersect(this, start, length);
}
/// <summary>
/// Finds out of range intersects another range
/// </summary>
/// <param name="start">Text range</param>
/// <returns>True if ranges intersect</returns>
public virtual bool Intersect(ITextRange range)
{
return TextRange.Intersect(this, range.Start, range.Length);
}
/// <summary>
/// Finds out if range represents valid text range (it's length is greater than zero)
/// </summary>
/// <returns>True if range is valid</returns>
public virtual bool IsValid()
{
return TextRange.IsValid(this);
}
#region ITextRange
/// <summary>
/// Text range start position
/// </summary>
public int Start => this._start;
/// <summary>
/// Text range end position (excluded)
/// </summary>
public int End => this._end;
/// <summary>
/// Text range length
/// </summary>
public int Length => this.End - this.Start;
/// <summary>
/// Determines if range contains given position
/// </summary>
public virtual bool Contains(int position)
{
return TextRange.Contains(this, position);
}
/// <summary>
/// Determines if text range fully contains another range
/// </summary>
/// <param name="range"></param>
public virtual bool Contains(ITextRange range)
{
return Contains(range.Start) && Contains(range.End);
}
/// <summary>
/// Determines if element contains one or more of the ranges
/// </summary>
/// <returns></returns>
public virtual bool Contains(IEnumerable<ITextRange> ranges)
{
if (ranges == null)
{
return false;
}
var contains = false;
foreach (var range in ranges)
{
if (Contains(range))
{
contains = true;
break;
}
}
return contains;
}
/// <summary>
/// Shifts text range by a given offset
/// </summary>
public void Shift(int offset)
{
this._start += offset;
this._end += offset;
}
public void Expand(int startOffset, int endOffset)
{
if (this._start + startOffset > this._end + endOffset)
{
throw new ArgumentException("Combination of start and end offsets should not be making range invalid");
}
this._start += startOffset;
this._end += endOffset;
}
#endregion
[ExcludeFromCodeCoverage]
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "[{0}...{1}]", this.Start, this.End);
}
/// <summary>
/// Determines if ranges are equal. Ranges are equal when they are either both null
/// or both are not null and their coordinates are equal.
/// </summary>
/// <param name="left">First range</param>
/// <param name="right">Second range</param>
/// <returns>True if ranges are equal</returns>
public static bool AreEqual(ITextRange left, ITextRange right)
{
if (Object.ReferenceEquals(left, right))
{
return true;
}
// If one is null, but not both, return false.
if (((object)left == null) || ((object)right == null))
{
return false;
}
return (left.Start == right.Start) && (left.End == right.End);
}
/// <summary>
/// Determines if range contains given position
/// </summary>
/// <param name="range">Text range</param>
/// <param name="position">Position</param>
/// <returns>True if position is inside the range</returns>
public static bool Contains(ITextRange range, int position)
{
return Contains(range.Start, range.Length, position);
}
/// <summary>
/// Determines if range contains another range
/// </summary>
public static bool Contains(ITextRange range, ITextRange other)
{
var textRange = new TextRange(range);
return textRange.Contains(other);
}
/// <summary>
/// Determines if range contains all ranges in a collection
/// </summary>
public static bool Contains(ITextRange range, IEnumerable<ITextRange> ranges)
{
var textRange = new TextRange(range);
return textRange.Contains(ranges);
}
/// <summary>
/// Determines if range contains given position
/// </summary>
/// <param name="rangeStart">Start of the text range</param>
/// <param name="rangeLength">Length of the text range</param>
/// <param name="position">Position</param>
/// <returns>Tru if position is inside the range</returns>
public static bool Contains(int rangeStart, int rangeLength, int position)
{
if (rangeLength == 0 && position == rangeStart)
{
return true;
}
return position >= rangeStart && position < rangeStart + rangeLength;
}
/// <summary>
/// Finds out if range intersects another range
/// </summary>
/// <param name="range1">First text range</param>
/// <param name="range2">Second text range</param>
/// <returns>True if ranges intersect</returns>
public static bool Intersect(ITextRange range1, ITextRange range2)
{
return Intersect(range1, range2.Start, range2.Length);
}
/// <summary>
/// Finds out if range intersects another range
/// </summary>
/// <param name="range">First text range</param>
/// <param name="rangeStart2">Start of the second range</param>
/// <param name="rangeLength2">Length of the second range</param>
/// <returns>True if ranges intersect</returns>
public static bool Intersect(ITextRange range1, int rangeStart2, int rangeLength2)
{
return Intersect(range1.Start, range1.Length, rangeStart2, rangeLength2);
}
/// <summary>
/// Finds out if range intersects another range
/// </summary>
/// <param name="rangeStart1">Start of the first range</param>
/// <param name="rangeLength1">Length of the first range</param>
/// <param name="rangeStart2">Start of the second range</param>
/// <param name="rangeLength2">Length of the second range</param>
/// <returns>True if ranges intersect</returns>
public static bool Intersect(int rangeStart1, int rangeLength1, int rangeStart2, int rangeLength2)
{
// !(rangeEnd2 <= rangeStart1 || rangeStart2 >= rangeEnd1)
// Support intersection with empty ranges
if (rangeLength1 == 0 && rangeLength2 == 0)
{
return rangeStart1 == rangeStart2;
}
if (rangeLength1 == 0)
{
return Contains(rangeStart2, rangeLength2, rangeStart1);
}
if (rangeLength2 == 0)
{
return Contains(rangeStart1, rangeLength1, rangeStart2);
}
return rangeStart2 + rangeLength2 > rangeStart1 && rangeStart2 < rangeStart1 + rangeLength1;
}
/// <summary>
/// Finds out if range represents valid text range (when range is not null and it's length is greater than zero)
/// </summary>
/// <returns>True if range is valid</returns>
public static bool IsValid(ITextRange range)
{
return range != null && range.Length > 0;
}
/// <summary>
/// Calculates range that includes both supplied ranges.
/// </summary>
public static ITextRange Union(ITextRange range1, ITextRange range2)
{
var start = Math.Min(range1.Start, range2.Start);
var end = Math.Max(range1.End, range2.End);
return start <= end ? TextRange.FromBounds(start, end) : TextRange.EmptyRange;
}
/// <summary>
/// Calculates range that includes both supplied ranges.
/// </summary>
public static ITextRange Union(ITextRange range1, int rangeStart, int rangeLength)
{
var start = Math.Min(range1.Start, rangeStart);
var end = Math.Max(range1.End, rangeStart + rangeLength);
return start <= end ? TextRange.FromBounds(start, end) : TextRange.EmptyRange;
}
/// <summary>
/// Calculates range that is an intersection of the supplied ranges.
/// </summary>
/// <returns>Intersection or empty range if ranges don't intersect</returns>
public static ITextRange Intersection(ITextRange range1, ITextRange range2)
{
var start = Math.Max(range1.Start, range2.Start);
var end = Math.Min(range1.End, range2.End);
return start <= end ? TextRange.FromBounds(start, end) : TextRange.EmptyRange;
}
/// <summary>
/// Calculates range that is an intersection of the supplied ranges.
/// </summary>
/// <returns>Intersection or empty range if ranges don't intersect</returns>
public static ITextRange Intersection(ITextRange range1, int rangeStart, int rangeLength)
{
var start = Math.Max(range1.Start, rangeStart);
var end = Math.Min(range1.End, rangeStart + rangeLength);
return start <= end ? TextRange.FromBounds(start, end) : TextRange.EmptyRange;
}
/// <summary>
/// Creates copy of the text range object via memberwise cloning
/// </summary>
public virtual object Clone()
{
return this.MemberwiseClone();
}
public int CompareTo(object obj)
{
var other = obj as TextRange;
if (other == null)
{
return -1;
}
return this.Start.CompareTo(other.Start);
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
return CompareTo(obj) == 0;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static bool operator ==(TextRange range1, TextRange range2)
{
if ((object)range1 == null && (object)range2 == null)
{
return true;
}
if ((object)range1 == null || (object)range2 == null)
{
return false;
}
return range1.Equals(range2);
}
public static bool operator !=(TextRange range1, TextRange range2)
{
return !(range1 == range2);
}
public static bool operator <(TextRange range1, TextRange range2)
{
if ((object)range1 == null || (object)range2 == null)
{
return false;
}
return range1.CompareTo(range2) < 0;
}
public static bool operator >(TextRange range1, TextRange range2)
{
if ((object)range1 == null || (object)range2 == null)
{
return false;
}
return range1.CompareTo(range2) > 0;
}
}
}
| |
namespace Stripe
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Reflection;
using Newtonsoft.Json;
using Stripe.Infrastructure;
/// <summary>
/// Global configuration class for Stripe.net settings.
/// </summary>
public static class StripeConfiguration
{
private static string apiKey;
private static AppInfo appInfo;
private static string clientId;
private static bool enableTelemetry = true;
private static int maxNetworkRetries = SystemNetHttpClient.DefaultMaxNumberRetries;
private static IStripeClient stripeClient;
static StripeConfiguration()
{
StripeNetVersion = new AssemblyName(typeof(StripeConfiguration).GetTypeInfo().Assembly.FullName).Version.ToString(3);
}
/// <summary>API version used by Stripe.net.</summary>
public static string ApiVersion => "2020-08-27";
/// <summary>Gets or sets the API key.</summary>
/// <remarks>
/// You can also set the API key using the <c>StripeApiKey</c> key in
/// <see cref="System.Configuration.ConfigurationManager.AppSettings"/>.
/// </remarks>
public static string ApiKey
{
get
{
if (string.IsNullOrEmpty(apiKey) &&
!string.IsNullOrEmpty(ConfigurationManager.AppSettings["StripeApiKey"]))
{
apiKey = ConfigurationManager.AppSettings["StripeApiKey"];
}
return apiKey;
}
set
{
if (value != apiKey)
{
StripeClient = null;
}
apiKey = value;
}
}
/// <summary>Gets or sets the client ID.</summary>
/// <remarks>
/// You can also set the client ID using the <c>StripeClientId</c> key in
/// <see cref="System.Configuration.ConfigurationManager.AppSettings"/>.
/// </remarks>
public static string ClientId
{
get
{
if (string.IsNullOrEmpty(apiKey) &&
!string.IsNullOrEmpty(ConfigurationManager.AppSettings["StripeClientId"]))
{
clientId = ConfigurationManager.AppSettings["StripeClientId"];
}
return clientId;
}
set
{
if (value != clientId)
{
StripeClient = null;
}
clientId = value;
}
}
/// <summary>
/// Gets or sets the settings used for deserializing JSON objects returned by Stripe's API.
/// It is highly recommended you do not change these settings, as doing so can produce
/// unexpected results. If you do change these settings, make sure that
/// <see cref="Stripe.Infrastructure.StripeObjectConverter"/> is among the converters,
/// otherwise Stripe.net will no longer be able to deserialize polymorphic resources
/// represented by interfaces (e.g. <see cref="IPaymentSource"/>).
/// </summary>
public static JsonSerializerSettings SerializerSettings { get; set; } = DefaultSerializerSettings();
/// <summary>
/// Gets or sets the maximum number of times that the library will retry requests that
/// appear to have failed due to an intermittent problem.
/// </summary>
public static int MaxNetworkRetries
{
get => maxNetworkRetries;
set
{
if (value != maxNetworkRetries)
{
StripeClient = null;
}
maxNetworkRetries = value;
}
}
/// <summary>
/// Gets or sets the flag enabling request latency telemetry. Enabled by default.
/// </summary>
public static bool EnableTelemetry
{
get => enableTelemetry;
set
{
if (value != enableTelemetry)
{
StripeClient = null;
}
enableTelemetry = value;
}
}
/// <summary>
/// Gets or sets a custom <see cref="StripeClient"/> for sending requests to Stripe's
/// API. You can use this to use a custom message handler, set proxy parameters, etc.
/// </summary>
/// <example>
/// To use a custom message handler:
/// <code>
/// System.Net.Http.HttpMessageHandler messageHandler = ...;
/// var httpClient = new System.Net.HttpClient(messageHandler);
/// var stripeClient = new Stripe.StripeClient(
/// stripeApiKey,
/// httpClient: new Stripe.SystemNetHttpClient(httpClient));
/// Stripe.StripeConfiguration.StripeClient = stripeClient;
/// </code>
/// </example>
public static IStripeClient StripeClient
{
get
{
if (stripeClient == null)
{
stripeClient = BuildDefaultStripeClient();
}
return stripeClient;
}
set => stripeClient = value;
}
/// <summary>Gets the version of the Stripe.net client library.</summary>
public static string StripeNetVersion { get; }
/// <summary>
/// Sets information about the "app" which this integration belongs to. This should be
/// reserved for plugins that wish to identify themselves with Stripe.
/// </summary>
public static AppInfo AppInfo
{
internal get => appInfo;
set
{
if ((value != null) && string.IsNullOrEmpty(value.Name))
{
throw new ArgumentException("AppInfo.Name cannot be empty");
}
if (value != appInfo)
{
StripeClient = null;
}
appInfo = value;
}
}
/// <summary>
/// Returns a new instance of <see cref="Newtonsoft.Json.JsonSerializerSettings"/> with
/// the default settings used by Stripe.net.
/// </summary>
/// <returns>A <see cref="Newtonsoft.Json.JsonSerializerSettings"/> instance.</returns>
public static JsonSerializerSettings DefaultSerializerSettings()
{
return new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new StripeObjectConverter(),
},
DateParseHandling = DateParseHandling.None,
};
}
/// <summary>
/// Sets the API key.
/// This method is deprecated and will be removed in a future version, please use the
/// <see cref="ApiKey"/> property setter instead.
/// </summary>
/// <param name="newApiKey">API key.</param>
// TODO; remove this method in a future major version
[Obsolete("Use StripeConfiguration.ApiKey setter instead.")]
public static void SetApiKey(string newApiKey)
{
ApiKey = newApiKey;
}
private static StripeClient BuildDefaultStripeClient()
{
if (ApiKey != null && ApiKey.Length == 0)
{
var message = "Your API key is invalid, as it is an empty string. You can "
+ "double-check your API key from the Stripe Dashboard. See "
+ "https://stripe.com/docs/api/authentication for details or contact support "
+ "at https://support.stripe.com/email if you have any questions.";
throw new StripeException(message);
}
if (ApiKey != null && StringUtils.ContainsWhitespace(ApiKey))
{
var message = "Your API key is invalid, as it contains whitespace. You can "
+ "double-check your API key from the Stripe Dashboard. See "
+ "https://stripe.com/docs/api/authentication for details or contact support "
+ "at https://support.stripe.com/email if you have any questions.";
throw new StripeException(message);
}
var httpClient = new SystemNetHttpClient(
httpClient: null,
maxNetworkRetries: MaxNetworkRetries,
appInfo: AppInfo,
enableTelemetry: EnableTelemetry);
return new StripeClient(ApiKey, ClientId, httpClient: httpClient);
}
}
}
| |
//RealtimeReflections for Daggerfall-Unity
//http://www.reddit.com/r/dftfu
//http://www.dfworkshop.net/
//Author: Michael Rauter (a.k.a. Nystul)
//License: MIT License (http://www.opensource.org/licenses/mit-license.php)
using System;
using UnityEngine;
using UnityEngine.Rendering;
using DaggerfallWorkshop.Game;
using RealtimeReflections;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace RealtimeReflections
{
[ExecuteInEditMode]
#if UNITY_5_4_OR_NEWER
[ImageEffectAllowedInSceneView]
#endif
public static class ImageEffectHelper
{
public static bool IsSupported(Shader s, bool needDepth, bool needHdr, MonoBehaviour effect)
{
#if UNITY_EDITOR
// Don't check for shader compatibility while it's building as it would disable most effects
// on build farms without good-enough gaming hardware.
if (!BuildPipeline.isBuildingPlayer)
{
#endif
if (s == null || !s.isSupported)
{
Debug.LogWarningFormat("Missing shader for image effect {0}", effect);
return false;
}
if (needDepth && !SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.Depth))
{
Debug.LogWarningFormat("Depth textures aren't supported on this device ({0})", effect);
return false;
}
if (needHdr && !SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf))
{
Debug.LogWarningFormat("Floating point textures aren't supported on this device ({0})", effect);
return false;
}
#if UNITY_EDITOR
}
#endif
return true;
}
public static Material CheckShaderAndCreateMaterial(Shader s)
{
//if (s == null || !s.isSupported)
// return null;
var material = new Material(s);
material.hideFlags = HideFlags.DontSave;
return material;
}
public static bool supportsDX11
{
get { return SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders; }
}
}
[RequireComponent(typeof(Camera))]
public class DeferredPlanarReflections : MonoBehaviour
{
///////////// Unexposed Variables //////////////////
[SerializeField]
private Shader m_Shader;
public Shader shader
{
get
{
if (m_Shader == null)
m_Shader = componentUpdateReflectionTextures.ShaderDeferredPlanarReflections;
return m_Shader;
}
}
private Material m_Material;
public Material material
{
get
{
if (m_Material == null)
m_Material = RealtimeReflections.ImageEffectHelper.CheckShaderAndCreateMaterial(shader);
return m_Material;
}
}
private Camera m_Camera;
public Camera camera_
{
get
{
if (m_Camera == null)
m_Camera = GetComponent<Camera>();
return m_Camera;
}
}
private CommandBuffer m_CommandBuffer;
private bool AddedCommandBuffer = false;
private static int kFinalReflectionTexture;
private static int kTempTexture;
private UpdateReflectionTextures componentUpdateReflectionTextures = null;
public RenderTexture reflectionGroundTexture;
public RenderTexture reflectionLowerLevelTexture;
CreateReflectionLookupTextures componentCreateReflectionLookupTextures = null;
GameObject goCreateReflectionLookupTextures = null;
// Shader pass indices used by the effect
private struct PassIndex
{
public const int
ReflectionStep = 0,
CompositeFinal = 1;
}
private void OnEnable()
{
//if (!RealtimeReflections.ImageEffectHelper.IsSupported(shader, false, true, this))
//{
// enabled = false;
// return;
//}
camera_.depthTextureMode |= DepthTextureMode.Depth;
kFinalReflectionTexture = Shader.PropertyToID("_FinalReflectionTexture");
kTempTexture = Shader.PropertyToID("_TempTexture");
GameObject goRealtimeReflections = GameObject.Find("RealtimeReflections");
componentUpdateReflectionTextures = goRealtimeReflections.GetComponent<UpdateReflectionTextures>();
goCreateReflectionLookupTextures = new GameObject("CreateReflectionLookupTextures");
goCreateReflectionLookupTextures.transform.SetParent(goRealtimeReflections.transform);
componentCreateReflectionLookupTextures = goCreateReflectionLookupTextures.AddComponent<CreateReflectionLookupTextures>();
}
void OnDisable()
{
if (componentCreateReflectionLookupTextures != null)
{
Destroy(componentCreateReflectionLookupTextures);
}
if (goCreateReflectionLookupTextures != null)
{
Destroy(goCreateReflectionLookupTextures);
}
if (m_Material)
DestroyImmediate(m_Material);
m_Material = null;
if (camera_ != null)
{
if (m_CommandBuffer != null)
{
camera_.RemoveCommandBuffer(CameraEvent.AfterReflections, m_CommandBuffer);
}
m_CommandBuffer = null;
}
}
#if UNITY_EDITOR
void OnValidate()
{
if (camera_ != null)
{
if (m_CommandBuffer != null)
{
camera_.RemoveCommandBuffer(CameraEvent.AfterReflections, m_CommandBuffer);
}
m_CommandBuffer = null;
}
}
#endif
//public void Update()
//{
// componentCreateReflectionLookupTextures.createReflectionTextureCoordinatesAndIndexTextures();
//}
public void OnPreRender()
{
if (material == null)
{
return;
}
else if (Camera.current.actualRenderingPath != RenderingPath.DeferredShading)
{
return;
}
componentCreateReflectionLookupTextures.createReflectionTextureCoordinatesAndIndexTextures();
int downsampleAmount = 1; // 2;
var rtW = camera_.pixelWidth / downsampleAmount;
var rtH = camera_.pixelHeight / downsampleAmount;
float sWidth = camera_.pixelWidth;
float sHeight = camera_.pixelHeight;
Matrix4x4 P = GetComponent<Camera>().projectionMatrix;
Vector4 projInfo = new Vector4
((-2.0f / (sWidth * P[0])),
(-2.0f / (sHeight * P[5])),
((1.0f - P[2]) / P[0]),
((1.0f + P[6]) / P[5]));
RenderTextureFormat intermediateFormat = camera_.allowHDR ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;
Matrix4x4 cameraToWorldMatrix = GetComponent<Camera>().worldToCameraMatrix.inverse;
material.SetVector("_ProjInfo", projInfo); // used for unprojection
material.SetMatrix("_CameraToWorldMatrix", cameraToWorldMatrix);
material.SetMatrix("_InverseViewProject", (GetComponent<Camera>().projectionMatrix * GetComponent<Camera>().worldToCameraMatrix).inverse);
reflectionGroundTexture = componentUpdateReflectionTextures.getGroundReflectionRenderTexture();
reflectionLowerLevelTexture = componentUpdateReflectionTextures.getSeaReflectionRenderTexture();
material.SetTexture("_ReflectionGroundTex", reflectionGroundTexture);
material.SetTexture("_ReflectionLowerLevelTex", reflectionLowerLevelTexture);
material.SetTexture("_ReflectionsTextureIndexTex", componentCreateReflectionLookupTextures.renderTextureReflectionTextureIndex);
material.SetTexture("_ReflectionsTextureCoordinatesTex", componentCreateReflectionLookupTextures.renderTextureReflectionTextureCoordinates);
material.SetFloat("_GroundLevelHeight", componentUpdateReflectionTextures.ReflectionPlaneGroundLevelY); // + GameManager.Instance.MainCamera.transform.localPosition.y);
material.SetFloat("_LowerLevelHeight", componentUpdateReflectionTextures.ReflectionPlaneLowerLevelY); // + GameManager.Instance.MainCamera.transform.localPosition.y);
//material.SetFloat("_CameraHeightFromGround", GameManager.Instance.MainCamera.transform.localPosition.y);
if ((componentUpdateReflectionTextures.IsEnabledOutdoorGroundReflections && componentUpdateReflectionTextures.CurrentPlayerEnvironment == UpdateReflectionTextures.PlayerEnvironment.Outdoors) ||
(componentUpdateReflectionTextures.IsEnabledIndoorBuildingFloorReflections && componentUpdateReflectionTextures.CurrentPlayerEnvironment == UpdateReflectionTextures.PlayerEnvironment.Building) ||
(componentUpdateReflectionTextures.IsEnabledDungeonGroundReflections && componentUpdateReflectionTextures.CurrentPlayerEnvironment == UpdateReflectionTextures.PlayerEnvironment.DungeonOrCastle))
{
material.EnableKeyword("_GROUND_LEVEL_REFLECTIONS");
}
else
{
material.DisableKeyword("_GROUND_LEVEL_REFLECTIONS");
}
if ((componentUpdateReflectionTextures.IsEnabledOutdoorSeaReflections && componentUpdateReflectionTextures.CurrentPlayerEnvironment == UpdateReflectionTextures.PlayerEnvironment.Outdoors) ||
(componentUpdateReflectionTextures.IsEnabledIndoorBuildingLowerLevelReflection && componentUpdateReflectionTextures.CurrentPlayerEnvironment == UpdateReflectionTextures.PlayerEnvironment.Building) ||
(componentUpdateReflectionTextures.IsEnabledDungeonWaterReflections && componentUpdateReflectionTextures.CurrentPlayerEnvironment == UpdateReflectionTextures.PlayerEnvironment.DungeonOrCastle))
{
material.EnableKeyword("_LOWER_LEVEL_REFLECTIONS");
}
else
{
material.DisableKeyword("_LOWER_LEVEL_REFLECTIONS");
}
if (componentUpdateReflectionTextures.IsFeatureEnabledFakeParallaxReflections && componentUpdateReflectionTextures.CurrentPlayerEnvironment == UpdateReflectionTextures.PlayerEnvironment.Outdoors)
{
material.EnableKeyword("_PARALLAX_REFLECTIONS");
}
else
{
material.DisableKeyword("_PARALLAX_REFLECTIONS");
}
int minDimValue = Math.Min(componentUpdateReflectionTextures.FloorReflectionTextureWidth, componentUpdateReflectionTextures.FloorReflectionTextureHeight);
int numMipMapLevels = (int)(Math.Log(minDimValue) / Math.Log(2));
material.SetInt("_NumMipMapLevelsReflectionGroundTex", numMipMapLevels);
minDimValue = Math.Min(componentUpdateReflectionTextures.LowerLevelReflectionTextureWidth, componentUpdateReflectionTextures.LowerLevelReflectionTextureHeight);
numMipMapLevels = (int)(Math.Log(minDimValue) / Math.Log(2));
material.SetInt("_NumMipMapLevelsReflectionLowerLevelTex", numMipMapLevels);
material.SetFloat("_RoughnessMultiplier", componentUpdateReflectionTextures.RoughnessMultiplier);
if (m_CommandBuffer == null)
{
m_CommandBuffer = new CommandBuffer();
m_CommandBuffer.name = "Deferred Planar Reflections";
m_CommandBuffer.GetTemporaryRT(kFinalReflectionTexture, rtW, rtH, 0, FilterMode.Point, intermediateFormat);
m_CommandBuffer.GetTemporaryRT(kTempTexture, camera_.pixelWidth, camera_.pixelHeight, 0, FilterMode.Bilinear, intermediateFormat);
m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kFinalReflectionTexture, material, (int)PassIndex.ReflectionStep);
m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kTempTexture, material, (int)PassIndex.CompositeFinal);
m_CommandBuffer.Blit(kTempTexture, BuiltinRenderTextureType.CameraTarget);
m_CommandBuffer.ReleaseTemporaryRT(kTempTexture);
camera_.AddCommandBuffer(CameraEvent.AfterFinalPass, m_CommandBuffer);
AddedCommandBuffer = true;
}
}
public void AddCommandBuffer()
{
if (m_CommandBuffer == null)
return;
if (!AddedCommandBuffer)
camera_.AddCommandBuffer(CameraEvent.AfterFinalPass, m_CommandBuffer);
AddedCommandBuffer = true;
}
public void RemoveCommandBuffer()
{
if (m_CommandBuffer == null)
return;
if (AddedCommandBuffer)
camera_.RemoveCommandBuffer(CameraEvent.AfterFinalPass, m_CommandBuffer);
AddedCommandBuffer = false;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.