context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers.Text;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Globalization
{
internal static class TimeSpanFormat
{
private static unsafe void AppendNonNegativeInt32(StringBuilder sb, int n, int digits)
{
Debug.Assert(n >= 0);
uint value = (uint)n;
const int MaxUInt32Digits = 10;
char* buffer = stackalloc char[MaxUInt32Digits];
int index = 0;
do
{
uint div = value / 10;
buffer[index++] = (char)(value - (div * 10) + '0');
value = div;
}
while (value != 0);
Debug.Assert(index <= MaxUInt32Digits);
for (int i = digits - index; i > 0; --i) sb.Append('0');
for (int i = index - 1; i >= 0; --i) sb.Append(buffer[i]);
}
internal static readonly FormatLiterals PositiveInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: false);
internal static readonly FormatLiterals NegativeInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: true);
/// <summary>Main method called from TimeSpan.ToString.</summary>
internal static string Format(TimeSpan value, string format, IFormatProvider formatProvider)
{
if (string.IsNullOrEmpty(format))
{
return FormatC(value); // formatProvider ignored, as "c" is invariant
}
if (format.Length == 1)
{
char c = format[0];
if (c == 'c' || (c | 0x20) == 't') // special-case to optimize the default TimeSpan format
{
return FormatC(value); // formatProvider ignored, as "c" is invariant
}
if ((c | 0x20) == 'g') // special-case to optimize the remaining 'g'/'G' standard formats
{
return FormatG(value, DateTimeFormatInfo.GetInstance(formatProvider), c == 'G' ? StandardFormat.G : StandardFormat.g);
}
throw new FormatException(SR.Format_InvalidString);
}
return StringBuilderCache.GetStringAndRelease(FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider), result: null));
}
/// <summary>Main method called from TimeSpan.TryFormat.</summary>
internal static bool TryFormat(TimeSpan value, Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider formatProvider)
{
if (format.Length == 0)
{
return TryFormatStandard(value, StandardFormat.C, null, destination, out charsWritten);
}
if (format.Length == 1)
{
char c = format[0];
if (c == 'c' || ((c | 0x20) == 't'))
{
return TryFormatStandard(value, StandardFormat.C, null, destination, out charsWritten);
}
else
{
StandardFormat sf =
c == 'g' ? StandardFormat.g :
c == 'G' ? StandardFormat.G :
throw new FormatException(SR.Format_InvalidString);
return TryFormatStandard(value, sf, DateTimeFormatInfo.GetInstance(formatProvider).DecimalSeparator, destination, out charsWritten);
}
}
StringBuilder sb = FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider), result: null);
if (sb.Length <= destination.Length)
{
sb.CopyTo(0, destination, sb.Length);
charsWritten = sb.Length;
StringBuilderCache.Release(sb);
return true;
}
charsWritten = 0;
StringBuilderCache.Release(sb);
return false;
}
internal static string FormatC(TimeSpan value)
{
Span<char> destination = stackalloc char[26]; // large enough for any "c" TimeSpan
TryFormatStandard(value, StandardFormat.C, null, destination, out int charsWritten);
return new string(destination.Slice(0, charsWritten));
}
private static string FormatG(TimeSpan value, DateTimeFormatInfo dtfi, StandardFormat format)
{
string decimalSeparator = dtfi.DecimalSeparator;
int maxLength = 25 + decimalSeparator.Length; // large enough for any "g"/"G" TimeSpan
Span<char> destination = maxLength < 128 ?
stackalloc char[maxLength] :
new char[maxLength]; // the chances of needing this case are almost 0, as DecimalSeparator.Length will basically always == 1
TryFormatStandard(value, format, decimalSeparator, destination, out int charsWritten);
return new string(destination.Slice(0, charsWritten));
}
private enum StandardFormat { C, G, g }
private static bool TryFormatStandard(TimeSpan value, StandardFormat format, string decimalSeparator, Span<char> destination, out int charsWritten)
{
Debug.Assert(format == StandardFormat.C || format == StandardFormat.G || format == StandardFormat.g);
// First, calculate how large an output buffer is needed to hold the entire output.
int requiredOutputLength = 8; // start with "hh:mm:ss" and adjust as necessary
uint fraction;
ulong totalSecondsRemaining;
{
// Turn this into a non-negative TimeSpan if possible.
long ticks = value.Ticks;
if (ticks < 0)
{
requiredOutputLength = 9; // requiredOutputLength + 1 for the leading '-' sign
ticks = -ticks;
if (ticks < 0)
{
Debug.Assert(ticks == long.MinValue /* -9223372036854775808 */);
// We computed these ahead of time; they're straight from the decimal representation of Int64.MinValue.
fraction = 4775808;
totalSecondsRemaining = 922337203685;
goto AfterComputeFraction;
}
}
totalSecondsRemaining = Math.DivRem((ulong)ticks, TimeSpan.TicksPerSecond, out ulong fraction64);
fraction = (uint)fraction64;
}
AfterComputeFraction:
// Only write out the fraction if it's non-zero, and in that
// case write out the entire fraction (all digits).
Debug.Assert(fraction < 10_000_000);
int fractionDigits = 0;
switch (format)
{
case StandardFormat.C:
// "c": Write out a fraction only if it's non-zero, and write out all 7 digits of it.
if (fraction != 0)
{
fractionDigits = DateTimeFormat.MaxSecondsFractionDigits;
requiredOutputLength += fractionDigits + 1; // digits plus leading decimal separator
}
break;
case StandardFormat.G:
// "G": Write out a fraction regardless of whether it's 0, and write out all 7 digits of it.
fractionDigits = DateTimeFormat.MaxSecondsFractionDigits;
requiredOutputLength += fractionDigits + 1; // digits plus leading decimal separator
break;
default:
// "g": Write out a fraction only if it's non-zero, and write out only the most significant digits.
Debug.Assert(format == StandardFormat.g);
if (fraction != 0)
{
fractionDigits = DateTimeFormat.MaxSecondsFractionDigits - FormattingHelpers.CountDecimalTrailingZeros(fraction, out fraction);
requiredOutputLength += fractionDigits + 1; // digits plus leading decimal separator
}
break;
}
ulong totalMinutesRemaining = 0, seconds = 0;
if (totalSecondsRemaining > 0)
{
// Only compute minutes if the TimeSpan has an absolute value of >= 1 minute.
totalMinutesRemaining = Math.DivRem(totalSecondsRemaining, 60 /* seconds per minute */, out seconds);
Debug.Assert(seconds < 60);
}
ulong totalHoursRemaining = 0, minutes = 0;
if (totalMinutesRemaining > 0)
{
// Only compute hours if the TimeSpan has an absolute value of >= 1 hour.
totalHoursRemaining = Math.DivRem(totalMinutesRemaining, 60 /* minutes per hour */, out minutes);
Debug.Assert(minutes < 60);
}
// At this point, we can switch over to 32-bit DivRem since the data has shrunk far enough.
Debug.Assert(totalHoursRemaining <= uint.MaxValue);
uint days = 0, hours = 0;
if (totalHoursRemaining > 0)
{
// Only compute days if the TimeSpan has an absolute value of >= 1 day.
days = Math.DivRem((uint)totalHoursRemaining, 24 /* hours per day */, out hours);
Debug.Assert(hours < 24);
}
int hourDigits = 2;
if (format == StandardFormat.g && hours < 10)
{
// "g": Only writing a one-digit hour, rather than expected two-digit hour
hourDigits = 1;
requiredOutputLength--;
}
int dayDigits = 0;
if (days > 0)
{
dayDigits = FormattingHelpers.CountDigits(days);
Debug.Assert(dayDigits <= 8);
requiredOutputLength += dayDigits + 1; // for the leading "d."
}
else if (format == StandardFormat.G)
{
// "G": has a leading "0:" if days is 0
requiredOutputLength += 2;
dayDigits = 1;
}
if (destination.Length < requiredOutputLength)
{
charsWritten = 0;
return false;
}
// Write leading '-' if necessary
int idx = 0;
if (value.Ticks < 0)
{
destination[idx++] = '-';
}
// Write day and separator, if necessary
if (dayDigits != 0)
{
WriteDigits(days, destination.Slice(idx, dayDigits));
idx += dayDigits;
destination[idx++] = format == StandardFormat.C ? '.' : ':';
}
// Write "[h]h:mm:ss
Debug.Assert(hourDigits == 1 || hourDigits == 2);
if (hourDigits == 2)
{
WriteTwoDigits(hours, destination.Slice(idx));
idx += 2;
}
else
{
destination[idx++] = (char)('0' + hours);
}
destination[idx++] = ':';
WriteTwoDigits((uint)minutes, destination.Slice(idx));
idx += 2;
destination[idx++] = ':';
WriteTwoDigits((uint)seconds, destination.Slice(idx));
idx += 2;
// Write fraction and separator, if necessary
if (fractionDigits != 0)
{
if (format == StandardFormat.C)
{
destination[idx++] = '.';
}
else if (decimalSeparator.Length == 1)
{
destination[idx++] = decimalSeparator[0];
}
else
{
decimalSeparator.AsSpan().CopyTo(destination);
idx += decimalSeparator.Length;
}
WriteDigits(fraction, destination.Slice(idx, fractionDigits));
idx += fractionDigits;
}
Debug.Assert(idx == requiredOutputLength);
charsWritten = requiredOutputLength;
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void WriteTwoDigits(uint value, Span<char> buffer)
{
Debug.Assert(buffer.Length >= 2);
uint temp = '0' + value;
value /= 10;
buffer[1] = (char)(temp - (value * 10));
buffer[0] = (char)('0' + value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void WriteDigits(uint value, Span<char> buffer)
{
Debug.Assert(buffer.Length > 0);
for (int i = buffer.Length - 1; i >= 1; i--)
{
uint temp = '0' + value;
value /= 10;
buffer[i] = (char)(temp - (value * 10));
}
Debug.Assert(value < 10);
buffer[0] = (char)('0' + value);
}
/// <summary>Format the TimeSpan instance using the specified format.</summary>
private static StringBuilder FormatCustomized(TimeSpan value, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, StringBuilder result = null)
{
Debug.Assert(dtfi != null);
bool resultBuilderIsPooled = false;
if (result == null)
{
result = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity);
resultBuilderIsPooled = true;
}
int day = (int)(value.Ticks / TimeSpan.TicksPerDay);
long time = value.Ticks % TimeSpan.TicksPerDay;
if (value.Ticks < 0)
{
day = -day;
time = -time;
}
int hours = (int)(time / TimeSpan.TicksPerHour % 24);
int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
int fraction = (int)(time % TimeSpan.TicksPerSecond);
long tmp = 0;
int i = 0;
int tokenLen;
while (i < format.Length)
{
char ch = format[i];
int nextChar;
switch (ch)
{
case 'h':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
{
goto default; // to release the builder and throw
}
DateTimeFormat.FormatDigits(result, hours, tokenLen);
break;
case 'm':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
{
goto default; // to release the builder and throw
}
DateTimeFormat.FormatDigits(result, minutes, tokenLen);
break;
case 's':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
{
goto default; // to release the builder and throw
}
DateTimeFormat.FormatDigits(result, seconds, tokenLen);
break;
case 'f':
//
// The fraction of a second in single-digit precision. The remaining digits are truncated.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
{
goto default; // to release the builder and throw
}
tmp = fraction;
tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
break;
case 'F':
//
// Displays the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
{
goto default; // to release the builder and throw
}
tmp = fraction;
tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
int effectiveDigits = tokenLen;
while (effectiveDigits > 0)
{
if (tmp % 10 == 0)
{
tmp = tmp / 10;
effectiveDigits--;
}
else
{
break;
}
}
if (effectiveDigits > 0)
{
result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
break;
case 'd':
//
// tokenLen == 1 : Day as digits with no leading zero.
// tokenLen == 2+: Day as digits with leading zero for single-digit days.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 8)
{
goto default; // to release the builder and throw
}
DateTimeFormat.FormatDigits(result, day, tokenLen, true);
break;
case '\'':
case '\"':
tokenLen = DateTimeFormat.ParseQuoteString(format, i, result);
break;
case '%':
// Optional format character.
// For example, format string "%d" will print day
// Most of the cases, "%" can be ignored.
nextChar = DateTimeFormat.ParseNextChar(format, i);
// nextChar will be -1 if we already reach the end of the format string.
// Besides, we will not allow "%%" appear in the pattern.
if (nextChar >= 0 && nextChar != (int)'%')
{
char nextCharChar = (char)nextChar;
StringBuilder origStringBuilder = FormatCustomized(value, MemoryMarshal.CreateReadOnlySpan<char>(ref nextCharChar, 1), dtfi, result);
Debug.Assert(ReferenceEquals(origStringBuilder, result));
tokenLen = 2;
}
else
{
//
// This means that '%' is at the end of the format string or
// "%%" appears in the format string.
//
goto default; // to release the builder and throw
}
break;
case '\\':
// Escaped character. Can be used to insert character into the format string.
// For example, "\d" will insert the character 'd' into the string.
//
nextChar = DateTimeFormat.ParseNextChar(format, i);
if (nextChar >= 0)
{
result.Append(((char)nextChar));
tokenLen = 2;
}
else
{
//
// This means that '\' is at the end of the formatting string.
//
goto default; // to release the builder and throw
}
break;
default:
// Invalid format string
if (resultBuilderIsPooled)
{
StringBuilderCache.Release(result);
}
throw new FormatException(SR.Format_InvalidString);
}
i += tokenLen;
}
return result;
}
internal struct FormatLiterals
{
internal string AppCompatLiteral;
internal int dd;
internal int hh;
internal int mm;
internal int ss;
internal int ff;
private string[] _literals;
internal string Start => _literals[0];
internal string DayHourSep => _literals[1];
internal string HourMinuteSep => _literals[2];
internal string MinuteSecondSep => _literals[3];
internal string SecondFractionSep => _literals[4];
internal string End => _literals[5];
/* factory method for static invariant FormatLiterals */
internal static FormatLiterals InitInvariant(bool isNegative)
{
FormatLiterals x = new FormatLiterals();
x._literals = new string[6];
x._literals[0] = isNegative ? "-" : string.Empty;
x._literals[1] = ".";
x._literals[2] = ":";
x._literals[3] = ":";
x._literals[4] = ".";
x._literals[5] = string.Empty;
x.AppCompatLiteral = ":."; // MinuteSecondSep+SecondFractionSep;
x.dd = 2;
x.hh = 2;
x.mm = 2;
x.ss = 2;
x.ff = DateTimeFormat.MaxSecondsFractionDigits;
return x;
}
// For the "v1" TimeSpan localized patterns, the data is simply literal field separators with
// the constants guaranteed to include DHMSF ordered greatest to least significant.
// Once the data becomes more complex than this we will need to write a proper tokenizer for
// parsing and formatting
internal void Init(ReadOnlySpan<char> format, bool useInvariantFieldLengths)
{
dd = hh = mm = ss = ff = 0;
_literals = new string[6];
for (int i = 0; i < _literals.Length; i++)
{
_literals[i] = string.Empty;
}
StringBuilder sb = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity);
bool inQuote = false;
char quote = '\'';
int field = 0;
for (int i = 0; i < format.Length; i++)
{
switch (format[i])
{
case '\'':
case '\"':
if (inQuote && (quote == format[i]))
{
/* we were in a quote and found a matching exit quote, so we are outside a quote now */
if (field >= 0 && field <= 5)
{
_literals[field] = sb.ToString();
sb.Length = 0;
inQuote = false;
}
else
{
Debug.Fail($"Unexpected field value: {field}");
return; // how did we get here?
}
}
else if (!inQuote)
{
/* we are at the start of a new quote block */
quote = format[i];
inQuote = true;
}
else
{
/* we were in a quote and saw the other type of quote character, so we are still in a quote */
}
break;
case '%':
Debug.Fail("Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
goto default;
case '\\':
if (!inQuote)
{
i++; /* skip next character that is escaped by this backslash or percent sign */
break;
}
goto default;
case 'd':
if (!inQuote)
{
Debug.Assert((field == 0 && sb.Length == 0) || field == 1, "field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 1; // DayHourSep
dd++;
}
break;
case 'h':
if (!inQuote)
{
Debug.Assert((field == 1 && sb.Length == 0) || field == 2, "field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 2; // HourMinuteSep
hh++;
}
break;
case 'm':
if (!inQuote)
{
Debug.Assert((field == 2 && sb.Length == 0) || field == 3, "field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 3; // MinuteSecondSep
mm++;
}
break;
case 's':
if (!inQuote)
{
Debug.Assert((field == 3 && sb.Length == 0) || field == 4, "field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 4; // SecondFractionSep
ss++;
}
break;
case 'f':
case 'F':
if (!inQuote)
{
Debug.Assert((field == 4 && sb.Length == 0) || field == 5, "field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 5; // End
ff++;
}
break;
default:
sb.Append(format[i]);
break;
}
}
Debug.Assert(field == 5);
AppCompatLiteral = MinuteSecondSep + SecondFractionSep;
Debug.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
if (useInvariantFieldLengths)
{
dd = 2;
hh = 2;
mm = 2;
ss = 2;
ff = DateTimeFormat.MaxSecondsFractionDigits;
}
else
{
if (dd < 1 || dd > 2) dd = 2; // The DTFI property has a problem. let's try to make the best of the situation.
if (hh < 1 || hh > 2) hh = 2;
if (mm < 1 || mm > 2) mm = 2;
if (ss < 1 || ss > 2) ss = 2;
if (ff < 1 || ff > 7) ff = 7;
}
StringBuilderCache.Release(sb);
}
}
}
}
| |
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using GroupDocs.Annotation;
using GroupDocs.Annotation.Domain;
using GroupDocs.Annotation.Exception;
using GroupDocs.Annotation.Handler;
using GroupDocs.Annotation.Handler.Input.DataObjects;
using GroupDocs.Demo.Annotation.Mvc.App_Start;
using GroupDocs.Demo.Annotation.Mvc.Options;
using GroupDocs.Demo.Annotation.Mvc.Responses;
using Microsoft.Practices.Unity;
using AnnotationReplyInfo = GroupDocs.Demo.Annotation.Mvc.AnnotationResults.Data.AnnotationReplyInfo;
using DeleteReplyResult = GroupDocs.Demo.Annotation.Mvc.AnnotationResults.DeleteReplyResult;
using Point = GroupDocs.Demo.Annotation.Mvc.AnnotationResults.DataGeometry.Point;
using Rectangle = GroupDocs.Demo.Annotation.Mvc.AnnotationResults.DataGeometry.Rectangle;
using RestoreRepliesResult = GroupDocs.Demo.Annotation.Mvc.AnnotationResults.RestoreRepliesResult;
namespace GroupDocs.Demo.Annotation.Mvc.Controllers
{
public class AnnotationController : Controller
{
#region Fields
private readonly EmbeddedResourceManager _resourceManager;
private readonly IAnnotationService _annotationSvc;
#endregion Fields
public AnnotationController(IAnnotationService annotationSvc)
{
_resourceManager = new EmbeddedResourceManager();
_annotationSvc = annotationSvc;
//Here you should apply proper GroupDocs.Annotation license (in case you want to
//use this sample without trial limits)
new License().SetLicense("D:/lic/GroupDocs.Total.lic");
}
#region Annotation members
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult CreateAnnotation(string connectionId, string userId, string privateKey,
string fileId, byte type, string message, Rectangle rectangle, int pageNumber, Point annotationPosition, string svgPath,
DrawingOptions drawingOptions, FontOptions font, string callback = null)
{
try
{
var result = _annotationSvc.CreateAnnotation(connectionId, fileId, type, message, rectangle, pageNumber, annotationPosition, svgPath, drawingOptions, font);
return this.JsonOrJsonP(result, callback);
}
catch(AnnotatorException e)
{
return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult DeleteAnnotation(string connectionId, string userId, string privateKey, string fileId, string annotationGuid, string callback = null)
{
try
{
var result = _annotationSvc.DeleteAnnotation(connectionId, fileId, annotationGuid);
return this.JsonOrJsonP(result, callback);
}
catch(AnnotatorException e)
{
return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult AddAnnotationReply(string connectionId, string userId, string privateKey, string fileId, string annotationGuid, string message, string parentReplyGuid, string callback = null)
{
try
{
var result = _annotationSvc.AddAnnotationReply(connectionId, fileId, annotationGuid, message, parentReplyGuid);
return this.JsonOrJsonP(result, callback);
}
catch(AnnotatorException e)
{
return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult DeleteAnnotationReply(string connectionId, string userId, string privateKey, string fileId, string annotationGuid, string replyGuid, string callback = null)
{
try
{
DeleteReplyResult result = _annotationSvc.DeleteAnnotationReply(connectionId, fileId, annotationGuid, replyGuid);
return this.JsonOrJsonP(result, callback);
}
catch(AnnotatorException e)
{
return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult EditAnnotationReply(string connectionId, string userId, string privateKey, string fileId, string annotationGuid, string replyGuid, string message, string callback = null)
{
try
{
var result = _annotationSvc.EditAnnotationReply(connectionId, fileId, annotationGuid, replyGuid, message);
return this.JsonOrJsonP(result, callback);
}
catch(AnnotatorException e)
{
return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult RestoreAnnotationReplies(string connectionId, string fileId, string annotationGuid, AnnotationReplyInfo[] replies, string callback = null)
{
try
{
var result = (replies == null || replies.Length == 0 ?
new RestoreRepliesResult { AnnotationGuid = annotationGuid, ReplyIds = new string[0] } :
_annotationSvc.RestoreAnnotationReplies(connectionId, fileId, annotationGuid, replies));
return this.JsonOrJsonP(result, callback);
}
catch(AnnotatorException e)
{
return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult ListAnnotations(string connectionId, string userId, string privateKey, string fileId, string callback = null)
{
try
{
var result = _annotationSvc.ListAnnotations(connectionId, fileId);
return this.JsonOrJsonP(result, callback);
}
catch(AnnotatorException e)
{
return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult ResizeAnnotation(string connectionId, string fileId, string annotationGuid, double width, double height, string callback = null)
{
try
{
var result = _annotationSvc.ResizeAnnotation(connectionId, fileId, annotationGuid, width, height);
return this.JsonOrJsonP(result, callback);
}
catch(AnnotatorException e)
{
return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult MoveAnnotationMarker(string connectionId, string userId, string privateKey, string fileId,
string annotationGuid, double left, double top, int? pageNumber, string callback = null)
{
try
{
var result = _annotationSvc.MoveAnnotationMarker(connectionId, fileId, annotationGuid, left, top, pageNumber);
return this.JsonOrJsonP(result, callback);
}
catch(AnnotatorException e)
{
return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult SaveTextField(string connectionId, string userId, string privateKey, string fileId,
string annotationGuid, string text, string fontFamily, double fontSize, string callback = null)
{
try
{
var result = _annotationSvc.SaveTextField(connectionId, fileId, annotationGuid, text, fontFamily, fontSize);
return this.JsonOrJsonP(result, callback);
}
catch(AnnotatorException e)
{
return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult SetTextFieldColor(string connectionId, string fileId, string annotationGuid, int fontColor, string callback = null)
{
try
{
var result = _annotationSvc.SetTextFieldColor(connectionId, fileId, annotationGuid, fontColor);
return this.JsonOrJsonP(new FailedResponse { success = true }, callback);
}
catch(AnnotatorException e)
{
return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult SetAnnotationBackgroundColor(string connectionId, string fileId, string annotationGuid, int color, string callback = null)
{
try
{
var result = _annotationSvc.SetAnnotationBackgroundColor(connectionId, fileId, annotationGuid, color);
return this.JsonOrJsonP(new FailedResponse { success = true }, callback);
}
catch(AnnotatorException e)
{
return this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult GetDocumentCollaborators(string userId, string privateKey, string fileId, string callback = null)
{
var result = _annotationSvc.GetCollaborators(fileId);
return this.JsonOrJsonP(result, callback);
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult AddDocumentReviewer(string userId, string privateKey,
string fileId, string reviewerEmail, string reviewerFirstName, string reviewerLastName, string reviewerInvitationMessage, string callback = null)
{
var result = _annotationSvc.AddCollaborator(fileId, reviewerEmail, reviewerFirstName, reviewerLastName, reviewerInvitationMessage);
return this.JsonOrJsonP(result, callback);
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult ExportAnnotations(string connectionId, string fileId, string format, string mode, string callback = null)
{
try
{
string fileName = _annotationSvc.ExportAnnotations(connectionId, fileId);
var url = Url.Action("DownloadFile", new
{
path = new HtmlString(fileName)
});
return this.JsonOrJsonP(new UrlResponse(url), callback);
}
catch(Exception e)
{
return this.JsonOrJsonP(new FailedResponse { success = false, Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult ImportAnnotations(string connectionId, string fileGuid, string callback = null)
{
try
{
_annotationSvc.ImportAnnotations(connectionId, fileGuid);
return this.JsonOrJsonP(new FileResponse(fileGuid), callback);
}
catch(Exception e)
{
return this.JsonOrJsonP(new FailedResponse { success = false, Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult GetPdfVersionOfDocument(string connectionId, string fileId, string callback = null)
{
try
{
var fileName = _annotationSvc.GetAsPdf(connectionId, fileId);
var url = this.Url.Action("DownloadFile", new
{
path = fileName
});
return this.JsonOrJsonP(new UrlResponse(url), callback);
}
catch(Exception e)
{
return this.JsonOrJsonP(new FailedResponse { success = false, Reason = e.Message }, callback);
}
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult DownloadFile(string path)
{
var filePath = AppDomain.CurrentDomain.GetData("DataDirectory") + "/" + path;
return File(filePath, "application/pdf", Path.GetFileName(path));
}
[AcceptVerbs("GET", "POST", "OPTIONS")]
public ActionResult UploadFile(string user_id, string fld, string fileName, bool? multiple = false, string callback = null)
{
var user = UnityConfig.GetConfiguredContainer().Resolve<AnnotationImageHandler>().GetUserDataHandler().GetUserByGuid(user_id) ??
new User();
try
{
var files = HttpContext.Request.Files;
var uploadDir = Path.Combine(Server.MapPath("~/App_Data"), fld);
var filePath = Path.Combine(uploadDir, fileName ?? files[0].FileName);
Directory.CreateDirectory(uploadDir);
using (var stream = System.IO.File.Create(filePath))
{
((multiple ?? false) ? HttpContext.Request.InputStream : files[0].InputStream).CopyTo(stream);
}
var fileId = Path.Combine(fld, fileName ?? files[0].FileName);
AnnotationImageHandler annotator = UnityConfig.GetConfiguredContainer().Resolve<AnnotationImageHandler>();
try
{
annotator.CreateDocument(fileId, DocumentType.Pdf, user.Id);
}
catch (AnnotatorException e)
{
if (annotator.RemoveDocument(fileId))
{
annotator.CreateDocument(fileId, DocumentType.Pdf, user.Id);
}
}
return this.JsonOrJsonP(new FileResponse(fileId), callback);
}
catch (Exception e)
{
return this.JsonOrJsonP(new FailedResponse {success = false, Reason = e.Message}, callback);
}
}
#endregion Annotation members
public ActionResult GetScript(string name)
{
string script = _resourceManager.GetScript(name);
return new JavaScriptResult { Script = script };
}
public ActionResult GetCss(string name)
{
string css = _resourceManager.GetCss(name);
return Content(css, "text/css");
}
public ActionResult GetEmbeddedImage(string name)
{
byte[] imageBody = _resourceManager.GetBinaryResource(name);
string mimeType = "image/png";
return File(imageBody, mimeType);
}
public ActionResult GetAvatar(string userId)
{
var collaborator = _annotationSvc.GetCollaboratorMetadata(userId);
if(collaborator == null || collaborator.Avatar == null)
{
return new EmptyResult();
}
const string mimeType = "image/png";
return File(collaborator.Avatar, mimeType);
}
}
}
| |
// $Id: List.java,v 1.6 2004/07/05 14:17:35 belaban Exp $
using System;
using Alachisoft.NCache.Runtime.Serialization.IO;
using Alachisoft.NCache.Runtime.Serialization;
namespace Alachisoft.NGroups.Util
{
/// <summary> Doubly-linked list. Elements can be added at head or tail and removed from head/tail.
/// This class is tuned for element access at either head or tail, random access to elements
/// is not very fast; in this case use Vector. Concurrent access is supported: a thread is blocked
/// while another thread adds/removes an object. When no objects are available, removal returns null.
/// </summary>
/// <author> Bela Ban
/// </author>
[Serializable]
internal class List : ICloneable, ICompactSerializable
{
public System.Collections.ArrayList Contents
{
get
{
System.Collections.ArrayList retval = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(_size));
Element el;
lock (mutex)
{
el = head;
while (el != null)
{
retval.Add(el.obj);
el = el.next;
}
}
return retval;
}
}
protected internal Element head = null, tail = null;
protected internal int _size = 0;
protected internal object mutex = new object();
[Serializable]
protected internal class Element
{
private void InitBlock(List enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private List enclosingInstance;
public List Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal object obj = null;
internal Element next = null;
internal Element prev = null;
internal Element(List enclosingInstance, object o)
{
InitBlock(enclosingInstance);
obj = o;
}
}
public List()
{
}
/// <summary>Adds an object at the tail of the list.</summary>
public virtual void add(object obj)
{
Element el = new Element(this, obj);
lock (mutex)
{
if (head == null)
{
head = el;
tail = head;
_size = 1;
}
else
{
el.prev = tail;
tail.next = el;
tail = el;
_size++;
}
}
}
/// <summary>Adds an object at the head of the list.</summary>
public virtual void addAtHead(object obj)
{
Element el = new Element(this, obj);
lock (mutex)
{
if (head == null)
{
head = el;
tail = head;
_size = 1;
}
else
{
el.next = head;
head.prev = el;
head = el;
_size++;
}
}
}
/// <summary>Removes an object from the tail of the list. Returns null if no elements available</summary>
public object remove()
{
Element retval = null;
lock (mutex)
{
if (tail == null)
return null;
retval = tail;
if (head == tail)
{
// last element
head = null;
tail = null;
}
else
{
tail.prev.next = null;
tail = tail.prev;
retval.prev = null;
}
_size--;
}
return retval.obj;
}
/// <summary>Removes an object from the head of the list. Returns null if no elements available </summary>
public object removeFromHead()
{
Element retval = null;
lock (mutex)
{
if (head == null)
return null;
retval = head;
if (head == tail)
{
// last element
head = null;
tail = null;
}
else
{
head = head.next;
head.prev = null;
retval.next = null;
}
_size--;
}
return retval.obj;
}
/// <summary>Returns element at the tail (if present), but does not remove it from list.</summary>
public object peek()
{
lock (mutex)
{
return tail != null?tail.obj:null;
}
}
/// <summary>Returns element at the head (if present), but does not remove it from list.</summary>
public object peekAtHead()
{
lock (mutex)
{
return head != null?head.obj:null;
}
}
/// <summary>Removes element <code>obj</code> from the list, checking for equality using the <code>equals</code>
/// operator. Only the first duplicate object is removed. Returns the removed object.
/// </summary>
public object removeElement(object obj)
{
Element el = null;
object retval = null;
lock (mutex)
{
el = head;
while (el != null)
{
if (el.obj.Equals(obj))
{
retval = el.obj;
if (head == tail)
{
// only 1 element left in the list
head = null;
tail = null;
}
else if (el.prev == null)
{
// we're at the head
head = el.next;
head.prev = null;
el.next = null;
}
else if (el.next == null)
{
// we're at the tail
tail = el.prev;
tail.next = null;
el.prev = null;
}
else
{
// we're somewhere in the middle of the list
el.prev.next = el.next;
el.next.prev = el.prev;
el.next = null;
el.prev = null;
}
_size--;
break;
}
el = el.next;
}
}
return retval;
}
public void removeAll()
{
lock (mutex)
{
_size = 0;
head = null;
tail = null;
}
}
public int size()
{
return _size;
}
public override string ToString()
{
System.Text.StringBuilder ret = new System.Text.StringBuilder("[");
Element el = head;
while (el != null)
{
if (el.obj != null)
{
ret.Append(el.obj + " ");
}
el = el.next;
}
ret.Append(']');
return ret.ToString();
}
public string dump()
{
System.Text.StringBuilder ret = new System.Text.StringBuilder("[");
for (Element el = head; el != null; el = el.next)
{
ret.Append(el.obj + " ");
}
return ret.ToString() + ']';
}
public System.Collections.IEnumerator elements()
{
return new ListEnumerator(this, head);
}
public bool contains(object obj)
{
Element el = head;
while (el != null)
{
if (el.obj != null && el.obj.Equals(obj))
return true;
el = el.next;
}
return false;
}
public List copy()
{
List retval = new List();
lock (mutex)
{
for (Element el = head; el != null; el = el.next)
retval.add(el.obj);
}
return retval;
}
public object Clone()
{
return copy();
}
internal class ListEnumerator : System.Collections.IEnumerator
{
private void InitBlock(List enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private object tempAuxObj;
public bool MoveNext()
{
bool result = hasMoreElements();
if (result)
{
tempAuxObj = nextElement();
}
return result;
}
public void Reset()
{
tempAuxObj = null;
}
public object Current
{
get
{
return tempAuxObj;
}
}
private List enclosingInstance;
public List Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal Element curr = null;
internal ListEnumerator(List enclosingInstance, Element start)
{
InitBlock(enclosingInstance);
curr = start;
}
public bool hasMoreElements()
{
return curr != null;
}
public object nextElement()
{
object retval;
if (curr == null)
throw new System.ArgumentOutOfRangeException();
retval = curr.obj;
curr = curr.next;
return retval;
}
}
#region ICompactSerializable Members
void ICompactSerializable.Deserialize(CompactReader reader)
{
object obj;
int new_size = reader.ReadInt32();
if (new_size == 0)
return;
for (int i = 0; i < new_size; i++)
{
obj = reader.ReadObject();
add(obj);
}
}
void ICompactSerializable.Serialize(CompactWriter writer)
{
Element el;
lock (mutex)
{
el = head;
writer.Write(_size);
for (int i = 0; i < _size; i++)
{
writer.WriteObject(el.obj);
el = el.next;
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Net.Security;
using System.Runtime.InteropServices;
namespace System.Net
{
internal static class SSPIWrapper
{
internal static SecurityPackageInfoClass[] EnumerateSecurityPackages(SSPIInterface secModule)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter(nameof(EnumerateSecurityPackages));
}
if (secModule.SecurityPackages == null)
{
lock (secModule)
{
if (secModule.SecurityPackages == null)
{
int moduleCount = 0;
SafeFreeContextBuffer arrayBaseHandle = null;
try
{
int errorCode = secModule.EnumerateSecurityPackages(out moduleCount, out arrayBaseHandle);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SSPIWrapper::arrayBase: " + (arrayBaseHandle.DangerousGetHandle().ToString("x")));
}
if (errorCode != 0)
{
throw new Win32Exception(errorCode);
}
var securityPackages = new SecurityPackageInfoClass[moduleCount];
int i;
for (i = 0; i < moduleCount; i++)
{
securityPackages[i] = new SecurityPackageInfoClass(arrayBaseHandle, i);
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.EnumerateSecurityPackages(securityPackages[i].Name);
}
}
secModule.SecurityPackages = securityPackages;
}
finally
{
if (arrayBaseHandle != null)
{
arrayBaseHandle.Dispose();
}
}
}
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave(nameof(EnumerateSecurityPackages));
}
return secModule.SecurityPackages;
}
internal static SecurityPackageInfoClass GetVerifyPackageInfo(SSPIInterface secModule, string packageName)
{
return GetVerifyPackageInfo(secModule, packageName, false);
}
internal static SecurityPackageInfoClass GetVerifyPackageInfo(SSPIInterface secModule, string packageName, bool throwIfMissing)
{
SecurityPackageInfoClass[] supportedSecurityPackages = EnumerateSecurityPackages(secModule);
if (supportedSecurityPackages != null)
{
for (int i = 0; i < supportedSecurityPackages.Length; i++)
{
if (string.Compare(supportedSecurityPackages[i].Name, packageName, StringComparison.OrdinalIgnoreCase) == 0)
{
return supportedSecurityPackages[i];
}
}
}
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.SspiPackageNotFound(packageName);
}
if (throwIfMissing)
{
throw new NotSupportedException(SR.net_securitypackagesupport);
}
return null;
}
public static SafeFreeCredentials AcquireDefaultCredential(SSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SSPIWrapper::AcquireDefaultCredential(): using " + package);
}
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.AcquireDefaultCredential(package, intent);
}
SafeFreeCredentials outCredential = null;
int errorCode = secModule.AcquireDefaultCredential(package, intent, out outCredential);
if (errorCode != 0)
{
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SSPIWrapper::AcquireDefaultCredential(): error " + Interop.MapSecurityStatus((uint)errorCode));
}
#endif
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_operation_failed_with_error, "AcquireDefaultCredential()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
}
throw new Win32Exception(errorCode);
}
return outCredential;
}
public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent, ref Interop.SspiCli.AuthIdentity authdata)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#2(): using " + package);
}
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.AcquireCredentialsHandle(package, intent, authdata);
}
SafeFreeCredentials credentialsHandle = null;
int errorCode = secModule.AcquireCredentialsHandle(package,
intent,
ref authdata,
out credentialsHandle);
if (errorCode != 0)
{
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#2(): error " + Interop.MapSecurityStatus((uint)errorCode));
}
#endif
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
}
throw new Win32Exception(errorCode);
}
return credentialsHandle;
}
public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent, ref SafeSspiAuthDataHandle authdata)
{
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.AcquireCredentialsHandle(package, intent, authdata);
}
SafeFreeCredentials credentialsHandle = null;
int errorCode = secModule.AcquireCredentialsHandle(package, intent, ref authdata, out credentialsHandle);
if (errorCode != 0)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
}
throw new Win32Exception(errorCode);
}
return credentialsHandle;
}
public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent, Interop.SspiCli.SecureCredential scc)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): using " + package);
}
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.AcquireCredentialsHandle(package, intent, scc);
}
SafeFreeCredentials outCredential = null;
int errorCode = secModule.AcquireCredentialsHandle(
package,
intent,
ref scc,
out outCredential);
if (errorCode != 0)
{
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): error " + Interop.MapSecurityStatus((uint)errorCode));
}
#endif
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
}
throw new Win32Exception(errorCode);
}
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): cred handle = " + outCredential.ToString());
}
#endif
return outCredential;
}
internal static int InitializeSecurityContext(SSPIInterface secModule, ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.InitializeSecurityContext(credential.ToString(),
LoggingHash.ObjectToString(context),
targetName,
inFlags);
}
int errorCode = secModule.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, datarep, inputBuffer, outputBuffer, ref outFlags);
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.SecurityContextInputBuffer(nameof(InitializeSecurityContext), (inputBuffer == null ? 0 : inputBuffer.size), outputBuffer.size, (Interop.SecurityStatus)errorCode);
}
return errorCode;
}
internal static int InitializeSecurityContext(SSPIInterface secModule, SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.InitializeSecurityContext(credential.ToString(),
LoggingHash.ObjectToString(context),
targetName,
inFlags);
}
int errorCode = secModule.InitializeSecurityContext(credential, ref context, targetName, inFlags, datarep, inputBuffers, outputBuffer, ref outFlags);
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.SecurityContextInputBuffers(nameof(InitializeSecurityContext), (inputBuffers == null ? 0 : inputBuffers.Length), outputBuffer.size, (Interop.SecurityStatus)errorCode);
}
return errorCode;
}
internal static int AcceptSecurityContext(SSPIInterface secModule, ref SafeFreeCredentials credential, ref SafeDeleteContext context, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.AcceptSecurityContext(credential.ToString(), LoggingHash.ObjectToString(context), inFlags);
}
int errorCode = secModule.AcceptSecurityContext(ref credential, ref context, inputBuffer, inFlags, datarep, outputBuffer, ref outFlags);
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.SecurityContextInputBuffer(nameof(AcceptSecurityContext), (inputBuffer == null ? 0 : inputBuffer.size), outputBuffer.size, (Interop.SecurityStatus)errorCode);
}
return errorCode;
}
internal static int AcceptSecurityContext(SSPIInterface secModule, SafeFreeCredentials credential, ref SafeDeleteContext context, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.AcceptSecurityContext(credential.ToString(), LoggingHash.ObjectToString(context), inFlags);
}
int errorCode = secModule.AcceptSecurityContext(credential, ref context, inputBuffers, inFlags, datarep, outputBuffer, ref outFlags);
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.SecurityContextInputBuffers(nameof(AcceptSecurityContext), (inputBuffers == null ? 0 : inputBuffers.Length), outputBuffer.size, (Interop.SecurityStatus)errorCode);
}
return errorCode;
}
internal static int CompleteAuthToken(SSPIInterface secModule, ref SafeDeleteContext context, SecurityBuffer[] inputBuffers)
{
int errorCode = secModule.CompleteAuthToken(ref context, inputBuffers);
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.OperationReturnedSomething("CompleteAuthToken()", (Interop.SecurityStatus)errorCode);
}
return errorCode;
}
public static int QuerySecurityContextToken(SSPIInterface secModule, SafeDeleteContext context, out SecurityContextTokenHandle token)
{
return secModule.QuerySecurityContextToken(context, out token);
}
public static int EncryptMessage(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
{
return EncryptDecryptHelper(OP.Encrypt, secModule, context, input, sequenceNumber);
}
public static int DecryptMessage(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
{
return EncryptDecryptHelper(OP.Decrypt, secModule, context, input, sequenceNumber);
}
internal static int MakeSignature(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
{
return EncryptDecryptHelper(OP.MakeSignature, secModule, context, input, sequenceNumber);
}
public static int VerifySignature(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
{
return EncryptDecryptHelper(OP.VerifySignature, secModule, context, input, sequenceNumber);
}
private enum OP
{
Encrypt = 1,
Decrypt,
MakeSignature,
VerifySignature
}
private unsafe static int EncryptDecryptHelper(OP op, SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
{
Interop.SspiCli.SecurityBufferDescriptor sdcInOut = new Interop.SspiCli.SecurityBufferDescriptor(input.Length);
var unmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[input.Length];
fixed (Interop.SspiCli.SecurityBufferStruct* unmanagedBufferPtr = unmanagedBuffer)
{
sdcInOut.UnmanagedPointer = unmanagedBufferPtr;
GCHandle[] pinnedBuffers = new GCHandle[input.Length];
byte[][] buffers = new byte[input.Length][];
try
{
for (int i = 0; i < input.Length; i++)
{
SecurityBuffer iBuffer = input[i];
unmanagedBuffer[i].count = iBuffer.size;
unmanagedBuffer[i].type = iBuffer.type;
if (iBuffer.token == null || iBuffer.token.Length == 0)
{
unmanagedBuffer[i].token = IntPtr.Zero;
}
else
{
pinnedBuffers[i] = GCHandle.Alloc(iBuffer.token, GCHandleType.Pinned);
unmanagedBuffer[i].token = Marshal.UnsafeAddrOfPinnedArrayElement(iBuffer.token, iBuffer.offset);
buffers[i] = iBuffer.token;
}
}
// The result is written in the input Buffer passed as type=BufferType.Data.
int errorCode;
switch (op)
{
case OP.Encrypt:
errorCode = secModule.EncryptMessage(context, sdcInOut, sequenceNumber);
break;
case OP.Decrypt:
errorCode = secModule.DecryptMessage(context, sdcInOut, sequenceNumber);
break;
case OP.MakeSignature:
errorCode = secModule.MakeSignature(context, sdcInOut, sequenceNumber);
break;
case OP.VerifySignature:
errorCode = secModule.VerifySignature(context, sdcInOut, sequenceNumber);
break;
default:
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SSPIWrapper::EncryptDecryptHelper", "Unknown OP: " + op);
}
Debug.Fail("SSPIWrapper::EncryptDecryptHelper", "Unknown OP: " + op);
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
// Marshalling back returned sizes / data.
for (int i = 0; i < input.Length; i++)
{
SecurityBuffer iBuffer = input[i];
iBuffer.size = unmanagedBuffer[i].count;
iBuffer.type = unmanagedBuffer[i].type;
if (iBuffer.size == 0)
{
iBuffer.offset = 0;
iBuffer.token = null;
}
else
{
checked
{
// Find the buffer this is inside of. Usually they all point inside buffer 0.
int j;
for (j = 0; j < input.Length; j++)
{
if (buffers[j] == null)
{
continue;
}
byte* bufferAddress = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(buffers[j], 0);
if ((byte*)unmanagedBuffer[i].token >= bufferAddress &&
(byte*)unmanagedBuffer[i].token + iBuffer.size <= bufferAddress + buffers[j].Length)
{
iBuffer.offset = (int)((byte*)unmanagedBuffer[i].token - bufferAddress);
iBuffer.token = buffers[j];
break;
}
}
if (j >= input.Length)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SSPIWrapper::EncryptDecryptHelper", "Output buffer out of range.");
}
Debug.Fail("SSPIWrapper::EncryptDecryptHelper", "Output buffer out of range.");
iBuffer.size = 0;
iBuffer.offset = 0;
iBuffer.token = null;
}
}
}
// Backup validate the new sizes.
if (iBuffer.offset < 0 || iBuffer.offset > (iBuffer.token == null ? 0 : iBuffer.token.Length))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("SSPIWrapper::EncryptDecryptHelper|'offset' out of range. [{0}]", iBuffer.offset);
}
Debug.Fail("SSPIWrapper::EncryptDecryptHelper|'offset' out of range. [" + iBuffer.offset + "]");
}
if (iBuffer.size < 0 || iBuffer.size > (iBuffer.token == null ? 0 : iBuffer.token.Length - iBuffer.offset))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("SSPIWrapper::EncryptDecryptHelper|'size' out of range. [{0}]", iBuffer.size);
}
Debug.Fail("SSPIWrapper::EncryptDecryptHelper|'size' out of range. [" + iBuffer.size + "]");
}
}
if (errorCode != 0 && NetEventSource.Log.IsEnabled())
{
if (errorCode == Interop.SspiCli.SEC_I_RENEGOTIATE)
{
NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.event_OperationReturnedSomething, op, "SEC_I_RENEGOTIATE"));
}
else
{
NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_operation_failed_with_error, op, String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
}
}
return errorCode;
}
finally
{
for (int i = 0; i < pinnedBuffers.Length; ++i)
{
if (pinnedBuffers[i].IsAllocated)
{
pinnedBuffers[i].Free();
}
}
}
}
}
public static SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter(nameof(QueryContextChannelBinding), contextAttribute.ToString());
}
SafeFreeContextBufferChannelBinding result;
int errorCode = secModule.QueryContextChannelBinding(securityContext, contextAttribute, out result);
if (errorCode != 0)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave(nameof(QueryContextChannelBinding), "ERROR = " + ErrorDescription(errorCode));
}
return null;
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave(nameof(QueryContextChannelBinding), LoggingHash.HashString(result));
}
return result;
}
public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute)
{
int errorCode;
return QueryContextAttributes(secModule, securityContext, contextAttribute, out errorCode);
}
public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute, out int errorCode)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter(nameof(QueryContextAttributes), contextAttribute.ToString());
}
int nativeBlockSize = IntPtr.Size;
Type handleType = null;
switch (contextAttribute)
{
case Interop.SspiCli.ContextAttribute.Sizes:
nativeBlockSize = SecSizes.SizeOf;
break;
case Interop.SspiCli.ContextAttribute.StreamSizes:
nativeBlockSize = StreamSizes.SizeOf;
break;
case Interop.SspiCli.ContextAttribute.Names:
handleType = typeof(SafeFreeContextBuffer);
break;
case Interop.SspiCli.ContextAttribute.PackageInfo:
handleType = typeof(SafeFreeContextBuffer);
break;
case Interop.SspiCli.ContextAttribute.NegotiationInfo:
handleType = typeof(SafeFreeContextBuffer);
nativeBlockSize = Marshal.SizeOf<NegotiationInfo>();
break;
case Interop.SspiCli.ContextAttribute.ClientSpecifiedSpn:
handleType = typeof(SafeFreeContextBuffer);
break;
case Interop.SspiCli.ContextAttribute.RemoteCertificate:
handleType = typeof(SafeFreeCertContext);
break;
case Interop.SspiCli.ContextAttribute.LocalCertificate:
handleType = typeof(SafeFreeCertContext);
break;
case Interop.SspiCli.ContextAttribute.IssuerListInfoEx:
nativeBlockSize = Marshal.SizeOf<Interop.SspiCli.IssuerListInfoEx>();
handleType = typeof(SafeFreeContextBuffer);
break;
case Interop.SspiCli.ContextAttribute.ConnectionInfo:
nativeBlockSize = Marshal.SizeOf<SslConnectionInfo>();
break;
default:
throw new ArgumentException(SR.Format(SR.net_invalid_enum, nameof(contextAttribute)), nameof(contextAttribute));
}
SafeHandle sspiHandle = null;
object attribute = null;
try
{
var nativeBuffer = new byte[nativeBlockSize];
errorCode = secModule.QueryContextAttributes(securityContext, contextAttribute, nativeBuffer, handleType, out sspiHandle);
if (errorCode != 0)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("Win32:QueryContextAttributes", "ERROR = " + ErrorDescription(errorCode));
}
return null;
}
switch (contextAttribute)
{
case Interop.SspiCli.ContextAttribute.Sizes:
attribute = new SecSizes(nativeBuffer);
break;
case Interop.SspiCli.ContextAttribute.StreamSizes:
attribute = new StreamSizes(nativeBuffer);
break;
case Interop.SspiCli.ContextAttribute.Names:
attribute = Marshal.PtrToStringUni(sspiHandle.DangerousGetHandle());
break;
case Interop.SspiCli.ContextAttribute.PackageInfo:
attribute = new SecurityPackageInfoClass(sspiHandle, 0);
break;
case Interop.SspiCli.ContextAttribute.NegotiationInfo:
unsafe
{
fixed (void* ptr = nativeBuffer)
{
attribute = new NegotiationInfoClass(sspiHandle, Marshal.ReadInt32(new IntPtr(ptr), NegotiationInfo.NegotiationStateOffest));
}
}
break;
case Interop.SspiCli.ContextAttribute.ClientSpecifiedSpn:
attribute = Marshal.PtrToStringUni(sspiHandle.DangerousGetHandle());
break;
case Interop.SspiCli.ContextAttribute.LocalCertificate:
// Fall-through to RemoteCertificate is intentional.
case Interop.SspiCli.ContextAttribute.RemoteCertificate:
attribute = sspiHandle;
sspiHandle = null;
break;
case Interop.SspiCli.ContextAttribute.IssuerListInfoEx:
attribute = new Interop.SspiCli.IssuerListInfoEx(sspiHandle, nativeBuffer);
sspiHandle = null;
break;
case Interop.SspiCli.ContextAttribute.ConnectionInfo:
attribute = new SslConnectionInfo(nativeBuffer);
break;
default:
// Will return null.
break;
}
}
finally
{
if (sspiHandle != null)
{
sspiHandle.Dispose();
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave(nameof(QueryContextAttributes), LoggingHash.ObjectToString(attribute));
}
return attribute;
}
public static string ErrorDescription(int errorCode)
{
if (errorCode == -1)
{
return "An exception when invoking Win32 API";
}
switch ((Interop.SecurityStatus)errorCode)
{
case Interop.SecurityStatus.InvalidHandle:
return "Invalid handle";
case Interop.SecurityStatus.InvalidToken:
return "Invalid token";
case Interop.SecurityStatus.ContinueNeeded:
return "Continue needed";
case Interop.SecurityStatus.IncompleteMessage:
return "Message incomplete";
case Interop.SecurityStatus.WrongPrincipal:
return "Wrong principal";
case Interop.SecurityStatus.TargetUnknown:
return "Target unknown";
case Interop.SecurityStatus.PackageNotFound:
return "Package not found";
case Interop.SecurityStatus.BufferNotEnough:
return "Buffer not enough";
case Interop.SecurityStatus.MessageAltered:
return "Message altered";
case Interop.SecurityStatus.UntrustedRoot:
return "Untrusted root";
default:
return "0x" + errorCode.ToString("x", NumberFormatInfo.InvariantInfo);
}
}
} // class SSPIWrapper
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. 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.
*******************************************************************************/
//
// Novell.Directory.Ldap.Asn1.LBEREncoder.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using System.IO;
namespace Novell.Directory.Ldap.Asn1
{
/// <summary>
/// This class provides LBER encoding routines for ASN.1 Types. LBER is a
/// subset of BER as described in the following taken from 5.1 of RFC 2251:
/// 5.1. Mapping Onto BER-based Transport Services
/// The protocol elements of Ldap are encoded for exchange using the
/// Basic Encoding Rules (BER) [11] of ASN.1 [3]. However, due to the
/// high overhead involved in using certain elements of the BER, the
/// following additional restrictions are placed on BER-encodings of Ldap
/// protocol elements:
/// <li>(1) Only the definite form of length encoding will be used.</li>
/// <li>(2) OCTET STRING values will be encoded in the primitive form only.</li>
/// <li>
/// (3) If the value of a BOOLEAN type is true, the encoding MUST have
/// its contents octets set to hex "FF".
/// </li>
/// <li>
/// (4) If a value of a type is its default value, it MUST be absent.
/// Only some BOOLEAN and INTEGER types have default values in this
/// protocol definition.
/// These restrictions do not apply to ASN.1 types encapsulated inside of
/// OCTET STRING values, such as attribute values, unless otherwise
/// noted.
/// </li>
/// [3] ITU-T Rec. X.680, "Abstract Syntax Notation One (ASN.1) -
/// Specification of Basic Notation", 1994.
/// [11] ITU-T Rec. X.690, "Specification of ASN.1 encoding rules: Basic,
/// Canonical, and Distinguished Encoding Rules", 1994.
/// </summary>
[CLSCompliant(true)]
public class LBEREncoder : Asn1Encoder
{
/* Encoders for ASN.1 simple type Contents
*/
/// <summary> BER Encode an Asn1Boolean directly into the specified output stream.</summary>
public virtual void encode(Asn1Boolean b, Stream out_Renamed)
{
/* Encode the id */
encode(b.getIdentifier(), out_Renamed);
/* Encode the length */
out_Renamed.WriteByte(0x01);
/* Encode the boolean content*/
out_Renamed.WriteByte((byte) (b.booleanValue() ? (sbyte) SupportClass.Identity(0xff) : (sbyte) 0x00));
}
/// <summary>
/// Encode an Asn1Numeric directly into the specified outputstream.
/// Use a two's complement representation in the fewest number of octets
/// possible.
/// Can be used to encode INTEGER and ENUMERATED values.
/// </summary>
public void encode(Asn1Numeric n, Stream out_Renamed)
{
var octets = new sbyte[8];
sbyte len;
var value_Renamed = n.longValue();
long endValue = value_Renamed < 0 ? -1 : 0;
var endSign = endValue & 0x80;
for (len = 0; len == 0 || value_Renamed != endValue || (octets[len - 1] & 0x80) != endSign; len++)
{
octets[len] = (sbyte) (value_Renamed & 0xFF);
value_Renamed >>= 8;
}
encode(n.getIdentifier(), out_Renamed);
out_Renamed.WriteByte((byte) len); // Length
for (var i = len - 1; i >= 0; i--)
// Content
out_Renamed.WriteByte((byte) octets[i]);
}
/* Asn1 TYPE NOT YET SUPPORTED
* Encode an Asn1Real directly to a stream.
public void encode(Asn1Real r, OutputStream out)
throws IOException
{
throw new IOException("LBEREncoder: Encode to a stream not implemented");
}
*/
/// <summary> Encode an Asn1Null directly into the specified outputstream.</summary>
public void encode(Asn1Null n, Stream out_Renamed)
{
encode(n.getIdentifier(), out_Renamed);
out_Renamed.WriteByte(0x00); // Length (with no Content)
}
/* Asn1 TYPE NOT YET SUPPORTED
* Encode an Asn1BitString directly to a stream.
public void encode(Asn1BitString bs, OutputStream out)
throws IOException
{
throw new IOException("LBEREncoder: Encode to a stream not implemented");
}
*/
/// <summary> Encode an Asn1OctetString directly into the specified outputstream.</summary>
public void encode(Asn1OctetString os, Stream out_Renamed)
{
encode(os.getIdentifier(), out_Renamed);
encodeLength(os.byteValue().Length, out_Renamed);
sbyte[] temp_sbyteArray;
temp_sbyteArray = os.byteValue();
out_Renamed.Write(SupportClass.ToByteArray(temp_sbyteArray), 0, temp_sbyteArray.Length);
;
;
}
/* Asn1 TYPE NOT YET SUPPORTED
* Encode an Asn1ObjectIdentifier directly to a stream.
* public void encode(Asn1ObjectIdentifier oi, OutputStream out)
* throws IOException
* {
* throw new IOException("LBEREncoder: Encode to a stream not implemented");
* }
*/
/* Asn1 TYPE NOT YET SUPPORTED
* Encode an Asn1CharacterString directly to a stream.
* public void encode(Asn1CharacterString cs, OutputStream out)
* throws IOException
* {
* throw new IOException("LBEREncoder: Encode to a stream not implemented");
* }
*/
/* Encoders for ASN.1 structured types
*/
/// <summary>
/// Encode an Asn1Structured into the specified outputstream. This method
/// can be used to encode SET, SET_OF, SEQUENCE, SEQUENCE_OF
/// </summary>
public void encode(Asn1Structured c, Stream out_Renamed)
{
encode(c.getIdentifier(), out_Renamed);
var value_Renamed = c.toArray();
var output = new MemoryStream();
/* Cycle through each element encoding each element */
for (var i = 0; i < value_Renamed.Length; i++)
{
value_Renamed[i].encode(this, output);
}
/* Encode the length */
encodeLength((int) output.Length, out_Renamed);
/* Add each encoded element into the output stream */
sbyte[] temp_sbyteArray;
temp_sbyteArray = SupportClass.ToSByteArray(output.ToArray());
out_Renamed.Write(SupportClass.ToByteArray(temp_sbyteArray), 0, temp_sbyteArray.Length);
;
;
}
/// <summary> Encode an Asn1Tagged directly into the specified outputstream.</summary>
public void encode(Asn1Tagged t, Stream out_Renamed)
{
if (t.Explicit)
{
encode(t.getIdentifier(), out_Renamed);
/* determine the encoded length of the base type. */
var encodedContent = new MemoryStream();
t.taggedValue().encode(this, encodedContent);
encodeLength((int) encodedContent.Length, out_Renamed);
sbyte[] temp_sbyteArray;
temp_sbyteArray = SupportClass.ToSByteArray(encodedContent.ToArray());
out_Renamed.Write(SupportClass.ToByteArray(temp_sbyteArray), 0, temp_sbyteArray.Length);
;
;
;
}
else
{
t.taggedValue().encode(this, out_Renamed);
}
}
/* Encoders for ASN.1 useful types
*/
/* Encoder for ASN.1 Identifier
*/
/// <summary> Encode an Asn1Identifier directly into the specified outputstream.</summary>
public void encode(Asn1Identifier id, Stream out_Renamed)
{
var c = id.Asn1Class;
var t = id.Tag;
var ccf = (sbyte) ((c << 6) | (id.Constructed ? 0x20 : 0));
if (t < 30)
{
/* single octet */
out_Renamed.WriteByte((byte) (ccf | t));
}
else
{
/* multiple octet */
out_Renamed.WriteByte((byte) (ccf | 0x1F));
encodeTagInteger(t, out_Renamed);
}
}
/* Private helper methods
*/
/*
* Encodes the specified length into the the outputstream
*/
private void encodeLength(int length, Stream out_Renamed)
{
if (length < 0x80)
{
out_Renamed.WriteByte((byte) length);
}
else
{
var octets = new sbyte[4]; // 4 bytes sufficient for 32 bit int.
sbyte n;
for (n = 0; length != 0; n++)
{
octets[n] = (sbyte) (length & 0xFF);
length >>= 8;
}
out_Renamed.WriteByte((byte) (0x80 | n));
for (var i = n - 1; i >= 0; i--)
out_Renamed.WriteByte((byte) octets[i]);
}
}
/// <summary> Encodes the provided tag into the outputstream.</summary>
private void encodeTagInteger(int value_Renamed, Stream out_Renamed)
{
var octets = new sbyte[5];
int n;
for (n = 0; value_Renamed != 0; n++)
{
octets[n] = (sbyte) (value_Renamed & 0x7F);
value_Renamed = value_Renamed >> 7;
}
for (var i = n - 1; i > 0; i--)
{
out_Renamed.WriteByte((byte) (octets[i] | 0x80));
}
out_Renamed.WriteByte((byte) octets[0]);
}
}
}
| |
// 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 System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Thrift;
using Thrift.Protocols;
using Thrift.Server;
using Thrift.Transports;
using Thrift.Transports.Server;
using tutorial;
using shared;
namespace Server
{
public class Program
{
private static readonly ILogger Logger = new LoggerFactory().AddConsole(LogLevel.Trace).AddDebug(LogLevel.Trace).CreateLogger(nameof(Server));
public static void Main(string[] args)
{
args = args ?? new string[0];
if (args.Any(x => x.StartsWith("-help", StringComparison.OrdinalIgnoreCase)))
{
DisplayHelp();
return;
}
using (var source = new CancellationTokenSource())
{
RunAsync(args, source.Token).GetAwaiter().GetResult();
Logger.LogInformation("Press any key to stop...");
Console.ReadLine();
source.Cancel();
}
Logger.LogInformation("Server stopped");
}
private static void DisplayHelp()
{
Logger.LogInformation(@"
Usage:
Server.exe -help
will diplay help information
Server.exe -tr:<transport> -pr:<protocol>
will run server with specified arguments (tcp transport and binary protocol by default)
Options:
-tr (transport):
tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090)
tcpbuffered - tcp buffered transport will be used (host - ""localhost"", port - 9090)
namedpipe - namedpipe transport will be used (pipe address - "".test"")
http - http transport will be used (http address - ""localhost:9090"")
tcptls - tcp transport with tls will be used (host - ""localhost"", port - 9090)
framed - tcp framed transport will be used (host - ""localhost"", port - 9090)
-pr (protocol):
binary - (default) binary protocol will be used
compact - compact protocol will be used
json - json protocol will be used
multiplexed - multiplexed protocol will be used
Sample:
Server.exe -tr:tcp
");
}
private static async Task RunAsync(string[] args, CancellationToken cancellationToken)
{
var selectedTransport = GetTransport(args);
var selectedProtocol = GetProtocol(args);
if (selectedTransport == Transport.Http)
{
new HttpServerSample().Run(cancellationToken);
}
else
{
await RunSelectedConfigurationAsync(selectedTransport, selectedProtocol, cancellationToken);
}
}
private static Protocol GetProtocol(string[] args)
{
var transport = args.FirstOrDefault(x => x.StartsWith("-pr"))?.Split(':')?[1];
Enum.TryParse(transport, true, out Protocol selectedProtocol);
return selectedProtocol;
}
private static Transport GetTransport(string[] args)
{
var transport = args.FirstOrDefault(x => x.StartsWith("-tr"))?.Split(':')?[1];
Enum.TryParse(transport, true, out Transport selectedTransport);
return selectedTransport;
}
private static async Task RunSelectedConfigurationAsync(Transport transport, Protocol protocol, CancellationToken cancellationToken)
{
var fabric = new LoggerFactory().AddConsole(LogLevel.Trace).AddDebug(LogLevel.Trace);
var handler = new CalculatorAsyncHandler();
ITAsyncProcessor processor = null;
TServerTransport serverTransport = null;
switch (transport)
{
case Transport.Tcp:
serverTransport = new TServerSocketTransport(9090);
break;
case Transport.TcpBuffered:
serverTransport = new TServerSocketTransport(port: 9090, clientTimeout: 10000, useBufferedSockets: true);
break;
case Transport.NamedPipe:
serverTransport = new TNamedPipeServerTransport(".test");
break;
case Transport.TcpTls:
serverTransport = new TTlsServerSocketTransport(9090, false, GetCertificate(), ClientCertValidator, LocalCertificateSelectionCallback);
break;
case Transport.Framed:
serverTransport = new TServerFramedTransport(9090);
break;
}
ITProtocolFactory inputProtocolFactory;
ITProtocolFactory outputProtocolFactory;
switch (protocol)
{
case Protocol.Binary:
{
inputProtocolFactory = new TBinaryProtocol.Factory();
outputProtocolFactory = new TBinaryProtocol.Factory();
processor = new Calculator.AsyncProcessor(handler);
}
break;
case Protocol.Compact:
{
inputProtocolFactory = new TCompactProtocol.Factory();
outputProtocolFactory = new TCompactProtocol.Factory();
processor = new Calculator.AsyncProcessor(handler);
}
break;
case Protocol.Json:
{
inputProtocolFactory = new TJsonProtocol.Factory();
outputProtocolFactory = new TJsonProtocol.Factory();
processor = new Calculator.AsyncProcessor(handler);
}
break;
case Protocol.Multiplexed:
{
inputProtocolFactory = new TBinaryProtocol.Factory();
outputProtocolFactory = new TBinaryProtocol.Factory();
var calcHandler = new CalculatorAsyncHandler();
var calcProcessor = new Calculator.AsyncProcessor(calcHandler);
var sharedServiceHandler = new SharedServiceAsyncHandler();
var sharedServiceProcessor = new SharedService.AsyncProcessor(sharedServiceHandler);
var multiplexedProcessor = new TMultiplexedProcessor();
multiplexedProcessor.RegisterProcessor(nameof(Calculator), calcProcessor);
multiplexedProcessor.RegisterProcessor(nameof(SharedService), sharedServiceProcessor);
processor = multiplexedProcessor;
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(protocol), protocol, null);
}
try
{
Logger.LogInformation(
$"Selected TAsyncServer with {serverTransport} transport, {processor} processor and {inputProtocolFactory} protocol factories");
var server = new AsyncBaseServer(processor, serverTransport, inputProtocolFactory, outputProtocolFactory, fabric);
Logger.LogInformation("Starting the server...");
await server.ServeAsync(cancellationToken);
}
catch (Exception x)
{
Logger.LogInformation(x.ToString());
}
}
private static X509Certificate2 GetCertificate()
{
// due to files location in net core better to take certs from top folder
var certFile = GetCertPath(Directory.GetParent(Directory.GetCurrentDirectory()));
return new X509Certificate2(certFile, "ThriftTest");
}
private static string GetCertPath(DirectoryInfo di, int maxCount = 6)
{
var topDir = di;
var certFile =
topDir.EnumerateFiles("ThriftTest.pfx", SearchOption.AllDirectories)
.FirstOrDefault();
if (certFile == null)
{
if (maxCount == 0)
throw new FileNotFoundException("Cannot find file in directories");
return GetCertPath(di.Parent, maxCount - 1);
}
return certFile.FullName;
}
private static X509Certificate LocalCertificateSelectionCallback(object sender,
string targetHost, X509CertificateCollection localCertificates,
X509Certificate remoteCertificate, string[] acceptableIssuers)
{
return GetCertificate();
}
private static bool ClientCertValidator(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
private enum Transport
{
Tcp,
TcpBuffered,
NamedPipe,
Http,
TcpTls,
Framed
}
private enum Protocol
{
Binary,
Compact,
Json,
Multiplexed
}
public class HttpServerSample
{
public void Run(CancellationToken cancellationToken)
{
var config = new ConfigurationBuilder()
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseUrls("http://localhost:9090")
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build();
host.RunAsync(cancellationToken).GetAwaiter().GetResult();
}
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<Calculator.IAsync, CalculatorAsyncHandler>();
services.AddTransient<ITAsyncProcessor, Calculator.AsyncProcessor>();
services.AddTransient<THttpServerTransport, THttpServerTransport>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
app.UseMiddleware<THttpServerTransport>();
}
}
}
public class CalculatorAsyncHandler : Calculator.IAsync
{
private readonly Dictionary<int, SharedStruct> _log = new Dictionary<int, SharedStruct>();
public CalculatorAsyncHandler()
{
}
public async Task<SharedStruct> getStructAsync(int key,
CancellationToken cancellationToken)
{
Logger.LogInformation("GetStructAsync({0})", key);
return await Task.FromResult(_log[key]);
}
public async Task pingAsync(CancellationToken cancellationToken)
{
Logger.LogInformation("PingAsync()");
await Task.CompletedTask;
}
public async Task<int> addAsync(int num1, int num2, CancellationToken cancellationToken)
{
Logger.LogInformation($"AddAsync({num1},{num2})");
return await Task.FromResult(num1 + num2);
}
public async Task<int> calculateAsync(int logid, Work w, CancellationToken cancellationToken)
{
Logger.LogInformation($"CalculateAsync({logid}, [{w.Op},{w.Num1},{w.Num2}])");
var val = 0;
switch (w.Op)
{
case Operation.ADD:
val = w.Num1 + w.Num2;
break;
case Operation.SUBTRACT:
val = w.Num1 - w.Num2;
break;
case Operation.MULTIPLY:
val = w.Num1 * w.Num2;
break;
case Operation.DIVIDE:
if (w.Num2 == 0)
{
var io = new InvalidOperation
{
WhatOp = (int) w.Op,
Why = "Cannot divide by 0"
};
throw io;
}
val = w.Num1 / w.Num2;
break;
default:
{
var io = new InvalidOperation
{
WhatOp = (int) w.Op,
Why = "Unknown operation"
};
throw io;
}
}
var entry = new SharedStruct
{
Key = logid,
Value = val.ToString()
};
_log[logid] = entry;
return await Task.FromResult(val);
}
public async Task zipAsync(CancellationToken cancellationToken)
{
Logger.LogInformation("ZipAsync() with delay 100mc");
await Task.Delay(100, CancellationToken.None);
}
}
public class SharedServiceAsyncHandler : SharedService.IAsync
{
public async Task<SharedStruct> getStructAsync(int key, CancellationToken cancellationToken)
{
Logger.LogInformation("GetStructAsync({0})", key);
return await Task.FromResult(new SharedStruct()
{
Key = key,
Value = "GetStructAsync"
});
}
}
}
}
| |
// Copyright (c) 2007-2014 SIL International
// Licensed under the MIT license: opensource.org/licenses/MIT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing.Text;
using System.Globalization;
using System.Linq;
using SolidGui.Engine;
using SolidGui.Model;
namespace SolidGui.Processes
{
public class ProcessStructure : IProcess
{
readonly SolidSettings _settings;
private IDictionary<string, HashSet<string>> _requiredChildren;
public ProcessStructure(SolidSettings settings)
{
_settings = settings;
_requiredChildren = SolidSettings.AllRequiredChildren(settings.MarkerSettings);
}
private static void InsertInTreeAnyway(SfmFieldModel source, List<SfmFieldModel> scope, SfmLexEntry outputEntry, SolidReport report)
{
UpdateScope(scope, scope.Count, source, outputEntry, report); // I believe this is why the children of a bad parent don't all turn red. Nice. -JMC
outputEntry.AppendField(source);
}
private bool InsertInTree(SfmFieldModel source, SolidReport report, List<SfmFieldModel> scope, SfmLexEntry outputEntry)
{
int index = CanInsertInTree(source, scope);
if (index < 0)
{
return false;
}
scope[index].AppendChild(source); // Add the node under this parent
UpdateScope(scope, index, source, outputEntry, report); // Add to list of possible parents
//source.Depth = scope.Count - 1;
outputEntry.AppendField(source);
return true;
}
private int CanInsertInTree(SfmFieldModel source, List<SfmFieldModel> scope)
{
// Get the marker settings for this node.
SolidMarkerSetting sourceSetting = _settings.FindOrCreateMarkerSetting(source.Marker);
bool foundParent = false;
int i = scope.Count;
// Check for record marker (assume is root)
while (i > 0 && !foundParent)
{
i--;
SolidStructureProperty sourceStructurePropertiesForParent = sourceSetting.GetStructurePropertiesForParent(scope[i].Marker);
if (sourceStructurePropertiesForParent != null)
{
switch (sourceStructurePropertiesForParent.Multiplicity)
{
case MultiplicityAdjacency.Once:
foundParent = true;
foreach (SfmFieldModel childNode in scope[i].Children)
{
if (childNode.Marker == source.Marker)
foundParent = false;
}
break;
case MultiplicityAdjacency.MultipleTogether:
{
foundParent = true;
bool foundSelfAsSibling = false;
//make sure the parent doesn't already contain the node we want to add,
//except immediately preceding the current one. (Note that 'immediately'
//assumes the tree has been pruned regularly.
foreach (SfmFieldModel childNode in scope[i].Children)
{
if (childNode.Marker == source.Marker)
{
foundSelfAsSibling = true;
}
else
{
if (foundSelfAsSibling)
{
foundParent = false; //non-sibling found after sibling(s) had already been found
}
}
}
}
break;
case MultiplicityAdjacency.MultipleApart:
foundParent = true;
break;
}
}
}
return foundParent ? i : -1;
}
private static void UpdateScope(List<SfmFieldModel> scope, int i, SfmFieldModel n, SfmLexEntry outputEntry, SolidReport report)
{
bool kickout = false;
for (int j = scope.Count - 1; j > i; j--)
{
var s = scope[j];
CheckForRequired(s, outputEntry, report);
if (s.Depth > n.Depth)
{
kickout = true;
}
else if (s.Marker == n.Marker && s.Depth == n.Depth) //the latter should be guaranteed anyway
{
kickout = false; // there's no "Move Up" recommendation for repeating field bundles
}
scope.RemoveAt(j);
}
if (kickout)
{
//report
report.AddEntry(
SolidReport.EntryType.StructureKickout,
outputEntry,
n,
String.Format("Optional: Check whether marker \\{0} should be moved up.", n.Marker)
);
}
/*
if (i < scope.Count - 1)
{
scope.RemoveRange(i + 1, scope.Count-1 - i); // remove i+1 and following--those nephews are now closed out
}
*/
if (n != null) scope.Add(n);
}
private static void CheckForRequired(SfmFieldModel parentField, SfmLexEntry outputEntry, SolidReport report)
{
if (parentField == null) return;
var mr = parentField.MissingRequiredChildren();
if (mr.Any())
{
report.AddEntry(
SolidReport.EntryType.StructureRequiredMissing,
outputEntry,
parentField,
"Required field missing : " + string.Join(", ", mr)
);
}
}
private bool InferNode(SfmFieldModel sourceField, SolidReport report, List<SfmFieldModel> scope, SfmLexEntry outputEntry, ref int recurseCount)
{
// Can we infer a node?
bool retval = false; // assume the worst
SolidMarkerSetting setting = _settings.FindOrCreateMarkerSetting(sourceField.Marker);
if (setting.InferedParent != String.Empty)
{
var inferredNode = new SfmFieldModel(setting.InferedParent);
// TODO: fill in inferredNode._requiredChildren
inferredNode.Inferred = true;
//!!! inferredNode.AppendChild(sourceField);
// Attempt to insert the inferred node in the tree.
// The inferred node needs to find a valid parent
if (InsertInTree(inferredNode, report, scope, outputEntry))
{
// Now try and add the current node under the inferred node.
if (InsertInTree(sourceField, report, scope, outputEntry))
{
retval = true;
}
else
{
//??? This is bordering on an exception. It indicates that there is an inconsistency with the setings file, which the UI shouldn't make possible.
// Error.
report.AddEntry(
SolidReport.EntryType.StructureInsertInInferredFailed,
outputEntry,
sourceField,
String.Format("ERROR: Inferred marker \\{0} is not a valid parent of \\{1}. Someone may have manually edited your settings file.", setting.InferedParent, sourceField.Marker)
);
InsertInTreeAnyway(sourceField, scope, outputEntry, report);
}
}
else
{
if (recurseCount < 10)
{
if (InferNode(inferredNode, report, scope, outputEntry, ref recurseCount))
{
// Now try and add the current node under the inferred node.
if (InsertInTree(sourceField, report, scope, outputEntry))
{
retval = true;
}
else
{
//??? This is bordering on an exception. It indicates that there is an inconsistency with the seutp.
// Error.
report.AddEntry(
SolidReport.EntryType.StructureInsertInInferredFailed,
outputEntry,
sourceField,
String.Format("ERROR: Inferred marker \\{0} is not a valid parent of \\{1}", setting.InferedParent, sourceField.Marker)
);
InsertInTreeAnyway(sourceField, scope, outputEntry, report);
}
}
else
{
if (InsertInTree(sourceField, report, scope, outputEntry))
{
retval = true;
}
}
// No else required, the InferNode puts the entries in the tree.
}
else
{
throw new Exception("Circular inference rules detected");
}
if (!retval)
{
// Error.
report.AddEntry(
SolidReport.EntryType.StructureParentNotFoundForInferred,
outputEntry,
inferredNode,
String.Format("Inferred marker \\{0} could not be placed in structure.", inferredNode.Marker)
);
// Error
report.AddEntry(
SolidReport.EntryType.StructureParentNotFound,
outputEntry,
sourceField,
string.Format("Marker \\{0} could not be placed in structure", sourceField.Marker)
);
InsertInTreeAnyway(sourceField, scope, outputEntry, report);
}
}
}
else
{
// Error
report.AddEntry(
SolidReport.EntryType.StructureParentNotFound,
outputEntry,
sourceField,
string.Format("Marker \\{0} could not be placed in structure, and nothing could be inferred.", sourceField.Marker)
);
InsertInTreeAnyway(sourceField, scope, outputEntry, report);
}
return retval;
}
public SfmLexEntry Process(SfmLexEntry lexEntry, SolidReport report)
{
// Iterate through each (flat) node in the src
var scope = new List<SfmFieldModel>();
scope.Add(lexEntry.FirstField/* The lx field */);
var outputEntry = SfmLexEntry.CreateDefault(lexEntry.FirstField);
bool passedFirst = false; // adding a check; don't want to bother/risk refactoring this. -JMC Mar 2014
foreach (SfmFieldModel sfmField in lexEntry.Fields)
{
var rc = new HashSet<string>();
_requiredChildren.TryGetValue(sfmField.Marker, out rc); //it's important to *copy* the object
sfmField.SetRequiredChildren(rc);
if(sfmField != lexEntry.FirstField)
{
passedFirst = true;
if (!InsertInTree(sfmField, report, scope, outputEntry))
{
int recurseCount = 0;
InferNode(sfmField, report, scope, outputEntry, ref recurseCount);
}
}
else
{
if (passedFirst)
{
throw new DataMisalignedException ("The marker " + lexEntry.FirstField + " was found in the middle of a field.");
}
}
}
foreach (var s in scope)
{
CheckForRequired(s, outputEntry, report);
//CheckForRequired(lexEntry.FirstField, outputEntry, report, lexEntry.Fields.Last());
}
// Walk the tree of nodes, appending closing tags as needed.
AddClosers(outputEntry.Fields[0]);
return outputEntry;
}
//private static Stack<string> _stack;
/*
private static void AddClosers(SfmLexEntry lexEntry)
{
SfmFieldModel root = lexEntry.Fields[0];
_stack = new Stack<string>();
_stack.Push(root.Marker);
}
*/
private static SfmFieldModel _appendTo;
// Recursive
private static void AddClosers(SfmFieldModel node)
{
if (node == null)
{
return;
}
if (node.Closers == null)
{
node.Closers = new List<string>();
}
_appendTo = node;
foreach (SfmFieldModel child in node.Children)
{
AddClosers(child);
}
_appendTo.Closers.Add(node.Marker);
}
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Graphics\Testing\Tcl\HyperScalarBar.tcl
// output file is AVHyperScalarBar.cs
/// <summary>
/// The testing class derived from AVHyperScalarBar
/// </summary>
public class AVHyperScalarBarClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVHyperScalarBar(String [] argv)
{
//Prefix Content is: ""
// Test the scalar bar actor using a logarithmic lookup table[]
//[]
VTK_INTEGRATE_BOTH_DIRECTIONS = 2;
//[]
// generate tensors[]
ptLoad = new vtkPointLoad();
ptLoad.SetLoadValue((double)100.0);
ptLoad.SetSampleDimensions((int)20,(int)20,(int)20);
ptLoad.ComputeEffectiveStressOn();
ptLoad.SetModelBounds((double)-10,(double)10,(double)-10,(double)10,(double)-10,(double)10);
// Generate hyperstreamlines[]
s1 = new vtkHyperStreamline();
s1.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort());
s1.SetStartPosition((double)9,(double)9,(double)-9);
s1.IntegrateMinorEigenvector();
s1.SetMaximumPropagationDistance((double)18.0);
s1.SetIntegrationStepLength((double)0.1);
s1.SetStepLength((double)0.01);
s1.SetRadius((double)0.25);
s1.SetNumberOfSides((int)18);
s1.SetIntegrationDirection((int)VTK_INTEGRATE_BOTH_DIRECTIONS);
s1.Update();
// Map hyperstreamlines[]
lut = new vtkLogLookupTable();
lut.SetHueRange((double).6667,(double)0.0);
scalarBar = new vtkScalarBarActor();
scalarBar.SetLookupTable((vtkScalarsToColors)lut);
scalarBar.SetTitle((string)"Stress");
scalarBar.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport();
scalarBar.GetPositionCoordinate().SetValue((double)0.1,(double)0.05);
scalarBar.SetOrientationToVertical();
scalarBar.SetWidth((double)0.1);
scalarBar.SetHeight((double)0.9);
scalarBar.SetPosition((double)0.01,(double)0.1);
scalarBar.SetLabelFormat((string)"%-#6.3f");
scalarBar.GetLabelTextProperty().SetColor((double)1,(double)0,(double)0);
scalarBar.GetTitleTextProperty().SetColor((double)1,(double)0,(double)0);
s1Mapper = vtkPolyDataMapper.New();
s1Mapper.SetInputConnection((vtkAlgorithmOutput)s1.GetOutputPort());
s1Mapper.SetLookupTable((vtkScalarsToColors)lut);
ptLoad.Update();
//force update for scalar range[]
s1Mapper.SetScalarRange((double)((vtkDataSet)ptLoad.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)ptLoad.GetOutput()).GetScalarRange()[1]);
s1Actor = new vtkActor();
s1Actor.SetMapper((vtkMapper)s1Mapper);
s2 = new vtkHyperStreamline();
s2.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort());
s2.SetStartPosition((double)-9,(double)-9,(double)-9);
s2.IntegrateMinorEigenvector();
s2.SetMaximumPropagationDistance((double)18.0);
s2.SetIntegrationStepLength((double)0.1);
s2.SetStepLength((double)0.01);
s2.SetRadius((double)0.25);
s2.SetNumberOfSides((int)18);
s2.SetIntegrationDirection((int)VTK_INTEGRATE_BOTH_DIRECTIONS);
s2.Update();
s2Mapper = vtkPolyDataMapper.New();
s2Mapper.SetInputConnection((vtkAlgorithmOutput)s2.GetOutputPort());
s2Mapper.SetLookupTable((vtkScalarsToColors)lut);
s2Mapper.SetScalarRange((double)((vtkDataSet)ptLoad.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)ptLoad.GetOutput()).GetScalarRange()[1]);
s2Actor = new vtkActor();
s2Actor.SetMapper((vtkMapper)s2Mapper);
s3 = new vtkHyperStreamline();
s3.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort());
s3.SetStartPosition((double)9,(double)-9,(double)-9);
s3.IntegrateMinorEigenvector();
s3.SetMaximumPropagationDistance((double)18.0);
s3.SetIntegrationStepLength((double)0.1);
s3.SetStepLength((double)0.01);
s3.SetRadius((double)0.25);
s3.SetNumberOfSides((int)18);
s3.SetIntegrationDirection((int)VTK_INTEGRATE_BOTH_DIRECTIONS);
s3.Update();
s3Mapper = vtkPolyDataMapper.New();
s3Mapper.SetInputConnection((vtkAlgorithmOutput)s3.GetOutputPort());
s3Mapper.SetLookupTable((vtkScalarsToColors)lut);
s3Mapper.SetScalarRange((double)((vtkDataSet)ptLoad.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)ptLoad.GetOutput()).GetScalarRange()[1]);
s3Actor = new vtkActor();
s3Actor.SetMapper((vtkMapper)s3Mapper);
s4 = new vtkHyperStreamline();
s4.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort());
s4.SetStartPosition((double)-9,(double)9,(double)-9);
s4.IntegrateMinorEigenvector();
s4.SetMaximumPropagationDistance((double)18.0);
s4.SetIntegrationStepLength((double)0.1);
s4.SetStepLength((double)0.01);
s4.SetRadius((double)0.25);
s4.SetNumberOfSides((int)18);
s4.SetIntegrationDirection((int)VTK_INTEGRATE_BOTH_DIRECTIONS);
s4.Update();
s4Mapper = vtkPolyDataMapper.New();
s4Mapper.SetInputConnection((vtkAlgorithmOutput)s4.GetOutputPort());
s4Mapper.SetLookupTable((vtkScalarsToColors)lut);
s4Mapper.SetScalarRange((double)((vtkDataSet)ptLoad.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)ptLoad.GetOutput()).GetScalarRange()[1]);
s4Actor = new vtkActor();
s4Actor.SetMapper((vtkMapper)s4Mapper);
// plane for context[]
//[]
g = new vtkImageDataGeometryFilter();
g.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort());
g.SetExtent((int)0,(int)100,(int)0,(int)100,(int)0,(int)0);
g.Update();
//for scalar range[]
gm = vtkPolyDataMapper.New();
gm.SetInputConnection((vtkAlgorithmOutput)g.GetOutputPort());
gm.SetScalarRange((double)((vtkImageDataGeometryFilter)g).GetOutput().GetScalarRange()[0], (double)((vtkImageDataGeometryFilter)g).GetOutput().GetScalarRange()[1]);
ga = new vtkActor();
ga.SetMapper((vtkMapper)gm);
// Create outline around data[]
//[]
outline = new vtkOutlineFilter();
outline.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort());
outlineMapper = vtkPolyDataMapper.New();
outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort());
outlineActor = new vtkActor();
outlineActor.SetMapper((vtkMapper)outlineMapper);
outlineActor.GetProperty().SetColor((double)0,(double)0,(double)0);
// Create cone indicating application of load[]
//[]
coneSrc = new vtkConeSource();
coneSrc.SetRadius((double).5);
coneSrc.SetHeight((double)2);
coneMap = vtkPolyDataMapper.New();
coneMap.SetInputConnection((vtkAlgorithmOutput)coneSrc.GetOutputPort());
coneActor = new vtkActor();
coneActor.SetMapper((vtkMapper)coneMap);
coneActor.SetPosition((double)0,(double)0,(double)11);
coneActor.RotateY((double)90);
coneActor.GetProperty().SetColor((double)1,(double)0,(double)0);
// Create the rendering infrastructure[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
camera = new vtkCamera();
camera.SetFocalPoint((double)0.113766,(double)-1.13665,(double)-1.01919);
camera.SetPosition((double)-29.4886,(double)-63.1488,(double)26.5807);
camera.SetViewAngle((double)24.4617);
camera.SetViewUp((double)0.17138,(double)0.331163,(double)0.927879);
camera.SetClippingRange((double)1,(double)100);
ren1.AddActor2D((vtkProp)scalarBar);
ren1.AddActor((vtkProp)s1Actor);
ren1.AddActor((vtkProp)s2Actor);
ren1.AddActor((vtkProp)s3Actor);
ren1.AddActor((vtkProp)s4Actor);
ren1.AddActor((vtkProp)outlineActor);
ren1.AddActor((vtkProp)coneActor);
ren1.AddActor((vtkProp)ga);
ren1.SetBackground((double)1.0,(double)1.0,(double)1.0);
ren1.SetActiveCamera((vtkCamera)camera);
renWin.SetSize((int)300,(int)300);
renWin.Render();
// prevent the tk window from showing up then start the event loop[]
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static int VTK_INTEGRATE_BOTH_DIRECTIONS;
static vtkPointLoad ptLoad;
static vtkHyperStreamline s1;
static vtkLogLookupTable lut;
static vtkScalarBarActor scalarBar;
static vtkPolyDataMapper s1Mapper;
static vtkActor s1Actor;
static vtkHyperStreamline s2;
static vtkPolyDataMapper s2Mapper;
static vtkActor s2Actor;
static vtkHyperStreamline s3;
static vtkPolyDataMapper s3Mapper;
static vtkActor s3Actor;
static vtkHyperStreamline s4;
static vtkPolyDataMapper s4Mapper;
static vtkActor s4Actor;
static vtkImageDataGeometryFilter g;
static vtkPolyDataMapper gm;
static vtkActor ga;
static vtkOutlineFilter outline;
static vtkPolyDataMapper outlineMapper;
static vtkActor outlineActor;
static vtkConeSource coneSrc;
static vtkPolyDataMapper coneMap;
static vtkActor coneActor;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkCamera camera;
///<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 int GetVTK_INTEGRATE_BOTH_DIRECTIONS()
{
return VTK_INTEGRATE_BOTH_DIRECTIONS;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_INTEGRATE_BOTH_DIRECTIONS(int toSet)
{
VTK_INTEGRATE_BOTH_DIRECTIONS = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPointLoad GetptLoad()
{
return ptLoad;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetptLoad(vtkPointLoad toSet)
{
ptLoad = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkHyperStreamline Gets1()
{
return s1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets1(vtkHyperStreamline toSet)
{
s1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkLogLookupTable Getlut()
{
return lut;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setlut(vtkLogLookupTable toSet)
{
lut = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkScalarBarActor GetscalarBar()
{
return scalarBar;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetscalarBar(vtkScalarBarActor toSet)
{
scalarBar = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Gets1Mapper()
{
return s1Mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets1Mapper(vtkPolyDataMapper toSet)
{
s1Mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Gets1Actor()
{
return s1Actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets1Actor(vtkActor toSet)
{
s1Actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkHyperStreamline Gets2()
{
return s2;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets2(vtkHyperStreamline toSet)
{
s2 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Gets2Mapper()
{
return s2Mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets2Mapper(vtkPolyDataMapper toSet)
{
s2Mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Gets2Actor()
{
return s2Actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets2Actor(vtkActor toSet)
{
s2Actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkHyperStreamline Gets3()
{
return s3;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets3(vtkHyperStreamline toSet)
{
s3 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Gets3Mapper()
{
return s3Mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets3Mapper(vtkPolyDataMapper toSet)
{
s3Mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Gets3Actor()
{
return s3Actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets3Actor(vtkActor toSet)
{
s3Actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkHyperStreamline Gets4()
{
return s4;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets4(vtkHyperStreamline toSet)
{
s4 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Gets4Mapper()
{
return s4Mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets4Mapper(vtkPolyDataMapper toSet)
{
s4Mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Gets4Actor()
{
return s4Actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets4Actor(vtkActor toSet)
{
s4Actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkImageDataGeometryFilter Getg()
{
return g;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setg(vtkImageDataGeometryFilter toSet)
{
g = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Getgm()
{
return gm;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setgm(vtkPolyDataMapper toSet)
{
gm = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Getga()
{
return ga;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setga(vtkActor toSet)
{
ga = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkOutlineFilter Getoutline()
{
return outline;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setoutline(vtkOutlineFilter 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 vtkConeSource GetconeSrc()
{
return coneSrc;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetconeSrc(vtkConeSource toSet)
{
coneSrc = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetconeMap()
{
return coneMap;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetconeMap(vtkPolyDataMapper toSet)
{
coneMap = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetconeActor()
{
return coneActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetconeActor(vtkActor toSet)
{
coneActor = 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 vtkCamera Getcamera()
{
return camera;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcamera(vtkCamera toSet)
{
camera = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(ptLoad!= null){ptLoad.Dispose();}
if(s1!= null){s1.Dispose();}
if(lut!= null){lut.Dispose();}
if(scalarBar!= null){scalarBar.Dispose();}
if(s1Mapper!= null){s1Mapper.Dispose();}
if(s1Actor!= null){s1Actor.Dispose();}
if(s2!= null){s2.Dispose();}
if(s2Mapper!= null){s2Mapper.Dispose();}
if(s2Actor!= null){s2Actor.Dispose();}
if(s3!= null){s3.Dispose();}
if(s3Mapper!= null){s3Mapper.Dispose();}
if(s3Actor!= null){s3Actor.Dispose();}
if(s4!= null){s4.Dispose();}
if(s4Mapper!= null){s4Mapper.Dispose();}
if(s4Actor!= null){s4Actor.Dispose();}
if(g!= null){g.Dispose();}
if(gm!= null){gm.Dispose();}
if(ga!= null){ga.Dispose();}
if(outline!= null){outline.Dispose();}
if(outlineMapper!= null){outlineMapper.Dispose();}
if(outlineActor!= null){outlineActor.Dispose();}
if(coneSrc!= null){coneSrc.Dispose();}
if(coneMap!= null){coneMap.Dispose();}
if(coneActor!= null){coneActor.Dispose();}
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(camera!= null){camera.Dispose();}
}
}
//--- end of script --//
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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.
*********************************************************************/
#region Using directives
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Text;
#endregion
namespace Multiverse.Config
{
// The registry has only
public class ParameterRegistry
{
#region ParameterRegistry Protected Members
static protected ParameterRegistry instance = null;
protected struct SubsystemHandlers
{
internal string subsystemName;
internal SetParameterHandler setHandler;
internal GetParameterHandler getHandler;
internal SubsystemHandlers(string subsystemName, SetParameterHandler setHandler,
GetParameterHandler getHandler)
{
this.subsystemName = subsystemName;
this.setHandler = setHandler;
this.getHandler = getHandler;
}
}
protected Dictionary<string, SubsystemHandlers> getSetHandlers = new Dictionary<string, SubsystemHandlers>();
protected bool GetHandlersForSubsystem(string SubsystemName, out SubsystemHandlers value)
{
if (getSetHandlers.TryGetValue(SubsystemName, out value))
return true;
else
return false;
}
// Breaks apart a string of the form subsystem.parameter into
// the two strings; if it doesn't have this form, returns
// false, otherwise true
static protected bool BreakSubsystemAndParameter(string subsystemAndParameter,
out string subsystem, out string parameter)
{
int i = subsystemAndParameter.IndexOf('.');
if (i > 0 && i < subsystemAndParameter.Length - 1) {
subsystem = subsystemAndParameter.Substring(0, i);
parameter = subsystemAndParameter.Substring(i + 1);
return true;
}
else {
subsystem = "";
parameter = "";
return false;
}
}
static protected ParameterRegistry Instance
{
get {
if (instance == null)
instance = new ParameterRegistry();
return instance;
}
}
protected void RegisterSubsystemHandlersInternal(string subsystemName,
SetParameterHandler setHandler,
GetParameterHandler getHandler)
{
// SubsystemHandlers handlers; (unused)
UnregisterSubsystemHandlersInternal(subsystemName);
getSetHandlers.Add(subsystemName, new SubsystemHandlers(subsystemName, setHandler, getHandler));
}
protected void UnregisterSubsystemHandlersInternal(string subsystemName)
{
SubsystemHandlers handlers;
if (GetHandlersForSubsystem(subsystemName, out handlers))
getSetHandlers.Remove(subsystemName);
}
protected bool SetParameterInternal (string subsystemName, string parameterName, string value)
{
SubsystemHandlers handlers;
if (GetHandlersForSubsystem(subsystemName, out handlers))
return handlers.setHandler(parameterName, value);
else
return false;
}
protected string GetParameterInternal (string subsystemName, string parameterName)
{
SubsystemHandlers handlers;
string value;
if (GetHandlersForSubsystem(subsystemName, out handlers))
handlers.getHandler(parameterName, out value);
else
value = "";
return value;
}
#endregion ParameterRegistry Protected Members
#region ParameterRegistry Public Interface
// The delegate returns true if setting the parameter succeeded; false otherwise
public delegate bool SetParameterHandler(string parameterName, string parameterValue);
// The delegate returns true if the value was returned in the out parameter; false otherwise
public delegate bool GetParameterHandler(string parameterName, out string parameterValue);
static public void RegisterSubsystemHandlers(string subsystemName,
SetParameterHandler setHandler,
GetParameterHandler getHandler)
{
Instance.RegisterSubsystemHandlersInternal(subsystemName, setHandler, getHandler);
}
static public void UnregisterSubsystemHandlers(string subsystemName)
{
Instance.UnregisterSubsystemHandlersInternal(subsystemName);
}
static public bool SetParameter (string subsystemNameAndParameter, string value)
{
string subsystemName;
string parameterName;
if (BreakSubsystemAndParameter(subsystemNameAndParameter, out subsystemName, out parameterName))
return Instance.SetParameterInternal(subsystemName, parameterName, value);
else
return false;
}
static bool SetParameter (string subsystemName, string parameterName, string value)
{
return Instance.SetParameterInternal(subsystemName, parameterName, value);
}
static public string GetParameter (string subsystemNameAndParameter)
{
string subsystemName;
string parameterName;
// Special case: if the subsystemNameAndParameter is
// "Help", return the help for all the subsystems
if (subsystemNameAndParameter == "Help") {
string value = "";
foreach (SubsystemHandlers handlers in Instance.getSetHandlers.Values) {
value += "Documentation for subsystem " + handlers.subsystemName + "\r\n";
value += Instance.GetParameterInternal(handlers.subsystemName, "Help") + "\r\n";
}
return value;
}
else if (BreakSubsystemAndParameter(subsystemNameAndParameter, out subsystemName, out parameterName))
return Instance.GetParameterInternal(subsystemName, parameterName);
else {
return "";
}
}
// Returns a string containing all the subsystems separated by spaces
static public string GetSubsystems ()
{
string s = "";
foreach (SubsystemHandlers handlers in Instance.getSetHandlers.Values) {
if (s != "")
s += " ";
s += handlers.subsystemName;
}
return s;
}
static public string GetParameter (string subsystemName, string parameterName)
{
return Instance.GetParameterInternal(subsystemName, parameterName);
}
#endregion ParameterRegistry Public Interface
}
public class ClientParameter
{
public static string GetClientParameter(string parameterName)
{
return ParameterRegistry.GetParameter(parameterName);
}
public static void SetClientParameter(string parameterName, string parameterValue)
{
ParameterRegistry.SetParameter(parameterName, parameterValue);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using Vulcan.DapperExtensions.Contract;
using Vulcan.DapperExtensions.Internal;
namespace Vulcan.DapperExtensions.ORMapping
{
public abstract class BaseRepository
{
private readonly string _conStr;
private readonly IConnectionFactory _dbFactory;
private readonly IConnectionManagerFactory _mgr;
protected BaseRepository(IConnectionManagerFactory mgr, string constr, IConnectionFactory factory = null)
{
_conStr = constr;
_dbFactory = factory;
_mgr = mgr;
}
/// <summary>
/// insert entity value to db
/// If the primary key is an identity column, return auto-increment value otherwise returns 0
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public long Insert(AbstractBaseEntity entity)
{
long ret;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
var sql = entity.GetInsertSQL();
ret = mgr.Connection.QueryFirstOrDefault<long>(sql, entity, mgr.Transaction, null,
CommandType.Text);
metrics.AddToMetrics(sql, entity);
}
}
return ret;
}
/// <summary>
/// async insert entity value to db
/// If the primary key is an identity column, return auto-increment value otherwise returns 0
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public async Task<long> InsertAsync(AbstractBaseEntity entity)
{
long ret;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
var sql = entity.GetInsertSQL();
ret = await mgr.Connection.QueryFirstOrDefaultAsync<long>(entity.GetInsertSQL(), entity,
mgr.Transaction, null, CommandType.Text);
metrics.AddToMetrics(sql, entity);
}
}
return ret;
}
/// <summary>
/// batch insert
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public int BatchInsert<T>(List<T> list) where T : AbstractBaseEntity
{
var ret = -1;
if (list == null || list.Count <= 0) return ret;
var sql = list[0].GetInsertSQL();
ret = Execute(sql, list);
return ret;
}
/// <summary>
/// batch insert asynchronous
/// </summary>
/// <param name="list"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public Task<int> BatchInsertAsync<T>(List<T> list) where T : AbstractBaseEntity
{
if (list == null || list.Count <= 0) return Task.FromResult(-1);
var sql = list[0].GetInsertSQL();
return ExecuteAsync(sql, list);
}
/// <summary>
/// update entity changed value
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public int Update(AbstractBaseEntity model)
{
return Execute(model.GetUpdateSQL(), model);
}
/// <summary>
/// update asynchronous
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public Task<int> UpdateAsync(AbstractBaseEntity model)
{
return ExecuteAsync(model.GetUpdateSQL(), model);
}
/// <summary>
/// batch update
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public int BatchUpdate<T>(List<T> list) where T : AbstractBaseEntity
{
var ret = -1;
if (list == null || list.Count <= 0) return ret;
var sql = list[0].GetUpdateSQL();
ret = Execute(sql, list);
return ret;
}
/// <summary>
/// batch update asynchronous
/// </summary>
/// <param name="list"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public async Task<int> BatchUpdateAsync<T>(List<T> list) where T : AbstractBaseEntity
{
var ret = -1;
if (list == null || list.Count <= 0) return ret;
var sql = list[0].GetUpdateSQL();
ret = await ExecuteAsync(sql, list);
return ret;
}
/// <summary>
/// begin a transaction scope ,if it's exists, otherwise reuse same one
/// </summary>
/// <param name="option"></param>
/// <returns></returns>
public TransScope BeginTransScope(TransScopeOption option = TransScopeOption.Required)
{
return new TransScope(_mgr, _dbFactory, _conStr, option);
}
/// <summary>
/// create a connection scope to share db connection and reuse it;
/// </summary>
/// <returns></returns>
public ConnectionScope BeginConnectionScope()
{
return new ConnectionScope(_mgr, _conStr, _dbFactory);
}
/// <summary>
/// execute sql whit parameters
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <returns></returns>
protected int Execute(string sql, object paras)
{
int ret;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
ret = mgr.Connection.Execute(sql, paras, mgr.Transaction, null, CommandType.Text);
metrics.AddToMetrics(sql, paras);
}
}
return ret;
}
/// <summary>
/// Execute parameterized SQL
/// </summary>
/// <param name="sql"></param>
/// <param name="timeOut">number of timeout seconds</param>
/// <param name="paras"></param>
/// <returns></returns>
protected int Execute(string sql, int timeOut, object paras)
{
int ret;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
ret = mgr.Connection.Execute(sql, paras, mgr.Transaction, timeOut, CommandType.Text);
metrics.AddToMetrics(sql, paras);
}
}
return ret;
}
/// <summary>
/// Execute parameterized SQL Asynchronous
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <returns></returns>
protected async Task<int> ExecuteAsync(string sql, object paras)
{
int ret;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
ret = await mgr.Connection.ExecuteAsync(sql, paras, mgr.Transaction, null, CommandType.Text);
metrics.AddToMetrics(sql, paras);
}
}
return ret;
}
/// <summary>
/// Execute parameterized SQL Asynchronous
/// </summary>
/// <param name="sql"></param>
/// <param name="timeOut">number of timeout seconds</param>
/// <param name="paras"></param>
/// <returns></returns>
protected async Task<int> ExecuteAsync(string sql, int timeOut, object paras)
{
int ret;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
ret = await mgr.Connection.ExecuteAsync(sql, paras, mgr.Transaction, timeOut, CommandType.Text);
metrics.AddToMetrics(sql, paras);
}
}
return ret;
}
/// <summary>
/// get first or default result
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
protected T Get<T>(string sql, object paras)
{
return Query<T>(sql, paras).FirstOrDefault();
}
/// <summary>
/// get first or default result
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
protected async Task<T> GetAsync<T>(string sql, object paras)
{
T ret;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
ret = await mgr.Connection.QueryFirstOrDefaultAsync<T>(sql, paras, mgr.Transaction, null,
CommandType.Text);
metrics.AddToMetrics(sql, paras);
}
}
return ret;
}
/// <summary>
/// Executes a query, returning the data typed as T
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
protected List<T> Query<T>(string sql, object paras)
{
List<T> list;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
list = mgr.Connection.Query<T>(sql, paras, mgr.Transaction, false, null, CommandType.Text).ToList();
metrics.AddToMetrics(sql, paras);
}
}
return list;
}
/// <summary>
/// Executes a query, returning the data typed as T
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
protected async Task<List<T>> QueryAsync<T>(string sql, object paras)
{
List<T> list;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
var qList = await mgr.Connection.QueryAsync<T>(sql, paras, mgr.Transaction, null, CommandType.Text);
list = qList.ToList();
metrics.AddToMetrics(sql, paras);
}
}
return list;
}
/// <summary>
/// Executes a query, returning the data typed as T
/// </summary>
/// <param name="sql"></param>
/// <param name="timeOut"></param>
/// <param name="paras"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
protected List<T> Query<T>(string sql, int timeOut, object paras)
{
List<T> list;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
list = mgr.Connection.Query<T>(sql, paras, mgr.Transaction, false, timeOut, CommandType.Text)
.ToList();
metrics.AddToMetrics(sql, paras);
}
}
return list;
}
/// <summary>
/// Executes a query, returning the data typed as T
/// </summary>
/// <param name="sql"></param>
/// <param name="timeOut"></param>
/// <param name="paras"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
protected async Task<List<T>> QueryAsync<T>(string sql, int timeOut, object paras)
{
List<T> list;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
var qList = await mgr.Connection.QueryAsync<T>(sql, paras, mgr.Transaction, timeOut,
CommandType.Text);
list = qList.ToList();
metrics.AddToMetrics(sql, paras);
}
}
return list;
}
/// <summary>
/// Executes a query, returning the data typed as T
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <param name="parse"></param>
/// <param name="splitOn"></param>
/// <typeparam name="T"></typeparam>
/// <typeparam name="T1"></typeparam>
/// <returns></returns>
protected List<T> Query<T, T1>(string sql, object paras, Func<T, T1, T> parse, string splitOn)
{
List<T> list;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
list = mgr.Connection
.Query(sql, parse, paras, mgr.Transaction, false, splitOn, 360, CommandType.Text).ToList();
metrics.AddToMetrics(sql, paras);
}
}
return list;
}
protected List<T> Query<T, T1, T2>(string sql, object paras, Func<T, T1, T2, T> parse, string splitOn)
{
List<T> list;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
list = mgr.Connection
.Query(sql, parse, paras, mgr.Transaction, false, splitOn, 360, CommandType.Text).ToList();
metrics.AddToMetrics(sql, paras);
}
}
return list;
}
protected List<T> Query<T, T1, T2, T3>(string sql, object paras, Func<T, T1, T2, T3, T> parse, string splitOn)
{
List<T> list;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
list = mgr.Connection
.Query(sql, parse, paras, mgr.Transaction, false, splitOn, 360, CommandType.Text).ToList();
metrics.AddToMetrics(sql, paras);
}
}
return list;
}
protected async Task<List<T>> QueryAsync<T, T1>(string sql, object paras, Func<T, T1, T> parse, string splitOn)
{
List<T> list;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
var qList = await mgr.Connection.QueryAsync(sql, parse, paras, mgr.Transaction, false, splitOn, 360,
CommandType.Text);
list = qList.ToList();
metrics.AddToMetrics(sql, paras);
}
}
return list;
}
protected async Task<List<T>> QueryAsync<T, T1, T2>(string sql, object paras, Func<T, T1, T2, T> parse,
string splitOn)
{
List<T> list;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
var qList = await mgr.Connection.QueryAsync(sql, parse, paras, mgr.Transaction, false, splitOn, 360,
CommandType.Text);
list = qList.ToList();
metrics.AddToMetrics(sql, paras);
}
}
return list;
}
protected async Task<List<T>> QueryAsync<T, T1, T2, T3>(string sql, object paras, Func<T, T1, T2, T3, T> parse,
string splitOn)
{
List<T> list;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
var qList = await mgr.Connection.QueryAsync(sql, parse, paras, mgr.Transaction, false, splitOn, 360,
CommandType.Text);
list = qList.ToList();
metrics.AddToMetrics(sql, paras);
}
}
return list;
}
protected int SPExecute(string spName, object paras)
{
int ret;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
ret = mgr.Connection.Execute(spName, paras, mgr.Transaction, null, CommandType.StoredProcedure);
metrics.AddToMetrics(spName, paras);
}
}
return ret;
}
protected async Task<int> SPExecuteAsync(string spName, object paras)
{
int ret;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
ret = await mgr.Connection.ExecuteAsync(spName, paras, mgr.Transaction, null,
CommandType.StoredProcedure);
metrics.AddToMetrics(spName, paras);
}
}
return ret;
}
protected T SPGet<T>(string spName, object paras)
{
return SPQuery<T>(spName, paras).FirstOrDefault();
}
protected async Task<T> SPGetAsync<T>(string spName, object paras)
{
T ret;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
ret = await mgr.Connection.QueryFirstOrDefaultAsync<T>(spName, paras, mgr.Transaction, null,
CommandType.StoredProcedure);
metrics.AddToMetrics(spName, paras);
}
}
return ret;
}
protected List<T> SPQuery<T>(string spName, object paras)
{
List<T> list;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
list = mgr.Connection
.Query<T>(spName, paras, mgr.Transaction, false, null, CommandType.StoredProcedure).ToList();
metrics.AddToMetrics(spName, paras);
}
}
return list;
}
protected async Task<List<T>> SPQueryAsync<T>(string spName, object paras)
{
List<T> ret;
using (var mgr = GetConnection())
{
using (var metrics = CreateSQLMetrics())
{
var list = await mgr.Connection.QueryAsync<T>(spName, paras, mgr.Transaction, null,
CommandType.StoredProcedure);
ret = list.ToList();
metrics.AddToMetrics(spName, paras);
}
}
return ret;
}
protected ConnectionManager GetConnection()
{
return _mgr.GetConnectionManager(_conStr, _dbFactory);
}
protected virtual ISQLMetrics CreateSQLMetrics()
{
return new NoopSQLMetrics();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Collections.Generic;
namespace System.Runtime.InteropServices
{
public class ComAwareEventInfo : EventInfo
{
#if FEATURE_COMAWAREEVENTINFO
#region private fields
private System.Reflection.EventInfo _innerEventInfo;
#endregion
#region ctor
public ComAwareEventInfo(Type type, string eventName)
{
_innerEventInfo = type.GetEvent(eventName);
}
#endregion
#region protected overrides
public override void AddEventHandler(object target, Delegate handler)
{
if (Marshal.IsComObject(target))
{
// retrieve sourceIid and dispid
Guid sourceIid;
int dispid;
GetDataForComInvocation(_innerEventInfo, out sourceIid, out dispid);
// now validate the caller can call into native and redirect to ComEventHelpers.Combine
SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
perm.Demand();
System.Runtime.InteropServices.ComEventsHelper.Combine(target, sourceIid, dispid, handler);
}
else
{
// we are dealing with a managed object - just add the delegate through reflection
_innerEventInfo.AddEventHandler(target, handler);
}
}
public override void RemoveEventHandler(object target, Delegate handler)
{
if (Marshal.IsComObject(target))
{
// retrieve sourceIid and dispid
Guid sourceIid;
int dispid;
GetDataForComInvocation(_innerEventInfo, out sourceIid, out dispid);
// now validate the caller can call into native and redirect to ComEventHelpers.Combine
SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
perm.Demand();
System.Runtime.InteropServices.ComEventsHelper.Remove(target, sourceIid, dispid, handler);
}
else
{
// we are dealing with a managed object - just add the delegate through relection
_innerEventInfo.RemoveEventHandler(target, handler);
}
}
#endregion
#region public overrides
public override System.Reflection.EventAttributes Attributes
{
get { return _innerEventInfo.Attributes; }
}
public override System.Reflection.MethodInfo GetAddMethod(bool nonPublic)
{
return _innerEventInfo.GetAddMethod(nonPublic);
}
public override System.Reflection.MethodInfo GetRaiseMethod(bool nonPublic)
{
return _innerEventInfo.GetRaiseMethod(nonPublic);
}
public override System.Reflection.MethodInfo GetRemoveMethod(bool nonPublic)
{
return _innerEventInfo.GetRemoveMethod(nonPublic);
}
public override Type DeclaringType
{
get { return _innerEventInfo.DeclaringType; }
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return _innerEventInfo.GetCustomAttributes(attributeType, inherit);
}
public override object[] GetCustomAttributes(bool inherit)
{
return _innerEventInfo.GetCustomAttributes(inherit);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return _innerEventInfo.IsDefined(attributeType, inherit);
}
public override string Name
{
get { return _innerEventInfo.Name; }
}
public override Type ReflectedType
{
get { return _innerEventInfo.ReflectedType; }
}
#endregion
#region private methods
private static void GetDataForComInvocation(System.Reflection.EventInfo eventInfo, out Guid sourceIid, out int dispid)
{
object[] comEventInterfaces = eventInfo.DeclaringType.GetCustomAttributes(typeof(ComEventInterfaceAttribute), false);
if (comEventInterfaces == null || comEventInterfaces.Length == 0)
{
// TODO: event strings need to be localizable
throw new InvalidOperationException("event invocation for COM objects requires interface to be attributed with ComSourceInterfaceGuidAttribute");
}
if (comEventInterfaces.Length > 1)
{
// TODO: event strings need to be localizable
throw new System.Reflection.AmbiguousMatchException("more than one ComSourceInterfaceGuidAttribute found");
}
Type sourceItf = ((ComEventInterfaceAttribute)comEventInterfaces[0]).SourceInterface;
Guid guid = sourceItf.GUID;
System.Reflection.MethodInfo methodInfo = sourceItf.GetMethod(eventInfo.Name);
Attribute dispIdAttribute = Attribute.GetCustomAttribute(methodInfo, typeof(DispIdAttribute));
if (dispIdAttribute == null)
{
// TODO: event strings need to be localizable
throw new InvalidOperationException("event invocation for COM objects requires event to be attributed with DispIdAttribute");
}
sourceIid = guid;
dispid = ((DispIdAttribute)dispIdAttribute).Value;
}
#endregion
#else
public ComAwareEventInfo(Type type, string eventName)
{
throw new PlatformNotSupportedException();
}
public override System.Reflection.EventAttributes Attributes
{
get { throw new PlatformNotSupportedException(); }
}
public override Type DeclaringType
{
get { throw new PlatformNotSupportedException(); }
}
public override string Name
{
get { throw new PlatformNotSupportedException(); }
}
public override void AddEventHandler(object target, Delegate handler)
{
throw new PlatformNotSupportedException();
}
public override void RemoveEventHandler(object target, Delegate handler)
{
throw new PlatformNotSupportedException();
}
public override object[] GetCustomAttributes(bool inherit)
{
throw new PlatformNotSupportedException();
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new PlatformNotSupportedException();
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new PlatformNotSupportedException();
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
throw new PlatformNotSupportedException();
}
public override Type ReflectedType
{
get { throw new PlatformNotSupportedException(); }
}
public override MethodInfo GetAddMethod(bool nonPublic)
{
throw new PlatformNotSupportedException();
}
public override MethodInfo GetRemoveMethod(bool nonPublic)
{
throw new PlatformNotSupportedException();
}
public override MethodInfo GetRaiseMethod(bool nonPublic)
{
throw new PlatformNotSupportedException();
}
#endif // FEATURE_COMAWAREEVENTINFO
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using NUnit.Framework;
namespace Dominion.Specs
{
public delegate void MethodThatThrows();
public static class SpecificationExtensions
{
public static void ShouldBeFalse(this bool condition)
{
Assert.IsFalse(condition);
}
public static void ShouldBeTrue(this bool condition)
{
Assert.IsTrue(condition);
}
public static object ShouldEqual(this object actual, object expected)
{
Assert.AreEqual(expected, actual);
return expected;
}
public static object ShouldNotEqual(this object actual, object expected)
{
Assert.AreNotEqual(expected, actual);
return expected;
}
public static void ShouldBeNull(this object anObject)
{
Assert.IsNull(anObject);
}
public static void ShouldNotBeNull(this object anObject)
{
Assert.IsNotNull(anObject);
}
public static object ShouldBeTheSameAs(this object actual, object expected)
{
Assert.AreSame(expected, actual);
return expected;
}
public static object ShouldNotBeTheSameAs(this object actual, object expected)
{
Assert.AreNotSame(expected, actual);
return expected;
}
public static void ShouldBeOfType<T>(this object actual)
{
Assert.IsInstanceOf<T>(actual);
}
public static void ShouldNotBeOfType<T>(this object actual, Type expected)
{
Assert.IsNotInstanceOf<T>(actual);
}
public static void ShouldContain(this IList actual, object expected)
{
Assert.Contains(expected, actual);
}
public static void ShouldContain<T>(this IEnumerable<T> actual, T expected)
{
ShouldContain(actual, x => x.Equals(expected));
}
public static void ShouldContain<T>(this IEnumerable<T> actual, Func<T, bool> expected)
{
actual.Single(expected).ShouldNotEqual(default(T));
}
public static void ShouldContain<T>(this T[] actual, T expected)
{
ShouldContain((IList)actual, expected);
}
public static void ShouldBeEmpty<T>(this IEnumerable<T> actual)
{
actual.Count().ShouldEqual(0);
}
public static void ShouldHaveCount<T>(this IEnumerable<T> actual, int expected)
{
actual.Count().ShouldEqual(expected);
}
public static IComparable ShouldBeGreaterThan(this IComparable arg1, IComparable arg2)
{
Assert.Greater(arg1, arg2);
return arg2;
}
public static IComparable ShouldBeLessThan(this IComparable arg1, IComparable arg2)
{
Assert.Less(arg1, arg2);
return arg2;
}
public static void ShouldBeEmpty(this ICollection collection)
{
Assert.IsEmpty(collection);
}
public static void ShouldBeEmpty(this string aString)
{
Assert.IsEmpty(aString);
}
public static void ShouldNotBeEmpty(this ICollection collection)
{
Assert.IsNotEmpty(collection);
}
public static void ShouldNotBeEmpty(this string aString)
{
Assert.IsNotEmpty(aString);
}
public static void ShouldContain(this string actual, string expected)
{
StringAssert.Contains(expected, actual);
}
public static string ShouldBeEqualIgnoringCase(this string actual, string expected)
{
StringAssert.AreEqualIgnoringCase(expected, actual);
return expected;
}
public static void ShouldEndWith(this string actual, string expected)
{
StringAssert.EndsWith(expected, actual);
}
public static void ShouldStartWith(this string actual, string expected)
{
StringAssert.StartsWith(expected, actual);
}
public static void ShouldContainErrorMessage(this Exception exception, string expected)
{
StringAssert.Contains(expected, exception.Message);
}
public static Exception ShouldBeThrownBy(this Type exceptionType, MethodThatThrows method)
{
Exception exception = null;
try
{
method();
}
catch (Exception e)
{
Assert.AreEqual(exceptionType, e.GetType());
exception = e;
}
if (exception == null)
{
Assert.Fail(String.Format("Expected {0} to be thrown.", exceptionType.FullName));
}
return exception;
}
public static void ShouldEqualSqlDate(this DateTime actual, DateTime expected)
{
TimeSpan timeSpan = actual - expected;
Assert.Less(Math.Abs(timeSpan.TotalMilliseconds), 3);
}
public static object AttributeShouldEqual(this XmlElement element, string attributeName, object expected)
{
Assert.IsNotNull(element, "The Element is null");
string actual = element.GetAttribute(attributeName);
Assert.AreEqual(expected, actual);
return expected;
}
public static XmlElement ShouldHaveChild(this XmlElement element, string xpath)
{
XmlElement child = element.SelectSingleNode(xpath) as XmlElement;
Assert.IsNotNull(child, "Should have a child element matching " + xpath);
return child;
}
public static XmlElement DoesNotHaveAttribute(this XmlElement element, string attributeName)
{
Assert.IsNotNull(element, "The Element is null");
Assert.IsFalse(element.HasAttribute(attributeName), "Element should not have an attribute named " + attributeName);
return element;
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using Franson.BlueTools;
using Franson.Protocols.Obex.OBEXService;
namespace ObexServiceSampleCF
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.ComponentModel.Container components = null;
private System.Windows.Forms.ListBox listBoxCommands;
private System.Windows.Forms.ListBox listBoxConnections;
private System.Windows.Forms.RadioButton radioButtonFTP;
private System.Windows.Forms.RadioButton radioButtonPush;
private System.Windows.Forms.Button buttonStart;
private System.Windows.Forms.Button buttonStop;
private ServiceExtended m_extendedService = null;
private Manager m_manager;
private string m_sRootFolderPath = @"\My Documents\";
private System.Windows.Forms.Label labelStackID;
private System.Windows.Forms.Label labelActivityLog;
private System.Windows.Forms.Label labelConnectedDevices;
private bool m_bIsRunning = false;
public MainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.Closing += new System.ComponentModel.CancelEventHandler(MainForm_Closing);
m_manager = Manager.GetManager();
switch(Manager.StackID)
{
case StackID.STACK_MICROSOFT:
labelStackID.Text = "Microsoft Bluetooth Stack";
break;
case StackID.STACK_WIDCOMM:
labelStackID.Text = "WidComm Bluetooth Stack";
break;
}
Franson.BlueTools.License license = new Franson.BlueTools.License();
license.LicenseKey = "HU5UZew052MOLX88jhmhNlURXvu0TRNbHY5b";
}
private void OnConnect(ObexSession obexSession)
{
listBoxCommands.Items.Add(obexSession.RemoteDevice.Name + ": Connecting");
listBoxCommands.SelectedIndex = listBoxCommands.Items.Count - 1;
listBoxConnections.Items.Add(obexSession.RemoteDevice);
}
private void OnDisconnect(ObexSession obexSession)
{
listBoxCommands.Items.Add(obexSession.RemoteDevice.Name + ": Disconnecting");
listBoxCommands.SelectedIndex = listBoxCommands.Items.Count - 1;
listBoxConnections.Items.Remove(obexSession.RemoteDevice);
}
private void OnAbort(ObexSession obexSession)
{
listBoxCommands.Items.Add(obexSession.RemoteDevice.Name + ": Aborting...");
listBoxCommands.SelectedIndex = listBoxCommands.Items.Count - 1;
}
private void OnCreateFolder(ObexSession obexSession, ObexFolder folder)
{
listBoxCommands.Items.Add(obexSession.RemoteDevice.Name + ": Create folder " + folder.Path);
listBoxCommands.SelectedIndex = listBoxCommands.Items.Count - 1;
}
private void OnDelete(ObexSession obexSession, ObexFolderItem folderItem)
{
listBoxCommands.Items.Add(obexSession.RemoteDevice.Name + ": Delete " + folderItem.Path);
listBoxCommands.SelectedIndex = listBoxCommands.Items.Count - 1;
}
private void OnGet(ObexSession obexSession, ObexFile obexFile)
{
listBoxCommands.Items.Add(obexSession.RemoteDevice.Name + ": Get file " + obexFile.Path);
listBoxCommands.SelectedIndex = listBoxCommands.Items.Count - 1;
}
private void OnPut(ObexSession obexSession, ObexFile obexFile)
{
listBoxCommands.Items.Add(obexSession.RemoteDevice.Name + ": Put file " + obexFile.Name + " To: " + obexFile.ShortPath);
listBoxCommands.SelectedIndex = listBoxCommands.Items.Count - 1;
}
private void OnSetPath(ObexSession obexSession, ObexFolder obexFolder)
{
listBoxCommands.Items.Add(obexSession.RemoteDevice.Name + ": Set path " + obexFolder.Path);
listBoxCommands.SelectedIndex = listBoxCommands.Items.Count - 1;
}
private void OnGetPath(ObexSession obexSession)
{
listBoxCommands.Items.Add(obexSession.RemoteDevice.Name + ": Get path " + obexSession.CurrentFolder.Path);
listBoxCommands.SelectedIndex = listBoxCommands.Items.Count - 1;
}
private void OnException(ObexSession obexSession, Exception exception)
{
System.Windows.Forms.MessageBox.Show(exception.Message);
listBoxCommands.Items.Add(exception.Message);
listBoxCommands.SelectedIndex = listBoxCommands.Items.Count - 1;
if(listBoxConnections.Items.Contains(obexSession.RemoteDevice))
{
listBoxConnections.Items.Remove(obexSession.RemoteDevice);
}
}
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
m_extendedService.Stop();
Dispose();
}
/// <summary>
/// TODO. Proper shutdown Manager.GetManager().Dispose();
/// </summary>
protected override void Dispose( bool disposing )
{
if(m_bIsRunning)
m_extendedService.Stop();
m_manager.Dispose();
if( disposing )
{
if (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.listBoxCommands = new System.Windows.Forms.ListBox();
this.listBoxConnections = new System.Windows.Forms.ListBox();
this.radioButtonFTP = new System.Windows.Forms.RadioButton();
this.radioButtonPush = new System.Windows.Forms.RadioButton();
this.buttonStart = new System.Windows.Forms.Button();
this.buttonStop = new System.Windows.Forms.Button();
this.labelStackID = new System.Windows.Forms.Label();
this.labelActivityLog = new System.Windows.Forms.Label();
this.labelConnectedDevices = new System.Windows.Forms.Label();
//
// listBoxCommands
//
this.listBoxCommands.Location = new System.Drawing.Point(8, 104);
this.listBoxCommands.Size = new System.Drawing.Size(224, 132);
//
// listBoxConnections
//
this.listBoxConnections.Location = new System.Drawing.Point(128, 16);
this.listBoxConnections.Size = new System.Drawing.Size(104, 67);
//
// radioButtonFTP
//
this.radioButtonFTP.Checked = true;
this.radioButtonFTP.Location = new System.Drawing.Point(16, 8);
this.radioButtonFTP.Size = new System.Drawing.Size(96, 20);
this.radioButtonFTP.Text = "Obex FTP";
//
// radioButtonPush
//
this.radioButtonPush.Location = new System.Drawing.Point(16, 32);
this.radioButtonPush.Size = new System.Drawing.Size(96, 20);
this.radioButtonPush.Text = "Object Push";
//
// buttonStart
//
this.buttonStart.Location = new System.Drawing.Point(8, 64);
this.buttonStart.Size = new System.Drawing.Size(48, 20);
this.buttonStart.Text = "Start";
this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
//
// buttonStop
//
this.buttonStop.Location = new System.Drawing.Point(64, 64);
this.buttonStop.Size = new System.Drawing.Size(48, 20);
this.buttonStop.Text = "Stop";
this.buttonStop.Click += new System.EventHandler(this.buttonStop_Click);
//
// labelStackID
//
this.labelStackID.Location = new System.Drawing.Point(8, 248);
this.labelStackID.Size = new System.Drawing.Size(224, 20);
this.labelStackID.Text = "labelStackID";
//
// labelActivityLog
//
this.labelActivityLog.Location = new System.Drawing.Point(8, 88);
this.labelActivityLog.Size = new System.Drawing.Size(100, 16);
this.labelActivityLog.Text = "Activity Log";
//
// labelConnectedDevices
//
this.labelConnectedDevices.Location = new System.Drawing.Point(128, 0);
this.labelConnectedDevices.Size = new System.Drawing.Size(100, 16);
this.labelConnectedDevices.Text = "Connected devices";
//
// MainForm
//
this.Controls.Add(this.labelConnectedDevices);
this.Controls.Add(this.labelActivityLog);
this.Controls.Add(this.labelStackID);
this.Controls.Add(this.buttonStop);
this.Controls.Add(this.buttonStart);
this.Controls.Add(this.radioButtonPush);
this.Controls.Add(this.radioButtonFTP);
this.Controls.Add(this.listBoxConnections);
this.Controls.Add(this.listBoxCommands);
this.Text = "MainForm";
this.Load += new System.EventHandler(this.MainForm_Load);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
Application.Run(new MainForm());
}
private void MainForm_Load(object sender, System.EventArgs e)
{
}
private void buttonStart_Click(object sender, System.EventArgs e)
{
try
{
//Create serbvce root folder ObexFolder("Name", "Path");
ObexFolder serviceRootFolder = new ObexFolder(m_sRootFolderPath , m_sRootFolderPath);
//Instantiate the service. (Type, "Name", "Description", rootFolder)
m_extendedService = new ServiceExtended(radioButtonFTP.Checked ? ObexServiceType.ObexFTP : ObexServiceType.ObexObjectPush, "Obex Service", "Sample Obex Service", serviceRootFolder);
//Adds event from the Extended service
m_extendedService.OnConnect += new ServiceExtended.ObexServiceEventHandler(OnConnect);
m_extendedService.OnDisconnect += new ServiceExtended.ObexServiceEventHandler(OnDisconnect);
m_extendedService.OnAbort += new ServiceExtended.ObexServiceEventHandler(OnAbort);
m_extendedService.OnCreateFolder += new ServiceExtended.ObexServiceFolderOperationEventHandler(OnCreateFolder);
m_extendedService.OnDelete += new ServiceExtended.ObexServiceFolderItemEventHandler(OnDelete);
m_extendedService.OnGet += new ServiceExtended.ObexServiceFileTransferEventHandler(OnGet);
m_extendedService.OnPut += new ServiceExtended.ObexServiceFileTransferEventHandler(OnPut);
m_extendedService.OnSetPath += new ServiceExtended.ObexServiceFolderOperationEventHandler(OnSetPath);
m_extendedService.OnGetPath += new ServiceExtended.ObexServiceEventHandler(OnGetPath);
m_extendedService.OnObexException += new ServiceExtended.ObexServiceExceptionEventHandler(OnException);
//Start the service
m_extendedService.Start();
m_bIsRunning = true;
buttonStop.Enabled = true;
buttonStart.Enabled = false;
radioButtonFTP.Enabled = false;
radioButtonPush.Enabled = false;
}
catch(Exception ex)
{
throw ex;
}
}
private void buttonStop_Click(object sender, System.EventArgs e)
{
m_extendedService.Stop();
m_bIsRunning = false;
buttonStop.Enabled = false;
buttonStart.Enabled = true;
radioButtonFTP.Enabled = true;
radioButtonPush.Enabled = true;
}
private void menuItemExit_Click(object sender, System.EventArgs e)
{
Dispose();
}
private void menuItemRootFolder_Click(object sender, System.EventArgs e)
{
//Form settings = new Form();
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
namespace System.Net.Sockets
{
internal partial class SafeCloseSocket :
#if DEBUG
DebugSafeHandleMinusOneIsInvalid
#else
SafeHandleMinusOneIsInvalid
#endif
{
private int _receiveTimeout = -1;
private int _sendTimeout = -1;
private bool _nonBlocking;
private SocketAsyncContext _asyncContext;
private TrackedSocketOptions _trackedOptions;
internal bool LastConnectFailed { get; set; }
internal bool DualMode { get; set; }
internal bool ExposedHandleOrUntrackedConfiguration { get; private set; }
public void RegisterConnectResult(SocketError error)
{
switch (error)
{
case SocketError.Success:
case SocketError.WouldBlock:
break;
default:
LastConnectFailed = true;
break;
}
}
public void TransferTrackedState(SafeCloseSocket target)
{
target._trackedOptions = _trackedOptions;
target.LastConnectFailed = LastConnectFailed;
target.DualMode = DualMode;
target.ExposedHandleOrUntrackedConfiguration = ExposedHandleOrUntrackedConfiguration;
}
public void SetExposed() => ExposedHandleOrUntrackedConfiguration = true;
public bool IsTrackedOption(TrackedSocketOptions option) => (_trackedOptions & option) != 0;
public void TrackOption(SocketOptionLevel level, SocketOptionName name)
{
// As long as only these options are set, we can support Connect{Async}(IPAddress[], ...).
switch (level)
{
case SocketOptionLevel.Tcp:
switch (name)
{
case SocketOptionName.NoDelay: _trackedOptions |= TrackedSocketOptions.NoDelay; return;
}
break;
case SocketOptionLevel.IP:
switch (name)
{
case SocketOptionName.DontFragment: _trackedOptions |= TrackedSocketOptions.DontFragment; return;
case SocketOptionName.IpTimeToLive: _trackedOptions |= TrackedSocketOptions.Ttl; return;
}
break;
case SocketOptionLevel.IPv6:
switch (name)
{
case SocketOptionName.IPv6Only: _trackedOptions |= TrackedSocketOptions.DualMode; return;
case SocketOptionName.IpTimeToLive: _trackedOptions |= TrackedSocketOptions.Ttl; return;
}
break;
case SocketOptionLevel.Socket:
switch (name)
{
case SocketOptionName.Broadcast: _trackedOptions |= TrackedSocketOptions.EnableBroadcast; return;
case SocketOptionName.Linger: _trackedOptions |= TrackedSocketOptions.LingerState; return;
case SocketOptionName.ReceiveBuffer: _trackedOptions |= TrackedSocketOptions.ReceiveBufferSize; return;
case SocketOptionName.ReceiveTimeout: _trackedOptions |= TrackedSocketOptions.ReceiveTimeout; return;
case SocketOptionName.SendBuffer: _trackedOptions |= TrackedSocketOptions.SendBufferSize; return;
case SocketOptionName.SendTimeout: _trackedOptions |= TrackedSocketOptions.SendTimeout; return;
}
break;
}
// For any other settings, we need to track that they were used so that we can error out
// if a Connect{Async}(IPAddress[],...) attempt is made.
ExposedHandleOrUntrackedConfiguration = true;
}
public SocketAsyncContext AsyncContext
{
get
{
if (Volatile.Read(ref _asyncContext) == null)
{
Interlocked.CompareExchange(ref _asyncContext, new SocketAsyncContext(this), null);
}
return _asyncContext;
}
}
public bool IsNonBlocking
{
get
{
return _nonBlocking;
}
set
{
_nonBlocking = value;
//
// If transitioning to non-blocking, we need to set the native socket to non-blocking mode.
// If we ever transition back to blocking, we keep the native socket in non-blocking mode, and emulate
// blocking. This avoids problems with switching to native blocking while there are pending async
// operations.
//
if (value)
{
AsyncContext.SetNonBlocking();
}
}
}
public int ReceiveTimeout
{
get
{
return _receiveTimeout;
}
set
{
Debug.Assert(value == -1 || value > 0, $"Unexpected value: {value}");
_receiveTimeout = value;;
}
}
public int SendTimeout
{
get
{
return _sendTimeout;
}
set
{
Debug.Assert(value == -1 || value > 0, $"Unexpected value: {value}");
_sendTimeout = value;
}
}
public bool IsDisconnected { get; private set; } = false;
public void SetToDisconnected()
{
IsDisconnected = true;
}
public static unsafe SafeCloseSocket CreateSocket(IntPtr fileDescriptor)
{
return CreateSocket(InnerSafeCloseSocket.CreateSocket(fileDescriptor));
}
public static unsafe SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeCloseSocket socket)
{
SocketError errorCode;
socket = CreateSocket(InnerSafeCloseSocket.CreateSocket(addressFamily, socketType, protocolType, out errorCode));
return errorCode;
}
public static unsafe SocketError Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressSize, out SafeCloseSocket socket)
{
SocketError errorCode;
socket = CreateSocket(InnerSafeCloseSocket.Accept(socketHandle, socketAddress, ref socketAddressSize, out errorCode));
return errorCode;
}
private void InnerReleaseHandle()
{
if (_asyncContext != null)
{
_asyncContext.Close();
}
}
internal sealed partial class InnerSafeCloseSocket : SafeHandleMinusOneIsInvalid
{
private unsafe SocketError InnerReleaseHandle()
{
int errorCode;
// If _blockable was set in BlockingRelease, it's safe to block here, which means
// we can honor the linger options set on the socket. It also means closesocket() might return WSAEWOULDBLOCK, in which
// case we need to do some recovery.
if (_blockable)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle} Following 'blockable' branch.");
errorCode = Interop.Sys.Close(handle);
if (errorCode == -1)
{
errorCode = (int)Interop.Sys.GetLastError();
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, close()#1:{errorCode}");
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
// If it's not EWOULDBLOCK, there's no more recourse - we either succeeded or failed.
if (errorCode != (int)Interop.Error.EWOULDBLOCK)
{
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
// The socket must be non-blocking with a linger timeout set.
// We have to set the socket to blocking.
errorCode = Interop.Sys.Fcntl.DangerousSetIsNonBlocking(handle, 0);
if (errorCode == 0)
{
// The socket successfully made blocking; retry the close().
errorCode = Interop.Sys.Close(handle);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, close()#2:{errorCode}");
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
// The socket could not be made blocking; fall through to the regular abortive close.
}
// By default or if CloseAsIs() path failed, set linger timeout to zero to get an abortive close (RST).
var linger = new Interop.Sys.LingerOption {
OnOff = 1,
Seconds = 0
};
errorCode = (int)Interop.Sys.SetLingerOption(handle, &linger);
#if DEBUG
_closeSocketLinger = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, setsockopt():{errorCode}");
if (errorCode != 0 && errorCode != (int)Interop.Error.EINVAL && errorCode != (int)Interop.Error.ENOPROTOOPT)
{
// Too dangerous to try closesocket() - it might block!
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
errorCode = Interop.Sys.Close(handle);
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, close#3():{(errorCode == -1 ? (int)Interop.Sys.GetLastError() : errorCode)}");
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
public static InnerSafeCloseSocket CreateSocket(IntPtr fileDescriptor)
{
var res = new InnerSafeCloseSocket();
res.SetHandle(fileDescriptor);
return res;
}
public static unsafe InnerSafeCloseSocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SocketError errorCode)
{
IntPtr fd;
Interop.Error error = Interop.Sys.Socket(addressFamily, socketType, protocolType, &fd);
if (error == Interop.Error.SUCCESS)
{
Debug.Assert(fd != (IntPtr)(-1), "fd should not be -1");
errorCode = SocketError.Success;
// The socket was created successfully; enable IPV6_V6ONLY by default for AF_INET6 sockets.
if (addressFamily == AddressFamily.InterNetworkV6)
{
int on = 1;
error = Interop.Sys.SetSockOpt(fd, SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, (byte*)&on, sizeof(int));
if (error != Interop.Error.SUCCESS)
{
Interop.Sys.Close(fd);
fd = (IntPtr)(-1);
errorCode = SocketPal.GetSocketErrorForErrorCode(error);
}
}
}
else
{
Debug.Assert(fd == (IntPtr)(-1), $"Unexpected fd: {fd}");
errorCode = SocketPal.GetSocketErrorForErrorCode(error);
}
var res = new InnerSafeCloseSocket();
res.SetHandle(fd);
return res;
}
public static unsafe InnerSafeCloseSocket Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressLen, out SocketError errorCode)
{
IntPtr acceptedFd;
if (!socketHandle.IsNonBlocking)
{
errorCode = socketHandle.AsyncContext.Accept(socketAddress, ref socketAddressLen, -1, out acceptedFd);
}
else
{
bool completed = SocketPal.TryCompleteAccept(socketHandle, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode);
if (!completed)
{
errorCode = SocketError.WouldBlock;
}
}
var res = new InnerSafeCloseSocket();
res.SetHandle(acceptedFd);
return res;
}
}
}
/// <summary>Flags that correspond to exposed options on Socket.</summary>
[Flags]
internal enum TrackedSocketOptions : short
{
DontFragment = 0x1,
DualMode = 0x2,
EnableBroadcast = 0x4,
LingerState = 0x8,
NoDelay = 0x10,
ReceiveBufferSize = 0x20,
ReceiveTimeout = 0x40,
SendBufferSize = 0x80,
SendTimeout = 0x100,
Ttl = 0x200,
}
}
| |
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Windows.Kinect
{
//
// Windows.Kinect.LongExposureInfraredFrameReader
//
public sealed partial class LongExposureInfraredFrameReader : RootSystem.IDisposable, Helper.INativeWrapper
{
internal RootSystem.IntPtr _pNative;
RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } }
// Constructors and Finalizers
internal LongExposureInfraredFrameReader(RootSystem.IntPtr pNative)
{
_pNative = pNative;
Windows_Kinect_LongExposureInfraredFrameReader_AddRefObject(ref _pNative);
}
~LongExposureInfraredFrameReader()
{
Dispose(false);
}
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReader_ReleaseObject(ref RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReader_AddRefObject(ref RootSystem.IntPtr pNative);
private void Dispose(bool disposing)
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
__EventCleanup();
Helper.NativeObjectCache.RemoveObject<LongExposureInfraredFrameReader>(_pNative);
if (disposing)
{
Windows_Kinect_LongExposureInfraredFrameReader_Dispose(_pNative);
}
Windows_Kinect_LongExposureInfraredFrameReader_ReleaseObject(ref _pNative);
_pNative = RootSystem.IntPtr.Zero;
}
// Public Properties
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern bool Windows_Kinect_LongExposureInfraredFrameReader_get_IsPaused(RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReader_put_IsPaused(RootSystem.IntPtr pNative, bool isPaused);
public bool IsPaused
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameReader");
}
return Windows_Kinect_LongExposureInfraredFrameReader_get_IsPaused(_pNative);
}
set
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameReader");
}
Windows_Kinect_LongExposureInfraredFrameReader_put_IsPaused(_pNative, value);
Helper.ExceptionHelper.CheckLastError();
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Windows_Kinect_LongExposureInfraredFrameReader_get_LongExposureInfraredFrameSource(RootSystem.IntPtr pNative);
public Windows.Kinect.LongExposureInfraredFrameSource LongExposureInfraredFrameSource
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameReader");
}
RootSystem.IntPtr objectPointer = Windows_Kinect_LongExposureInfraredFrameReader_get_LongExposureInfraredFrameSource(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.LongExposureInfraredFrameSource>(objectPointer, n => new Windows.Kinect.LongExposureInfraredFrameSource(n));
}
}
// Events
private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handle;
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void _Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative);
private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.LongExposureInfraredFrameArrivedEventArgs>>> Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.LongExposureInfraredFrameArrivedEventArgs>>>();
[AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate))]
private static void Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative)
{
List<RootSystem.EventHandler<Windows.Kinect.LongExposureInfraredFrameArrivedEventArgs>> callbackList = null;
Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList);
lock(callbackList)
{
var objThis = Helper.NativeObjectCache.GetObject<LongExposureInfraredFrameReader>(pNative);
var args = new Windows.Kinect.LongExposureInfraredFrameArrivedEventArgs(result);
foreach(var func in callbackList)
{
Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } });
}
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReader_add_FrameArrived(RootSystem.IntPtr pNative, _Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate eventCallback, bool unsubscribe);
public event RootSystem.EventHandler<Windows.Kinect.LongExposureInfraredFrameArrivedEventArgs> FrameArrived
{
add
{
Helper.EventPump.EnsureInitialized();
Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Add(value);
if(callbackList.Count == 1)
{
var del = new _Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate(Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handler);
_Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del);
Windows_Kinect_LongExposureInfraredFrameReader_add_FrameArrived(_pNative, del, false);
}
}
}
remove
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Remove(value);
if(callbackList.Count == 0)
{
Windows_Kinect_LongExposureInfraredFrameReader_add_FrameArrived(_pNative, Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handler, true);
_Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handle.Free();
}
}
}
}
private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Data_PropertyChangedEventArgs_Delegate_Handle;
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void _Windows_Data_PropertyChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative);
private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>> Windows_Data_PropertyChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>>();
[AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Data_PropertyChangedEventArgs_Delegate))]
private static void Windows_Data_PropertyChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative)
{
List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>> callbackList = null;
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList);
lock(callbackList)
{
var objThis = Helper.NativeObjectCache.GetObject<LongExposureInfraredFrameReader>(pNative);
var args = new Windows.Data.PropertyChangedEventArgs(result);
foreach(var func in callbackList)
{
Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } });
}
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReader_add_PropertyChanged(RootSystem.IntPtr pNative, _Windows_Data_PropertyChangedEventArgs_Delegate eventCallback, bool unsubscribe);
public event RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs> PropertyChanged
{
add
{
Helper.EventPump.EnsureInitialized();
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Add(value);
if(callbackList.Count == 1)
{
var del = new _Windows_Data_PropertyChangedEventArgs_Delegate(Windows_Data_PropertyChangedEventArgs_Delegate_Handler);
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del);
Windows_Kinect_LongExposureInfraredFrameReader_add_PropertyChanged(_pNative, del, false);
}
}
}
remove
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Remove(value);
if(callbackList.Count == 0)
{
Windows_Kinect_LongExposureInfraredFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true);
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free();
}
}
}
}
// Public Methods
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Windows_Kinect_LongExposureInfraredFrameReader_AcquireLatestFrame(RootSystem.IntPtr pNative);
public Windows.Kinect.LongExposureInfraredFrame AcquireLatestFrame()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrameReader");
}
RootSystem.IntPtr objectPointer = Windows_Kinect_LongExposureInfraredFrameReader_AcquireLatestFrame(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.LongExposureInfraredFrame>(objectPointer, n => new Windows.Kinect.LongExposureInfraredFrame(n));
}
[RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Windows_Kinect_LongExposureInfraredFrameReader_Dispose(RootSystem.IntPtr pNative);
public void Dispose()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Dispose(true);
RootSystem.GC.SuppressFinalize(this);
}
private void __EventCleanup()
{
{
Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
if (callbackList.Count > 0)
{
callbackList.Clear();
if (_pNative != RootSystem.IntPtr.Zero)
{
Windows_Kinect_LongExposureInfraredFrameReader_add_FrameArrived(_pNative, Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handler, true);
}
_Windows_Kinect_LongExposureInfraredFrameArrivedEventArgs_Delegate_Handle.Free();
}
}
}
{
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
if (callbackList.Count > 0)
{
callbackList.Clear();
if (_pNative != RootSystem.IntPtr.Zero)
{
Windows_Kinect_LongExposureInfraredFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true);
}
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free();
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Xml;
using System.Reflection;
using System.Reflection.Emit;
using System.IO;
using System.Security;
using System.Diagnostics;
#if !NET_NATIVE
namespace System.Runtime.Serialization
{
internal class CodeGenerator
{
/// <SecurityNote>
/// Critical - Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
[SecurityCritical]
private static MethodInfo s_getTypeFromHandle;
private static MethodInfo GetTypeFromHandle
{
/// <SecurityNote>
/// Critical - fetches the critical getTypeFromHandle field
/// Safe - get-only properties only needs to be protected for write; initialized in getter if null.
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (s_getTypeFromHandle == null)
{
s_getTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle");
Debug.Assert(s_getTypeFromHandle != null);
}
return s_getTypeFromHandle;
}
}
/// <SecurityNote>
/// Critical - Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
[SecurityCritical]
private static MethodInfo s_objectEquals;
private static MethodInfo ObjectEquals
{
/// <SecurityNote>
/// Critical - fetches the critical objectEquals field
/// Safe - get-only properties only needs to be protected for write; initialized in getter if null.
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (s_objectEquals == null)
{
s_objectEquals = Globals.TypeOfObject.GetMethod("Equals", BindingFlags.Public | BindingFlags.Static);
Debug.Assert(s_objectEquals != null);
}
return s_objectEquals;
}
}
/// <SecurityNote>
/// Critical - Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
[SecurityCritical]
private static MethodInfo s_arraySetValue;
private static MethodInfo ArraySetValue
{
/// <SecurityNote>
/// Critical - fetches the critical arraySetValue field
/// Safe - get-only properties only needs to be protected for write; initialized in getter if null.
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (s_arraySetValue == null)
{
s_arraySetValue = typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) });
Debug.Assert(s_arraySetValue != null);
}
return s_arraySetValue;
}
}
#if !NET_NATIVE
[SecurityCritical]
private static MethodInfo s_objectToString;
private static MethodInfo ObjectToString
{
[SecuritySafeCritical]
get
{
if (s_objectToString == null)
{
s_objectToString = typeof(object).GetMethod("ToString", Array.Empty<Type>());
Debug.Assert(s_objectToString != null);
}
return s_objectToString;
}
}
private static MethodInfo s_stringFormat;
private static MethodInfo StringFormat
{
[SecuritySafeCritical]
get
{
if (s_stringFormat == null)
{
s_stringFormat = typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object[]) });
Debug.Assert(s_stringFormat != null);
}
return s_stringFormat;
}
}
#endif
private Type _delegateType;
#if USE_REFEMIT
AssemblyBuilder assemblyBuilder;
ModuleBuilder moduleBuilder;
TypeBuilder typeBuilder;
static int typeCounter;
MethodBuilder methodBuilder;
#else
/// <SecurityNote>
/// Critical - Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
[SecurityCritical]
private static Module s_serializationModule;
private static Module SerializationModule
{
/// <SecurityNote>
/// Critical - fetches the critical serializationModule field
/// Safe - get-only properties only needs to be protected for write; initialized in getter if null.
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (s_serializationModule == null)
{
s_serializationModule = typeof(CodeGenerator).GetTypeInfo().Module; // could to be replaced by different dll that has SkipVerification set to false
}
return s_serializationModule;
}
}
private DynamicMethod _dynamicMethod;
#endif
private ILGenerator _ilGen;
private List<ArgBuilder> _argList;
private Stack<object> _blockStack;
private Label _methodEndLabel;
private Dictionary<LocalBuilder, string> _localNames = new Dictionary<LocalBuilder, string>();
private enum CodeGenTrace { None, Save, Tron };
private CodeGenTrace _codeGenTrace;
#if !NET_NATIVE
private LocalBuilder _stringFormatArray;
#endif
internal CodeGenerator()
{
//Defaulting to None as thats the default value in WCF
_codeGenTrace = CodeGenTrace.None;
}
#if !USE_REFEMIT
internal void BeginMethod(DynamicMethod dynamicMethod, Type delegateType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess)
{
_dynamicMethod = dynamicMethod;
_ilGen = _dynamicMethod.GetILGenerator();
_delegateType = delegateType;
InitILGeneration(methodName, argTypes);
}
#endif
internal void BeginMethod(string methodName, Type delegateType, bool allowPrivateMemberAccess)
{
MethodInfo signature = delegateType.GetMethod("Invoke");
ParameterInfo[] parameters = signature.GetParameters();
Type[] paramTypes = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
paramTypes[i] = parameters[i].ParameterType;
BeginMethod(signature.ReturnType, methodName, paramTypes, allowPrivateMemberAccess);
_delegateType = delegateType;
}
[SecuritySafeCritical]
private void BeginMethod(Type returnType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess)
{
#if USE_REFEMIT
string typeName = "Type" + (typeCounter++);
InitAssemblyBuilder(typeName + "." + methodName);
this.typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public);
this.methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public|MethodAttributes.Static, returnType, argTypes);
this.ilGen = this.methodBuilder.GetILGenerator();
#else
_dynamicMethod = new DynamicMethod(methodName, returnType, argTypes, SerializationModule, allowPrivateMemberAccess);
_ilGen = _dynamicMethod.GetILGenerator();
#endif
InitILGeneration(methodName, argTypes);
}
private void InitILGeneration(string methodName, Type[] argTypes)
{
_methodEndLabel = _ilGen.DefineLabel();
_blockStack = new Stack<object>();
_argList = new List<ArgBuilder>();
for (int i = 0; i < argTypes.Length; i++)
_argList.Add(new ArgBuilder(i, argTypes[i]));
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceLabel("Begin method " + methodName + " {");
}
internal Delegate EndMethod()
{
MarkLabel(_methodEndLabel);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceLabel("} End method");
Ret();
Delegate retVal = null;
#if USE_REFEMIT
Type type = typeBuilder.CreateType();
MethodInfo method = type.GetMethod(methodBuilder.Name);
retVal = Delegate.CreateDelegate(delegateType, method);
methodBuilder = null;
#else
retVal = _dynamicMethod.CreateDelegate(_delegateType);
_dynamicMethod = null;
#endif
_delegateType = null;
_ilGen = null;
_blockStack = null;
_argList = null;
return retVal;
}
internal MethodInfo CurrentMethod
{
get
{
#if USE_REFEMIT
return methodBuilder;
#else
return _dynamicMethod;
#endif
}
}
internal ArgBuilder GetArg(int index)
{
return (ArgBuilder)_argList[index];
}
internal Type GetVariableType(object var)
{
if (var is ArgBuilder)
return ((ArgBuilder)var).ArgType;
else if (var is LocalBuilder)
return ((LocalBuilder)var).LocalType;
else
return var.GetType();
}
internal LocalBuilder DeclareLocal(Type type, string name, object initialValue)
{
LocalBuilder local = DeclareLocal(type, name);
Load(initialValue);
Store(local);
return local;
}
internal LocalBuilder DeclareLocal(Type type, string name)
{
return DeclareLocal(type, name, false);
}
internal LocalBuilder DeclareLocal(Type type, string name, bool isPinned)
{
LocalBuilder local = _ilGen.DeclareLocal(type, isPinned);
if (_codeGenTrace != CodeGenTrace.None)
{
_localNames[local] = name;
EmitSourceComment("Declare local '" + name + "' of type " + type);
}
return local;
}
internal void Set(LocalBuilder local, object value)
{
Load(value);
Store(local);
}
internal object For(LocalBuilder local, object start, object end)
{
ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end);
if (forState.Index != null)
{
Load(start);
Stloc(forState.Index);
Br(forState.TestLabel);
}
MarkLabel(forState.BeginLabel);
_blockStack.Push(forState);
return forState;
}
internal void EndFor()
{
object stackTop = _blockStack.Pop();
ForState forState = stackTop as ForState;
if (forState == null)
ThrowMismatchException(stackTop);
if (forState.Index != null)
{
Ldloc(forState.Index);
Ldc(1);
Add();
Stloc(forState.Index);
MarkLabel(forState.TestLabel);
Ldloc(forState.Index);
Load(forState.End);
if (GetVariableType(forState.End).IsArray)
Ldlen();
Blt(forState.BeginLabel);
}
else
Br(forState.BeginLabel);
if (forState.RequiresEndLabel)
MarkLabel(forState.EndLabel);
}
internal void Break(object forState)
{
InternalBreakFor(forState, OpCodes.Br);
}
internal void IfFalseBreak(object forState)
{
InternalBreakFor(forState, OpCodes.Brfalse);
}
internal void InternalBreakFor(object userForState, OpCode branchInstruction)
{
foreach (object block in _blockStack)
{
ForState forState = block as ForState;
if (forState != null && (object)forState == userForState)
{
if (!forState.RequiresEndLabel)
{
forState.EndLabel = DefineLabel();
forState.RequiresEndLabel = true;
}
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(branchInstruction + " " + forState.EndLabel.GetHashCode());
_ilGen.Emit(branchInstruction, forState.EndLabel);
break;
}
}
}
internal void ForEach(LocalBuilder local, Type elementType, Type enumeratorType,
LocalBuilder enumerator, MethodInfo getCurrentMethod)
{
ForState forState = new ForState(local, DefineLabel(), DefineLabel(), enumerator);
Br(forState.TestLabel);
MarkLabel(forState.BeginLabel);
Call(enumerator, getCurrentMethod);
ConvertValue(elementType, GetVariableType(local));
Stloc(local);
_blockStack.Push(forState);
}
internal void EndForEach(MethodInfo moveNextMethod)
{
object stackTop = _blockStack.Pop();
ForState forState = stackTop as ForState;
if (forState == null)
ThrowMismatchException(stackTop);
MarkLabel(forState.TestLabel);
object enumerator = forState.End;
Call(enumerator, moveNextMethod);
Brtrue(forState.BeginLabel);
if (forState.RequiresEndLabel)
MarkLabel(forState.EndLabel);
}
internal void IfNotDefaultValue(object value)
{
Type type = GetVariableType(value);
TypeCode typeCode = type.GetTypeCode();
if ((typeCode == TypeCode.Object && type.GetTypeInfo().IsValueType) ||
typeCode == TypeCode.DateTime || typeCode == TypeCode.Decimal)
{
LoadDefaultValue(type);
ConvertValue(type, Globals.TypeOfObject);
Load(value);
ConvertValue(type, Globals.TypeOfObject);
Call(ObjectEquals);
IfNot();
}
else
{
LoadDefaultValue(type);
Load(value);
If(Cmp.NotEqualTo);
}
}
internal void If()
{
InternalIf(false);
}
internal void IfNot()
{
InternalIf(true);
}
private OpCode GetBranchCode(Cmp cmp)
{
switch (cmp)
{
case Cmp.LessThan:
return OpCodes.Bge;
case Cmp.EqualTo:
return OpCodes.Bne_Un;
case Cmp.LessThanOrEqualTo:
return OpCodes.Bgt;
case Cmp.GreaterThan:
return OpCodes.Ble;
case Cmp.NotEqualTo:
return OpCodes.Beq;
default:
DiagnosticUtility.DebugAssert(cmp == Cmp.GreaterThanOrEqualTo, "Unexpected cmp");
return OpCodes.Blt;
}
}
internal void If(Cmp cmpOp)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void If(object value1, Cmp cmpOp, object value2)
{
Load(value1);
Load(value2);
If(cmpOp);
}
internal void Else()
{
IfState ifState = PopIfState();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
ifState.ElseBegin = ifState.EndIf;
_blockStack.Push(ifState);
}
internal void ElseIf(object value1, Cmp cmpOp, object value2)
{
IfState ifState = (IfState)_blockStack.Pop();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
Load(value1);
Load(value2);
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void EndIf()
{
IfState ifState = PopIfState();
if (!ifState.ElseBegin.Equals(ifState.EndIf))
MarkLabel(ifState.ElseBegin);
MarkLabel(ifState.EndIf);
}
internal void VerifyParameterCount(MethodInfo methodInfo, int expectedCount)
{
if (methodInfo.GetParameters().Length != expectedCount)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.ParameterCountMismatch, methodInfo.Name, methodInfo.GetParameters().Length, expectedCount)));
}
internal void Call(object thisObj, MethodInfo methodInfo)
{
VerifyParameterCount(methodInfo, 0);
LoadThis(thisObj, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1)
{
VerifyParameterCount(methodInfo, 1);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2)
{
VerifyParameterCount(methodInfo, 2);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3)
{
VerifyParameterCount(methodInfo, 3);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4)
{
VerifyParameterCount(methodInfo, 4);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
LoadParam(param4, 4, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5)
{
VerifyParameterCount(methodInfo, 5);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
LoadParam(param4, 4, methodInfo);
LoadParam(param5, 5, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5, object param6)
{
VerifyParameterCount(methodInfo, 6);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
LoadParam(param4, 4, methodInfo);
LoadParam(param5, 5, methodInfo);
LoadParam(param6, 6, methodInfo);
Call(methodInfo);
}
internal void Call(MethodInfo methodInfo)
{
if (methodInfo.IsVirtual && !methodInfo.DeclaringType.GetTypeInfo().IsValueType)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Callvirt " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Callvirt, methodInfo);
}
else if (methodInfo.IsStatic)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Static Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Call, methodInfo);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Call, methodInfo);
}
}
internal void Call(ConstructorInfo ctor)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Call " + ctor.ToString() + " on type " + ctor.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Call, ctor);
}
internal void New(ConstructorInfo constructorInfo)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Newobj " + constructorInfo.ToString() + " on type " + constructorInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Newobj, constructorInfo);
}
internal void InitObj(Type valueType)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Initobj " + valueType);
_ilGen.Emit(OpCodes.Initobj, valueType);
}
internal void NewArray(Type elementType, object len)
{
Load(len);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Newarr " + elementType);
_ilGen.Emit(OpCodes.Newarr, elementType);
}
internal void LoadArrayElement(object obj, object arrayIndex)
{
Type objType = GetVariableType(obj).GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
{
Ldelema(objType);
Ldobj(objType);
}
else
Ldelem(objType);
}
internal void StoreArrayElement(object obj, object arrayIndex, object value)
{
Type arrayType = GetVariableType(obj);
if (arrayType == Globals.TypeOfArray)
{
Call(obj, ArraySetValue, value, arrayIndex);
}
else
{
Type objType = arrayType.GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
Ldelema(objType);
Load(value);
ConvertValue(GetVariableType(value), objType);
if (IsStruct(objType))
Stobj(objType);
else
Stelem(objType);
}
}
private static bool IsStruct(Type objType)
{
return objType.GetTypeInfo().IsValueType && !objType.GetTypeInfo().IsPrimitive;
}
internal Type LoadMember(MemberInfo memberInfo)
{
Type memberType = null;
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
memberType = fieldInfo.FieldType;
if (fieldInfo.IsStatic)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Ldsfld, fieldInfo);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Ldfld, fieldInfo);
}
}
else if (memberInfo is PropertyInfo)
{
PropertyInfo property = memberInfo as PropertyInfo;
memberType = property.PropertyType;
if (property != null)
{
MethodInfo getMethod = property.GetMethod;
if (getMethod == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.NoGetMethodForProperty, property.DeclaringType, property)));
Call(getMethod);
}
}
else if (memberInfo is MethodInfo)
{
MethodInfo method = (MethodInfo)memberInfo;
memberType = method.ReturnType;
Call(method);
}
else
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.CannotLoadMemberType, "Unknown", memberInfo.DeclaringType, memberInfo.Name)));
EmitStackTop(memberType);
return memberType;
}
internal void StoreMember(MemberInfo memberInfo)
{
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
if (fieldInfo.IsStatic)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Stsfld, fieldInfo);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Stfld, fieldInfo);
}
}
else if (memberInfo is PropertyInfo)
{
PropertyInfo property = memberInfo as PropertyInfo;
if (property != null)
{
MethodInfo setMethod = property.SetMethod;
if (setMethod == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.NoSetMethodForProperty, property.DeclaringType, property)));
Call(setMethod);
}
}
else if (memberInfo is MethodInfo)
Call((MethodInfo)memberInfo);
else
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.CannotLoadMemberType, "Unknown")));
}
internal void LoadDefaultValue(Type type)
{
if (type.GetTypeInfo().IsValueType)
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
Ldc(false);
break;
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
Ldc(0);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
Ldc(0L);
break;
case TypeCode.Single:
Ldc(0.0F);
break;
case TypeCode.Double:
Ldc(0.0);
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
default:
LocalBuilder zero = DeclareLocal(type, "zero");
LoadAddress(zero);
InitObj(type);
Load(zero);
break;
}
}
else
Load(null);
}
internal void Load(object obj)
{
if (obj == null)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldnull");
_ilGen.Emit(OpCodes.Ldnull);
}
else if (obj is ArgBuilder)
Ldarg((ArgBuilder)obj);
else if (obj is LocalBuilder)
Ldloc((LocalBuilder)obj);
else
Ldc(obj);
}
internal void Store(object var)
{
if (var is ArgBuilder)
Starg((ArgBuilder)var);
else if (var is LocalBuilder)
Stloc((LocalBuilder)var);
else
{
DiagnosticUtility.DebugAssert("Data can only be stored into ArgBuilder or LocalBuilder.");
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.CanOnlyStoreIntoArgOrLocGot0, DataContract.GetClrTypeFullName(var.GetType()))));
}
}
internal void Dec(object var)
{
Load(var);
Load(1);
Subtract();
Store(var);
}
internal void LoadAddress(object obj)
{
if (obj is ArgBuilder)
LdargAddress((ArgBuilder)obj);
else if (obj is LocalBuilder)
LdlocAddress((LocalBuilder)obj);
else
Load(obj);
}
internal void ConvertAddress(Type source, Type target)
{
InternalConvert(source, target, true);
}
internal void ConvertValue(Type source, Type target)
{
InternalConvert(source, target, false);
}
internal void Castclass(Type target)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Castclass " + target);
_ilGen.Emit(OpCodes.Castclass, target);
}
internal void Box(Type type)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Box " + type);
_ilGen.Emit(OpCodes.Box, type);
}
internal void Unbox(Type type)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Unbox " + type);
_ilGen.Emit(OpCodes.Unbox, type);
}
private OpCode GetLdindOpCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Boolean:
return OpCodes.Ldind_I1; // TypeCode.Boolean:
case TypeCode.Char:
return OpCodes.Ldind_I2; // TypeCode.Char:
case TypeCode.SByte:
return OpCodes.Ldind_I1; // TypeCode.SByte:
case TypeCode.Byte:
return OpCodes.Ldind_U1; // TypeCode.Byte:
case TypeCode.Int16:
return OpCodes.Ldind_I2; // TypeCode.Int16:
case TypeCode.UInt16:
return OpCodes.Ldind_U2; // TypeCode.UInt16:
case TypeCode.Int32:
return OpCodes.Ldind_I4; // TypeCode.Int32:
case TypeCode.UInt32:
return OpCodes.Ldind_U4; // TypeCode.UInt32:
case TypeCode.Int64:
return OpCodes.Ldind_I8; // TypeCode.Int64:
case TypeCode.UInt64:
return OpCodes.Ldind_I8; // TypeCode.UInt64:
case TypeCode.Single:
return OpCodes.Ldind_R4; // TypeCode.Single:
case TypeCode.Double:
return OpCodes.Ldind_R8; // TypeCode.Double:
case TypeCode.String:
return OpCodes.Ldind_Ref; // TypeCode.String:
default:
return OpCodes.Nop;
}
}
internal void Ldobj(Type type)
{
OpCode opCode = GetLdindOpCode(type.GetTypeCode());
if (!opCode.Equals(OpCodes.Nop))
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldobj " + type);
_ilGen.Emit(OpCodes.Ldobj, type);
}
}
internal void Stobj(Type type)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stobj " + type);
_ilGen.Emit(OpCodes.Stobj, type);
}
internal void Ceq()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ceq");
_ilGen.Emit(OpCodes.Ceq);
}
internal void Throw()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Throw");
_ilGen.Emit(OpCodes.Throw);
}
internal void Ldtoken(Type t)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldtoken " + t);
_ilGen.Emit(OpCodes.Ldtoken, t);
}
internal void Ldc(object o)
{
Type valueType = o.GetType();
if (o is Type)
{
Ldtoken((Type)o);
Call(GetTypeFromHandle);
}
else if (valueType.GetTypeInfo().IsEnum)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceComment("Ldc " + o.GetType() + "." + o);
Ldc(Convert.ChangeType(o, Enum.GetUnderlyingType(valueType), null));
}
else
{
switch (valueType.GetTypeCode())
{
case TypeCode.Boolean:
Ldc((bool)o);
break;
case TypeCode.Char:
DiagnosticUtility.DebugAssert("Char is not a valid schema primitive and should be treated as int in DataContract");
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(string.Format(SRSerialization.CharIsInvalidPrimitive)));
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
Ldc(Convert.ToInt32(o, CultureInfo.InvariantCulture));
break;
case TypeCode.Int32:
Ldc((int)o);
break;
case TypeCode.UInt32:
Ldc((int)(uint)o);
break;
case TypeCode.UInt64:
Ldc((long)(ulong)o);
break;
case TypeCode.Int64:
Ldc((long)o);
break;
case TypeCode.Single:
Ldc((float)o);
break;
case TypeCode.Double:
Ldc((double)o);
break;
case TypeCode.String:
Ldstr((string)o);
break;
case TypeCode.Object:
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.Empty:
default:
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.UnknownConstantType, DataContract.GetClrTypeFullName(valueType))));
}
}
}
internal void Ldc(bool boolVar)
{
if (boolVar)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i4 1");
_ilGen.Emit(OpCodes.Ldc_I4_1);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i4 0");
_ilGen.Emit(OpCodes.Ldc_I4_0);
}
}
internal void Ldc(int intVar)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i4 " + intVar);
switch (intVar)
{
case -1:
_ilGen.Emit(OpCodes.Ldc_I4_M1);
break;
case 0:
_ilGen.Emit(OpCodes.Ldc_I4_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldc_I4_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldc_I4_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldc_I4_3);
break;
case 4:
_ilGen.Emit(OpCodes.Ldc_I4_4);
break;
case 5:
_ilGen.Emit(OpCodes.Ldc_I4_5);
break;
case 6:
_ilGen.Emit(OpCodes.Ldc_I4_6);
break;
case 7:
_ilGen.Emit(OpCodes.Ldc_I4_7);
break;
case 8:
_ilGen.Emit(OpCodes.Ldc_I4_8);
break;
default:
_ilGen.Emit(OpCodes.Ldc_I4, intVar);
break;
}
}
internal void Ldc(long l)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i8 " + l);
_ilGen.Emit(OpCodes.Ldc_I8, l);
}
internal void Ldc(float f)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.r4 " + f);
_ilGen.Emit(OpCodes.Ldc_R4, f);
}
internal void Ldc(double d)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.r8 " + d);
_ilGen.Emit(OpCodes.Ldc_R8, d);
}
internal void Ldstr(string strVar)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldstr " + strVar);
_ilGen.Emit(OpCodes.Ldstr, strVar);
}
internal void LdlocAddress(LocalBuilder localBuilder)
{
if (localBuilder.LocalType.GetTypeInfo().IsValueType)
Ldloca(localBuilder);
else
Ldloc(localBuilder);
}
internal void Ldloc(LocalBuilder localBuilder)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldloc " + _localNames[localBuilder]);
_ilGen.Emit(OpCodes.Ldloc, localBuilder);
EmitStackTop(localBuilder.LocalType);
}
internal void Stloc(LocalBuilder local)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stloc " + _localNames[local]);
EmitStackTop(local.LocalType);
_ilGen.Emit(OpCodes.Stloc, local);
}
internal void Ldloca(LocalBuilder localBuilder)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldloca " + _localNames[localBuilder]);
_ilGen.Emit(OpCodes.Ldloca, localBuilder);
EmitStackTop(localBuilder.LocalType);
}
internal void LdargAddress(ArgBuilder argBuilder)
{
if (argBuilder.ArgType.GetTypeInfo().IsValueType)
Ldarga(argBuilder);
else
Ldarg(argBuilder);
}
internal void Ldarg(ArgBuilder arg)
{
Ldarg(arg.Index);
}
internal void Starg(ArgBuilder arg)
{
Starg(arg.Index);
}
internal void Ldarg(int slot)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldarg " + slot);
switch (slot)
{
case 0:
_ilGen.Emit(OpCodes.Ldarg_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldarg_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldarg_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldarg_3);
break;
default:
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarg_S, slot);
else
_ilGen.Emit(OpCodes.Ldarg, slot);
break;
}
}
internal void Starg(int slot)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Starg " + slot);
if (slot <= 255)
_ilGen.Emit(OpCodes.Starg_S, slot);
else
_ilGen.Emit(OpCodes.Starg, slot);
}
internal void Ldarga(ArgBuilder argBuilder)
{
Ldarga(argBuilder.Index);
}
internal void Ldarga(int slot)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldarga " + slot);
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarga_S, slot);
else
_ilGen.Emit(OpCodes.Ldarga, slot);
}
internal void Ldlen()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldlen");
_ilGen.Emit(OpCodes.Ldlen);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Conv.i4");
_ilGen.Emit(OpCodes.Conv_I4);
}
private OpCode GetLdelemOpCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Object:
return OpCodes.Ldelem_Ref;// TypeCode.Object:
case TypeCode.Boolean:
return OpCodes.Ldelem_I1;// TypeCode.Boolean:
case TypeCode.Char:
return OpCodes.Ldelem_I2;// TypeCode.Char:
case TypeCode.SByte:
return OpCodes.Ldelem_I1;// TypeCode.SByte:
case TypeCode.Byte:
return OpCodes.Ldelem_U1;// TypeCode.Byte:
case TypeCode.Int16:
return OpCodes.Ldelem_I2;// TypeCode.Int16:
case TypeCode.UInt16:
return OpCodes.Ldelem_U2;// TypeCode.UInt16:
case TypeCode.Int32:
return OpCodes.Ldelem_I4;// TypeCode.Int32:
case TypeCode.UInt32:
return OpCodes.Ldelem_U4;// TypeCode.UInt32:
case TypeCode.Int64:
return OpCodes.Ldelem_I8;// TypeCode.Int64:
case TypeCode.UInt64:
return OpCodes.Ldelem_I8;// TypeCode.UInt64:
case TypeCode.Single:
return OpCodes.Ldelem_R4;// TypeCode.Single:
case TypeCode.Double:
return OpCodes.Ldelem_R8;// TypeCode.Double:
case TypeCode.String:
return OpCodes.Ldelem_Ref;// TypeCode.String:
default:
return OpCodes.Nop;
}
}
internal void Ldelem(Type arrayElementType)
{
if (arrayElementType.GetTypeInfo().IsEnum)
{
Ldelem(Enum.GetUnderlyingType(arrayElementType));
}
else
{
OpCode opCode = GetLdelemOpCode(arrayElementType.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.ArrayTypeIsNotSupported, DataContract.GetClrTypeFullName(arrayElementType))));
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode);
EmitStackTop(arrayElementType);
}
}
internal void Ldelema(Type arrayElementType)
{
OpCode opCode = OpCodes.Ldelema;
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode, arrayElementType);
EmitStackTop(arrayElementType);
}
private OpCode GetStelemOpCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Object:
return OpCodes.Stelem_Ref;// TypeCode.Object:
case TypeCode.Boolean:
return OpCodes.Stelem_I1;// TypeCode.Boolean:
case TypeCode.Char:
return OpCodes.Stelem_I2;// TypeCode.Char:
case TypeCode.SByte:
return OpCodes.Stelem_I1;// TypeCode.SByte:
case TypeCode.Byte:
return OpCodes.Stelem_I1;// TypeCode.Byte:
case TypeCode.Int16:
return OpCodes.Stelem_I2;// TypeCode.Int16:
case TypeCode.UInt16:
return OpCodes.Stelem_I2;// TypeCode.UInt16:
case TypeCode.Int32:
return OpCodes.Stelem_I4;// TypeCode.Int32:
case TypeCode.UInt32:
return OpCodes.Stelem_I4;// TypeCode.UInt32:
case TypeCode.Int64:
return OpCodes.Stelem_I8;// TypeCode.Int64:
case TypeCode.UInt64:
return OpCodes.Stelem_I8;// TypeCode.UInt64:
case TypeCode.Single:
return OpCodes.Stelem_R4;// TypeCode.Single:
case TypeCode.Double:
return OpCodes.Stelem_R8;// TypeCode.Double:
case TypeCode.String:
return OpCodes.Stelem_Ref;// TypeCode.String:
default:
return OpCodes.Nop;
}
}
internal void Stelem(Type arrayElementType)
{
if (arrayElementType.GetTypeInfo().IsEnum)
Stelem(Enum.GetUnderlyingType(arrayElementType));
else
{
OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.ArrayTypeIsNotSupported, DataContract.GetClrTypeFullName(arrayElementType))));
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
EmitStackTop(arrayElementType);
_ilGen.Emit(opCode);
}
}
internal Label DefineLabel()
{
return _ilGen.DefineLabel();
}
internal void MarkLabel(Label label)
{
_ilGen.MarkLabel(label);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceLabel(label.GetHashCode() + ":");
}
internal void Add()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Add");
_ilGen.Emit(OpCodes.Add);
}
internal void Subtract()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Sub");
_ilGen.Emit(OpCodes.Sub);
}
internal void And()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("And");
_ilGen.Emit(OpCodes.And);
}
internal void Or()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Or");
_ilGen.Emit(OpCodes.Or);
}
internal void Not()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Not");
_ilGen.Emit(OpCodes.Not);
}
internal void Ret()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ret");
_ilGen.Emit(OpCodes.Ret);
}
internal void Br(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Br " + label.GetHashCode());
_ilGen.Emit(OpCodes.Br, label);
}
internal void Blt(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Blt " + label.GetHashCode());
_ilGen.Emit(OpCodes.Blt, label);
}
internal void Brfalse(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Brfalse " + label.GetHashCode());
_ilGen.Emit(OpCodes.Brfalse, label);
}
internal void Brtrue(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Brtrue " + label.GetHashCode());
_ilGen.Emit(OpCodes.Brtrue, label);
}
internal void Pop()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Pop");
_ilGen.Emit(OpCodes.Pop);
}
internal void Dup()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Dup");
_ilGen.Emit(OpCodes.Dup);
}
private void LoadThis(object thisObj, MethodInfo methodInfo)
{
if (thisObj != null && !methodInfo.IsStatic)
{
LoadAddress(thisObj);
ConvertAddress(GetVariableType(thisObj), methodInfo.DeclaringType);
}
}
private void LoadParam(object arg, int oneBasedArgIndex, MethodBase methodInfo)
{
Load(arg);
if (arg != null)
ConvertValue(GetVariableType(arg), methodInfo.GetParameters()[oneBasedArgIndex - 1].ParameterType);
}
private void InternalIf(bool negate)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
if (negate)
Brtrue(ifState.ElseBegin);
else
Brfalse(ifState.ElseBegin);
_blockStack.Push(ifState);
}
private OpCode GetConvOpCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Boolean:
return OpCodes.Conv_I1;// TypeCode.Boolean:
case TypeCode.Char:
return OpCodes.Conv_I2;// TypeCode.Char:
case TypeCode.SByte:
return OpCodes.Conv_I1;// TypeCode.SByte:
case TypeCode.Byte:
return OpCodes.Conv_U1;// TypeCode.Byte:
case TypeCode.Int16:
return OpCodes.Conv_I2;// TypeCode.Int16:
case TypeCode.UInt16:
return OpCodes.Conv_U2;// TypeCode.UInt16:
case TypeCode.Int32:
return OpCodes.Conv_I4;// TypeCode.Int32:
case TypeCode.UInt32:
return OpCodes.Conv_U4;// TypeCode.UInt32:
case TypeCode.Int64:
return OpCodes.Conv_I8;// TypeCode.Int64:
case TypeCode.UInt64:
return OpCodes.Conv_I8;// TypeCode.UInt64:
case TypeCode.Single:
return OpCodes.Conv_R4;// TypeCode.Single:
case TypeCode.Double:
return OpCodes.Conv_R8;// TypeCode.Double:
default:
return OpCodes.Nop;
}
}
private void InternalConvert(Type source, Type target, bool isAddress)
{
if (target == source)
return;
if (target.GetTypeInfo().IsValueType)
{
if (source.GetTypeInfo().IsValueType)
{
OpCode opCode = GetConvOpCode(target.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.NoConversionPossibleTo, DataContract.GetClrTypeFullName(target))));
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode);
}
}
else if (source.IsAssignableFrom(target))
{
Unbox(target);
if (!isAddress)
Ldobj(target);
}
else
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source))));
}
else if (target.IsAssignableFrom(source))
{
if (source.GetTypeInfo().IsValueType)
{
if (isAddress)
Ldobj(source);
Box(source);
}
}
else if (source.IsAssignableFrom(target))
{
Castclass(target);
}
else if (target.GetTypeInfo().IsInterface || source.GetTypeInfo().IsInterface)
{
Castclass(target);
}
else
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source))));
}
private IfState PopIfState()
{
object stackTop = _blockStack.Pop();
IfState ifState = stackTop as IfState;
if (ifState == null)
ThrowMismatchException(stackTop);
return ifState;
}
#if USE_REFEMIT
[SecuritySafeCritical]
void InitAssemblyBuilder(string methodName)
{
AssemblyName name = new AssemblyName();
name.Name = "Microsoft.GeneratedCode."+methodName;
//Add SecurityCritical and SecurityTreatAsSafe attributes to the generated method
assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name + ".dll", false);
}
#endif
private void ThrowMismatchException(object expected)
{
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.ExpectingEnd, expected.ToString())));
}
[Conditional("NOT_SILVERLIGHT")]
internal void EmitSourceInstruction(string line)
{
}
[Conditional("NOT_SILVERLIGHT")]
internal void EmitSourceLabel(string line)
{
}
[Conditional("NOT_SILVERLIGHT")]
internal void EmitSourceComment(string comment)
{
}
internal void EmitStackTop(Type stackTopType)
{
if (_codeGenTrace != CodeGenTrace.Tron)
return;
}
internal Label[] Switch(int labelCount)
{
SwitchState switchState = new SwitchState(DefineLabel(), DefineLabel());
Label[] caseLabels = new Label[labelCount];
for (int i = 0; i < caseLabels.Length; i++)
caseLabels[i] = DefineLabel();
_ilGen.Emit(OpCodes.Switch, caseLabels);
Br(switchState.DefaultLabel);
_blockStack.Push(switchState);
return caseLabels;
}
internal void Case(Label caseLabel1, string caseLabelName)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("case " + caseLabelName + "{");
MarkLabel(caseLabel1);
}
internal void EndCase()
{
object stackTop = _blockStack.Peek();
SwitchState switchState = stackTop as SwitchState;
if (switchState == null)
ThrowMismatchException(stackTop);
Br(switchState.EndOfSwitchLabel);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("} //end case ");
}
internal void EndSwitch()
{
object stackTop = _blockStack.Pop();
SwitchState switchState = stackTop as SwitchState;
if (switchState == null)
ThrowMismatchException(stackTop);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("} //end switch");
if (!switchState.DefaultDefined)
MarkLabel(switchState.DefaultLabel);
MarkLabel(switchState.EndOfSwitchLabel);
}
private static MethodInfo s_stringLength = typeof(string).GetProperty("Length").GetMethod;
internal void ElseIfIsEmptyString(LocalBuilder strLocal)
{
IfState ifState = (IfState)_blockStack.Pop();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
Load(strLocal);
Call(s_stringLength);
Load(0);
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(Cmp.EqualTo), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void IfNotIsEmptyString(LocalBuilder strLocal)
{
Load(strLocal);
Call(s_stringLength);
Load(0);
If(Cmp.NotEqualTo);
}
#if !NET_NATIVE
internal void BeginWhileCondition()
{
Label startWhile = DefineLabel();
MarkLabel(startWhile);
_blockStack.Push(startWhile);
}
internal void BeginWhileBody(Cmp cmpOp)
{
Label startWhile = (Label)_blockStack.Pop();
If(cmpOp);
_blockStack.Push(startWhile);
}
internal void EndWhile()
{
Label startWhile = (Label)_blockStack.Pop();
Br(startWhile);
EndIf();
}
internal void CallStringFormat(string msg, params object[] values)
{
NewArray(typeof(object), values.Length);
if (_stringFormatArray == null)
_stringFormatArray = DeclareLocal(typeof(object[]), "stringFormatArray");
Stloc(_stringFormatArray);
for (int i = 0; i < values.Length; i++)
StoreArrayElement(_stringFormatArray, i, values[i]);
Load(msg);
Load(_stringFormatArray);
Call(StringFormat);
}
internal void ToString(Type type)
{
if (type != Globals.TypeOfString)
{
if (type.GetTypeInfo().IsValueType)
{
Box(type);
}
Call(ObjectToString);
}
}
#endif
}
internal class ArgBuilder
{
internal int Index;
internal Type ArgType;
internal ArgBuilder(int index, Type argType)
{
this.Index = index;
this.ArgType = argType;
}
}
internal class ForState
{
private LocalBuilder _indexVar;
private Label _beginLabel;
private Label _testLabel;
private Label _endLabel;
private bool _requiresEndLabel;
private object _end;
internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end)
{
_indexVar = indexVar;
_beginLabel = beginLabel;
_testLabel = testLabel;
_end = end;
}
internal LocalBuilder Index
{
get
{
return _indexVar;
}
}
internal Label BeginLabel
{
get
{
return _beginLabel;
}
}
internal Label TestLabel
{
get
{
return _testLabel;
}
}
internal Label EndLabel
{
get
{
return _endLabel;
}
set
{
_endLabel = value;
}
}
internal bool RequiresEndLabel
{
get
{
return _requiresEndLabel;
}
set
{
_requiresEndLabel = value;
}
}
internal object End
{
get
{
return _end;
}
}
}
internal enum Cmp
{
LessThan,
EqualTo,
LessThanOrEqualTo,
GreaterThan,
NotEqualTo,
GreaterThanOrEqualTo
}
internal class IfState
{
private Label _elseBegin;
private Label _endIf;
internal Label EndIf
{
get
{
return _endIf;
}
set
{
_endIf = value;
}
}
internal Label ElseBegin
{
get
{
return _elseBegin;
}
set
{
_elseBegin = value;
}
}
}
internal class SwitchState
{
private Label _defaultLabel;
private Label _endOfSwitchLabel;
private bool _defaultDefined;
internal SwitchState(Label defaultLabel, Label endOfSwitchLabel)
{
_defaultLabel = defaultLabel;
_endOfSwitchLabel = endOfSwitchLabel;
_defaultDefined = false;
}
internal Label DefaultLabel
{
get
{
return _defaultLabel;
}
}
internal Label EndOfSwitchLabel
{
get
{
return _endOfSwitchLabel;
}
}
internal bool DefaultDefined
{
get
{
return _defaultDefined;
}
set
{
_defaultDefined = value;
}
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using GitTfs.Commands;
using GitTfs.Core.TfsInterop;
using GitTfs.Util;
namespace GitTfs.Core
{
public class GitTfsRemote : IGitTfsRemote
{
private static readonly Regex isInDotGit = new Regex("(?:^|/)\\.git(?:/|$)", RegexOptions.Compiled);
private readonly Globals _globals;
private readonly RemoteOptions _remoteOptions;
private readonly ConfigProperties _properties;
private readonly bool _useGitIgnore;
private int? firstChangesetId;
private int? maxChangesetId;
private string maxCommitHash;
private bool isTfsAuthenticated;
public RemoteInfo RemoteInfo { get; private set; }
public GitTfsRemote(RemoteInfo info, IGitRepository repository, RemoteOptions remoteOptions, Globals globals,
ITfsHelper tfsHelper, ConfigProperties properties)
{
_remoteOptions = remoteOptions;
_globals = globals;
_properties = properties;
Tfs = tfsHelper;
Repository = repository;
RemoteInfo = info;
Id = info.Id;
Tfs.Url = info.Url;
TfsRepositoryPath = info.Repository;
TfsUsername = info.Username;
TfsPassword = info.Password;
Aliases = (info.Aliases ?? Enumerable.Empty<string>()).ToArray();
IgnoreRegexExpression = info.IgnoreRegex;
IgnoreExceptRegexExpression = info.IgnoreExceptRegex;
_useGitIgnore = !_remoteOptions.NoGitIgnore && (_remoteOptions.UseGitIgnore || IsGitIgnoreSupportEnabled());
Autotag = info.Autotag;
IsSubtree = CheckSubtree();
}
private bool IsGitIgnoreSupportEnabled()
{
var isGitIgnoreSupportDisabled = true;
var value = Repository.GetConfig<string>(GitTfsConstants.DisableGitignoreSupport, null);
bool disableGitignoreSupport;
if (value != null && bool.TryParse(value, out disableGitignoreSupport))
isGitIgnoreSupportDisabled = disableGitignoreSupport;
return !isGitIgnoreSupportDisabled;
}
private bool CheckSubtree()
{
var m = GitTfsConstants.RemoteSubtreeRegex.Match(Id);
if (m.Success)
{
OwningRemoteId = m.Groups["owner"].Value;
Prefix = m.Groups["prefix"].Value;
return true;
}
return false;
}
public void EnsureTfsAuthenticated()
{
if (isTfsAuthenticated)
return;
Tfs.EnsureAuthenticated();
isTfsAuthenticated = true;
}
public bool IsDerived
{
get { return false; }
}
public int? GetFirstChangeset()
{
return firstChangesetId;
}
public void SetFirstChangeset(int? changesetId)
{
Trace.WriteLine($"Set first changeset in branch to C{changesetId}");
firstChangesetId = changesetId;
}
public bool IsSubtree { get; }
public bool IsSubtreeOwner
{
get
{
return TfsRepositoryPath == null;
}
}
public string Id { get; }
public string TfsUrl
{
get { return Tfs.Url; }
}
private string[] Aliases { get; set; }
public bool Autotag { get; }
public string TfsUsername
{
get { return Tfs.Username; }
set { Tfs.Username = value; }
}
public string TfsPassword
{
get { return Tfs.Password; }
set { Tfs.Password = value; }
}
public string TfsRepositoryPath { get; }
/// <summary>
/// Gets the TFS server-side paths of all subtrees of this remote.
/// Valid if the remote has subtrees, which occurs when <see cref="TfsRepositoryPath"/> is null.
/// </summary>
public string[] TfsSubtreePaths
{
get
{
if (tfsSubtreePaths == null)
tfsSubtreePaths = Repository.GetSubtrees(this).Select(x => x.TfsRepositoryPath).ToArray();
return tfsSubtreePaths;
}
}
private string[] tfsSubtreePaths = null;
public string IgnoreRegexExpression { get; }
public string IgnoreExceptRegexExpression { get; }
public IGitRepository Repository { get; }
public ITfsHelper Tfs { get; }
public string OwningRemoteId { get; private set; }
public string Prefix { get; private set; }
public bool ExportMetadatas { get; set; }
public Dictionary<string, IExportWorkItem> ExportWorkitemsMapping { get; set; }
// MaxChangesetId is the ID of the TFS changeset most recently commited to the
// TFS remote reference branch of the git repository. A value of 0 means that
// no TFS changesets have been committed yet.
public int MaxChangesetId
{
get { InitHistory(); return maxChangesetId.Value; }
set { maxChangesetId = value; }
}
// MaxCommitHash is the hash of the most recent commit of any type on the remote
// reference branch of the git repository. It is typically the hash of the commit
// corresponding to the MaxChangesetId property, but isn't guaranteed to be. When
// MaxChangesetId is zero, MaxCommitHash could be the hash of the last commit made
// during repository initialization (e.g. the commit of a .gitignore file).
public string MaxCommitHash
{
get { InitHistory(); return maxCommitHash; }
set { maxCommitHash = value; }
}
private TfsChangesetInfo GetTfsChangesetById(int id)
{
return Repository.GetTfsChangesetById(RemoteRef, id);
}
private void InitHistory()
{
if (maxChangesetId == null)
{
var mostRecentUpdate = Repository.GetLastParentTfsCommits(RemoteRef).FirstOrDefault();
if (mostRecentUpdate != null)
{
MaxCommitHash = mostRecentUpdate.GitCommit;
MaxChangesetId = mostRecentUpdate.ChangesetId;
}
else
{
// Use 0 as the flag to indicate that no TFS changesets have yet been committed
MaxChangesetId = 0;
// Manage the special case where commits were made to the repository before the
// first commit from TFS (e.g. .gitignore was committed during initialization)
var gitCommit = Repository.GetCommit(RemoteRef);
if (gitCommit != null)
{
MaxCommitHash = gitCommit.Sha;
}
}
}
}
private const string WorkspaceDirectory = "~w";
private string WorkingDirectory
{
get
{
var dir = Repository.GetConfig(GitTfsConstants.WorkspaceConfigKey);
if (IsSubtree)
{
if (dir != null)
{
return Path.Combine(dir, Prefix);
}
//find the relative path to the owning remote
return Ext.CombinePaths(_globals.GitDir, WorkspaceDirectory, OwningRemoteId, Prefix);
}
return dir ?? DefaultWorkingDirectory;
}
}
private string DefaultWorkingDirectory
{
get
{
return Path.Combine(_globals.GitDir, WorkspaceDirectory);
}
}
public void CleanupWorkspace()
{
Tfs.CleanupWorkspaces(WorkingDirectory);
}
public void CleanupWorkspaceDirectory()
{
try
{
if (Directory.Exists(WorkingDirectory))
{
var allFiles = Directory.EnumerateFiles(WorkingDirectory, "*", SearchOption.AllDirectories);
foreach (var file in allFiles)
File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly);
Directory.Delete(WorkingDirectory, true);
}
}
catch (Exception ex)
{
Trace.WriteLine("CleanupWorkspaceDirectory: " + ex.Message);
}
}
public bool ShouldSkip(string path)
{
return IsInDotGit(path) || IsIgnored(path);
}
public bool IsIgnored(string path)
{
return Ignorance.IsIncluded(path) || IsPathIgnored(path);
}
private bool IsPathIgnored(string path)
{
return _useGitIgnore && Repository.IsPathIgnored(path);
}
private Bouncer _ignorance;
private Bouncer Ignorance
{
get
{
if (_ignorance == null)
{
_ignorance = new Bouncer();
_ignorance.Include(IgnoreRegexExpression);
_ignorance.Include(_remoteOptions.IgnoreRegex);
_ignorance.Exclude(IgnoreExceptRegexExpression);
_ignorance.Exclude(_remoteOptions.ExceptRegex);
}
return _ignorance;
}
}
public bool IsInDotGit(string path)
{
return isInDotGit.IsMatch(path);
}
public string GetPathInGitRepo(string tfsPath)
{
if (tfsPath == null) return null;
if (!IsSubtreeOwner)
{
if (!tfsPath.StartsWith(TfsRepositoryPath, StringComparison.InvariantCultureIgnoreCase)) return null;
if (TfsRepositoryPath == GitTfsConstants.TfsRoot)
{
tfsPath = tfsPath.Substring(TfsRepositoryPath.Length);
}
else
{
if (tfsPath.Length > TfsRepositoryPath.Length && tfsPath[TfsRepositoryPath.Length] != '/')
return null;
tfsPath = tfsPath.Substring(TfsRepositoryPath.Length);
}
}
else
{
//look through the subtrees
var p = _globals.Repository.GetSubtrees(this)
.Where(x => x.IsSubtree)
.FirstOrDefault(x => tfsPath.StartsWith(x.TfsRepositoryPath, StringComparison.InvariantCultureIgnoreCase)
&& (tfsPath.Length == x.TfsRepositoryPath.Length || tfsPath[x.TfsRepositoryPath.Length] == '/'));
if (p == null) return null;
tfsPath = p.GetPathInGitRepo(tfsPath);
//we must prepend the prefix in order to get the correct directory
if (tfsPath.StartsWith("/"))
tfsPath = p.Prefix + tfsPath;
else
tfsPath = p.Prefix + "/" + tfsPath;
}
while (tfsPath.StartsWith("/"))
tfsPath = tfsPath.Substring(1);
return tfsPath;
}
public class FetchResult : IFetchResult
{
public bool IsSuccess { get; set; }
public int LastFetchedChangesetId { get; set; }
public int NewChangesetCount { get; set; }
public string ParentBranchTfsPath { get; set; }
public bool IsProcessingRenameChangeset { get; set; }
public string LastParentCommitBeforeRename { get; set; }
}
public IFetchResult Fetch(bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, IRenameResult renameResult = null)
{
return FetchWithMerge(-1, stopOnFailMergeCommit, lastChangesetIdToFetch, renameResult);
}
public IFetchResult FetchWithMerge(int mergeChangesetId, bool stopOnFailMergeCommit = false, IRenameResult renameResult = null, params string[] parentCommitsHashes)
{
return FetchWithMerge(mergeChangesetId, stopOnFailMergeCommit, -1, renameResult, parentCommitsHashes);
}
public IFetchResult FetchWithMerge(int mergeChangesetId, bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, IRenameResult renameResult = null, params string[] parentCommitsHashes)
{
var fetchResult = new FetchResult { IsSuccess = true, NewChangesetCount = 0 };
var latestChangesetId = GetLatestChangesetId();
if (lastChangesetIdToFetch != -1)
latestChangesetId = Math.Min(latestChangesetId, lastChangesetIdToFetch);
// TFS 2010 doesn't like when we ask for history past its last changeset.
if (MaxChangesetId >= latestChangesetId)
return fetchResult;
bool fetchRetrievedChangesets;
do
{
var fetchedChangesets = FetchChangesets(true, lastChangesetIdToFetch);
var objects = BuildEntryDictionary();
fetchRetrievedChangesets = false;
foreach (var changeset in fetchedChangesets)
{
fetchRetrievedChangesets = true;
fetchResult.NewChangesetCount++;
if (lastChangesetIdToFetch > 0 && changeset.Summary.ChangesetId > lastChangesetIdToFetch)
return fetchResult;
string parentCommitSha = null;
if (changeset.IsMergeChangeset && !ProcessMergeChangeset(changeset, stopOnFailMergeCommit, ref parentCommitSha))
{
fetchResult.NewChangesetCount--; // Merge wasn't successful - so don't count the changeset we found
fetchResult.IsSuccess = false;
return fetchResult;
}
var parentSha = (renameResult != null && renameResult.IsProcessingRenameChangeset) ? renameResult.LastParentCommitBeforeRename : MaxCommitHash;
var isFirstTFSCommitInRepository = (MaxChangesetId == 0);
var log = Apply(parentSha, changeset, objects);
if (changeset.IsRenameChangeset && !isFirstTFSCommitInRepository)
{
if (renameResult == null || !renameResult.IsProcessingRenameChangeset)
{
fetchResult.IsProcessingRenameChangeset = true;
fetchResult.LastParentCommitBeforeRename = MaxCommitHash;
return fetchResult;
}
renameResult.IsProcessingRenameChangeset = false;
renameResult.LastParentCommitBeforeRename = null;
}
if (parentCommitSha != null)
log.CommitParents.Add(parentCommitSha);
if (changeset.Summary.ChangesetId == mergeChangesetId)
{
foreach (var parent in parentCommitsHashes)
log.CommitParents.Add(parent);
}
var commitSha = ProcessChangeset(changeset, log);
fetchResult.LastFetchedChangesetId = changeset.Summary.ChangesetId;
// set commit sha for added git objects
foreach (var commit in objects)
{
if (commit.Value.Commit == null)
commit.Value.Commit = commitSha;
}
DoGcIfNeeded();
}
} while (fetchRetrievedChangesets && latestChangesetId > fetchResult.LastFetchedChangesetId);
return fetchResult;
}
private Dictionary<string, GitObject> BuildEntryDictionary()
{
return new Dictionary<string, GitObject>(StringComparer.InvariantCultureIgnoreCase);
}
private bool ProcessMergeChangeset(ITfsChangeset changeset, bool stopOnFailMergeCommit, ref string parentCommit)
{
if (!IsIgnoringBranches())
{
var parentChangesetId = Tfs.FindMergeChangesetParent(TfsRepositoryPath, changeset.Summary.ChangesetId, this);
if (parentChangesetId < 1) // Handle missing merge parent info
{
if (stopOnFailMergeCommit)
{
return false;
}
Trace.TraceInformation("warning: this changeset " + changeset.Summary.ChangesetId +
" is a merge changeset. But git-tfs is unable to determine the parent changeset.");
return true;
}
var shaParent = Repository.FindCommitHashByChangesetId(parentChangesetId);
if (shaParent == null)
{
string omittedParentBranch;
shaParent = FindMergedRemoteAndFetch(parentChangesetId, stopOnFailMergeCommit, out omittedParentBranch);
changeset.OmittedParentBranch = omittedParentBranch;
}
if (shaParent != null)
{
parentCommit = shaParent;
}
else
{
if (stopOnFailMergeCommit)
return false;
Trace.TraceInformation("warning: this changeset " + changeset.Summary.ChangesetId +
" is a merge changeset. But git-tfs failed to find and fetch the parent changeset "
+ parentChangesetId + ". Parent changeset will be ignored...");
}
}
else
{
Trace.TraceInformation("info: this changeset " + changeset.Summary.ChangesetId +
" is a merge changeset. But was not treated as is because of your git setting...");
changeset.OmittedParentBranch = ";C" + changeset.Summary.ChangesetId;
}
return true;
}
public bool IsIgnoringBranches()
{
var value = Repository.GetConfig<string>(GitTfsConstants.IgnoreBranches, null);
bool isIgnoringBranches;
if (value != null && bool.TryParse(value, out isIgnoringBranches))
return isIgnoringBranches;
Trace.TraceInformation("warning: no value found for branch management setting '" + GitTfsConstants.IgnoreBranches +
"'...");
var isIgnoringBranchesDetected = Repository.ReadAllTfsRemotes().Count() < 2;
Trace.TraceInformation("=> Branch support " + (isIgnoringBranchesDetected ? "disabled!" : "enabled!"));
if (isIgnoringBranchesDetected)
Trace.TraceInformation(" if you want to enable branch support, use the command:" + Environment.NewLine
+ " git config --local " + GitTfsConstants.IgnoreBranches + " false");
_globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, isIgnoringBranchesDetected);
return isIgnoringBranchesDetected;
}
private string ProcessChangeset(ITfsChangeset changeset, LogEntry log)
{
if (ExportMetadatas)
{
if (changeset.Summary.Workitems.Any())
{
var workItems = TranslateWorkItems(changeset.Summary.Workitems.Select(wi => new ExportWorkItem(wi)));
if (workItems != null)
{
log.Log += "\nWorkitems:";
foreach (var workItem in workItems)
{
log.Log += "\n#" + workItem.Id + " " + workItem.Title;
}
}
}
if (!string.IsNullOrWhiteSpace(changeset.Summary.PolicyOverrideComment))
log.Log += "\n" + GitTfsConstants.GitTfsPolicyOverrideCommentPrefix + " " + changeset.Summary.PolicyOverrideComment;
foreach (var checkinNote in changeset.Summary.CheckinNotes)
{
if (!string.IsNullOrWhiteSpace(checkinNote.Name) && !string.IsNullOrWhiteSpace(checkinNote.Value))
log.Log += "\n" + GitTfsConstants.GitTfsPrefix + "-" + CamelCaseToDelimitedStringConverter.Convert(checkinNote.Name, "-") + ": " + checkinNote.Value;
}
}
var commitSha = Commit(log);
UpdateTfsHead(commitSha, changeset.Summary.ChangesetId);
StringBuilder metadatas = new StringBuilder();
if (changeset.Summary.Workitems.Any())
{
string workitemNote = "Workitems:\n";
foreach (var workitem in changeset.Summary.Workitems)
{
var workitemId = workitem.Id.ToString();
var workitemUrl = workitem.Url;
if (ExportMetadatas && ExportWorkitemsMapping.Count != 0)
{
if (ExportWorkitemsMapping.ContainsKey(workitemId))
{
var oldWorkitemId = workitemId;
workitemId = ExportWorkitemsMapping[workitemId].Id;
workitemUrl = workitemUrl.Replace(oldWorkitemId, workitemId);
}
}
workitemNote += string.Format("[{0}] {1}\n {2}\n", workitemId, workitem.Title, workitemUrl);
}
metadatas.Append(workitemNote);
}
if (!string.IsNullOrWhiteSpace(changeset.Summary.PolicyOverrideComment))
metadatas.Append("\nPolicy Override Comment: " + changeset.Summary.PolicyOverrideComment);
foreach (var checkinNote in changeset.Summary.CheckinNotes)
{
if (!string.IsNullOrWhiteSpace(checkinNote.Name) && !string.IsNullOrWhiteSpace(checkinNote.Value))
metadatas.Append("\n" + checkinNote.Name + ": " + checkinNote.Value);
}
if (!string.IsNullOrWhiteSpace(changeset.OmittedParentBranch))
metadatas.Append("\nOmitted parent branch: " + changeset.OmittedParentBranch);
if (metadatas.Length != 0)
Repository.CreateNote(commitSha, metadatas.ToString(), log.AuthorName, log.AuthorEmail, log.Date);
return commitSha;
}
private IEnumerable<IExportWorkItem> TranslateWorkItems(IEnumerable<IExportWorkItem> workItemsOriginal)
{
if (ExportWorkitemsMapping.Count == 0)
return workItemsOriginal;
List<IExportWorkItem> workItemsTranslated = new List<IExportWorkItem>();
if (workItemsOriginal == null)
return workItemsTranslated;
foreach (var oldWorkItemId in workItemsOriginal)
{
IExportWorkItem translatedWorkItem = null;
if (oldWorkItemId != null && !ExportWorkitemsMapping.TryGetValue(oldWorkItemId.Id, out translatedWorkItem))
translatedWorkItem = oldWorkItemId;
if (translatedWorkItem != null)
workItemsTranslated.Add(translatedWorkItem);
}
return workItemsTranslated;
}
private string FindRootRemoteAndFetch(int parentChangesetId, IRenameResult renameResult = null)
{
string omittedParentBranch;
return FindRemoteAndFetch(parentChangesetId, false, false, renameResult, out omittedParentBranch);
}
private string FindMergedRemoteAndFetch(int parentChangesetId, bool stopOnFailMergeCommit, out string omittedParentBranch)
{
return FindRemoteAndFetch(parentChangesetId, false, true, null, out omittedParentBranch);
}
private string FindRemoteAndFetch(int parentChangesetId, bool stopOnFailMergeCommit, bool mergeChangeset, IRenameResult renameResult, out string omittedParentBranch)
{
var tfsRemote = FindOrInitTfsRemoteOfChangeset(parentChangesetId, mergeChangeset, renameResult, out omittedParentBranch);
if (tfsRemote != null && string.Compare(tfsRemote.TfsRepositoryPath, TfsRepositoryPath, StringComparison.InvariantCultureIgnoreCase) != 0)
{
Trace.TraceInformation("\tFetching from dependent TFS remote '{0}'...", tfsRemote.Id);
try
{
var fetchResult = ((GitTfsRemote)tfsRemote).FetchWithMerge(-1, stopOnFailMergeCommit, parentChangesetId, renameResult);
}
finally
{
Trace.WriteLine("Cleaning...");
tfsRemote.CleanupWorkspaceDirectory();
if (tfsRemote.Repository.IsBare)
tfsRemote.Repository.UpdateRef(GitRepository.ShortToLocalName(tfsRemote.Id), tfsRemote.MaxCommitHash);
}
return Repository.FindCommitHashByChangesetId(parentChangesetId);
}
return null;
}
private IGitTfsRemote FindOrInitTfsRemoteOfChangeset(int parentChangesetId, bool mergeChangeset, IRenameResult renameResult, out string omittedParentBranch)
{
omittedParentBranch = null;
IGitTfsRemote tfsRemote;
IChangeset parentChangeset = Tfs.GetChangeset(parentChangesetId);
//I think you want something that uses GetPathInGitRepo and ShouldSkip. See TfsChangeset.Apply.
//Don't know if there is a way to extract remote tfs repository path from changeset datas! Should be better!!!
var remote = Repository.ReadAllTfsRemotes().FirstOrDefault(r => parentChangeset.Changes.Any(c => r.GetPathInGitRepo(c.Item.ServerItem) != null));
if (remote != null)
tfsRemote = remote;
else
{
// If the changeset has created multiple folders, the expected branch folder will not always be the first
// so we scan all the changes of type folder to try to detect the first one which is a branch.
// In most cases it will change nothing: the first folder is the good one
IBranchObject tfsBranch = null;
string tfsPath = null;
var allBranches = Tfs.GetBranches(true);
foreach (var change in parentChangeset.Changes)
{
tfsPath = change.Item.ServerItem;
tfsPath = tfsPath.EndsWith("/") ? tfsPath : tfsPath + "/";
tfsBranch = allBranches.SingleOrDefault(b => tfsPath.StartsWith(b.Path.EndsWith("/") ? b.Path : b.Path + "/"));
if (tfsBranch != null)
{
// we found a branch, we stop here
break;
}
}
var filterRegex = Repository.GetConfig(GitTfsConstants.IgnoreBranchesRegex);
if (mergeChangeset && tfsBranch != null && !string.IsNullOrEmpty(filterRegex)
&& Regex.IsMatch(tfsBranch.Path, filterRegex, RegexOptions.IgnoreCase))
{
Trace.TraceInformation("warning: skip filtered branch for path " + tfsBranch.Path + " (regex:" + filterRegex + ")");
tfsRemote = null;
omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId;
}
else if (mergeChangeset && tfsBranch != null &&
string.Equals(Repository.GetConfig(GitTfsConstants.IgnoreNotInitBranches), true.ToString(), StringComparison.InvariantCultureIgnoreCase))
{
Trace.TraceInformation("warning: skip not initialized branch for path " + tfsBranch.Path);
tfsRemote = null;
omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId;
}
else if (tfsBranch == null)
{
Trace.TraceInformation("error: branch not found. Verify that all the folders have been converted to branches (or something else :().\n\tpath {0}", tfsPath);
tfsRemote = null;
omittedParentBranch = ";C" + parentChangesetId;
}
else
{
tfsRemote = InitTfsRemoteOfChangeset(tfsBranch, parentChangeset.ChangesetId, renameResult);
if (tfsRemote == null)
omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId;
}
}
return tfsRemote;
}
private IGitTfsRemote InitTfsRemoteOfChangeset(IBranchObject tfsBranch, int parentChangesetId, IRenameResult renameResult = null)
{
if (tfsBranch.IsRoot)
{
return InitTfsBranch(_remoteOptions, tfsBranch.Path);
}
var branchesDatas = Tfs.GetRootChangesetForBranch(tfsBranch.Path, parentChangesetId);
IGitTfsRemote remote = null;
foreach (var branch in branchesDatas)
{
var rootChangesetId = branch.SourceBranchChangesetId;
remote = InitBranch(_remoteOptions, tfsBranch.Path, rootChangesetId, true);
if (remote == null)
{
Trace.TraceInformation("warning: root commit not found corresponding to changeset " + rootChangesetId);
Trace.TraceInformation("=> continuing anyway by creating a branch without parent...");
return InitTfsBranch(_remoteOptions, tfsBranch.Path);
}
if (branch.IsRenamedBranch)
{
try
{
remote.Fetch(renameResult: renameResult);
}
finally
{
Trace.WriteLine("Cleaning...");
remote.CleanupWorkspaceDirectory();
if (remote.Repository.IsBare)
remote.Repository.UpdateRef(GitRepository.ShortToLocalName(remote.Id), remote.MaxCommitHash);
}
}
}
return remote;
}
public void QuickFetch(int changesetId, bool ignoreRestricted, bool printRestrictionHint)
{
try
{
ITfsChangeset changeset;
if (changesetId < 0)
changeset = GetLatestChangeset();
else
changeset = Tfs.GetChangeset(changesetId, this);
quickFetch(changeset);
}
catch (Exception ex)
{
Trace.WriteLine("Quick fetch failed: " + ex.Message);
if (!IgnoreException(ex.Message, ignoreRestricted, printRestrictionHint))
throw;
}
}
private void quickFetch(ITfsChangeset changeset)
{
var log = CopyTree(MaxCommitHash, changeset);
UpdateTfsHead(Commit(log), changeset.Summary.ChangesetId);
DoGcIfNeeded();
}
private IEnumerable<ITfsChangeset> FetchChangesets(bool byLots, int lastVersion = -1)
{
int lowerBoundChangesetId;
// If we're starting at the Root side of a branch commit (e.g. C1), but there ar
// invalid commits between C1 and the actual branch side of the commit operation
// (e.g. a Folder with the branch name was created [C2] and then deleted [C3],
// then the root-side was branched [C4; C1 --branch--> C4]), this will detecte
// only the folder creation and deletion operations due to the lowerBound being
// detected as the root-side of the commit +1 (C1+1=C2) instead of referencing
// the branch-side of the branching operation [C4].
if (_properties.InitialChangeset.HasValue || firstChangesetId.HasValue)
{
var firstChangesetInBranch = Math.Max(_properties.InitialChangeset ?? int.MinValue, firstChangesetId ?? int.MinValue);
lowerBoundChangesetId = Math.Max(MaxChangesetId + 1, firstChangesetInBranch);
}
else
lowerBoundChangesetId = MaxChangesetId + 1;
Trace.WriteLine(RemoteRef + ": Getting changesets from " + lowerBoundChangesetId +
" to " + lastVersion + " ...", "info");
if (!IsSubtreeOwner)
return Tfs.GetChangesets(TfsRepositoryPath, lowerBoundChangesetId, this, lastVersion, byLots);
return _globals.Repository.GetSubtrees(this)
.SelectMany(x => Tfs.GetChangesets(x.TfsRepositoryPath, lowerBoundChangesetId, x, lastVersion, byLots))
.OrderBy(x => x.Summary.ChangesetId);
}
public ITfsChangeset GetChangeset(int changesetId)
{
return Tfs.GetChangeset(changesetId, this);
}
private ITfsChangeset GetLatestChangeset()
{
if (!string.IsNullOrEmpty(TfsRepositoryPath))
return Tfs.GetLatestChangeset(this);
var changesetId = _globals.Repository.GetSubtrees(this).Select(x => Tfs.GetLatestChangeset(x)).Max(x => x.Summary.ChangesetId);
return GetChangeset(changesetId);
}
private int GetLatestChangesetId()
{
if (!string.IsNullOrEmpty(TfsRepositoryPath))
return Tfs.GetLatestChangesetId(this);
return _globals.Repository.GetSubtrees(this).Select(x => Tfs.GetLatestChangesetId(x)).Max();
}
public void UpdateTfsHead(string commitHash, int changesetId)
{
MaxCommitHash = commitHash;
MaxChangesetId = changesetId;
Repository.UpdateRef(RemoteRef, MaxCommitHash, "C" + MaxChangesetId);
if (Autotag)
Repository.UpdateRef(TagPrefix + "C" + MaxChangesetId, MaxCommitHash);
LogCurrentMapping();
}
private void LogCurrentMapping()
{
Trace.TraceInformation("C" + MaxChangesetId + " = " + MaxCommitHash);
}
private string TagPrefix
{
get { return "refs/tags/tfs/" + Id + "/"; }
}
public string RemoteRef
{
get { return "refs/remotes/tfs/" + Id; }
}
private void DoGcIfNeeded()
{
Trace.WriteLine("GC Countdown: " + _globals.GcCountdown);
if (--_globals.GcCountdown < 0)
{
_globals.GcCountdown = _globals.GcPeriod;
Repository.GarbageCollect(true, "Try running it after git-tfs is finished.");
}
}
private LogEntry Apply(string parent, ITfsChangeset changeset, IDictionary<string, GitObject> entries)
{
return Apply(parent, changeset, entries, null);
}
private LogEntry Apply(string parent, ITfsChangeset changeset, Action<Exception> ignorableErrorHandler)
{
return Apply(parent, changeset, BuildEntryDictionary(), ignorableErrorHandler);
}
private LogEntry Apply(string parent, ITfsChangeset changeset, IDictionary<string, GitObject> entries, Action<Exception> ignorableErrorHandler)
{
LogEntry result = null;
WithWorkspace(changeset.Summary, workspace =>
{
var treeBuilder = workspace.Remote.Repository.GetTreeBuilder(parent);
result = changeset.Apply(parent, treeBuilder, workspace, entries, ignorableErrorHandler);
result.Tree = treeBuilder.GetTree();
});
if (!string.IsNullOrEmpty(parent)) result.CommitParents.Add(parent);
return result;
}
private LogEntry CopyTree(string lastCommit, ITfsChangeset changeset)
{
LogEntry result = null;
WithWorkspace(changeset.Summary, workspace =>
{
var treeBuilder = workspace.Remote.Repository.GetTreeBuilder(lastCommit);
result = changeset.CopyTree(treeBuilder, workspace);
result.Tree = treeBuilder.GetTree();
});
if (!string.IsNullOrEmpty(lastCommit)) result.CommitParents.Add(lastCommit);
return result;
}
private string Commit(LogEntry logEntry)
{
logEntry.Log = BuildCommitMessage(logEntry.Log, logEntry.ChangesetId);
return Repository.Commit(logEntry).Sha;
}
private string BuildCommitMessage(string tfsCheckinComment, int changesetId)
{
var builder = new StringWriter();
builder.WriteLine(tfsCheckinComment);
builder.WriteLine(GitTfsConstants.TfsCommitInfoFormat,
TfsUrl, TfsRepositoryPath, changesetId);
return builder.ToString();
}
public void Unshelve(string shelvesetOwner, string shelvesetName, string destinationBranch, Action<Exception> ignorableErrorHandler, bool force)
{
var destinationRef = GitRepository.ShortToLocalName(destinationBranch);
if (Repository.HasRef(destinationRef))
throw new GitTfsException("ERROR: Destination branch (" + destinationBranch + ") already exists!");
var shelvesetChangeset = Tfs.GetShelvesetData(this, shelvesetOwner, shelvesetName);
var parentId = shelvesetChangeset.BaseChangesetId;
var ch = GetTfsChangesetById(parentId);
string rootCommit;
if (ch == null)
{
if (!force)
throw new GitTfsException("ERROR: Parent changeset C" + parentId + " not found.", new[]
{
"Try fetching the latest changes from TFS",
"Try applying the shelveset on the currently checkouted commit using the '--force' option"
}
);
Trace.TraceInformation("warning: Parent changeset C" + parentId + " not found."
+ " Trying to apply the shelveset on the current commit...");
rootCommit = Repository.GetCurrentCommit();
}
else
{
rootCommit = ch.GitCommit;
}
var log = Apply(rootCommit, shelvesetChangeset, ignorableErrorHandler);
var commit = Commit(log);
Repository.UpdateRef(destinationRef, commit, "Shelveset " + shelvesetName + " from " + shelvesetOwner);
}
public void Shelve(string shelvesetName, string head, TfsChangesetInfo parentChangeset, CheckinOptions options, bool evaluateCheckinPolicies)
{
WithWorkspace(parentChangeset, workspace => Shelve(shelvesetName, head, parentChangeset, options, evaluateCheckinPolicies, workspace));
}
public bool HasShelveset(string shelvesetName)
{
return Tfs.HasShelveset(shelvesetName);
}
private void Shelve(string shelvesetName, string head, TfsChangesetInfo parentChangeset, CheckinOptions options, bool evaluateCheckinPolicies, ITfsWorkspace workspace)
{
PendChangesToWorkspace(head, parentChangeset.GitCommit, workspace);
workspace.Shelve(shelvesetName, evaluateCheckinPolicies, options, () => Repository.GetCommitMessage(head, parentChangeset.GitCommit));
}
public int CheckinTool(string head, TfsChangesetInfo parentChangeset)
{
var changeset = 0;
WithWorkspace(parentChangeset, workspace => changeset = CheckinTool(head, parentChangeset, workspace));
return changeset;
}
private int CheckinTool(string head, TfsChangesetInfo parentChangeset, ITfsWorkspace workspace)
{
PendChangesToWorkspace(head, parentChangeset.GitCommit, workspace);
return workspace.CheckinTool(() => Repository.GetCommitMessage(head, parentChangeset.GitCommit));
}
private void PendChangesToWorkspace(string head, string parent, ITfsWorkspaceModifier workspace)
{
using (var tidyWorkspace = new DirectoryTidier(workspace, () => GetLatestChangeset().GetFullTree()))
{
foreach (var change in Repository.GetChangedFiles(parent, head))
{
change.Apply(tidyWorkspace);
}
}
}
public int Checkin(string head, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null)
{
var changeset = 0;
WithWorkspace(parentChangeset, workspace => changeset = Checkin(head, parentChangeset.GitCommit, workspace, options, sourceTfsPath));
return changeset;
}
public int Checkin(string head, string parent, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null)
{
var changeset = 0;
WithWorkspace(parentChangeset, workspace => changeset = Checkin(head, parent, workspace, options, sourceTfsPath));
return changeset;
}
private void WithWorkspace(TfsChangesetInfo parentChangeset, Action<ITfsWorkspace> action)
{
//are there any subtrees?
var subtrees = _globals.Repository.GetSubtrees(this);
if (subtrees.Any())
{
Tfs.WithWorkspace(WorkingDirectory, this, subtrees.Select(x => new Tuple<string, string>(x.TfsRepositoryPath, x.Prefix)), parentChangeset, action);
}
else
{
Tfs.WithWorkspace(WorkingDirectory, this, parentChangeset, action);
}
}
private int Checkin(string head, string parent, ITfsWorkspace workspace, CheckinOptions options, string sourceTfsPath)
{
PendChangesToWorkspace(head, parent, workspace);
if (!string.IsNullOrWhiteSpace(sourceTfsPath))
workspace.Merge(sourceTfsPath, TfsRepositoryPath);
return workspace.Checkin(options, () => Repository.GetCommitMessage(head, parent));
}
public bool MatchesUrlAndRepositoryPath(string tfsUrl, string tfsRepositoryPath)
{
if (!MatchesTfsUrl(tfsUrl))
return false;
if (TfsRepositoryPath == null)
return tfsRepositoryPath == null;
return TfsRepositoryPath.Equals(tfsRepositoryPath, StringComparison.OrdinalIgnoreCase);
}
public void DeleteShelveset(string shelvesetName)
{
WithWorkspace(null, workspace => workspace.DeleteShelveset(shelvesetName));
}
private bool MatchesTfsUrl(string tfsUrl)
{
return TfsUrl.Equals(tfsUrl, StringComparison.OrdinalIgnoreCase) || Aliases.Contains(tfsUrl, StringComparison.OrdinalIgnoreCase);
}
private string ExtractGitBranchNameFromTfsRepositoryPath(string tfsRepositoryPath)
{
var includeTeamProjectName = !Repository.IsInSameTeamProjectAsDefaultRepository(tfsRepositoryPath);
var gitBranchName = tfsRepositoryPath.ToGitBranchNameFromTfsRepositoryPath(includeTeamProjectName);
gitBranchName = Repository.AssertValidBranchName(gitBranchName);
Trace.TraceInformation("The name of the local branch will be : " + gitBranchName);
return gitBranchName;
}
public IGitTfsRemote InitBranch(RemoteOptions remoteOptions, string tfsRepositoryPath, int rootChangesetId, bool fetchParentBranch, string gitBranchNameExpected = null, IRenameResult renameResult = null)
{
return InitTfsBranch(remoteOptions, tfsRepositoryPath, rootChangesetId, fetchParentBranch, gitBranchNameExpected, renameResult);
}
private bool IgnoreException(string message, bool ignoreRestricted, bool printHint = true)
{
// Detect exception "TF14098: Access Denied: User ??? needs
// Read permission(s) for at least one item in changeset ???."
if (message.Contains("TF14098"))
{
if (ignoreRestricted)
return true;
if (printHint)
Trace.TraceWarning("\nAccess to changeset denied. Try the '--ignore-restricted-changesets' option!\n");
}
return false;
}
private IGitTfsRemote InitTfsBranch(RemoteOptions remoteOptions, string tfsRepositoryPath, int rootChangesetId = -1, bool fetchParentBranch = false, string gitBranchNameExpected = null, IRenameResult renameResult = null, bool ignoreRestricted = false)
{
Trace.WriteLine("Begin process of creating branch for remote :" + tfsRepositoryPath);
// TFS string representations of repository paths do not end in trailing slashes
tfsRepositoryPath = (tfsRepositoryPath ?? string.Empty).TrimEnd('/');
string gitBranchName = ExtractGitBranchNameFromTfsRepositoryPath(
string.IsNullOrWhiteSpace(gitBranchNameExpected) ? tfsRepositoryPath : gitBranchNameExpected);
if (string.IsNullOrWhiteSpace(gitBranchName))
throw new GitTfsException("error: The Git branch name '" + gitBranchName + "' is not valid...\n");
Trace.WriteLine("Git local branch will be :" + gitBranchName);
string sha1RootCommit = null;
if (rootChangesetId != -1)
{
sha1RootCommit = Repository.FindCommitHashByChangesetId(rootChangesetId);
if (fetchParentBranch && string.IsNullOrWhiteSpace(sha1RootCommit))
{
try
{
sha1RootCommit = FindRootRemoteAndFetch(rootChangesetId, renameResult);
}
catch (Exception ex)
{
Trace.WriteLine("Getting changeset fetch failed: " + ex.Message);
if (!IgnoreException(ex.Message, ignoreRestricted))
throw;
}
}
if (string.IsNullOrWhiteSpace(sha1RootCommit))
return null;
Trace.WriteLine("Found commit " + sha1RootCommit + " for changeset :" + rootChangesetId);
}
IGitTfsRemote tfsRemote;
if (Repository.HasRemote(gitBranchName))
{
Trace.WriteLine("Remote already exist");
tfsRemote = Repository.ReadTfsRemote(gitBranchName);
if (tfsRemote.TfsUrl != TfsUrl)
Trace.WriteLine("warning: Url is different");
if (tfsRemote.TfsRepositoryPath != tfsRepositoryPath)
Trace.WriteLine("warning: TFS repository path is different");
}
else
{
Trace.WriteLine("Try creating remote...");
tfsRemote = Repository.CreateTfsRemote(new RemoteInfo
{
Id = gitBranchName,
Url = TfsUrl,
Repository = tfsRepositoryPath,
RemoteOptions = remoteOptions
});
tfsRemote.ExportMetadatas = ExportMetadatas;
tfsRemote.ExportWorkitemsMapping = ExportWorkitemsMapping;
}
if (sha1RootCommit != null && !Repository.HasRef(tfsRemote.RemoteRef))
{
if (!Repository.CreateBranch(tfsRemote.RemoteRef, sha1RootCommit))
throw new GitTfsException("error: Fail to create remote branch ref file!");
}
Trace.WriteLine("Remote created!");
return tfsRemote;
}
}
}
| |
#pragma warning disable SA1633 // File should have header - This is an imported file,
// original header with license shall remain the same
namespace UtfUnknown.Core.Analyzers.Chinese;
internal class GB18030DistributionAnalyser : CharDistributionAnalyser
{
// GB2312 most frequently used character table
// Char to FreqOrder table, from hz6763
/******************************************************************************
* 512 --> 0.79 -- 0.79
* 1024 --> 0.92 -- 0.13
* 2048 --> 0.98 -- 0.06
* 6768 --> 1.00 -- 0.02
*
* Idea Distribution Ratio = 0.79135/(1-0.79135) = 3.79
* Random Distribution Ration = 512 / (3755 - 512) = 0.157
*
* Typical Distribution Ratio about 25% of Ideal one, still much higher that RDR
*****************************************************************************/
private static float GB2312_TYPICAL_DISTRIBUTION_RATIO = 0.9f;
private static int[] GB2312_CHAR2FREQ_ORDER =
{
1671,
749,
1443,
2364,
3924,
3807,
2330,
3921,
1704,
3463,
2691,
1511,
1515,
572,
3191,
2205,
2361,
224,
2558,
479,
1711,
963,
3162,
440,
4060,
1905,
2966,
2947,
3580,
2647,
3961,
3842,
2204,
869,
4207,
970,
2678,
5626,
2944,
2956,
1479,
4048,
514,
3595,
588,
1346,
2820,
3409,
249,
4088,
1746,
1873,
2047,
1774,
581,
1813,
358,
1174,
3590,
1014,
1561,
4844,
2245,
670,
1636,
3112,
889,
1286,
953,
556,
2327,
3060,
1290,
3141,
613,
185,
3477,
1367,
850,
3820,
1715,
2428,
2642,
2303,
2732,
3041,
2562,
2648,
3566,
3946,
1349,
388,
3098,
2091,
1360,
3585,
152,
1687,
1539,
738,
1559,
59,
1232,
2925,
2267,
1388,
1249,
1741,
1679,
2960,
151,
1566,
1125,
1352,
4271,
924,
4296,
385,
3166,
4459,
310,
1245,
2850,
70,
3285,
2729,
3534,
3575,
2398,
3298,
3466,
1960,
2265,
217,
3647,
864,
1909,
2084,
4401,
2773,
1010,
3269,
5152,
853,
3051,
3121,
1244,
4251,
1895,
364,
1499,
1540,
2313,
1180,
3655,
2268,
562,
715,
2417,
3061,
544,
336,
3768,
2380,
1752,
4075,
950,
280,
2425,
4382,
183,
2759,
3272,
333,
4297,
2155,
1688,
2356,
1444,
1039,
4540,
736,
1177,
3349,
2443,
2368,
2144,
2225,
565,
196,
1482,
3406,
927,
1335,
4147,
692,
878,
1311,
1653,
3911,
3622,
1378,
4200,
1840,
2969,
3149,
2126,
1816,
2534,
1546,
2393,
2760,
737,
2494,
13,
447,
245,
2747,
38,
2765,
2129,
2589,
1079,
606,
360,
471,
3755,
2890,
404,
848,
699,
1785,
1236,
370,
2221,
1023,
3746,
2074,
2026,
2023,
2388,
1581,
2119,
812,
1141,
3091,
2536,
1519,
804,
2053,
406,
1596,
1090,
784,
548,
4414,
1806,
2264,
2936,
1100,
343,
4114,
5096,
622,
3358,
743,
3668,
1510,
1626,
5020,
3567,
2513,
3195,
4115,
5627,
2489,
2991,
24,
2065,
2697,
1087,
2719,
48,
1634,
315,
68,
985,
2052,
198,
2239,
1347,
1107,
1439,
597,
2366,
2172,
871,
3307,
919,
2487,
2790,
1867,
236,
2570,
1413,
3794,
906,
3365,
3381,
1701,
1982,
1818,
1524,
2924,
1205,
616,
2586,
2072,
2004,
575,
253,
3099,
32,
1365,
1182,
197,
1714,
2454,
1201,
554,
3388,
3224,
2748,
756,
2587,
250,
2567,
1507,
1517,
3529,
1922,
2761,
2337,
3416,
1961,
1677,
2452,
2238,
3153,
615,
911,
1506,
1474,
2495,
1265,
1906,
2749,
3756,
3280,
2161,
898,
2714,
1759,
3450,
2243,
2444,
563,
26,
3286,
2266,
3769,
3344,
2707,
3677,
611,
1402,
531,
1028,
2871,
4548,
1375,
261,
2948,
835,
1190,
4134,
353,
840,
2684,
1900,
3082,
1435,
2109,
1207,
1674,
329,
1872,
2781,
4055,
2686,
2104,
608,
3318,
2423,
2957,
2768,
1108,
3739,
3512,
3271,
3985,
2203,
1771,
3520,
1418,
2054,
1681,
1153,
225,
1627,
2929,
162,
2050,
2511,
3687,
1954,
124,
1859,
2431,
1684,
3032,
2894,
585,
4805,
3969,
2869,
2704,
2088,
2032,
2095,
3656,
2635,
4362,
2209,
256,
518,
2042,
2105,
3777,
3657,
643,
2298,
1148,
1779,
190,
989,
3544,
414,
11,
2135,
2063,
2979,
1471,
403,
3678,
126,
770,
1563,
671,
2499,
3216,
2877,
600,
1179,
307,
2805,
4937,
1268,
1297,
2694,
252,
4032,
1448,
1494,
1331,
1394,
127,
2256,
222,
1647,
1035,
1481,
3056,
1915,
1048,
873,
3651,
210,
33,
1608,
2516,
200,
1520,
415,
102,
0,
3389,
1287,
817,
91,
3299,
2940,
836,
1814,
549,
2197,
1396,
1669,
2987,
3582,
2297,
2848,
4528,
1070,
687,
20,
1819,
121,
1552,
1364,
1461,
1968,
2617,
3540,
2824,
2083,
177,
948,
4938,
2291,
110,
4549,
2066,
648,
3359,
1755,
2110,
2114,
4642,
4845,
1693,
3937,
3308,
1257,
1869,
2123,
208,
1804,
3159,
2992,
2531,
2549,
3361,
2418,
1350,
2347,
2800,
2568,
1291,
2036,
2680,
72,
842,
1990,
212,
1233,
1154,
1586,
75,
2027,
3410,
4900,
1823,
1337,
2710,
2676,
728,
2810,
1522,
3026,
4995,
157,
755,
1050,
4022,
710,
785,
1936,
2194,
2085,
1406,
2777,
2400,
150,
1250,
4049,
1206,
807,
1910,
534,
529,
3309,
1721,
1660,
274,
39,
2827,
661,
2670,
1578,
925,
3248,
3815,
1094,
4278,
4901,
4252,
41,
1150,
3747,
2572,
2227,
4501,
3658,
4902,
3813,
3357,
3617,
2884,
2258,
887,
538,
4187,
3199,
1294,
2439,
3042,
2329,
2343,
2497,
1255,
107,
543,
1527,
521,
3478,
3568,
194,
5062,
15,
961,
3870,
1241,
1192,
2664,
66,
5215,
3260,
2111,
1295,
1127,
2152,
3805,
4135,
901,
1164,
1976,
398,
1278,
530,
1460,
748,
904,
1054,
1966,
1426,
53,
2909,
509,
523,
2279,
1534,
536,
1019,
239,
1685,
460,
2353,
673,
1065,
2401,
3600,
4298,
2272,
1272,
2363,
284,
1753,
3679,
4064,
1695,
81,
815,
2677,
2757,
2731,
1386,
859,
500,
4221,
2190,
2566,
757,
1006,
2519,
2068,
1166,
1455,
337,
2654,
3203,
1863,
1682,
1914,
3025,
1252,
1409,
1366,
847,
714,
2834,
2038,
3209,
964,
2970,
1901,
885,
2553,
1078,
1756,
3049,
301,
1572,
3326,
688,
2130,
1996,
2429,
1805,
1648,
2930,
3421,
2750,
3652,
3088,
262,
1158,
1254,
389,
1641,
1812,
526,
1719,
923,
2073,
1073,
1902,
468,
489,
4625,
1140,
857,
2375,
3070,
3319,
2863,
380,
116,
1328,
2693,
1161,
2244,
273,
1212,
1884,
2769,
3011,
1775,
1142,
461,
3066,
1200,
2147,
2212,
790,
702,
2695,
4222,
1601,
1058,
434,
2338,
5153,
3640,
67,
2360,
4099,
2502,
618,
3472,
1329,
416,
1132,
830,
2782,
1807,
2653,
3211,
3510,
1662,
192,
2124,
296,
3979,
1739,
1611,
3684,
23,
118,
324,
446,
1239,
1225,
293,
2520,
3814,
3795,
2535,
3116,
17,
1074,
467,
2692,
2201,
387,
2922,
45,
1326,
3055,
1645,
3659,
2817,
958,
243,
1903,
2320,
1339,
2825,
1784,
3289,
356,
576,
865,
2315,
2381,
3377,
3916,
1088,
3122,
1713,
1655,
935,
628,
4689,
1034,
1327,
441,
800,
720,
894,
1979,
2183,
1528,
5289,
2702,
1071,
4046,
3572,
2399,
1571,
3281,
79,
761,
1103,
327,
134,
758,
1899,
1371,
1615,
879,
442,
215,
2605,
2579,
173,
2048,
2485,
1057,
2975,
3317,
1097,
2253,
3801,
4263,
1403,
1650,
2946,
814,
4968,
3487,
1548,
2644,
1567,
1285,
2,
295,
2636,
97,
946,
3576,
832,
141,
4257,
3273,
760,
3821,
3521,
3156,
2607,
949,
1024,
1733,
1516,
1803,
1920,
2125,
2283,
2665,
3180,
1501,
2064,
3560,
2171,
1592,
803,
3518,
1416,
732,
3897,
4258,
1363,
1362,
2458,
119,
1427,
602,
1525,
2608,
1605,
1639,
3175,
694,
3064,
10,
465,
76,
2000,
4846,
4208,
444,
3781,
1619,
3353,
2206,
1273,
3796,
740,
2483,
320,
1723,
2377,
3660,
2619,
1359,
1137,
1762,
1724,
2345,
2842,
1850,
1862,
912,
821,
1866,
612,
2625,
1735,
2573,
3369,
1093,
844,
89,
937,
930,
1424,
3564,
2413,
2972,
1004,
3046,
3019,
2011,
711,
3171,
1452,
4178,
428,
801,
1943,
432,
445,
2811,
206,
4136,
1472,
730,
349,
73,
397,
2802,
2547,
998,
1637,
1167,
789,
396,
3217,
154,
1218,
716,
1120,
1780,
2819,
4826,
1931,
3334,
3762,
2139,
1215,
2627,
552,
3664,
3628,
3232,
1405,
2383,
3111,
1356,
2652,
3577,
3320,
3101,
1703,
640,
1045,
1370,
1246,
4996,
371,
1575,
2436,
1621,
2210,
984,
4033,
1734,
2638,
16,
4529,
663,
2755,
3255,
1451,
3917,
2257,
1253,
1955,
2234,
1263,
2951,
214,
1229,
617,
485,
359,
1831,
1969,
473,
2310,
750,
2058,
165,
80,
2864,
2419,
361,
4344,
2416,
2479,
1134,
796,
3726,
1266,
2943,
860,
2715,
938,
390,
2734,
1313,
1384,
248,
202,
877,
1064,
2854,
522,
3907,
279,
1602,
297,
2357,
395,
3740,
137,
2075,
944,
4089,
2584,
1267,
3802,
62,
1533,
2285,
178,
176,
780,
2440,
201,
3707,
590,
478,
1560,
4354,
2117,
1075,
30,
74,
4643,
4004,
1635,
1441,
2745,
776,
2596,
238,
1077,
1692,
1912,
2844,
605,
499,
1742,
3947,
241,
3053,
980,
1749,
936,
2640,
4511,
2582,
515,
1543,
2162,
5322,
2892,
2993,
890,
2148,
1924,
665,
1827,
3581,
1032,
968,
3163,
339,
1044,
1896,
270,
583,
1791,
1720,
4367,
1194,
3488,
3669,
43,
2523,
1657,
163,
2167,
290,
1209,
1622,
3378,
550,
634,
2508,
2510,
695,
2634,
2384,
2512,
1476,
1414,
220,
1469,
2341,
2138,
2852,
3183,
2900,
4939,
2865,
3502,
1211,
3680,
854,
3227,
1299,
2976,
3172,
186,
2998,
1459,
443,
1067,
3251,
1495,
321,
1932,
3054,
909,
753,
1410,
1828,
436,
2441,
1119,
1587,
3164,
2186,
1258,
227,
231,
1425,
1890,
3200,
3942,
247,
959,
725,
5254,
2741,
577,
2158,
2079,
929,
120,
174,
838,
2813,
591,
1115,
417,
2024,
40,
3240,
1536,
1037,
291,
4151,
2354,
632,
1298,
2406,
2500,
3535,
1825,
1846,
3451,
205,
1171,
345,
4238,
18,
1163,
811,
685,
2208,
1217,
425,
1312,
1508,
1175,
4308,
2552,
1033,
587,
1381,
3059,
2984,
3482,
340,
1316,
4023,
3972,
792,
3176,
519,
777,
4690,
918,
933,
4130,
2981,
3741,
90,
3360,
2911,
2200,
5184,
4550,
609,
3079,
2030,
272,
3379,
2736,
363,
3881,
1130,
1447,
286,
779,
357,
1169,
3350,
3137,
1630,
1220,
2687,
2391,
747,
1277,
3688,
2618,
2682,
2601,
1156,
3196,
5290,
4034,
3102,
1689,
3596,
3128,
874,
219,
2783,
798,
508,
1843,
2461,
269,
1658,
1776,
1392,
1913,
2983,
3287,
2866,
2159,
2372,
829,
4076,
46,
4253,
2873,
1889,
1894,
915,
1834,
1631,
2181,
2318,
298,
664,
2818,
3555,
2735,
954,
3228,
3117,
527,
3511,
2173,
681,
2712,
3033,
2247,
2346,
3467,
1652,
155,
2164,
3382,
113,
1994,
450,
899,
494,
994,
1237,
2958,
1875,
2336,
1926,
3727,
545,
1577,
1550,
633,
3473,
204,
1305,
3072,
2410,
1956,
2471,
707,
2134,
841,
2195,
2196,
2663,
3843,
1026,
4940,
990,
3252,
4997,
368,
1092,
437,
3212,
3258,
1933,
1829,
675,
2977,
2893,
412,
943,
3723,
4644,
3294,
3283,
2230,
2373,
5154,
2389,
2241,
2661,
2323,
1404,
2524,
593,
787,
677,
3008,
1275,
2059,
438,
2709,
2609,
2240,
2269,
2246,
1446,
36,
1568,
1373,
3892,
1574,
2301,
1456,
3962,
693,
2276,
5216,
2035,
1143,
2720,
1919,
1797,
1811,
2763,
4137,
2597,
1830,
1699,
1488,
1198,
2090,
424,
1694,
312,
3634,
3390,
4179,
3335,
2252,
1214,
561,
1059,
3243,
2295,
2561,
975,
5155,
2321,
2751,
3772,
472,
1537,
3282,
3398,
1047,
2077,
2348,
2878,
1323,
3340,
3076,
690,
2906,
51,
369,
170,
3541,
1060,
2187,
2688,
3670,
2541,
1083,
1683,
928,
3918,
459,
109,
4427,
599,
3744,
4286,
143,
2101,
2730,
2490,
82,
1588,
3036,
2121,
281,
1860,
477,
4035,
1238,
2812,
3020,
2716,
3312,
1530,
2188,
2055,
1317,
843,
636,
1808,
1173,
3495,
649,
181,
1002,
147,
3641,
1159,
2414,
3750,
2289,
2795,
813,
3123,
2610,
1136,
4368,
5,
3391,
4541,
2174,
420,
429,
1728,
754,
1228,
2115,
2219,
347,
2223,
2733,
735,
1518,
3003,
2355,
3134,
1764,
3948,
3329,
1888,
2424,
1001,
1234,
1972,
3321,
3363,
1672,
1021,
1450,
1584,
226,
765,
655,
2526,
3404,
3244,
2302,
3665,
731,
594,
2184,
319,
1576,
621,
658,
2656,
4299,
2099,
3864,
1279,
2071,
2598,
2739,
795,
3086,
3699,
3908,
1707,
2352,
2402,
1382,
3136,
2475,
1465,
4847,
3496,
3865,
1085,
3004,
2591,
1084,
213,
2287,
1963,
3565,
2250,
822,
793,
4574,
3187,
1772,
1789,
3050,
595,
1484,
1959,
2770,
1080,
2650,
456,
422,
2996,
940,
3322,
4328,
4345,
3092,
2742,
965,
2784,
739,
4124,
952,
1358,
2498,
2949,
2565,
332,
2698,
2378,
660,
2260,
2473,
4194,
3856,
2919,
535,
1260,
2651,
1208,
1428,
1300,
1949,
1303,
2942,
433,
2455,
2450,
1251,
1946,
614,
1269,
641,
1306,
1810,
2737,
3078,
2912,
564,
2365,
1419,
1415,
1497,
4460,
2367,
2185,
1379,
3005,
1307,
3218,
2175,
1897,
3063,
682,
1157,
4040,
4005,
1712,
1160,
1941,
1399,
394,
402,
2952,
1573,
1151,
2986,
2404,
862,
299,
2033,
1489,
3006,
346,
171,
2886,
3401,
1726,
2932,
168,
2533,
47,
2507,
1030,
3735,
1145,
3370,
1395,
1318,
1579,
3609,
4560,
2857,
4116,
1457,
2529,
1965,
504,
1036,
2690,
2988,
2405,
745,
5871,
849,
2397,
2056,
3081,
863,
2359,
3857,
2096,
99,
1397,
1769,
2300,
4428,
1643,
3455,
1978,
1757,
3718,
1440,
35,
4879,
3742,
1296,
4228,
2280,
160,
5063,
1599,
2013,
166,
520,
3479,
1646,
3345,
3012,
490,
1937,
1545,
1264,
2182,
2505,
1096,
1188,
1369,
1436,
2421,
1667,
2792,
2460,
1270,
2122,
727,
3167,
2143,
806,
1706,
1012,
1800,
3037,
960,
2218,
1882,
805,
139,
2456,
1139,
1521,
851,
1052,
3093,
3089,
342,
2039,
744,
5097,
1468,
1502,
1585,
2087,
223,
939,
326,
2140,
2577,
892,
2481,
1623,
4077,
982,
3708,
135,
2131,
87,
2503,
3114,
2326,
1106,
876,
1616,
547,
2997,
2831,
2093,
3441,
4530,
4314,
9,
3256,
4229,
4148,
659,
1462,
1986,
1710,
2046,
2913,
2231,
4090,
4880,
5255,
3392,
3274,
1368,
3689,
4645,
1477,
705,
3384,
3635,
1068,
1529,
2941,
1458,
3782,
1509,
100,
1656,
2548,
718,
2339,
408,
1590,
2780,
3548,
1838,
4117,
3719,
1345,
3530,
717,
3442,
2778,
3220,
2898,
1892,
4590,
3614,
3371,
2043,
1998,
1224,
3483,
891,
635,
584,
2559,
3355,
733,
1766,
1729,
1172,
3789,
1891,
2307,
781,
2982,
2271,
1957,
1580,
5773,
2633,
2005,
4195,
3097,
1535,
3213,
1189,
1934,
5693,
3262,
586,
3118,
1324,
1598,
517,
1564,
2217,
1868,
1893,
4445,
3728,
2703,
3139,
1526,
1787,
1992,
3882,
2875,
1549,
1199,
1056,
2224,
1904,
2711,
5098,
4287,
338,
1993,
3129,
3489,
2689,
1809,
2815,
1997,
957,
1855,
3898,
2550,
3275,
3057,
1105,
1319,
627,
1505,
1911,
1883,
3526,
698,
3629,
3456,
1833,
1431,
746,
77,
1261,
2017,
2296,
1977,
1885,
125,
1334,
1600,
525,
1798,
1109,
2222,
1470,
1945,
559,
2236,
1186,
3443,
2476,
1929,
1411,
2411,
3135,
1777,
3372,
2621,
1841,
1613,
3229,
668,
1430,
1839,
2643,
2916,
195,
1989,
2671,
2358,
1387,
629,
3205,
2293,
5256,
4439,
123,
1310,
888,
1879,
4300,
3021,
3605,
1003,
1162,
3192,
2910,
2010,
140,
2395,
2859,
55,
1082,
2012,
2901,
662,
419,
2081,
1438,
680,
2774,
4654,
3912,
1620,
1731,
1625,
5035,
4065,
2328,
512,
1344,
802,
5443,
2163,
2311,
2537,
524,
3399,
98,
1155,
2103,
1918,
2606,
3925,
2816,
1393,
2465,
1504,
3773,
2177,
3963,
1478,
4346,
180,
1113,
4655,
3461,
2028,
1698,
833,
2696,
1235,
1322,
1594,
4408,
3623,
3013,
3225,
2040,
3022,
541,
2881,
607,
3632,
2029,
1665,
1219,
639,
1385,
1686,
1099,
2803,
3231,
1938,
3188,
2858,
427,
676,
2772,
1168,
2025,
454,
3253,
2486,
3556,
230,
1950,
580,
791,
1991,
1280,
1086,
1974,
2034,
630,
257,
3338,
2788,
4903,
1017,
86,
4790,
966,
2789,
1995,
1696,
1131,
259,
3095,
4188,
1308,
179,
1463,
5257,
289,
4107,
1248,
42,
3413,
1725,
2288,
896,
1947,
774,
4474,
4254,
604,
3430,
4264,
392,
2514,
2588,
452,
237,
1408,
3018,
988,
4531,
1970,
3034,
3310,
540,
2370,
1562,
1288,
2990,
502,
4765,
1147,
4,
1853,
2708,
207,
294,
2814,
4078,
2902,
2509,
684,
34,
3105,
3532,
2551,
644,
709,
2801,
2344,
573,
1727,
3573,
3557,
2021,
1081,
3100,
4315,
2100,
3681,
199,
2263,
1837,
2385,
146,
3484,
1195,
2776,
3949,
997,
1939,
3973,
1008,
1091,
1202,
1962,
1847,
1149,
4209,
5444,
1076,
493,
117,
5400,
2521,
972,
1490,
2934,
1796,
4542,
2374,
1512,
2933,
2657,
413,
2888,
1135,
2762,
2314,
2156,
1355,
2369,
766,
2007,
2527,
2170,
3124,
2491,
2593,
2632,
4757,
2437,
234,
3125,
3591,
1898,
1750,
1376,
1942,
3468,
3138,
570,
2127,
2145,
3276,
4131,
962,
132,
1445,
4196,
19,
941,
3624,
3480,
3366,
1973,
1374,
4461,
3431,
2629,
283,
2415,
2275,
808,
2887,
3620,
2112,
2563,
1353,
3610,
955,
1089,
3103,
1053,
96,
88,
4097,
823,
3808,
1583,
399,
292,
4091,
3313,
421,
1128,
642,
4006,
903,
2539,
1877,
2082,
596,
29,
4066,
1790,
722,
2157,
130,
995,
1569,
769,
1485,
464,
513,
2213,
288,
1923,
1101,
2453,
4316,
133,
486,
2445,
50,
625,
487,
2207,
57,
423,
481,
2962,
159,
3729,
1558,
491,
303,
482,
501,
240,
2837,
112,
3648,
2392,
1783,
362,
8,
3433,
3422,
610,
2793,
3277,
1390,
1284,
1654,
21,
3823,
734,
367,
623,
193,
287,
374,
1009,
1483,
816,
476,
313,
2255,
2340,
1262,
2150,
2899,
1146,
2581,
782,
2116,
1659,
2018,
1880,
255,
3586,
3314,
1110,
2867,
2137,
2564,
986,
2767,
5185,
2006,
650,
158,
926,
762,
881,
3157,
2717,
2362,
3587,
306,
3690,
3245,
1542,
3077,
2427,
1691,
2478,
2118,
2985,
3490,
2438,
539,
2305,
983,
129,
1754,
355,
4201,
2386,
827,
2923,
104,
1773,
2838,
2771,
411,
2905,
3919,
376,
767,
122,
1114,
828,
2422,
1817,
3506,
266,
3460,
1007,
1609,
4998,
945,
2612,
4429,
2274,
726,
1247,
1964,
2914,
2199,
2070,
4002,
4108,
657,
3323,
1422,
579,
455,
2764,
4737,
1222,
2895,
1670,
824,
1223,
1487,
2525,
558,
861,
3080,
598,
2659,
2515,
1967,
752,
2583,
2376,
2214,
4180,
977,
704,
2464,
4999,
2622,
4109,
1210,
2961,
819,
1541,
142,
2284,
44,
418,
457,
1126,
3730,
4347,
4626,
1644,
1876,
3671,
1864,
302,
1063,
5694,
624,
723,
1984,
3745,
1314,
1676,
2488,
1610,
1449,
3558,
3569,
2166,
2098,
409,
1011,
2325,
3704,
2306,
818,
1732,
1383,
1824,
1844,
3757,
999,
2705,
3497,
1216,
1423,
2683,
2426,
2954,
2501,
2726,
2229,
1475,
2554,
5064,
1971,
1794,
1666,
2014,
1343,
783,
724,
191,
2434,
1354,
2220,
5065,
1763,
2752,
2472,
4152,
131,
175,
2885,
3434,
92,
1466,
4920,
2616,
3871,
3872,
3866,
128,
1551,
1632,
669,
1854,
3682,
4691,
4125,
1230,
188,
2973,
3290,
1302,
1213,
560,
3266,
917,
763,
3909,
3249,
1760,
868,
1958,
764,
1782,
2097,
145,
2277,
3774,
4462,
64,
1491,
3062,
971,
2132,
3606,
2442,
221,
1226,
1617,
218,
323,
1185,
3207,
3147,
571,
619,
1473,
1005,
1744,
2281,
449,
1887,
2396,
3685,
275,
375,
3816,
1743,
3844,
3731,
845,
1983,
2350,
4210,
1377,
773,
967,
3499,
3052,
3743,
2725,
4007,
1697,
1022,
3943,
1464,
3264,
2855,
2722,
1952,
1029,
2839,
2467,
84,
4383,
2215,
820,
1391,
2015,
2448,
3672,
377,
1948,
2168,
797,
2545,
3536,
2578,
2645,
94,
2874,
1678,
405,
1259,
3071,
771,
546,
1315,
470,
1243,
3083,
895,
2468,
981,
969,
2037,
846,
4181,
653,
1276,
2928,
14,
2594,
557,
3007,
2474,
156,
902,
1338,
1740,
2574,
537,
2518,
973,
2282,
2216,
2433,
1928,
138,
2903,
1293,
2631,
1612,
646,
3457,
839,
2935,
111,
496,
2191,
2847,
589,
3186,
149,
3994,
2060,
4031,
2641,
4067,
3145,
1870,
37,
3597,
2136,
1025,
2051,
3009,
3383,
3549,
1121,
1016,
3261,
1301,
251,
2446,
2599,
2153,
872,
3246,
637,
334,
3705,
831,
884,
921,
3065,
3140,
4092,
2198,
1944,
246,
2964,
108,
2045,
1152,
1921,
2308,
1031,
203,
3173,
4170,
1907,
3890,
810,
1401,
2003,
1690,
506,
647,
1242,
2828,
1761,
1649,
3208,
2249,
1589,
3709,
2931,
5156,
1708,
498,
666,
2613,
834,
3817,
1231,
184,
2851,
1124,
883,
3197,
2261,
3710,
1765,
1553,
2658,
1178,
2639,
2351,
93,
1193,
942,
2538,
2141,
4402,
235,
1821,
870,
1591,
2192,
1709,
1871,
3341,
1618,
4126,
2595,
2334,
603,
651,
69,
701,
268,
2662,
3411,
2555,
1380,
1606,
503,
448,
254,
2371,
2646,
574,
1187,
2309,
1770,
322,
2235,
1292,
1801,
305,
566,
1133,
229,
2067,
2057,
706,
167,
483,
2002,
2672,
3295,
1820,
3561,
3067,
316,
378,
2746,
3452,
1112,
136,
1981,
507,
1651,
2917,
1117,
285,
4591,
182,
2580,
3522,
1304,
335,
3303,
1835,
2504,
1795,
1792,
2248,
674,
1018,
2106,
2449,
1857,
2292,
2845,
976,
3047,
1781,
2600,
2727,
1389,
1281,
52,
3152,
153,
265,
3950,
672,
3485,
3951,
4463,
430,
1183,
365,
278,
2169,
27,
1407,
1336,
2304,
209,
1340,
1730,
2202,
1852,
2403,
2883,
979,
1737,
1062,
631,
2829,
2542,
3876,
2592,
825,
2086,
2226,
3048,
3625,
352,
1417,
3724,
542,
991,
431,
1351,
3938,
1861,
2294,
826,
1361,
2927,
3142,
3503,
1738,
463,
2462,
2723,
582,
1916,
1595,
2808,
400,
3845,
3891,
2868,
3621,
2254,
58,
2492,
1123,
910,
2160,
2614,
1372,
1603,
1196,
1072,
3385,
1700,
3267,
1980,
696,
480,
2430,
920,
799,
1570,
2920,
1951,
2041,
4047,
2540,
1321,
4223,
2469,
3562,
2228,
1271,
2602,
401,
2833,
3351,
2575,
5157,
907,
2312,
1256,
410,
263,
3507,
1582,
996,
678,
1849,
2316,
1480,
908,
3545,
2237,
703,
2322,
667,
1826,
2849,
1531,
2604,
2999,
2407,
3146,
2151,
2630,
1786,
3711,
469,
3542,
497,
3899,
2409,
858,
837,
4446,
3393,
1274,
786,
620,
1845,
2001,
3311,
484,
308,
3367,
1204,
1815,
3691,
2332,
1532,
2557,
1842,
2020,
2724,
1927,
2333,
4440,
567,
22,
1673,
2728,
4475,
1987,
1858,
1144,
1597,
101,
1832,
3601,
12,
974,
3783,
4391,
951,
1412,
1,
3720,
453,
4608,
4041,
528,
1041,
1027,
3230,
2628,
1129,
875,
1051,
3291,
1203,
2262,
1069,
2860,
2799,
2149,
2615,
3278,
144,
1758,
3040,
31,
475,
1680,
366,
2685,
3184,
311,
1642,
4008,
2466,
5036,
1593,
1493,
2809,
216,
1420,
1668,
233,
304,
2128,
3284,
232,
1429,
1768,
1040,
2008,
3407,
2740,
2967,
2543,
242,
2133,
778,
1565,
2022,
2620,
505,
2189,
2756,
1098,
2273,
372,
1614,
708,
553,
2846,
2094,
2278,
169,
3626,
2835,
4161,
228,
2674,
3165,
809,
1454,
1309,
466,
1705,
1095,
900,
3423,
880,
2667,
3751,
5258,
2317,
3109,
2571,
4317,
2766,
1503,
1342,
866,
4447,
1118,
63,
2076,
314,
1881,
1348,
1061,
172,
978,
3515,
1747,
532,
511,
3970,
6,
601,
905,
2699,
3300,
1751,
276,
1467,
3725,
2668,
65,
4239,
2544,
2779,
2556,
1604,
578,
2451,
1802,
992,
2331,
2624,
1320,
3446,
713,
1513,
1013,
103,
2786,
2447,
1661,
886,
1702,
916,
654,
3574,
2031,
1556,
751,
2178,
2821,
2179,
1498,
1538,
2176,
271,
914,
2251,
2080,
1325,
638,
1953,
2937,
3877,
2432,
2754,
95,
3265,
1716,
260,
1227,
4083,
775,
106,
1357,
3254,
426,
1607,
555,
2480,
772,
1985,
244,
2546,
474,
495,
1046,
2611,
1851,
2061,
71,
2089,
1675,
2590,
742,
3758,
2843,
3222,
1433,
267,
2180,
2576,
2826,
2233,
2092,
3913,
2435,
956,
1745,
3075,
856,
2113,
1116,
451,
3,
1988,
2896,
1398,
993,
2463,
1878,
2049,
1341,
2718,
2721,
2870,
2108,
712,
2904,
4363,
2753,
2324,
277,
2872,
2349,
2649,
384,
987,
435,
691,
3000,
922,
164,
3939,
652,
1500,
1184,
4153,
2482,
3373,
2165,
4848,
2335,
3775,
3508,
3154,
2806,
2830,
1554,
2102,
1664,
2530,
1434,
2408,
893,
1547,
2623,
3447,
2832,
2242,
2532,
3169,
2856,
3223,
2078,
49,
3770,
3469,
462,
318,
656,
2259,
3250,
3069,
679,
1629,
2758,
344,
1138,
1104,
3120,
1836,
1283,
3115,
2154,
1437,
4448,
934,
759,
1999,
794,
2862,
1038,
533,
2560,
1722,
2342,
855,
2626,
1197,
1663,
4476,
3127,
85,
4240,
2528,
25,
1111,
1181,
3673,
407,
3470,
4561,
2679,
2713,
768,
1925,
2841,
3986,
1544,
1165,
932,
373,
1240,
2146,
1930,
2673,
721,
4766,
354,
4333,
391,
2963,
187,
61,
3364,
1442,
1102,
330,
1940,
1767,
341,
3809,
4118,
393,
2496,
2062,
2211,
105,
331,
300,
439,
913,
1332,
626,
379,
3304,
1557,
328,
689,
3952,
309,
1555,
931,
317,
2517,
3027,
325,
569,
686,
2107,
3084,
60,
1042,
1333,
2794,
264,
3177,
4014,
1628,
258,
3712,
7,
4464,
1176,
1043,
1778,
683,
114,
1975,
78,
1492,
383,
1886,
510,
386,
645,
5291,
2891,
2069,
3305,
4138,
3867,
2939,
2603,
2493,
1935,
1066,
1848,
3588,
1015,
1282,
1289,
4609,
697,
1453,
3044,
2666,
3611,
1856,
2412,
54,
719,
1330,
568,
3778,
2459,
1748,
788,
492,
551,
1191,
1000,
488,
3394,
3763,
282,
1799,
348,
2016,
1523,
3155,
2390,
1049,
382,
2019,
1788,
1170,
729,
2968,
3523,
897,
3926,
2785,
2938,
3292,
350,
2319,
3238,
1718,
1717,
2655,
3453,
3143,
4465,
161,
2889,
2980,
2009,
1421,
56,
1908,
1640,
2387,
2232,
1917,
1874,
2477,
4921,
148,
83,
3438,
592,
4245,
2882,
1822,
1055,
741,
115,
1496,
1624,
381,
1638,
4592,
1020,
516,
3214,
458,
947,
4575,
1432,
211,
1514,
2926,
1865,
2142,
189,
852,
1221,
1400,
1486,
882,
2299,
4036,
351,
28,
1122,
700,
6479,
6480,
6481,
6482,
6483 //last 512
/***************************************************************************************
*Everything below is of no interest for detection purpose *
***************************************************************************************
5508,6484,3900,3414,3974,4441,4024,3537,4037,5628,5099,3633,6485,3148,6486,3636,
5509,3257,5510,5973,5445,5872,4941,4403,3174,4627,5873,6276,2286,4230,5446,5874,
5122,6102,6103,4162,5447,5123,5323,4849,6277,3980,3851,5066,4246,5774,5067,6278,
3001,2807,5695,3346,5775,5974,5158,5448,6487,5975,5976,5776,3598,6279,5696,4806,
4211,4154,6280,6488,6489,6490,6281,4212,5037,3374,4171,6491,4562,4807,4722,4827,
5977,6104,4532,4079,5159,5324,5160,4404,3858,5359,5875,3975,4288,4610,3486,4512,
5325,3893,5360,6282,6283,5560,2522,4231,5978,5186,5449,2569,3878,6284,5401,3578,
4415,6285,4656,5124,5979,2506,4247,4449,3219,3417,4334,4969,4329,6492,4576,4828,
4172,4416,4829,5402,6286,3927,3852,5361,4369,4830,4477,4867,5876,4173,6493,6105,
4657,6287,6106,5877,5450,6494,4155,4868,5451,3700,5629,4384,6288,6289,5878,3189,
4881,6107,6290,6495,4513,6496,4692,4515,4723,5100,3356,6497,6291,3810,4080,5561,
3570,4430,5980,6498,4355,5697,6499,4724,6108,6109,3764,4050,5038,5879,4093,3226,
6292,5068,5217,4693,3342,5630,3504,4831,4377,4466,4309,5698,4431,5777,6293,5778,
4272,3706,6110,5326,3752,4676,5327,4273,5403,4767,5631,6500,5699,5880,3475,5039,
6294,5562,5125,4348,4301,4482,4068,5126,4593,5700,3380,3462,5981,5563,3824,5404,
4970,5511,3825,4738,6295,6501,5452,4516,6111,5881,5564,6502,6296,5982,6503,4213,
4163,3454,6504,6112,4009,4450,6113,4658,6297,6114,3035,6505,6115,3995,4904,4739,
4563,4942,4110,5040,3661,3928,5362,3674,6506,5292,3612,4791,5565,4149,5983,5328,
5259,5021,4725,4577,4564,4517,4364,6298,5405,4578,5260,4594,4156,4157,5453,3592,
3491,6507,5127,5512,4709,4922,5984,5701,4726,4289,6508,4015,6116,5128,4628,3424,
4241,5779,6299,4905,6509,6510,5454,5702,5780,6300,4365,4923,3971,6511,5161,3270,
3158,5985,4100, 867,5129,5703,6117,5363,3695,3301,5513,4467,6118,6512,5455,4232,
4242,4629,6513,3959,4478,6514,5514,5329,5986,4850,5162,5566,3846,4694,6119,5456,
4869,5781,3779,6301,5704,5987,5515,4710,6302,5882,6120,4392,5364,5705,6515,6121,
6516,6517,3736,5988,5457,5989,4695,2457,5883,4551,5782,6303,6304,6305,5130,4971,
6122,5163,6123,4870,3263,5365,3150,4871,6518,6306,5783,5069,5706,3513,3498,4409,
5330,5632,5366,5458,5459,3991,5990,4502,3324,5991,5784,3696,4518,5633,4119,6519,
4630,5634,4417,5707,4832,5992,3418,6124,5993,5567,4768,5218,6520,4595,3458,5367,
6125,5635,6126,4202,6521,4740,4924,6307,3981,4069,4385,6308,3883,2675,4051,3834,
4302,4483,5568,5994,4972,4101,5368,6309,5164,5884,3922,6127,6522,6523,5261,5460,
5187,4164,5219,3538,5516,4111,3524,5995,6310,6311,5369,3181,3386,2484,5188,3464,
5569,3627,5708,6524,5406,5165,4677,4492,6312,4872,4851,5885,4468,5996,6313,5709,
5710,6128,2470,5886,6314,5293,4882,5785,3325,5461,5101,6129,5711,5786,6525,4906,
6526,6527,4418,5887,5712,4808,2907,3701,5713,5888,6528,3765,5636,5331,6529,6530,
3593,5889,3637,4943,3692,5714,5787,4925,6315,6130,5462,4405,6131,6132,6316,5262,
6531,6532,5715,3859,5716,5070,4696,5102,3929,5788,3987,4792,5997,6533,6534,3920,
4809,5000,5998,6535,2974,5370,6317,5189,5263,5717,3826,6536,3953,5001,4883,3190,
5463,5890,4973,5999,4741,6133,6134,3607,5570,6000,4711,3362,3630,4552,5041,6318,
6001,2950,2953,5637,4646,5371,4944,6002,2044,4120,3429,6319,6537,5103,4833,6538,
6539,4884,4647,3884,6003,6004,4758,3835,5220,5789,4565,5407,6540,6135,5294,4697,
4852,6320,6321,3206,4907,6541,6322,4945,6542,6136,6543,6323,6005,4631,3519,6544,
5891,6545,5464,3784,5221,6546,5571,4659,6547,6324,6137,5190,6548,3853,6549,4016,
4834,3954,6138,5332,3827,4017,3210,3546,4469,5408,5718,3505,4648,5790,5131,5638,
5791,5465,4727,4318,6325,6326,5792,4553,4010,4698,3439,4974,3638,4335,3085,6006,
5104,5042,5166,5892,5572,6327,4356,4519,5222,5573,5333,5793,5043,6550,5639,5071,
4503,6328,6139,6551,6140,3914,3901,5372,6007,5640,4728,4793,3976,3836,4885,6552,
4127,6553,4451,4102,5002,6554,3686,5105,6555,5191,5072,5295,4611,5794,5296,6556,
5893,5264,5894,4975,5466,5265,4699,4976,4370,4056,3492,5044,4886,6557,5795,4432,
4769,4357,5467,3940,4660,4290,6141,4484,4770,4661,3992,6329,4025,4662,5022,4632,
4835,4070,5297,4663,4596,5574,5132,5409,5895,6142,4504,5192,4664,5796,5896,3885,
5575,5797,5023,4810,5798,3732,5223,4712,5298,4084,5334,5468,6143,4052,4053,4336,
4977,4794,6558,5335,4908,5576,5224,4233,5024,4128,5469,5225,4873,6008,5045,4729,
4742,4633,3675,4597,6559,5897,5133,5577,5003,5641,5719,6330,6560,3017,2382,3854,
4406,4811,6331,4393,3964,4946,6561,2420,3722,6562,4926,4378,3247,1736,4442,6332,
5134,6333,5226,3996,2918,5470,4319,4003,4598,4743,4744,4485,3785,3902,5167,5004,
5373,4394,5898,6144,4874,1793,3997,6334,4085,4214,5106,5642,4909,5799,6009,4419,
4189,3330,5899,4165,4420,5299,5720,5227,3347,6145,4081,6335,2876,3930,6146,3293,
3786,3910,3998,5900,5300,5578,2840,6563,5901,5579,6147,3531,5374,6564,6565,5580,
4759,5375,6566,6148,3559,5643,6336,6010,5517,6337,6338,5721,5902,3873,6011,6339,
6567,5518,3868,3649,5722,6568,4771,4947,6569,6149,4812,6570,2853,5471,6340,6341,
5644,4795,6342,6012,5723,6343,5724,6013,4349,6344,3160,6150,5193,4599,4514,4493,
5168,4320,6345,4927,3666,4745,5169,5903,5005,4928,6346,5725,6014,4730,4203,5046,
4948,3395,5170,6015,4150,6016,5726,5519,6347,5047,3550,6151,6348,4197,4310,5904,
6571,5581,2965,6152,4978,3960,4291,5135,6572,5301,5727,4129,4026,5905,4853,5728,
5472,6153,6349,4533,2700,4505,5336,4678,3583,5073,2994,4486,3043,4554,5520,6350,
6017,5800,4487,6351,3931,4103,5376,6352,4011,4321,4311,4190,5136,6018,3988,3233,
4350,5906,5645,4198,6573,5107,3432,4191,3435,5582,6574,4139,5410,6353,5411,3944,
5583,5074,3198,6575,6354,4358,6576,5302,4600,5584,5194,5412,6577,6578,5585,5413,
5303,4248,5414,3879,4433,6579,4479,5025,4854,5415,6355,4760,4772,3683,2978,4700,
3797,4452,3965,3932,3721,4910,5801,6580,5195,3551,5907,3221,3471,3029,6019,3999,
5908,5909,5266,5267,3444,3023,3828,3170,4796,5646,4979,4259,6356,5647,5337,3694,
6357,5648,5338,4520,4322,5802,3031,3759,4071,6020,5586,4836,4386,5048,6581,3571,
4679,4174,4949,6154,4813,3787,3402,3822,3958,3215,3552,5268,4387,3933,4950,4359,
6021,5910,5075,3579,6358,4234,4566,5521,6359,3613,5049,6022,5911,3375,3702,3178,
4911,5339,4521,6582,6583,4395,3087,3811,5377,6023,6360,6155,4027,5171,5649,4421,
4249,2804,6584,2270,6585,4000,4235,3045,6156,5137,5729,4140,4312,3886,6361,4330,
6157,4215,6158,3500,3676,4929,4331,3713,4930,5912,4265,3776,3368,5587,4470,4855,
3038,4980,3631,6159,6160,4132,4680,6161,6362,3923,4379,5588,4255,6586,4121,6587,
6363,4649,6364,3288,4773,4774,6162,6024,6365,3543,6588,4274,3107,3737,5050,5803,
4797,4522,5589,5051,5730,3714,4887,5378,4001,4523,6163,5026,5522,4701,4175,2791,
3760,6589,5473,4224,4133,3847,4814,4815,4775,3259,5416,6590,2738,6164,6025,5304,
3733,5076,5650,4816,5590,6591,6165,6592,3934,5269,6593,3396,5340,6594,5804,3445,
3602,4042,4488,5731,5732,3525,5591,4601,5196,6166,6026,5172,3642,4612,3202,4506,
4798,6366,3818,5108,4303,5138,5139,4776,3332,4304,2915,3415,4434,5077,5109,4856,
2879,5305,4817,6595,5913,3104,3144,3903,4634,5341,3133,5110,5651,5805,6167,4057,
5592,2945,4371,5593,6596,3474,4182,6367,6597,6168,4507,4279,6598,2822,6599,4777,
4713,5594,3829,6169,3887,5417,6170,3653,5474,6368,4216,2971,5228,3790,4579,6369,
5733,6600,6601,4951,4746,4555,6602,5418,5475,6027,3400,4665,5806,6171,4799,6028,
5052,6172,3343,4800,4747,5006,6370,4556,4217,5476,4396,5229,5379,5477,3839,5914,
5652,5807,4714,3068,4635,5808,6173,5342,4192,5078,5419,5523,5734,6174,4557,6175,
4602,6371,6176,6603,5809,6372,5735,4260,3869,5111,5230,6029,5112,6177,3126,4681,
5524,5915,2706,3563,4748,3130,6178,4018,5525,6604,6605,5478,4012,4837,6606,4534,
4193,5810,4857,3615,5479,6030,4082,3697,3539,4086,5270,3662,4508,4931,5916,4912,
5811,5027,3888,6607,4397,3527,3302,3798,2775,2921,2637,3966,4122,4388,4028,4054,
1633,4858,5079,3024,5007,3982,3412,5736,6608,3426,3236,5595,3030,6179,3427,3336,
3279,3110,6373,3874,3039,5080,5917,5140,4489,3119,6374,5812,3405,4494,6031,4666,
4141,6180,4166,6032,5813,4981,6609,5081,4422,4982,4112,3915,5653,3296,3983,6375,
4266,4410,5654,6610,6181,3436,5082,6611,5380,6033,3819,5596,4535,5231,5306,5113,
6612,4952,5918,4275,3113,6613,6376,6182,6183,5814,3073,4731,4838,5008,3831,6614,
4888,3090,3848,4280,5526,5232,3014,5655,5009,5737,5420,5527,6615,5815,5343,5173,
5381,4818,6616,3151,4953,6617,5738,2796,3204,4360,2989,4281,5739,5174,5421,5197,
3132,5141,3849,5142,5528,5083,3799,3904,4839,5480,2880,4495,3448,6377,6184,5271,
5919,3771,3193,6034,6035,5920,5010,6036,5597,6037,6378,6038,3106,5422,6618,5423,
5424,4142,6619,4889,5084,4890,4313,5740,6620,3437,5175,5307,5816,4199,5198,5529,
5817,5199,5656,4913,5028,5344,3850,6185,2955,5272,5011,5818,4567,4580,5029,5921,
3616,5233,6621,6622,6186,4176,6039,6379,6380,3352,5200,5273,2908,5598,5234,3837,
5308,6623,6624,5819,4496,4323,5309,5201,6625,6626,4983,3194,3838,4167,5530,5922,
5274,6381,6382,3860,3861,5599,3333,4292,4509,6383,3553,5481,5820,5531,4778,6187,
3955,3956,4324,4389,4218,3945,4325,3397,2681,5923,4779,5085,4019,5482,4891,5382,
5383,6040,4682,3425,5275,4094,6627,5310,3015,5483,5657,4398,5924,3168,4819,6628,
5925,6629,5532,4932,4613,6041,6630,4636,6384,4780,4204,5658,4423,5821,3989,4683,
5822,6385,4954,6631,5345,6188,5425,5012,5384,3894,6386,4490,4104,6632,5741,5053,
6633,5823,5926,5659,5660,5927,6634,5235,5742,5824,4840,4933,4820,6387,4859,5928,
4955,6388,4143,3584,5825,5346,5013,6635,5661,6389,5014,5484,5743,4337,5176,5662,
6390,2836,6391,3268,6392,6636,6042,5236,6637,4158,6638,5744,5663,4471,5347,3663,
4123,5143,4293,3895,6639,6640,5311,5929,5826,3800,6189,6393,6190,5664,5348,3554,
3594,4749,4603,6641,5385,4801,6043,5827,4183,6642,5312,5426,4761,6394,5665,6191,
4715,2669,6643,6644,5533,3185,5427,5086,5930,5931,5386,6192,6044,6645,4781,4013,
5745,4282,4435,5534,4390,4267,6045,5746,4984,6046,2743,6193,3501,4087,5485,5932,
5428,4184,4095,5747,4061,5054,3058,3862,5933,5600,6646,5144,3618,6395,3131,5055,
5313,6396,4650,4956,3855,6194,3896,5202,4985,4029,4225,6195,6647,5828,5486,5829,
3589,3002,6648,6397,4782,5276,6649,6196,6650,4105,3803,4043,5237,5830,6398,4096,
3643,6399,3528,6651,4453,3315,4637,6652,3984,6197,5535,3182,3339,6653,3096,2660,
6400,6654,3449,5934,4250,4236,6047,6401,5831,6655,5487,3753,4062,5832,6198,6199,
6656,3766,6657,3403,4667,6048,6658,4338,2897,5833,3880,2797,3780,4326,6659,5748,
5015,6660,5387,4351,5601,4411,6661,3654,4424,5935,4339,4072,5277,4568,5536,6402,
6662,5238,6663,5349,5203,6200,5204,6201,5145,4536,5016,5056,4762,5834,4399,4957,
6202,6403,5666,5749,6664,4340,6665,5936,5177,5667,6666,6667,3459,4668,6404,6668,
6669,4543,6203,6670,4276,6405,4480,5537,6671,4614,5205,5668,6672,3348,2193,4763,
6406,6204,5937,5602,4177,5669,3419,6673,4020,6205,4443,4569,5388,3715,3639,6407,
6049,4058,6206,6674,5938,4544,6050,4185,4294,4841,4651,4615,5488,6207,6408,6051,
5178,3241,3509,5835,6208,4958,5836,4341,5489,5278,6209,2823,5538,5350,5206,5429,
6675,4638,4875,4073,3516,4684,4914,4860,5939,5603,5389,6052,5057,3237,5490,3791,
6676,6409,6677,4821,4915,4106,5351,5058,4243,5539,4244,5604,4842,4916,5239,3028,
3716,5837,5114,5605,5390,5940,5430,6210,4332,6678,5540,4732,3667,3840,6053,4305,
3408,5670,5541,6410,2744,5240,5750,6679,3234,5606,6680,5607,5671,3608,4283,4159,
4400,5352,4783,6681,6411,6682,4491,4802,6211,6412,5941,6413,6414,5542,5751,6683,
4669,3734,5942,6684,6415,5943,5059,3328,4670,4144,4268,6685,6686,6687,6688,4372,
3603,6689,5944,5491,4373,3440,6416,5543,4784,4822,5608,3792,4616,5838,5672,3514,
5391,6417,4892,6690,4639,6691,6054,5673,5839,6055,6692,6056,5392,6212,4038,5544,
5674,4497,6057,6693,5840,4284,5675,4021,4545,5609,6418,4454,6419,6213,4113,4472,
5314,3738,5087,5279,4074,5610,4959,4063,3179,4750,6058,6420,6214,3476,4498,4716,
5431,4960,4685,6215,5241,6694,6421,6216,6695,5841,5945,6422,3748,5946,5179,3905,
5752,5545,5947,4374,6217,4455,6423,4412,6218,4803,5353,6696,3832,5280,6219,4327,
4702,6220,6221,6059,4652,5432,6424,3749,4751,6425,5753,4986,5393,4917,5948,5030,
5754,4861,4733,6426,4703,6697,6222,4671,5949,4546,4961,5180,6223,5031,3316,5281,
6698,4862,4295,4934,5207,3644,6427,5842,5950,6428,6429,4570,5843,5282,6430,6224,
5088,3239,6060,6699,5844,5755,6061,6431,2701,5546,6432,5115,5676,4039,3993,3327,
4752,4425,5315,6433,3941,6434,5677,4617,4604,3074,4581,6225,5433,6435,6226,6062,
4823,5756,5116,6227,3717,5678,4717,5845,6436,5679,5846,6063,5847,6064,3977,3354,
6437,3863,5117,6228,5547,5394,4499,4524,6229,4605,6230,4306,4500,6700,5951,6065,
3693,5952,5089,4366,4918,6701,6231,5548,6232,6702,6438,4704,5434,6703,6704,5953,
4168,6705,5680,3420,6706,5242,4407,6066,3812,5757,5090,5954,4672,4525,3481,5681,
4618,5395,5354,5316,5955,6439,4962,6707,4526,6440,3465,4673,6067,6441,5682,6708,
5435,5492,5758,5683,4619,4571,4674,4804,4893,4686,5493,4753,6233,6068,4269,6442,
6234,5032,4705,5146,5243,5208,5848,6235,6443,4963,5033,4640,4226,6236,5849,3387,
6444,6445,4436,4437,5850,4843,5494,4785,4894,6709,4361,6710,5091,5956,3331,6237,
4987,5549,6069,6711,4342,3517,4473,5317,6070,6712,6071,4706,6446,5017,5355,6713,
6714,4988,5436,6447,4734,5759,6715,4735,4547,4456,4754,6448,5851,6449,6450,3547,
5852,5318,6451,6452,5092,4205,6716,6238,4620,4219,5611,6239,6072,4481,5760,5957,
5958,4059,6240,6453,4227,4537,6241,5761,4030,4186,5244,5209,3761,4457,4876,3337,
5495,5181,6242,5959,5319,5612,5684,5853,3493,5854,6073,4169,5613,5147,4895,6074,
5210,6717,5182,6718,3830,6243,2798,3841,6075,6244,5855,5614,3604,4606,5496,5685,
5118,5356,6719,6454,5960,5357,5961,6720,4145,3935,4621,5119,5962,4261,6721,6455,
4786,5963,4375,4582,6245,6246,6247,6076,5437,4877,5856,3376,4380,6248,4160,6722,
5148,6456,5211,6457,6723,4718,6458,6724,6249,5358,4044,3297,6459,6250,5857,5615,
5497,5245,6460,5498,6725,6251,6252,5550,3793,5499,2959,5396,6461,6462,4572,5093,
5500,5964,3806,4146,6463,4426,5762,5858,6077,6253,4755,3967,4220,5965,6254,4989,
5501,6464,4352,6726,6078,4764,2290,5246,3906,5438,5283,3767,4964,2861,5763,5094,
6255,6256,4622,5616,5859,5860,4707,6727,4285,4708,4824,5617,6257,5551,4787,5212,
4965,4935,4687,6465,6728,6466,5686,6079,3494,4413,2995,5247,5966,5618,6729,5967,
5764,5765,5687,5502,6730,6731,6080,5397,6467,4990,6258,6732,4538,5060,5619,6733,
4719,5688,5439,5018,5149,5284,5503,6734,6081,4607,6259,5120,3645,5861,4583,6260,
4584,4675,5620,4098,5440,6261,4863,2379,3306,4585,5552,5689,4586,5285,6735,4864,
6736,5286,6082,6737,4623,3010,4788,4381,4558,5621,4587,4896,3698,3161,5248,4353,
4045,6262,3754,5183,4588,6738,6263,6739,6740,5622,3936,6741,6468,6742,6264,5095,
6469,4991,5968,6743,4992,6744,6083,4897,6745,4256,5766,4307,3108,3968,4444,5287,
3889,4343,6084,4510,6085,4559,6086,4898,5969,6746,5623,5061,4919,5249,5250,5504,
5441,6265,5320,4878,3242,5862,5251,3428,6087,6747,4237,5624,5442,6266,5553,4539,
6748,2585,3533,5398,4262,6088,5150,4736,4438,6089,6267,5505,4966,6749,6268,6750,
6269,5288,5554,3650,6090,6091,4624,6092,5690,6751,5863,4270,5691,4277,5555,5864,
6752,5692,4720,4865,6470,5151,4688,4825,6753,3094,6754,6471,3235,4653,6755,5213,
5399,6756,3201,4589,5865,4967,6472,5866,6473,5019,3016,6757,5321,4756,3957,4573,
6093,4993,5767,4721,6474,6758,5625,6759,4458,6475,6270,6760,5556,4994,5214,5252,
6271,3875,5768,6094,5034,5506,4376,5769,6761,2120,6476,5253,5770,6762,5771,5970,
3990,5971,5557,5558,5772,6477,6095,2787,4641,5972,5121,6096,6097,6272,6763,3703,
5867,5507,6273,4206,6274,4789,6098,6764,3619,3646,3833,3804,2394,3788,4936,3978,
4866,4899,6099,6100,5559,6478,6765,3599,5868,6101,5869,5870,6275,6766,4527,6767,
*******************************************************************************/
};
public GB18030DistributionAnalyser()
: base()
{
this.charToFreqOrder = GB2312_CHAR2FREQ_ORDER;
this.typicalDistributionRatio = GB2312_TYPICAL_DISTRIBUTION_RATIO;
}
/// <summary>
/// for GB2312 encoding, we are interested
/// first byte range: 0xb0 -- 0xfe
/// second byte range: 0xa1 -- 0xfe
/// no validation needed here. State machine has done that
/// </summary>
/// <returns></returns>
public override int GetOrder(
byte[] buf,
int offset)
{
if (buf[offset] >= 0xB0 && buf[offset + 1] >= 0xA1)
{
return (94 * (buf[offset] - 0xb0)) + buf[offset + 1] - 0xA1;
}
else
{
return -1;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.Shell.Interop;
using NuGet.VisualStudio.Resources;
namespace NuGet.VisualStudio
{
public class VsPackageManager : PackageManager, IVsPackageManager
{
private readonly ISharedPackageRepository _sharedRepository;
private readonly IDictionary<string, IProjectManager> _projects;
private readonly ISolutionManager _solutionManager;
private readonly IRecentPackageRepository _recentPackagesRepository;
private readonly IFileSystemProvider _fileSystemProvider;
private readonly VsPackageInstallerEvents _packageEvents;
private bool _bindingRedirectEnabled = true;
public VsPackageManager(ISolutionManager solutionManager,
IPackageRepository sourceRepository,
IFileSystemProvider fileSystemProvider,
IFileSystem fileSystem,
ISharedPackageRepository sharedRepository,
IRecentPackageRepository recentPackagesRepository,
VsPackageInstallerEvents packageEvents) :
base(sourceRepository, new DefaultPackagePathResolver(fileSystem), fileSystem, sharedRepository)
{
_solutionManager = solutionManager;
_sharedRepository = sharedRepository;
_recentPackagesRepository = recentPackagesRepository;
_packageEvents = packageEvents;
_fileSystemProvider = fileSystemProvider;
_projects = new Dictionary<string, IProjectManager>(StringComparer.OrdinalIgnoreCase);
}
public bool BindingRedirectEnabled
{
get { return _bindingRedirectEnabled; }
set { _bindingRedirectEnabled = value; }
}
internal bool AddToRecent { get; set; }
internal void EnsureCached(Project project)
{
if (_projects.ContainsKey(project.UniqueName))
{
return;
}
_projects[project.UniqueName] = CreateProjectManager(project);
}
public virtual IProjectManager GetProjectManager(Project project)
{
EnsureCached(project);
IProjectManager projectManager;
bool projectExists = _projects.TryGetValue(project.UniqueName, out projectManager);
Debug.Assert(projectExists, "Unknown project");
return projectManager;
}
private IProjectManager CreateProjectManager(Project project)
{
// Create the project system
IProjectSystem projectSystem = VsProjectSystemFactory.CreateProjectSystem(project, _fileSystemProvider);
var repository = new PackageReferenceRepository(projectSystem, _sharedRepository);
// Ensure the logger is null while registering the repository
FileSystem.Logger = null;
Logger = null;
// Ensure that this repository is registered with the shared repository if it needs to be
repository.RegisterIfNecessary();
// The source repository of the project is an aggregate since it might need to look for all
// available packages to perform updates on dependent packages
var sourceRepository = CreateProjectManagerSourceRepository();
var projectManager = new ProjectManager(sourceRepository, PathResolver, projectSystem, repository);
// The package reference repository also provides constraints for packages (via the allowedVersions attribute)
projectManager.ConstraintProvider = repository;
return projectManager;
}
public void InstallPackage(
IEnumerable<Project> projects,
IPackage package,
IEnumerable<PackageOperation> operations,
bool ignoreDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener packageOperationEventListener)
{
if (package == null)
{
throw new ArgumentNullException("package");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
if (projects == null)
{
throw new ArgumentNullException("projects");
}
ExecuteOperationsWithPackage(
projects,
package,
operations,
projectManager => AddPackageReference(projectManager, package.Id, package.Version, ignoreDependencies, allowPrereleaseVersions),
logger,
packageOperationEventListener);
}
public virtual void InstallPackage(
IProjectManager projectManager,
string packageId,
SemanticVersion version,
bool ignoreDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
InstallPackage(projectManager, packageId, version, ignoreDependencies, allowPrereleaseVersions,
skipAssemblyReferences: false, logger: logger);
}
public void InstallPackage(
IProjectManager projectManager,
string packageId,
SemanticVersion version,
bool ignoreDependencies,
bool allowPrereleaseVersions,
bool skipAssemblyReferences,
ILogger logger)
{
InitializeLogger(logger, projectManager);
IPackage package = PackageHelper.ResolvePackage(SourceRepository, LocalRepository, packageId, version, allowPrereleaseVersions);
if (skipAssemblyReferences)
{
package = new SkipAssemblyReferencesPackage(package);
}
RunSolutionAction(() =>
{
InstallPackage(package, ignoreDependencies, allowPrereleaseVersions);
AddPackageReference(projectManager, package, ignoreDependencies, allowPrereleaseVersions);
AddSolutionPackageConfigEntry(package);
});
// Add package to recent repository
AddPackageToRecentRepository(package);
}
public void InstallPackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, bool ignoreDependencies,
bool allowPrereleaseVersions, ILogger logger)
{
if (package == null)
{
throw new ArgumentNullException("package");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
ExecuteOperationsWithPackage(
projectManager,
package,
operations,
() => AddPackageReference(projectManager, package.Id, package.Version, ignoreDependencies, allowPrereleaseVersions),
logger);
}
public void UninstallPackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies)
{
UninstallPackage(projectManager, packageId, version, forceRemove, removeDependencies, NullLogger.Instance);
}
public virtual void UninstallPackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies, ILogger logger)
{
EventHandler<PackageOperationEventArgs> uninstallingHandler =
(sender, e) => _packageEvents.NotifyUninstalling(e);
EventHandler<PackageOperationEventArgs> uninstalledHandler =
(sender, e) => _packageEvents.NotifyUninstalled(e);
try
{
InitializeLogger(logger, projectManager);
bool appliesToProject;
IPackage package = FindLocalPackage(projectManager,
packageId,
version,
CreateAmbiguousUninstallException,
out appliesToProject);
PackageUninstalling += uninstallingHandler;
PackageUninstalled += uninstalledHandler;
if (appliesToProject)
{
RemovePackageReference(projectManager, packageId, forceRemove, removeDependencies);
}
else
{
UninstallPackage(package, forceRemove, removeDependencies);
}
}
finally
{
PackageUninstalling -= uninstallingHandler;
PackageUninstalled -= uninstalledHandler;
}
}
public void UpdatePackage(
IEnumerable<Project> projects,
IPackage package,
IEnumerable<PackageOperation> operations,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener packageOperationEventListener)
{
if (operations == null)
{
throw new ArgumentNullException("operations");
}
if (projects == null)
{
throw new ArgumentNullException("projects");
}
ExecuteOperationsWithPackage(
projects,
package,
operations,
projectManager => UpdatePackageReference(projectManager, package.Id, package.Version, updateDependencies, allowPrereleaseVersions),
logger,
packageOperationEventListener);
}
public virtual void UpdatePackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackage(projectManager,
packageId,
() => UpdatePackageReference(projectManager, packageId, version, updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger);
}
private void UpdatePackage(IProjectManager projectManager, string packageId, Action projectAction, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
try
{
InitializeLogger(logger, projectManager);
bool appliesToProject;
IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject);
// Find the package we're going to update to
IPackage newPackage = resolvePackage();
if (newPackage != null && package.Version != newPackage.Version)
{
if (appliesToProject)
{
RunSolutionAction(projectAction);
}
else
{
// We might be updating a solution only package
UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions);
}
// Add package to recent repository
AddPackageToRecentRepository(newPackage);
}
else
{
Logger.Log(MessageLevel.Info, VsResources.NoUpdatesAvailable, packageId);
}
}
finally
{
ClearLogger(projectManager);
}
}
public void UpdatePackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
if (package == null)
{
throw new ArgumentNullException("package");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
ExecuteOperationsWithPackage(projectManager, package, operations, () => UpdatePackageReference(projectManager, package.Id, package.Version, updateDependencies, allowPrereleaseVersions), logger);
}
public void UpdatePackage(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackage(packageId,
projectManager => UpdatePackageReference(projectManager, packageId, versionSpec, updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger,
eventListener);
}
public void UpdatePackage(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackage(packageId,
projectManager => UpdatePackageReference(projectManager, packageId, version, updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger,
eventListener);
}
public void UpdatePackages(bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackages(updateDependencies, safeUpdate: false, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener);
}
public void UpdatePackages(IProjectManager projectManager, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackages(projectManager, updateDependencies, safeUpdate: false, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger);
}
public void SafeUpdatePackages(IProjectManager projectManager, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackages(projectManager, updateDependencies, safeUpdate: true, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger);
}
public void SafeUpdatePackage(string packageId, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackage(packageId,
projectManager => UpdatePackageReference(projectManager, packageId, GetSafeRange(projectManager, packageId), updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, GetSafeRange(packageId), allowPrereleaseVersions: false, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger,
eventListener);
}
public void SafeUpdatePackage(IProjectManager projectManager, string packageId, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackage(projectManager,
packageId,
() => UpdatePackageReference(projectManager, packageId, GetSafeRange(projectManager, packageId), updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, GetSafeRange(packageId), allowPrereleaseVersions: false, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger);
}
public void SafeUpdatePackages(bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackages(updateDependencies, safeUpdate: true, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener);
}
protected override void ExecuteUninstall(IPackage package)
{
// Check if the package is in use before removing it
if (!_sharedRepository.IsReferenced(package.Id, package.Version))
{
base.ExecuteUninstall(package);
}
}
protected override void OnInstalled(PackageOperationEventArgs e)
{
base.OnInstalled(e);
AddPackageToRecentRepository(e.Package, updateOnly: true);
}
private IPackage FindLocalPackageForUpdate(IProjectManager projectManager, string packageId, out bool appliesToProject)
{
return FindLocalPackage(projectManager, packageId, null /* version */, CreateAmbiguousUpdateException, out appliesToProject);
}
private IPackage FindLocalPackage(IProjectManager projectManager,
string packageId,
SemanticVersion version,
Func<IProjectManager, IList<IPackage>, Exception> getAmbiguousMatchException,
out bool appliesToProject)
{
IPackage package = null;
bool existsInProject = false;
appliesToProject = false;
if (projectManager != null)
{
// Try the project repository first
package = projectManager.LocalRepository.FindPackage(packageId, version);
existsInProject = package != null;
}
// Fallback to the solution repository (it might be a solution only package)
if (package == null)
{
if (version != null)
{
// Get the exact package
package = LocalRepository.FindPackage(packageId, version);
}
else
{
// Get all packages by this name to see if we find an ambiguous match
var packages = LocalRepository.FindPackagesById(packageId).ToList();
if (packages.Count > 1)
{
throw getAmbiguousMatchException(projectManager, packages);
}
// Pick the only one of default if none match
package = packages.SingleOrDefault();
}
}
// Can't find the package in the solution or in the project then fail
if (package == null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackage, packageId));
}
appliesToProject = IsProjectLevel(package);
if (appliesToProject)
{
if (!existsInProject)
{
if (_sharedRepository.IsReferenced(package.Id, package.Version))
{
// If the package doesn't exist in the project and is referenced by other projects
// then fail.
if (projectManager != null)
{
if (version == null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
package.Id,
projectManager.Project.ProjectName));
}
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
package.GetFullName(),
projectManager.Project.ProjectName));
}
}
else
{
// The operation applies to solution level since it's not installed in the current project
// but it is installed in some other project
appliesToProject = false;
}
}
}
// Can't have a project level operation if no project was specified
if (appliesToProject && projectManager == null)
{
throw new InvalidOperationException(VsResources.ProjectNotSpecified);
}
return package;
}
private IPackage FindLocalPackage(string packageId, out bool appliesToProject)
{
// It doesn't matter if there are multiple versions of the package installed at solution level,
// we just want to know that one exists.
var packages = LocalRepository.FindPackagesById(packageId).ToList();
// Can't find the package in the solution.
if (!packages.Any())
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackage, packageId));
}
IPackage package = packages.FirstOrDefault();
appliesToProject = IsProjectLevel(package);
if (!appliesToProject)
{
if (packages.Count > 1)
{
throw CreateAmbiguousUpdateException(projectManager: null, packages: packages);
}
}
else if (!_sharedRepository.IsReferenced(package.Id, package.Version))
{
// If this package applies to a project but isn't installed in any project then
// it's probably a borked install.
throw new PackageNotInstalledException(
String.Format(CultureInfo.CurrentCulture,
VsResources.PackageNotInstalledInAnyProject, packageId));
}
return package;
}
/// <summary>
/// Check to see if this package applies to a project based on 2 criteria:
/// 1. The package has project content (i.e. content that can be applied to a project lib or content files)
/// 2. The package is referenced by any other project
///
/// This logic will probably fail in one edge case. If there is a meta package that applies to a project
/// that ended up not being installed in any of the projects and it only exists at solution level.
/// If this happens, then we think that the following operation applies to the solution instead of showing an error.
/// To solve that edge case we'd have to walk the graph to find out what the package applies to.
/// </summary>
public bool IsProjectLevel(IPackage package)
{
return package.HasProjectContent() || _sharedRepository.IsReferenced(package.Id, package.Version);
}
private Exception CreateAmbiguousUpdateException(IProjectManager projectManager, IList<IPackage> packages)
{
if (projectManager != null && packages.Any(IsProjectLevel))
{
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
packages[0].Id,
projectManager.Project.ProjectName));
}
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousUpdate,
packages[0].Id));
}
private Exception CreateAmbiguousUninstallException(IProjectManager projectManager, IList<IPackage> packages)
{
if (projectManager != null && packages.Any(IsProjectLevel))
{
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousProjectLevelUninstal,
packages[0].Id,
projectManager.Project.ProjectName));
}
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousUninstall,
packages[0].Id));
}
private void RemovePackageReference(IProjectManager projectManager, string packageId, bool forceRemove, bool removeDependencies)
{
RunProjectAction(projectManager, () => projectManager.RemovePackageReference(packageId, forceRemove, removeDependencies));
}
private void UpdatePackageReference(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.UpdatePackageReference(packageId, version, updateDependencies, allowPrereleaseVersions));
}
private void UpdatePackageReference(IProjectManager projectManager, string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.UpdatePackageReference(packageId, versionSpec, updateDependencies, allowPrereleaseVersions));
}
private void AddPackageReference(IProjectManager projectManager, string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.AddPackageReference(packageId, version, ignoreDependencies, allowPrereleaseVersions));
}
private void AddPackageReference(IProjectManager projectManager, IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.AddPackageReference(package, ignoreDependencies, allowPrereleaseVersions));
}
private void ExecuteOperationsWithPackage(IEnumerable<Project> projects, IPackage package, IEnumerable<PackageOperation> operations, Action<IProjectManager> projectAction, ILogger logger, IPackageOperationEventListener eventListener)
{
if (eventListener == null)
{
eventListener = NullPackageOperationEventListener.Instance;
}
ExecuteOperationsWithPackage(
null,
package,
operations,
() =>
{
bool successfulAtLeastOnce = false;
foreach (var project in projects)
{
try
{
eventListener.OnBeforeAddPackageReference(project);
IProjectManager projectManager = GetProjectManager(project);
InitializeLogger(logger, projectManager);
projectAction(projectManager);
successfulAtLeastOnce = true;
}
catch (Exception ex)
{
eventListener.OnAddPackageReferenceError(project, ex);
}
finally
{
eventListener.OnAfterAddPackageReference(project);
}
}
// Throw an exception only if all the update failed for all projects
// so we rollback any solution level operations that might have happened
if (projects.Any() && !successfulAtLeastOnce)
{
throw new InvalidOperationException(VsResources.OperationFailed);
}
},
logger);
}
private void ExecuteOperationsWithPackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, Action action, ILogger logger)
{
try
{
InitializeLogger(logger, projectManager);
RunSolutionAction(() =>
{
if (operations.Any())
{
foreach (var operation in operations)
{
Execute(operation);
}
}
else if (LocalRepository.Exists(package))
{
Logger.Log(MessageLevel.Info, VsResources.Log_PackageAlreadyInstalled, package.GetFullName());
}
action();
AddSolutionPackageConfigEntry(package);
});
// Add package to recent repository
AddPackageToRecentRepository(package);
}
finally
{
ClearLogger(projectManager);
}
}
private Project GetProject(IProjectManager projectManager)
{
// We only support project systems that implement IVsProjectSystem
var vsProjectSystem = projectManager.Project as IVsProjectSystem;
if (vsProjectSystem == null)
{
return null;
}
// Find the project by it's unique name
return _solutionManager.GetProject(vsProjectSystem.UniqueName);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "If we failed to add binding redirects we don't want it to stop the install/update.")]
private void AddBindingRedirects(IProjectManager projectManager)
{
// Find the project by it's unique name
Project project = GetProject(projectManager);
// If we can't find the project or it doesn't support binding redirects then don't add any redirects
if (project == null || !project.SupportsBindingRedirects())
{
return;
}
try
{
RuntimeHelpers.AddBindingRedirects(_solutionManager, project, _fileSystemProvider);
}
catch (Exception e)
{
// If there was an error adding binding redirects then print a warning and continue
Logger.Log(MessageLevel.Warning, String.Format(CultureInfo.CurrentCulture, VsResources.Warning_FailedToAddBindingRedirects, projectManager.Project.ProjectName, e.Message));
}
}
private void AddPackageToRecentRepository(IPackage package, bool updateOnly = false)
{
if (!AddToRecent)
{
return;
}
// add the installed package to the recent repository
if (_recentPackagesRepository != null)
{
if (updateOnly)
{
_recentPackagesRepository.UpdatePackage(package);
}
else
{
_recentPackagesRepository.AddPackage(package);
}
}
}
private void InitializeLogger(ILogger logger, IProjectManager projectManager)
{
// Setup logging on all of our objects
Logger = logger;
FileSystem.Logger = logger;
if (projectManager != null)
{
projectManager.Logger = logger;
projectManager.Project.Logger = logger;
}
}
private void ClearLogger(IProjectManager projectManager)
{
// clear logging on all of our objects
Logger = null;
FileSystem.Logger = null;
if (projectManager != null)
{
projectManager.Logger = null;
projectManager.Project.Logger = null;
}
}
/// <summary>
/// Runs the specified action and rolls back any installed packages if on failure.
/// </summary>
private void RunSolutionAction(Action action)
{
var packagesAdded = new List<IPackage>();
EventHandler<PackageOperationEventArgs> installHandler = (sender, e) =>
{
// Record packages that we are installing so that if one fails, we can rollback
packagesAdded.Add(e.Package);
_packageEvents.NotifyInstalling(e);
};
EventHandler<PackageOperationEventArgs> installedHandler = (sender, e) =>
{
_packageEvents.NotifyInstalled(e);
};
PackageInstalling += installHandler;
PackageInstalled += installedHandler;
try
{
// Execute the action
action();
}
catch
{
if (packagesAdded.Any())
{
// Only print the rollback warning if we have something to rollback
Logger.Log(MessageLevel.Warning, VsResources.Warning_RollingBack);
}
// Don't log anything during the rollback
Logger = null;
// Rollback the install if it fails
Uninstall(packagesAdded);
throw;
}
finally
{
// Remove the event handler
PackageInstalling -= installHandler;
PackageInstalled -= installedHandler;
}
}
/// <summary>
/// Runs action on the project manager and rollsback any package installs if it fails.
/// </summary>
private void RunProjectAction(IProjectManager projectManager, Action action)
{
if (projectManager == null)
{
return;
}
// Keep track of what was added and removed
var packagesAdded = new Stack<IPackage>();
var packagesRemoved = new List<IPackage>();
EventHandler<PackageOperationEventArgs> removeHandler = (sender, e) =>
{
packagesRemoved.Add(e.Package);
_packageEvents.NotifyReferenceRemoved(e);
};
EventHandler<PackageOperationEventArgs> addingHandler = (sender, e) =>
{
packagesAdded.Push(e.Package);
_packageEvents.NotifyReferenceAdded(e);
// If this package doesn't exist at solution level (it might not be because of leveling)
// then we need to install it.
if (!LocalRepository.Exists(e.Package))
{
ExecuteInstall(e.Package);
}
};
// Try to get the project for this project manager
Project project = GetProject(projectManager);
IVsProjectBuildSystem build = null;
if (project != null)
{
build = project.ToVsProjectBuildSystem();
}
// Add the handlers
projectManager.PackageReferenceRemoved += removeHandler;
projectManager.PackageReferenceAdding += addingHandler;
try
{
if (build != null)
{
// Start a batch edit so there is no background compilation until we're done
// processing project actions
build.StartBatchEdit();
}
action();
if (BindingRedirectEnabled && projectManager.Project.IsBindingRedirectSupported)
{
// Only add binding redirects if install was successful
AddBindingRedirects(projectManager);
}
}
catch
{
// We need to Remove the handlers here since we're going to attempt
// a rollback and we don't want modify the collections while rolling back.
projectManager.PackageReferenceRemoved -= removeHandler;
projectManager.PackageReferenceAdded -= addingHandler;
// When things fail attempt a rollback
RollbackProjectActions(projectManager, packagesAdded, packagesRemoved);
// Rollback solution packages
Uninstall(packagesAdded);
// Clear removed packages so we don't try to remove them again (small optimization)
packagesRemoved.Clear();
throw;
}
finally
{
if (build != null)
{
// End the batch edit when we are done.
build.EndBatchEdit();
}
// Remove the handlers
projectManager.PackageReferenceRemoved -= removeHandler;
projectManager.PackageReferenceAdding -= addingHandler;
// Remove any packages that would be removed as a result of updating a dependency or the package itself
// We can execute the uninstall directly since we don't need to resolve dependencies again.
Uninstall(packagesRemoved);
}
}
private static void RollbackProjectActions(IProjectManager projectManager, IEnumerable<IPackage> packagesAdded, IEnumerable<IPackage> packagesRemoved)
{
// Disable logging when rolling back project operations
projectManager.Logger = null;
foreach (var package in packagesAdded)
{
// Remove each package that was added
projectManager.RemovePackageReference(package, forceRemove: false, removeDependencies: false);
}
foreach (var package in packagesRemoved)
{
// Add each package that was removed
projectManager.AddPackageReference(package, ignoreDependencies: true, allowPrereleaseVersions: true);
}
}
private void Uninstall(IEnumerable<IPackage> packages)
{
foreach (var package in packages)
{
ExecuteUninstall(package);
}
}
private void UpdatePackage(string packageId, Action<IProjectManager> projectAction, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions,
ILogger logger, IPackageOperationEventListener eventListener)
{
bool appliesToProject;
IPackage package = FindLocalPackage(packageId, out appliesToProject);
if (appliesToProject)
{
eventListener = eventListener ?? NullPackageOperationEventListener.Instance;
IPackage newPackage = null;
foreach (var project in _solutionManager.GetProjects())
{
IProjectManager projectManager = GetProjectManager(project);
try
{
InitializeLogger(logger, projectManager);
if (projectManager.LocalRepository.Exists(packageId))
{
eventListener.OnBeforeAddPackageReference(project);
try
{
RunSolutionAction(() => projectAction(projectManager));
if (newPackage == null)
{
// after the update, get the new version to add to the recent package repository
newPackage = projectManager.LocalRepository.FindPackage(packageId);
}
}
catch (Exception e)
{
logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message);
eventListener.OnAddPackageReferenceError(project, e);
}
finally
{
eventListener.OnAfterAddPackageReference(project);
}
}
}
finally
{
ClearLogger(projectManager);
}
}
if (newPackage != null)
{
AddPackageToRecentRepository(newPackage);
}
}
else
{
// Find the package we're going to update to
IPackage newPackage = resolvePackage();
if (newPackage != null && package.Version != newPackage.Version)
{
try
{
InitializeLogger(logger, projectManager: null);
// We might be updating a solution only package
UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions);
}
finally
{
ClearLogger(projectManager: null);
}
// Add package to recent repository
AddPackageToRecentRepository(newPackage);
}
else
{
logger.Log(MessageLevel.Info, VsResources.NoUpdatesAvailable, packageId);
}
}
}
private void UpdatePackages(IProjectManager projectManager, bool updateDependencies, bool safeUpdate, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackages(projectManager.LocalRepository, package =>
{
if (safeUpdate)
{
SafeUpdatePackage(projectManager, package.Id, updateDependencies, allowPrereleaseVersions, logger);
}
else
{
UpdatePackage(projectManager, package.Id, version: null, updateDependencies: updateDependencies,
allowPrereleaseVersions: allowPrereleaseVersions, logger: logger);
}
}, logger);
}
private void UpdatePackages(bool updateDependencies, bool safeUpdate, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackages(LocalRepository, package =>
{
if (safeUpdate)
{
SafeUpdatePackage(package.Id, updateDependencies, allowPrereleaseVersions, logger, eventListener);
}
else
{
UpdatePackage(package.Id, version: null, updateDependencies: updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener);
}
},
logger);
}
private void UpdatePackages(IPackageRepository localRepository, Action<IPackage> updateAction, ILogger logger)
{
var packageSorter = new PackageSorter();
// Get the packages in reverse dependency order then run update on each one i.e. if A -> B run Update(A) then Update(B)
var packages = packageSorter.GetPackagesByDependencyOrder(localRepository).Reverse();
foreach (var package in packages)
{
// While updating we might remove packages that were initially in the list. e.g.
// A 1.0 -> B 2.0, A 2.0 -> [], since updating to A 2.0 removes B, we end up skipping it.
if (localRepository.Exists(package.Id))
{
try
{
updateAction(package);
}
catch (PackageNotInstalledException e)
{
logger.Log(MessageLevel.Warning, ExceptionUtility.Unwrap(e).Message);
}
catch (Exception e)
{
logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message);
}
}
}
}
private void AddSolutionPackageConfigEntry(IPackage package)
{
var sharedPackageRepository = LocalRepository as ISharedPackageRepository;
if (sharedPackageRepository != null && !IsProjectLevel(package))
{
sharedPackageRepository.AddPackageReferenceEntry(package.Id, package.Version);
}
}
private IPackageRepository CreateProjectManagerSourceRepository()
{
// The source repo for the project manager is the aggregate of the shared repo and the selected repo.
// For dependency resolution, we want VS to look for packages in the selected source and then use the fallback logic
var fallbackRepository = SourceRepository as FallbackRepository;
if (fallbackRepository != null)
{
var primaryRepositories = new[] { _sharedRepository, fallbackRepository.SourceRepository.Clone() };
return new FallbackRepository(new AggregateRepository(primaryRepositories), fallbackRepository.DependencyResolver);
}
return new AggregateRepository(new[] { _sharedRepository, SourceRepository.Clone() });
}
private IVersionSpec GetSafeRange(string packageId)
{
bool appliesToProject;
IPackage package = FindLocalPackage(packageId, out appliesToProject);
return VersionUtility.GetSafeRange(package.Version);
}
private IVersionSpec GetSafeRange(IProjectManager projectManager, string packageId)
{
bool appliesToProject;
IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject);
return VersionUtility.GetSafeRange(package.Version);
}
}
}
| |
#region change history
//seyed #001 (Dec 13, 05) - compiler complains about needing instance of an object in version 2.0 - removed in V3.0
//seyed #002 (Dec 13, 05) - error in displaying tag name for location in tagHistory tab V2.0
//seyed #003 (Dec 13, 05) - compiler complains about needing instance of an object V2.0 - removed in V3.0
//seyed #004 (Dec 21, 05) - error in displaying tag name in ZoneHistory V3.0
#endregion
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Threading;
using System.Windows.Forms;
//using ActiveWave.RfidDb;
namespace ActiveWave.Mapper
{
public class TagHistoryView : System.Windows.Forms.UserControl, IComparer
{
private delegate void RefreshHandler();
//private RfidDbController m_rfid = RfidDbController.theRfidDbController;
//private IRfidTag m_tag = null;
//private IRfidReader m_reader = null;
private int m_sortColumn = -1;
private bool m_sortReverse = false;
private Color m_backColor0 = Color.FromArgb(255, 255, 255);
private Color m_backColor1 = Color.FromArgb(244, 244, 255);
private System.Windows.Forms.DateTimePicker m_dtFrom;
private System.Windows.Forms.DateTimePicker m_dtTo;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ListView m_lvHistory;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.ColumnHeader columnHeader4;
private ActiveWave.Controls.TitleBar m_lblName;
private System.Windows.Forms.LinkLabel m_lnkRefresh;
private System.Windows.Forms.Label m_lblEventCount;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private enum HistoryType { Tags, Zones }; //seyed #004
#region Constructor
public TagHistoryView()
{
InitializeComponent();
// Set initial dates to span all of today
m_dtFrom.Value = DateTime.Today;
m_dtTo.Value = m_dtFrom.Value.AddDays(1);
// Some kind bug in DateTimePicker with the Checked property
// This seems to resolve it
m_dtFrom.Checked = true;
m_dtTo.Checked = true;
m_dtFrom.Checked = false;
m_dtTo.Checked = false;
}
#endregion
#region Properties
/*public new IRfidTag Tag
{
get { return m_tag; }
set
{
m_reader = null;
m_tag = value;
RefreshData();
}
}*/
/*public IRfidReader Reader
{
get { return m_reader; }
set
{
m_tag = null;
m_reader = value;
RefreshData();
}
}*/
#endregion
/// <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()
{
this.m_dtFrom = new System.Windows.Forms.DateTimePicker();
this.m_dtTo = new System.Windows.Forms.DateTimePicker();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.m_lvHistory = new System.Windows.Forms.ListView();
this.columnHeader4 = new System.Windows.Forms.ColumnHeader();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
this.m_lblName = new ActiveWave.Controls.TitleBar();
this.m_lnkRefresh = new System.Windows.Forms.LinkLabel();
this.m_lblEventCount = new System.Windows.Forms.Label();
this.m_lblName.SuspendLayout();
this.SuspendLayout();
//
// m_dtFrom
//
this.m_dtFrom.Checked = false;
this.m_dtFrom.CustomFormat = "MM/dd/yyyy hh:mm:ss tt";
this.m_dtFrom.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
this.m_dtFrom.Location = new System.Drawing.Point(48, 32);
this.m_dtFrom.Name = "m_dtFrom";
this.m_dtFrom.ShowCheckBox = true;
this.m_dtFrom.Size = new System.Drawing.Size(168, 20);
this.m_dtFrom.TabIndex = 1;
this.m_dtFrom.Value = new System.DateTime(2005, 9, 1, 21, 20, 58, 825);
//
// m_dtTo
//
this.m_dtTo.Checked = false;
this.m_dtTo.CustomFormat = "MM/dd/yyyy hh:mm:ss tt";
this.m_dtTo.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
this.m_dtTo.Location = new System.Drawing.Point(256, 32);
this.m_dtTo.Name = "m_dtTo";
this.m_dtTo.ShowCheckBox = true;
this.m_dtTo.Size = new System.Drawing.Size(168, 20);
this.m_dtTo.TabIndex = 0;
this.m_dtTo.Value = new System.DateTime(2005, 9, 1, 21, 20, 58, 765);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(232, 34);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(21, 16);
this.label1.TabIndex = 2;
this.label1.Text = "To:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(8, 34);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(34, 16);
this.label2.TabIndex = 3;
this.label2.Text = "From:";
//
// m_lvHistory
//
this.m_lvHistory.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.m_lvHistory.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.m_lvHistory.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader4,
this.columnHeader2,
this.columnHeader3});
this.m_lvHistory.FullRowSelect = true;
this.m_lvHistory.GridLines = true;
this.m_lvHistory.Location = new System.Drawing.Point(8, 64);
this.m_lvHistory.Name = "m_lvHistory";
this.m_lvHistory.Size = new System.Drawing.Size(568, 208);
this.m_lvHistory.TabIndex = 4;
this.m_lvHistory.View = System.Windows.Forms.View.Details;
this.m_lvHistory.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.ListViewHistory_ColumnClick);
//
// columnHeader4
//
this.columnHeader4.Text = "Name";
this.columnHeader4.Width = 150;
//
// columnHeader2
//
this.columnHeader2.Text = "Event";
this.columnHeader2.Width = 120;
//
// columnHeader3
//
this.columnHeader3.Text = "Timestamp";
this.columnHeader3.Width = 140;
//
// m_lblName
//
this.m_lblName.AllowDrop = true;
this.m_lblName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.m_lblName.BackColor = System.Drawing.Color.Navy;
this.m_lblName.BorderColor = System.Drawing.Color.White;
this.m_lblName.Controls.Add(this.m_lnkRefresh);
this.m_lblName.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.m_lblName.ForeColor = System.Drawing.Color.White;
this.m_lblName.GradientColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(0)), ((System.Byte)(192)));
this.m_lblName.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical;
this.m_lblName.Location = new System.Drawing.Point(0, 0);
this.m_lblName.Name = "m_lblName";
this.m_lblName.ShadowColor = System.Drawing.Color.Black;
this.m_lblName.ShadowOffset = new System.Drawing.Size(1, 1);
this.m_lblName.Size = new System.Drawing.Size(584, 24);
this.m_lblName.TabIndex = 5;
this.m_lblName.Text = "Title";
//
// m_lnkRefresh
//
this.m_lnkRefresh.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.m_lnkRefresh.AutoSize = true;
this.m_lnkRefresh.BackColor = System.Drawing.Color.Transparent;
this.m_lnkRefresh.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.m_lnkRefresh.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.m_lnkRefresh.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.m_lnkRefresh.LinkColor = System.Drawing.Color.White;
this.m_lnkRefresh.Location = new System.Drawing.Point(528, 4);
this.m_lnkRefresh.Name = "m_lnkRefresh";
this.m_lnkRefresh.Size = new System.Drawing.Size(48, 17);
this.m_lnkRefresh.TabIndex = 6;
this.m_lnkRefresh.TabStop = true;
this.m_lnkRefresh.Text = "Refresh";
this.m_lnkRefresh.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.Refresh_LinkClicked);
//
// m_lblEventCount
//
this.m_lblEventCount.Location = new System.Drawing.Point(440, 34);
this.m_lblEventCount.Name = "m_lblEventCount";
this.m_lblEventCount.Size = new System.Drawing.Size(88, 16);
this.m_lblEventCount.TabIndex = 7;
this.m_lblEventCount.Text = "0 Events";
//
// TagHistoryView
//
this.Controls.Add(this.m_lblEventCount);
this.Controls.Add(this.m_lblName);
this.Controls.Add(this.m_lvHistory);
this.Controls.Add(this.label2);
this.Controls.Add(this.m_dtFrom);
this.Controls.Add(this.m_dtTo);
this.Controls.Add(this.label1);
this.Name = "TagHistoryView";
this.Size = new System.Drawing.Size(584, 280);
this.m_lblName.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
#region User events
private void ListViewHistory_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
{
m_sortReverse = (e.Column == m_sortColumn) ? !m_sortReverse : false;
m_sortColumn = e.Column;
m_lvHistory.ListViewItemSorter = this;
m_lvHistory.Sort();
m_lvHistory.ListViewItemSorter = null;
}
private void Refresh_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
RefreshData();
}
#endregion
#region Misc
public void RefreshData()
{
Thread thread = new Thread(new ThreadStart(RefreshThread));
thread.Start();
}
public void RefreshThread()
{
if (this.InvokeRequired)
{
this.BeginInvoke(new RefreshHandler(RefreshThread));
return;
}
/*if (m_reader != null)
GetReaderHistory();
else
GetTagHistory();*/
m_lblEventCount.Text = m_lvHistory.Items.Count.ToString() + " Events";
m_lblEventCount.Visible = m_lvHistory.Items.Count > 0;
}
private void GetTagHistory()
{
/*m_lvHistory.Items.Clear();
m_lvHistory.Columns[0].Text = "Location";
//seyed #001 (added)- compiler complains about needing instance of an object
//ActiveWave.Controls.TitleBar m_lblName = new ActiveWave.Controls.TitleBar();
//seyed #001 (Dec 13, 2005)-------------------------------------------------
m_lblName.Text = string.Empty;
if (m_tag != null)
{
try
{
m_lblName.Text = m_tag.Name;
DateTime dtFrom = m_dtFrom.Checked ? m_dtFrom.Value : DateTime.MinValue;
DateTime dtTo = m_dtTo.Checked ? m_dtTo.Value : DateTime.MaxValue;
IRfidTagActivity[] tagActivityList = m_rfid.RfidDb.GetTagHistory(m_tag.Id, dtFrom, dtTo);
//AddItems(tagActivityList); //seyed #004
AddItems(tagActivityList, HistoryType.Tags);
}
catch {} // ignore errors for now
} */
}
private void GetReaderHistory()
{
/*m_lvHistory.Items.Clear();
m_lvHistory.Columns[0].Text = "Name";
//seyed #003 (added)- compiler complains about needing instance of an object
//ActiveWave.Controls.TitleBar m_lblName = new ActiveWave.Controls.TitleBar();
//seyed #003 (Dec 13, 2005)-------------------------------------------------
m_lblName.Text = string.Empty;
if (m_reader != null)
{
try
{
m_lblName.Text = m_reader.Name;
DateTime dtFrom = m_dtFrom.Checked ? m_dtFrom.Value : DateTime.MinValue;
DateTime dtTo = m_dtTo.Checked ? m_dtTo.Value : DateTime.MaxValue;
IRfidTagActivity[] tagActivityList = m_rfid.RfidDb.GetReaderHistory(m_reader.Id, dtFrom, dtTo);
//AddItems(tagActivityList); //seyed #004
AddItems(tagActivityList, HistoryType.Zones);
}
catch {} // ignore errors for now
}*/
}
//private void AddItems(IRfidTagActivity[] tagActivityList) //seyed #004
/*private void AddItems(IRfidTagActivity[] tagActivityList, HistoryType type)
{
m_lvHistory.BeginUpdate();
try
{
bool even = false;
foreach (IRfidTagActivity tagActivity in tagActivityList)
{
IRfidTag tag = m_rfid.Tags[tagActivity.TagId];
string name = (tag != null) ? tag.Name : tagActivity.TagId;
//seyed #002 error in displaying tag name for location in tagHistory tab
//displays tag name instead of location
//item = new ListViewItem(tagActivity.Location);
//seyed #002 (Dec 21, 2005) ---------------------------------------------
//seyed #004 error in displaying rdr/fgen for name in zoneHistory tab
//displays tag name instead of location in tagHistory and
//displays rdr/fgen instead of name in zoneHistory
//removed seyed #2 and inserted seyed #3 to fix the problem
//new param for AddItems added enum{Tags, Zones}
ListViewItem item;
if (type == HistoryType.Zones)
item = new ListViewItem(name);
else
item = new ListViewItem(tagActivity.Location);
//seyed #004 (Dec 21, 2005) ------------------------------------------
item.BackColor = even ? m_backColor0 : m_backColor1;
item.SubItems.Add(tagActivity.Event);
item.SubItems.Add(tagActivity.Timestamp.ToString("MM/dd/yyyy hh:mm:ss tt"));
item.Tag = tagActivity;
m_lvHistory.Items.Add(item);
even = !even;
}
}
catch
{
throw;
}
finally
{
m_lvHistory.EndUpdate();
}
}*/
public int Compare(object x, object y)
{
/*ListViewItem item1 = x as ListViewItem;
ListViewItem item2 = y as ListViewItem;
IRfidTagActivity activity1 = item1.Tag as IRfidTagActivity;
IRfidTagActivity activity2 = item2.Tag as IRfidTagActivity;
int rc = 0;
switch (m_sortColumn)
{
case 3: // Timestamp
rc = DateTime.Compare(activity1.Timestamp, activity2.Timestamp);
break;
default:
string s1 = item1.SubItems[m_sortColumn].Text;
string s2 = item2.SubItems[m_sortColumn].Text;
rc = string.Compare(s1, s2);
break;
}
return m_sortReverse ? -rc : rc; */
return 0;
}
#endregion
}
}
| |
namespace AngleSharp.Html.Dom
{
using AngleSharp.Dom;
using AngleSharp.Text;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Represents the HTML table element.
/// </summary>
sealed class HtmlTableElement : HtmlElement, IHtmlTableElement
{
#region Fields
private HtmlCollection<IHtmlTableSectionElement>? _bodies;
private HtmlCollection<IHtmlTableRowElement>? _rows;
#endregion
#region ctor
public HtmlTableElement(Document owner, String? prefix = null)
: base(owner, TagNames.Table, prefix, NodeFlags.Special | NodeFlags.Scoped | NodeFlags.HtmlTableScoped | NodeFlags.HtmlTableSectionScoped)
{
}
#endregion
#region Properties
public IHtmlTableCaptionElement? Caption
{
get => ChildNodes.OfType<IHtmlTableCaptionElement>().FirstOrDefault(m => m.LocalName.Is(TagNames.Caption));
set
{
DeleteCaption();
if (value != null)
{
InsertChild(0, value);
}
}
}
public IHtmlTableSectionElement? Head
{
get => ChildNodes.OfType<IHtmlTableSectionElement>().FirstOrDefault(m => m.LocalName.Is(TagNames.Thead));
set
{
DeleteHead();
if (value != null)
{
AppendChild(value);
}
}
}
public IHtmlCollection<IHtmlTableSectionElement> Bodies => _bodies ??= new HtmlCollection<IHtmlTableSectionElement>(this, deep: false, predicate: m => m.LocalName.Is(TagNames.Tbody));
public IHtmlTableSectionElement? Foot
{
get => ChildNodes.OfType<IHtmlTableSectionElement>().FirstOrDefault(m => m.LocalName.Is(TagNames.Tfoot));
set
{
DeleteFoot();
if (value != null)
{
AppendChild(value);
}
}
}
public IEnumerable<IHtmlTableRowElement> AllRows
{
get
{
var heads = ChildNodes.OfType<IHtmlTableSectionElement>().Where(m => m.LocalName.Is(TagNames.Thead));
var foots = ChildNodes.OfType<IHtmlTableSectionElement>().Where(m => m.LocalName.Is(TagNames.Tfoot));
foreach (var head in heads)
{
foreach (var row in head.Rows)
{
yield return row;
}
}
foreach (var child in ChildNodes)
{
if (child is IHtmlTableSectionElement sectionEl)
{
if (sectionEl.LocalName.Is(TagNames.Tbody))
{
foreach (var row in sectionEl.Rows)
{
yield return row;
}
}
}
else if (child is IHtmlTableRowElement rowEl)
{
yield return rowEl;
}
}
foreach (var foot in foots)
{
foreach (var row in foot.Rows)
{
yield return row;
}
}
}
}
public IHtmlCollection<IHtmlTableRowElement> Rows => _rows ??= new HtmlCollection<IHtmlTableRowElement>(AllRows);
public HorizontalAlignment Align
{
get => this.GetOwnAttribute(AttributeNames.Align).ToEnum(HorizontalAlignment.Left);
set => this.SetOwnAttribute(AttributeNames.Align, value.ToString());
}
public String? BgColor
{
get => this.GetOwnAttribute(AttributeNames.BgColor);
set => this.SetOwnAttribute(AttributeNames.BgColor, value);
}
public UInt32 Border
{
get => this.GetOwnAttribute(AttributeNames.Border).ToInteger(0u);
set => this.SetOwnAttribute(AttributeNames.Border, value.ToString());
}
public Int32 CellPadding
{
get => this.GetOwnAttribute(AttributeNames.CellPadding).ToInteger(0);
set => this.SetOwnAttribute(AttributeNames.CellPadding, value.ToString());
}
public Int32 CellSpacing
{
get => this.GetOwnAttribute(AttributeNames.CellSpacing).ToInteger(0);
set => this.SetOwnAttribute(AttributeNames.CellSpacing, value.ToString());
}
public TableFrames Frame
{
get => this.GetOwnAttribute(AttributeNames.Frame).ToEnum(TableFrames.Void);
set => this.SetOwnAttribute(AttributeNames.Frame, value.ToString());
}
public TableRules Rules
{
get => this.GetOwnAttribute(AttributeNames.Rules).ToEnum(TableRules.All);
set => this.SetOwnAttribute(AttributeNames.Rules, value.ToString());
}
public String? Summary
{
get => this.GetOwnAttribute(AttributeNames.Summary);
set => this.SetOwnAttribute(AttributeNames.Summary, value);
}
public String? Width
{
get => this.GetOwnAttribute(AttributeNames.Width);
set => this.SetOwnAttribute(AttributeNames.Width, value);
}
#endregion
#region Methods
public IHtmlTableRowElement InsertRowAt(Int32 index = -1)
{
var rows = Rows;
var newRow = (IHtmlTableRowElement)Owner.CreateElement(TagNames.Tr);
if (index >= 0 && index < rows.Length)
{
var row = rows[index];
row.ParentElement!.InsertBefore(newRow, row);
}
else if (rows.Length == 0)
{
var bodies = Bodies;
if (bodies.Length == 0)
{
var tbody = Owner.CreateElement(TagNames.Tbody);
AppendChild(tbody);
}
bodies[bodies.Length - 1].AppendChild(newRow);
}
else
{
rows[rows.Length - 1].ParentElement!.AppendChild(newRow);
}
return newRow;
}
public void RemoveRowAt(Int32 index)
{
var rows = Rows;
if (index >= 0 && index < rows.Length)
{
rows[index].Remove();
}
}
public IHtmlTableSectionElement CreateHead()
{
var head = Head;
if (head is null)
{
head = (IHtmlTableSectionElement)Owner.CreateElement(TagNames.Thead);
AppendChild(head);
}
return head;
}
public IHtmlTableSectionElement CreateBody()
{
var lastBody = Bodies.LastOrDefault();
var body = (IHtmlTableSectionElement)Owner.CreateElement(TagNames.Tbody);
var length = ChildNodes.Length;
var index = lastBody != null ? lastBody.Index() + 1 : length;
if (index == length)
{
AppendChild(body);
}
else
{
InsertChild(index, body);
}
return body;
}
public void DeleteHead()
{
Head?.Remove();
}
public IHtmlTableSectionElement CreateFoot()
{
var foot = Foot;
if (foot is null)
{
foot = (IHtmlTableSectionElement)Owner.CreateElement(TagNames.Tfoot);
AppendChild(foot);
}
return foot;
}
public void DeleteFoot()
{
Foot?.Remove();
}
public IHtmlTableCaptionElement CreateCaption()
{
var caption = Caption;
if (caption is null)
{
caption = (IHtmlTableCaptionElement)Owner.CreateElement(TagNames.Caption);
InsertChild(0, caption);
}
return caption;
}
public void DeleteCaption()
{
Caption?.Remove();
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Net;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.ApplicationParts;
using Orleans.CodeGeneration;
using Orleans.Messaging;
using Orleans.Runtime;
namespace Orleans
{
/// <summary>
/// Extension methods for <see cref="IClientBuilder"/>.
/// </summary>
public static class ClientBuilderExtensions
{
/// <summary>
/// Configures default client services.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <returns>The client builder.</returns>
public static IClientBuilder ConfigureDefaults(this IClientBuilder builder)
{
// Configure the container to use an Orleans client.
builder.ConfigureServices(services =>
{
const string key = "OrleansClientServicesAdded";
if (!builder.Properties.ContainsKey(key))
{
DefaultClientServices.AddDefaultServices(builder, services);
builder.Properties.Add(key, true);
}
});
return builder;
}
/// <summary>
/// Specify the environment to be used by the host.
/// </summary>
/// <param name="hostBuilder">The host builder to configure.</param>
/// <param name="environment">The environment to host the application in.</param>
/// <returns>The host builder.</returns>
public static IClientBuilder UseEnvironment(this IClientBuilder hostBuilder, string environment)
{
return hostBuilder.ConfigureHostConfiguration(configBuilder =>
{
configBuilder.AddInMemoryCollection(new[]
{
new KeyValuePair<string, string>(HostDefaults.EnvironmentKey,
environment ?? throw new ArgumentNullException(nameof(environment)))
});
});
}
/// <summary>
/// Adds services to the container. This can be called multiple times and the results will be additive.
/// </summary>
/// <param name="hostBuilder">The <see cref="IClientBuilder" /> to configure.</param>
/// <param name="configureDelegate"></param>
/// <returns>The same instance of the <see cref="IClientBuilder"/> for chaining.</returns>
public static IClientBuilder ConfigureServices(this IClientBuilder hostBuilder, Action<IServiceCollection> configureDelegate)
{
return hostBuilder.ConfigureServices((context, collection) => configureDelegate(collection));
}
/// <summary>
/// Sets up the configuration for the remainder of the build process and application. This can be called multiple times and
/// the results will be additive. The results will be available at <see cref="HostBuilderContext.Configuration"/> for
/// subsequent operations, as well as in <see cref="IClusterClient.Services"/>.
/// </summary>
/// <param name="hostBuilder">The host builder to configure.</param>
/// <param name="configureDelegate"></param>
/// <returns>The same instance of the host builder for chaining.</returns>
public static IClientBuilder ConfigureAppConfiguration(this IClientBuilder hostBuilder, Action<IConfigurationBuilder> configureDelegate)
{
return hostBuilder.ConfigureAppConfiguration((context, builder) => configureDelegate(builder));
}
/// <summary>
/// Registers an action used to configure a particular type of options.
/// </summary>
/// <typeparam name="TOptions">The options type to be configured.</typeparam>
/// <param name="builder">The host builder.</param>
/// <param name="configureOptions">The action used to configure the options.</param>
/// <returns>The client builder.</returns>
public static IClientBuilder Configure<TOptions>(this IClientBuilder builder, Action<TOptions> configureOptions) where TOptions : class
{
return builder.ConfigureServices(services => services.Configure(configureOptions));
}
/// <summary>
/// Adds a client invocation callback.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="callback">The callback.</param>
/// <remarks>
/// A <see cref="ClientInvokeCallback"/> ia a global pre-call interceptor.
/// Synchronous callback made just before a message is about to be constructed and sent by a client to a grain.
/// This call will be made from the same thread that constructs the message to be sent, so any thread-local settings
/// such as <c>Orleans.RequestContext</c> will be picked up.
/// The action receives an <see cref="InvokeMethodRequest"/> with details of the method to be invoked, including InterfaceId and MethodId,
/// and a <see cref="IGrain"/> which is the GrainReference this request is being sent through
/// This callback method should return promptly and do a minimum of work, to avoid blocking calling thread or impacting throughput.
/// </remarks>
/// <returns>The builder.</returns>
public static IClientBuilder AddClientInvokeCallback(this IClientBuilder builder, ClientInvokeCallback callback)
{
builder.ConfigureServices(services => services.AddSingleton(callback));
return builder;
}
/// <summary>
/// Registers a <see cref="ConnectionToClusterLostHandler"/> event handler.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="handler">The handler.</param>
/// <returns>The builder.</returns>
public static IClientBuilder AddClusterConnectionLostHandler(this IClientBuilder builder, ConnectionToClusterLostHandler handler)
{
builder.ConfigureServices(services => services.AddSingleton(handler));
return builder;
}
/// <summary>
/// Specifies how the <see cref="IServiceProvider"/> for this client is configured.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="factory">The service provider factory.</param>
/// <returns>The builder.</returns>
public static IClientBuilder UseServiceProviderFactory(this IClientBuilder builder, Func<IServiceCollection, IServiceProvider> factory)
{
builder.UseServiceProviderFactory(new DelegateServiceProviderFactory(factory));
return builder;
}
/// <summary>
/// Adds a delegate for configuring the provided <see cref="ILoggingBuilder"/>. This may be called multiple times.
/// </summary>
/// <param name="builder">The <see cref="IClientBuilder" /> to configure.</param>
/// <param name="configureLogging">The delegate that configures the <see cref="ILoggingBuilder"/>.</param>
/// <returns>The same instance of the <see cref="IClientBuilder"/> for chaining.</returns>
public static IClientBuilder ConfigureLogging(this IClientBuilder builder, Action<ILoggingBuilder> configureLogging)
{
return builder.ConfigureServices(collection => collection.AddLogging(loggingBuilder => configureLogging(loggingBuilder)));
}
/// <summary>
/// Configures the client to connect to a silo on the localhost.
/// </summary>
/// <param name="gatewayPort">The local silo's gateway port.</param>
public static IClientBuilder UseLocalhostClustering(
this IClientBuilder builder,
int gatewayPort = 30000,
string clusterId = ClusterOptions.DevelopmentClusterId)
{
return builder.UseStaticClustering(new IPEndPoint(IPAddress.Loopback, gatewayPort))
.ConfigureCluster(options =>
{
if (!string.IsNullOrWhiteSpace(clusterId)) options.ClusterId = clusterId;
});
}
/// <summary>
/// Configures the client to connect to a silo on the localhost.
/// </summary>
/// <param name="gatewayPorts">The local silo gateway port.</param>
public static IClientBuilder UseLocalhostClustering(this IClientBuilder builder, params int[] gatewayPorts)
{
return builder.UseStaticClustering(gatewayPorts.Select(p => new IPEndPoint(IPAddress.Loopback, p)).ToArray())
.ConfigureCluster(options =>
{
options.ClusterId = ClusterOptions.DevelopmentClusterId;
});
}
/// <summary>
/// Configures the client to use static clustering.
/// </summary>
/// <param name="endpoints">The gateway endpoints.</param>
public static IClientBuilder UseStaticClustering(this IClientBuilder builder, params IPEndPoint[] endpoints)
{
return builder.UseStaticClustering(options => options.Gateways = endpoints.Select(ep => ep.ToGatewayUri()).ToList());
}
/// <summary>
/// Configures the client to use static clustering.
/// </summary>
public static IClientBuilder UseStaticClustering(this IClientBuilder builder, Action<StaticGatewayListProviderOptions> configureOptions)
{
return builder.ConfigureServices(
collection =>
{
if (configureOptions != null)
{
collection.Configure(configureOptions);
}
collection.AddSingleton<IGatewayListProvider, StaticGatewayListProvider>()
.ConfigureFormatter<StaticGatewayListProviderOptions>();
});
}
/// <summary>
/// Configures the client to use static clustering.
/// </summary>
public static IClientBuilder UseStaticClustering(this IClientBuilder builder, Action<OptionsBuilder<StaticGatewayListProviderOptions>> configureOptions)
{
return builder.ConfigureServices(
collection =>
{
configureOptions?.Invoke(collection.AddOptions<StaticGatewayListProviderOptions>());
collection.AddSingleton<IGatewayListProvider, StaticGatewayListProvider>()
.ConfigureFormatter<StaticGatewayListProviderOptions>();
});
}
/// <summary>
/// Returns the <see cref="ApplicationPartManager"/> for this builder.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns>The <see cref="ApplicationPartManager"/> for this builder.</returns>
public static IApplicationPartManager GetApplicationPartManager(this IClientBuilder builder) => ApplicationPartManagerExtensions.GetApplicationPartManager(builder.Properties);
/// <summary>
/// Configures the <see cref="ApplicationPartManager"/> for this builder.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="configure">The configuration delegate.</param>
/// <returns>The builder.</returns>
public static IClientBuilder ConfigureApplicationParts(this IClientBuilder builder, Action<IApplicationPartManager> configure)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
configure(builder.GetApplicationPartManager());
return builder;
}
/// <summary>
/// Configures the cluster general options.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="configureOptions">The delegate that configures the options.</param>
/// <returns>The same instance of the <see cref="IClientBuilder"/> for chaining.</returns>
public static IClientBuilder ConfigureCluster(this IClientBuilder builder, Action<ClusterOptions> configureOptions)
{
if (configureOptions != null)
{
builder.ConfigureServices(services => services.Configure<ClusterOptions>(configureOptions));
}
return builder;
}
/// <summary>
/// Configures the cluster general options.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="configureOptions">The delegate that configures the options using the options builder.</param>
/// <returns>The same instance of the <see cref="IClientBuilder"/> for chaining.</returns>
public static IClientBuilder ConfigureCluster(this IClientBuilder builder, Action<OptionsBuilder<ClusterOptions>> configureOptions)
{
if (configureOptions != null)
{
builder.ConfigureServices(services =>
{
configureOptions.Invoke(services.AddOptions<ClusterOptions>());
});
}
return builder;
}
}
}
| |
using EIDSS.Reports.Parameterized.Human.AJ.DataSets;
using EIDSS.Reports.Parameterized.Human.AJ.DataSets.FormN1InfectiousDataSetTableAdapters;
namespace EIDSS.Reports.Parameterized.Human.AJ.Reports
{
partial class FormN1Page2
{
/// <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 Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormN1Page2));
this.Detail = new DevExpress.XtraReports.UI.DetailBand();
this.tableInterval = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.TopMargin = new DevExpress.XtraReports.UI.TopMarginBand();
this.BottomMargin = new DevExpress.XtraReports.UI.BottomMarginBand();
this.xrTable3 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell36 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell44 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell57 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell58 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell59 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell60 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell62 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell63 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell64 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell65 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.lblReportName = new DevExpress.XtraReports.UI.XRLabel();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell54 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell55 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell76 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
this.xrLabel2 = new DevExpress.XtraReports.UI.XRLabel();
this.formN1InfectiousDataSet1 = new FormN1InfectiousDataSet();
this.spRepHumFormN1InfectiousDiseasesTableAdapter = new spRepHumFormN1InfectiousDiseasesTableAdapter();
this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand();
this.labelFooterInfo = new DevExpress.XtraReports.UI.XRLabel();
this.labelFooterPage3 = new DevExpress.XtraReports.UI.XRLabel();
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.formN1InfectiousDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// Detail
//
this.Detail.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableInterval});
resources.ApplyResources(this.Detail, "Detail");
this.Detail.Name = "Detail";
this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.Detail.StylePriority.UseBorders = false;
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// tableInterval
//
resources.ApplyResources(this.tableInterval, "tableInterval");
this.tableInterval.Name = "tableInterval";
this.tableInterval.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.tableInterval.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow2});
this.tableInterval.StylePriority.UseBorders = false;
this.tableInterval.StylePriority.UseFont = false;
this.tableInterval.StylePriority.UsePadding = false;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell11,
this.xrTableCell10,
this.xrTableCell14,
this.xrTableCell9,
this.xrTableCell17,
this.xrTableCell16,
this.xrTableCell18,
this.xrTableCell20,
this.xrTableCell15,
this.xrTableCell21,
this.xrTableCell19,
this.xrTableCell22,
this.xrTableCell8});
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
this.xrTableRow2.Name = "xrTableRow2";
this.xrTableRow2.Weight = 0.22388047839877973;
//
// xrTableCell11
//
this.xrTableCell11.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intRowNumber")});
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.Weight = 0.067791687705544751;
//
// xrTableCell10
//
this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.strDiseaseName")});
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseTextAlignment = false;
this.xrTableCell10.Weight = 0.43096140632742513;
//
// xrTableCell14
//
this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.strICD10")});
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.StylePriority.UseFont = false;
this.xrTableCell14.Weight = 0.12347775383578021;
//
// xrTableCell9
//
this.xrTableCell9.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intTotal")});
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.Weight = 0.12589884859601166;
//
// xrTableCell17
//
this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intWomen")});
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.Weight = 0.12105658518847279;
//
// xrTableCell16
//
this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_0_17")});
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.Weight = 0.12347779077931817;
//
// xrTableCell18
//
this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_0_1")});
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.Weight = 0.12347771689224224;
//
// xrTableCell20
//
this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_1_4")});
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.Weight = 0.12347764300516634;
//
// xrTableCell15
//
this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_5_13")});
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Name = "xrTableCell15";
this.xrTableCell15.Weight = 0.12347771689224225;
//
// xrTableCell21
//
this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_14_17")});
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.Weight = 0.12347771689224224;
//
// xrTableCell19
//
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_18_more")});
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.Weight = 0.12347771689224223;
//
// xrTableCell22
//
this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intRuralTotal")});
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.Weight = 0.12347742134393856;
//
// xrTableCell8
//
this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intRuralAge_0_17")});
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.Weight = 0.12347801244054593;
//
// TopMargin
//
resources.ApplyResources(this.TopMargin, "TopMargin");
this.TopMargin.Name = "TopMargin";
this.TopMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
//
// BottomMargin
//
resources.ApplyResources(this.BottomMargin, "BottomMargin");
this.BottomMargin.Name = "BottomMargin";
this.BottomMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
//
// xrTable3
//
resources.ApplyResources(this.xrTable3, "xrTable3");
this.xrTable3.Name = "xrTable3";
this.xrTable3.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow7,
this.xrTableRow1,
this.xrTableRow8,
this.xrTableRow9});
this.xrTable3.StylePriority.UseTextAlignment = false;
//
// xrTableRow7
//
this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell31});
resources.ApplyResources(this.xrTableRow7, "xrTableRow7");
this.xrTableRow7.Name = "xrTableRow7";
this.xrTableRow7.Weight = 0.38143112346400654;
//
// xrTableCell31
//
this.xrTableCell31.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
this.xrTableCell31.Name = "xrTableCell31";
this.xrTableCell31.StylePriority.UseBorders = false;
this.xrTableCell31.Weight = 1.6299997275950411;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell7,
this.xrTableCell2,
this.xrTableCell4,
this.xrTableCell3,
this.xrTableCell5});
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.Weight = 0.57214672157211677;
//
// xrTableCell7
//
this.xrTableCell7.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.StylePriority.UseBorders = false;
this.xrTableCell7.Weight = 0.18111108084389344;
//
// xrTableCell2
//
this.xrTableCell2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.xrTableCell2.StylePriority.UseBorders = false;
this.xrTableCell2.StylePriority.UsePadding = false;
this.xrTableCell2.StylePriority.UseTextAlignment = false;
this.xrTableCell2.Weight = 0.18111108084389344;
//
// xrTableCell4
//
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.Weight = 0.72444432337557385;
//
// xrTableCell3
//
this.xrTableCell3.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.StylePriority.UseBorders = false;
this.xrTableCell3.StylePriority.UseTextAlignment = false;
this.xrTableCell3.Weight = 0.1811112975917977;
//
// xrTableCell5
//
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Multiline = true;
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.xrTableCell5.StylePriority.UsePadding = false;
this.xrTableCell5.Weight = 0.36222194493988263;
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1,
this.xrTableCell36,
this.xrTableCell37,
this.xrTableCell38,
this.xrTableCell39,
this.xrTableCell41,
this.xrTableCell42,
this.xrTableCell43,
this.xrTableCell44});
resources.ApplyResources(this.xrTableRow8, "xrTableRow8");
this.xrTableRow8.Name = "xrTableRow8";
this.xrTableRow8.Weight = 0.95357782949681591;
//
// xrTableCell1
//
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseTextAlignment = false;
this.xrTableCell1.Weight = 0.18111108084389346;
//
// xrTableCell36
//
this.xrTableCell36.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTableCell36, "xrTableCell36");
this.xrTableCell36.Multiline = true;
this.xrTableCell36.Name = "xrTableCell36";
this.xrTableCell36.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.xrTableCell36.StylePriority.UseBorders = false;
this.xrTableCell36.StylePriority.UsePadding = false;
this.xrTableCell36.StylePriority.UseTextAlignment = false;
this.xrTableCell36.Weight = 0.18111108084389352;
//
// xrTableCell37
//
this.xrTableCell37.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTableCell37, "xrTableCell37");
this.xrTableCell37.Multiline = true;
this.xrTableCell37.Name = "xrTableCell37";
this.xrTableCell37.StylePriority.UseBorders = false;
this.xrTableCell37.StylePriority.UseTextAlignment = false;
this.xrTableCell37.Weight = 0.18111108084389369;
//
// xrTableCell38
//
resources.ApplyResources(this.xrTableCell38, "xrTableCell38");
this.xrTableCell38.Multiline = true;
this.xrTableCell38.Name = "xrTableCell38";
this.xrTableCell38.Weight = 0.18111108084389332;
//
// xrTableCell39
//
resources.ApplyResources(this.xrTableCell39, "xrTableCell39");
this.xrTableCell39.Multiline = true;
this.xrTableCell39.Name = "xrTableCell39";
this.xrTableCell39.Weight = 0.18111108084389346;
//
// xrTableCell41
//
resources.ApplyResources(this.xrTableCell41, "xrTableCell41");
this.xrTableCell41.Multiline = true;
this.xrTableCell41.Name = "xrTableCell41";
this.xrTableCell41.Weight = 0.18111108084389369;
//
// xrTableCell42
//
this.xrTableCell42.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTableCell42, "xrTableCell42");
this.xrTableCell42.Name = "xrTableCell42";
this.xrTableCell42.StylePriority.UseBorders = false;
this.xrTableCell42.StylePriority.UseTextAlignment = false;
this.xrTableCell42.Weight = 0.18111108084389332;
//
// xrTableCell43
//
resources.ApplyResources(this.xrTableCell43, "xrTableCell43");
this.xrTableCell43.Multiline = true;
this.xrTableCell43.Name = "xrTableCell43";
this.xrTableCell43.Weight = 0.18111064734808507;
//
// xrTableCell44
//
resources.ApplyResources(this.xrTableCell44, "xrTableCell44");
this.xrTableCell44.Multiline = true;
this.xrTableCell44.Name = "xrTableCell44";
this.xrTableCell44.Weight = 0.18111151433970221;
//
// xrTableRow9
//
this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell6,
this.xrTableCell57,
this.xrTableCell58,
this.xrTableCell59,
this.xrTableCell60,
this.xrTableCell62,
this.xrTableCell63,
this.xrTableCell64,
this.xrTableCell65});
resources.ApplyResources(this.xrTableRow9, "xrTableRow9");
this.xrTableRow9.Name = "xrTableRow9";
this.xrTableRow9.StylePriority.UseFont = false;
this.xrTableRow9.Weight = 0.381431087441066;
//
// xrTableCell6
//
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.Weight = 0.18111108084389346;
//
// xrTableCell57
//
resources.ApplyResources(this.xrTableCell57, "xrTableCell57");
this.xrTableCell57.Name = "xrTableCell57";
this.xrTableCell57.Weight = 0.18111108084389344;
//
// xrTableCell58
//
resources.ApplyResources(this.xrTableCell58, "xrTableCell58");
this.xrTableCell58.Name = "xrTableCell58";
this.xrTableCell58.Weight = 0.18111108084389346;
//
// xrTableCell59
//
resources.ApplyResources(this.xrTableCell59, "xrTableCell59");
this.xrTableCell59.Name = "xrTableCell59";
this.xrTableCell59.Weight = 0.1811110808438936;
//
// xrTableCell60
//
resources.ApplyResources(this.xrTableCell60, "xrTableCell60");
this.xrTableCell60.Name = "xrTableCell60";
this.xrTableCell60.Weight = 0.18111108084389357;
//
// xrTableCell62
//
resources.ApplyResources(this.xrTableCell62, "xrTableCell62");
this.xrTableCell62.Name = "xrTableCell62";
this.xrTableCell62.Weight = 0.18111108084389357;
//
// xrTableCell63
//
resources.ApplyResources(this.xrTableCell63, "xrTableCell63");
this.xrTableCell63.Name = "xrTableCell63";
this.xrTableCell63.Weight = 0.18111108084389357;
//
// xrTableCell64
//
resources.ApplyResources(this.xrTableCell64, "xrTableCell64");
this.xrTableCell64.Name = "xrTableCell64";
this.xrTableCell64.Weight = 0.18111108084389346;
//
// xrTableCell65
//
resources.ApplyResources(this.xrTableCell65, "xrTableCell65");
this.xrTableCell65.Name = "xrTableCell65";
this.xrTableCell65.Weight = 0.1811110808438936;
//
// ReportHeader
//
this.ReportHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.lblReportName,
this.xrTable1,
this.xrTable3});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Name = "ReportHeader";
this.ReportHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.ReportHeader.StylePriority.UseBorders = false;
this.ReportHeader.StylePriority.UseFont = false;
this.ReportHeader.StylePriority.UsePadding = false;
//
// lblReportName
//
this.lblReportName.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.lblReportName.BorderWidth = 1;
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.Name = "lblReportName";
this.lblReportName.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// xrTable1
//
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow5,
this.xrTableRow10});
this.xrTable1.StylePriority.UsePadding = false;
this.xrTable1.StylePriority.UseTextAlignment = false;
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell24,
this.xrTableCell25,
this.xrTableCell12,
this.xrTableCell53});
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
this.xrTableRow5.Name = "xrTableRow5";
this.xrTableRow5.Weight = 1.9071560524138518;
//
// xrTableCell24
//
this.xrTableCell24.Angle = 90F;
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
this.xrTableCell24.Name = "xrTableCell24";
this.xrTableCell24.StylePriority.UseBorders = false;
this.xrTableCell24.StylePriority.UseFont = false;
this.xrTableCell24.StylePriority.UseTextAlignment = false;
this.xrTableCell24.Weight = 0.0995155735580328;
//
// xrTableCell25
//
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
this.xrTableCell25.Name = "xrTableCell25";
this.xrTableCell25.StylePriority.UseBorders = false;
this.xrTableCell25.StylePriority.UseTextAlignment = false;
this.xrTableCell25.Weight = 0.63263472307246038;
//
// xrTableCell12
//
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Multiline = true;
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.Weight = 0.18126050243020497;
//
// xrTableCell53
//
this.xrTableCell53.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTableCell53, "xrTableCell53");
this.xrTableCell53.Name = "xrTableCell53";
this.xrTableCell53.StylePriority.UseBorders = false;
this.xrTableCell53.Weight = 0.18126047618089528;
//
// xrTableRow10
//
this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell54,
this.xrTableCell55,
this.xrTableCell13,
this.xrTableCell76});
resources.ApplyResources(this.xrTableRow10, "xrTableRow10");
this.xrTableRow10.Name = "xrTableRow10";
this.xrTableRow10.StylePriority.UseFont = false;
this.xrTableRow10.Weight = 0.38143087907987572;
//
// xrTableCell54
//
resources.ApplyResources(this.xrTableCell54, "xrTableCell54");
this.xrTableCell54.Name = "xrTableCell54";
this.xrTableCell54.Weight = 0.099515573541268026;
//
// xrTableCell55
//
resources.ApplyResources(this.xrTableCell55, "xrTableCell55");
this.xrTableCell55.Name = "xrTableCell55";
this.xrTableCell55.Weight = 0.632634668857543;
//
// xrTableCell13
//
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.xrTableCell13.StylePriority.UseFont = false;
this.xrTableCell13.StylePriority.UsePadding = false;
this.xrTableCell13.Weight = 0.18126050287464796;
//
// xrTableCell76
//
this.xrTableCell76.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTableCell76, "xrTableCell76");
this.xrTableCell76.Name = "xrTableCell76";
this.xrTableCell76.StylePriority.UseBorders = false;
this.xrTableCell76.Weight = 0.18126052996813424;
//
// ReportFooter
//
resources.ApplyResources(this.ReportFooter, "ReportFooter");
this.ReportFooter.Name = "ReportFooter";
this.ReportFooter.StylePriority.UseFont = false;
//
// xrLabel2
//
this.xrLabel2.BorderWidth = 1;
this.xrLabel2.CanGrow = false;
resources.ApplyResources(this.xrLabel2, "xrLabel2");
this.xrLabel2.Name = "xrLabel2";
this.xrLabel2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel2.StylePriority.UseBorders = false;
this.xrLabel2.StylePriority.UseBorderWidth = false;
this.xrLabel2.StylePriority.UseFont = false;
this.xrLabel2.StylePriority.UseTextAlignment = false;
//
// formN1InfectiousDataSet1
//
this.formN1InfectiousDataSet1.DataSetName = "FormN1InfectiousDataSet";
this.formN1InfectiousDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// spRepHumFormN1InfectiousDiseasesTableAdapter
//
this.spRepHumFormN1InfectiousDiseasesTableAdapter.ClearBeforeFill = true;
//
// PageFooter
//
this.PageFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.labelFooterInfo,
this.labelFooterPage3,
this.xrLabel2});
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.Name = "PageFooter";
//
// labelFooterInfo
//
this.labelFooterInfo.CanGrow = false;
resources.ApplyResources(this.labelFooterInfo, "labelFooterInfo");
this.labelFooterInfo.Multiline = true;
this.labelFooterInfo.Name = "labelFooterInfo";
this.labelFooterInfo.StylePriority.UseBorders = false;
this.labelFooterInfo.StylePriority.UseBorderWidth = false;
this.labelFooterInfo.StylePriority.UseFont = false;
this.labelFooterInfo.StylePriority.UsePadding = false;
this.labelFooterInfo.StylePriority.UseTextAlignment = false;
//
// labelFooterPage3
//
this.labelFooterPage3.CanGrow = false;
resources.ApplyResources(this.labelFooterPage3, "labelFooterPage3");
this.labelFooterPage3.Name = "labelFooterPage3";
this.labelFooterPage3.StylePriority.UseBorders = false;
this.labelFooterPage3.StylePriority.UseBorderWidth = false;
this.labelFooterPage3.StylePriority.UseFont = false;
this.labelFooterPage3.StylePriority.UsePadding = false;
this.labelFooterPage3.StylePriority.UseTextAlignment = false;
//
// FormN1Page2
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.TopMargin,
this.BottomMargin,
this.ReportHeader,
this.ReportFooter,
this.PageFooter});
this.DataAdapter = this.spRepHumFormN1InfectiousDiseasesTableAdapter;
this.DataMember = "spRepHumFormN1InfectiousDiseases";
this.DataSource = this.formN1InfectiousDataSet1;
resources.ApplyResources(this, "$this");
this.PageHeight = 1169;
this.PageWidth = 827;
this.PaperKind = System.Drawing.Printing.PaperKind.A4;
this.Version = "10.1";
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.formN1InfectiousDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailBand Detail;
private DevExpress.XtraReports.UI.TopMarginBand TopMargin;
private DevExpress.XtraReports.UI.BottomMarginBand BottomMargin;
private DevExpress.XtraReports.UI.XRTable xrTable3;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell36;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell37;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell38;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell39;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell41;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell42;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell43;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell44;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell57;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell58;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell59;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell60;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell63;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell64;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell65;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell53;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell54;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell55;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell76;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
protected DevExpress.XtraReports.UI.XRLabel lblReportName;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell62;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
protected DevExpress.XtraReports.UI.XRTable tableInterval;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter;
protected DevExpress.XtraReports.UI.XRLabel xrLabel2;
private FormN1InfectiousDataSet formN1InfectiousDataSet1;
private spRepHumFormN1InfectiousDiseasesTableAdapter spRepHumFormN1InfectiousDiseasesTableAdapter;
private DevExpress.XtraReports.UI.PageFooterBand PageFooter;
private DevExpress.XtraReports.UI.XRLabel labelFooterPage3;
private DevExpress.XtraReports.UI.XRLabel labelFooterInfo;
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Microsoft.Reactive.Testing;
using Avalonia.Data;
using Avalonia.Logging;
using Avalonia.UnitTests;
using Xunit;
using System.Threading.Tasks;
using Avalonia.Platform;
using System.Threading;
using Moq;
using System.Reactive.Disposables;
using System.Reactive.Concurrency;
using Avalonia.Threading;
namespace Avalonia.Base.UnitTests
{
public class AvaloniaObjectTests_Binding
{
[Fact]
public void Bind_Sets_Current_Value()
{
Class1 target = new Class1();
Class1 source = new Class1();
source.SetValue(Class1.FooProperty, "initial");
target.Bind(Class1.FooProperty, source.GetObservable(Class1.FooProperty));
Assert.Equal("initial", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Bind_NonGeneric_Sets_Current_Value()
{
Class1 target = new Class1();
Class1 source = new Class1();
source.SetValue(Class1.FooProperty, "initial");
target.Bind((AvaloniaProperty)Class1.FooProperty, source.GetObservable(Class1.FooProperty));
Assert.Equal("initial", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Bind_To_ValueType_Accepts_UnsetValue()
{
var target = new Class1();
var source = new Subject<object>();
target.Bind(Class1.QuxProperty, source);
source.OnNext(6.7);
source.OnNext(AvaloniaProperty.UnsetValue);
Assert.Equal(5.6, target.GetValue(Class1.QuxProperty));
Assert.False(target.IsSet(Class1.QuxProperty));
}
[Fact]
public void OneTime_Binding_Ignores_UnsetValue()
{
var target = new Class1();
var source = new Subject<object>();
target.Bind(Class1.QuxProperty, new TestOneTimeBinding(source));
source.OnNext(AvaloniaProperty.UnsetValue);
Assert.Equal(5.6, target.GetValue(Class1.QuxProperty));
source.OnNext(6.7);
Assert.Equal(6.7, target.GetValue(Class1.QuxProperty));
}
[Fact]
public void OneTime_Binding_Ignores_Binding_Errors()
{
var target = new Class1();
var source = new Subject<object>();
target.Bind(Class1.QuxProperty, new TestOneTimeBinding(source));
source.OnNext(new BindingNotification(new Exception(), BindingErrorType.Error));
Assert.Equal(5.6, target.GetValue(Class1.QuxProperty));
source.OnNext(6.7);
Assert.Equal(6.7, target.GetValue(Class1.QuxProperty));
}
[Fact]
public void Bind_Throws_Exception_For_Unregistered_Property()
{
Class1 target = new Class1();
Assert.Throws<ArgumentException>(() =>
{
target.Bind(Class2.BarProperty, Observable.Return("foo"));
});
}
[Fact]
public void Bind_Sets_Subsequent_Value()
{
Class1 target = new Class1();
Class1 source = new Class1();
source.SetValue(Class1.FooProperty, "initial");
target.Bind(Class1.FooProperty, source.GetObservable(Class1.FooProperty));
source.SetValue(Class1.FooProperty, "subsequent");
Assert.Equal("subsequent", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Bind_Ignores_Invalid_Value_Type()
{
Class1 target = new Class1();
target.Bind((AvaloniaProperty)Class1.FooProperty, Observable.Return((object)123));
Assert.Equal("foodefault", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Observable_Is_Unsubscribed_When_Subscription_Disposed()
{
var scheduler = new TestScheduler();
var source = scheduler.CreateColdObservable<object>();
var target = new Class1();
var subscription = target.Bind(Class1.FooProperty, source);
Assert.Equal(1, source.Subscriptions.Count);
Assert.Equal(Subscription.Infinite, source.Subscriptions[0].Unsubscribe);
subscription.Dispose();
Assert.Equal(1, source.Subscriptions.Count);
Assert.Equal(0, source.Subscriptions[0].Unsubscribe);
}
[Fact]
public void Two_Way_Separate_Binding_Works()
{
Class1 obj1 = new Class1();
Class1 obj2 = new Class1();
obj1.SetValue(Class1.FooProperty, "initial1");
obj2.SetValue(Class1.FooProperty, "initial2");
obj1.Bind(Class1.FooProperty, obj2.GetObservable(Class1.FooProperty));
obj2.Bind(Class1.FooProperty, obj1.GetObservable(Class1.FooProperty));
Assert.Equal("initial2", obj1.GetValue(Class1.FooProperty));
Assert.Equal("initial2", obj2.GetValue(Class1.FooProperty));
obj1.SetValue(Class1.FooProperty, "first");
Assert.Equal("first", obj1.GetValue(Class1.FooProperty));
Assert.Equal("first", obj2.GetValue(Class1.FooProperty));
obj2.SetValue(Class1.FooProperty, "second");
Assert.Equal("second", obj1.GetValue(Class1.FooProperty));
Assert.Equal("second", obj2.GetValue(Class1.FooProperty));
obj1.SetValue(Class1.FooProperty, "third");
Assert.Equal("third", obj1.GetValue(Class1.FooProperty));
Assert.Equal("third", obj2.GetValue(Class1.FooProperty));
}
[Fact]
public void Two_Way_Binding_With_Priority_Works()
{
Class1 obj1 = new Class1();
Class1 obj2 = new Class1();
obj1.SetValue(Class1.FooProperty, "initial1", BindingPriority.Style);
obj2.SetValue(Class1.FooProperty, "initial2", BindingPriority.Style);
obj1.Bind(Class1.FooProperty, obj2.GetObservable(Class1.FooProperty), BindingPriority.Style);
obj2.Bind(Class1.FooProperty, obj1.GetObservable(Class1.FooProperty), BindingPriority.Style);
Assert.Equal("initial2", obj1.GetValue(Class1.FooProperty));
Assert.Equal("initial2", obj2.GetValue(Class1.FooProperty));
obj1.SetValue(Class1.FooProperty, "first", BindingPriority.Style);
Assert.Equal("first", obj1.GetValue(Class1.FooProperty));
Assert.Equal("first", obj2.GetValue(Class1.FooProperty));
obj2.SetValue(Class1.FooProperty, "second", BindingPriority.Style);
Assert.Equal("second", obj1.GetValue(Class1.FooProperty));
Assert.Equal("second", obj2.GetValue(Class1.FooProperty));
obj1.SetValue(Class1.FooProperty, "third", BindingPriority.Style);
Assert.Equal("third", obj1.GetValue(Class1.FooProperty));
Assert.Equal("third", obj2.GetValue(Class1.FooProperty));
}
[Fact]
public void Local_Binding_Overwrites_Local_Value()
{
var target = new Class1();
var binding = new Subject<string>();
target.Bind(Class1.FooProperty, binding);
binding.OnNext("first");
Assert.Equal("first", target.GetValue(Class1.FooProperty));
target.SetValue(Class1.FooProperty, "second");
Assert.Equal("second", target.GetValue(Class1.FooProperty));
binding.OnNext("third");
Assert.Equal("third", target.GetValue(Class1.FooProperty));
}
[Fact]
public void StyleBinding_Overrides_Default_Value()
{
Class1 target = new Class1();
target.Bind(Class1.FooProperty, Single("stylevalue"), BindingPriority.Style);
Assert.Equal("stylevalue", target.GetValue(Class1.FooProperty));
}
[Fact]
public void this_Operator_Returns_Value_Property()
{
Class1 target = new Class1();
target.SetValue(Class1.FooProperty, "newvalue");
Assert.Equal("newvalue", target[Class1.FooProperty]);
}
[Fact]
public void this_Operator_Sets_Value_Property()
{
Class1 target = new Class1();
target[Class1.FooProperty] = "newvalue";
Assert.Equal("newvalue", target.GetValue(Class1.FooProperty));
}
[Fact]
public void this_Operator_Doesnt_Accept_Observable()
{
Class1 target = new Class1();
Assert.Throws<ArgumentException>(() =>
{
target[Class1.FooProperty] = Observable.Return("newvalue");
});
}
[Fact]
public void this_Operator_Binds_One_Way()
{
Class1 target1 = new Class1();
Class2 target2 = new Class2();
IndexerDescriptor binding = Class2.BarProperty.Bind().WithMode(BindingMode.OneWay);
target1.SetValue(Class1.FooProperty, "first");
target2[binding] = target1[!Class1.FooProperty];
target1.SetValue(Class1.FooProperty, "second");
Assert.Equal("second", target2.GetValue(Class2.BarProperty));
}
[Fact]
public void this_Operator_Binds_Two_Way()
{
Class1 target1 = new Class1();
Class1 target2 = new Class1();
target1.SetValue(Class1.FooProperty, "first");
target2[!Class1.FooProperty] = target1[!!Class1.FooProperty];
Assert.Equal("first", target2.GetValue(Class1.FooProperty));
target1.SetValue(Class1.FooProperty, "second");
Assert.Equal("second", target2.GetValue(Class1.FooProperty));
target2.SetValue(Class1.FooProperty, "third");
Assert.Equal("third", target1.GetValue(Class1.FooProperty));
}
[Fact]
public void this_Operator_Binds_One_Time()
{
Class1 target1 = new Class1();
Class1 target2 = new Class1();
target1.SetValue(Class1.FooProperty, "first");
target2[!Class1.FooProperty] = target1[Class1.FooProperty.Bind().WithMode(BindingMode.OneTime)];
target1.SetValue(Class1.FooProperty, "second");
Assert.Equal("first", target2.GetValue(Class1.FooProperty));
}
[Fact]
public void BindingError_Does_Not_Cause_Target_Update()
{
var target = new Class1();
var source = new Subject<object>();
target.Bind(Class1.QuxProperty, source);
source.OnNext(6.7);
source.OnNext(new BindingNotification(
new InvalidOperationException("Foo"),
BindingErrorType.Error));
Assert.Equal(6.7, target.GetValue(Class1.QuxProperty));
}
[Fact]
public void BindingNotification_With_FallbackValue_Causes_Target_Update()
{
var target = new Class1();
var source = new Subject<object>();
target.Bind(Class1.QuxProperty, source);
source.OnNext(6.7);
source.OnNext(new BindingNotification(
new InvalidOperationException("Foo"),
BindingErrorType.Error,
8.9));
Assert.Equal(8.9, target.GetValue(Class1.QuxProperty));
}
[Fact]
public void Bind_Logs_Binding_Error()
{
var target = new Class1();
var source = new Subject<object>();
var called = false;
var expectedMessageTemplate = "Error in binding to {Target}.{Property}: {Message}";
LogCallback checkLogMessage = (level, area, src, mt, pv) =>
{
if (level == LogEventLevel.Error &&
area == LogArea.Binding &&
mt == expectedMessageTemplate)
{
called = true;
}
};
using (TestLogSink.Start(checkLogMessage))
{
target.Bind(Class1.QuxProperty, source);
source.OnNext(6.7);
source.OnNext(new BindingNotification(
new InvalidOperationException("Foo"),
BindingErrorType.Error));
Assert.Equal(6.7, target.GetValue(Class1.QuxProperty));
Assert.True(called);
}
}
[Fact]
public async Task Bind_With_Scheduler_Executes_On_Scheduler()
{
var target = new Class1();
var source = new Subject<object>();
var currentThreadId = Thread.CurrentThread.ManagedThreadId;
var threadingInterfaceMock = new Mock<IPlatformThreadingInterface>();
threadingInterfaceMock.SetupGet(mock => mock.CurrentThreadIsLoopThread)
.Returns(() => Thread.CurrentThread.ManagedThreadId == currentThreadId);
var services = new TestServices(
scheduler: AvaloniaScheduler.Instance,
threadingInterface: threadingInterfaceMock.Object);
using (UnitTestApplication.Start(services))
{
target.Bind(Class1.QuxProperty, source);
await Task.Run(() => source.OnNext(6.7));
}
}
/// <summary>
/// Returns an observable that returns a single value but does not complete.
/// </summary>
/// <typeparam name="T">The type of the observable.</typeparam>
/// <param name="value">The value.</param>
/// <returns>The observable.</returns>
private IObservable<T> Single<T>(T value)
{
return Observable.Never<T>().StartWith(value);
}
private class Class1 : AvaloniaObject
{
public static readonly StyledProperty<string> FooProperty =
AvaloniaProperty.Register<Class1, string>("Foo", "foodefault");
public static readonly StyledProperty<double> QuxProperty =
AvaloniaProperty.Register<Class1, double>("Qux", 5.6);
}
private class Class2 : Class1
{
public static readonly StyledProperty<string> BarProperty =
AvaloniaProperty.Register<Class2, string>("Bar", "bardefault");
}
private class TestOneTimeBinding : IBinding
{
private IObservable<object> _source;
public TestOneTimeBinding(IObservable<object> source)
{
_source = source;
}
public InstancedBinding Initiate(
IAvaloniaObject target,
AvaloniaProperty targetProperty,
object anchor = null,
bool enableDataValidation = false)
{
return new InstancedBinding(_source, BindingMode.OneTime);
}
}
}
}
| |
/*
* MindTouch MediaWiki Converter
* Copyright (C) 2006-2008 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* http://www.gnu.org/copyleft/lesser.html
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using MindTouch.Deki.Script.Compiler;
using MindTouch.Deki.Script.Expr;
using MindTouch.Dream;
using MindTouch.Tools;
using MindTouch.Xml;
namespace MindTouch.Deki.Converter {
public static class WikiTextProcessor {
//--- Types ---
private enum ParserState {
Text, // regular text, no special processing
External, // processing [ *external* ]
Internal
}
private enum ContextState {
None,
Argument,
Expression,
FirstExpressionThenArgument
}
public static class ExcludedTags {
//--- Constants
private static readonly List<String> _excludedTags = new List<string>(new string[] { "img", "pre", "embed", "script", "style", "applet", "input", "samp", "textarea", "nowiki", "h1", "h2", "h3", "h4", "h5", "h6" });
private static readonly List<String> _excludedClasses = new List<string>(new string[] { "nowiki", "urlexpansion", "plain", "live", "script", "comment" });
//--- Class Methods
public static bool Contains(XmlNode node) {
return Contains(node, false);
}
public static bool Contains(XmlNode node, bool checkParents) {
if(node == null) {
return false;
}
string classAttrValue = String.Empty;
if((null != node.Attributes) && (null != node.Attributes["class"])) {
classAttrValue = node.Attributes["class"].Value;
}
if(_excludedTags.Contains(node.LocalName.ToLowerInvariant()) || _excludedClasses.Contains(classAttrValue.ToLowerInvariant())) {
return true;
} else {
if(checkParents && (null != node.ParentNode)) {
return Contains(node.ParentNode, true);
} else {
return false;
}
}
}
}
//--- Class Fields ---
private static readonly Regex ID_REGEX = new Regex(@"^([a-zA-Z][a-zA-Z0-9_]*)$|^\$$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline);
private static readonly Regex ARG_REGEX = new Regex(@"^([a-zA-Z0-9_]+)$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline);
//--- Class Methods ---
public static void Convert(Site site, XDoc doc, bool isTemplate) {
XmlNamespaceManager ns = new XmlNamespaceManager(XDoc.XmlNameTable);
ns.AddNamespace("m", "#mediawiki");
DetectWikiTextLinks(doc.AsXmlNode);
Convert(site, doc, isTemplate, doc.AsXmlNode, ContextState.None, ns);
}
private static void Convert(Site site, XDoc doc, bool isTemplate, XmlNode node, ContextState state, XmlNamespaceManager ns) {
List<XmlNode> list = new List<XmlNode>();
foreach(XmlNode child in node.ChildNodes) {
list.Add(child);
}
ContextState original = state;
bool firstChild = true;
foreach(XmlNode child in list) {
// only first arguments can be expressions
if(original == ContextState.FirstExpressionThenArgument) {
if(!firstChild) {
state = ContextState.Argument;
} else {
state = ContextState.Expression;
}
}
firstChild = false;
// determine what kinf of child element this is
XDoc current = doc[child];
if((child.NodeType == XmlNodeType.Element) && (child.NamespaceURI == "#mediawiki")) {
switch(child.LocalName) {
case "internal": {
// check if this element contains elements that would prevent it from being an internal link
if(current.AtPath(".//m:link | .//m:internal | .//m:external", ns).IsEmpty) {
Convert(site, doc, isTemplate, child, ContextState.Argument, ns);
StringBuilder code = new StringBuilder();
code.Append("mediawiki.internal").Append("(");
code.Append(AsArgument(child));
if(!string.IsNullOrEmpty(site.Language)) {
code.Append(", ").Append(DekiScriptString.QuoteString(site.Language));
}
code.Append(")");
current.Replace(Scripted(code.ToString(), state, true));
} else {
Convert(site, doc, isTemplate, child, state, ns);
if(state == ContextState.Argument) {
current.AddBefore("'[['");
current.AddAfter("']]'");
} else {
current.AddBefore("[[");
current.AddAfter("]]");
}
current.ReplaceWithNodes(current);
}
}
break;
case "external": {
// check if this element contains elements that would prevent it from being an external link
if(current.AtPath(".//m:link | .//m:internal | .//m:external", ns).IsEmpty) {
Convert(site, doc, isTemplate, child, ContextState.Argument, ns);
StringBuilder code = new StringBuilder();
code.Append("mediawiki.external").Append("(");
code.Append(AsArgument(child));
code.Append(")");
current.Replace(Scripted(code.ToString(), state, true));
} else {
Convert(site, doc, isTemplate, child, state, ns);
if(state == ContextState.Argument) {
current.AddBefore("'['");
current.AddAfter("']'");
} else {
current.AddBefore("[");
current.AddAfter("]");
}
current.ReplaceWithNodes(current);
}
}
break;
case "link":
Convert(site, doc, isTemplate, child, state, ns);
switch(current["@type"].AsText) {
case "internal":
current.Replace(new XDoc("a").Attr("href", current["@href"].AsText).AddNodes(current));
break;
case "external":
current.Replace(new XDoc("a").Attr("class", "external").Attr("href", current["@href"].AsText).AddNodes(current));
break;
case "external-free":
if(state == ContextState.None) {
current.Replace(current["@href"].AsText);
} else {
current.Replace(QuoteString(current["@href"].AsText));
}
break;
case "external-ref":
current.Replace(new XDoc("a").Attr("class", "external").Attr("href", current["@href"].AsText));
break;
default:
// no idea what this link is, let's replace with a text version of itself
current.Replace(child.OuterXml);
break;
}
break;
case "image":
current.Replace(new XDoc("img").Attr("src", current["@href"].AsText).Attr("alt", current["@alt"].AsText).Attr("align", current["@align"].AsText));
break;
case "comment":
Convert(site, doc, isTemplate, child, state, ns);
current.Replace(new XDoc("span").Attr("class", "comment").AddNodes(current));
break;
case "nowiki":
current.Replace(new XDoc("span").Attr("class", "plain").AddNodes(current));
break;
case "extension":
// TODO: should the behavior be different depending on 'state'?
Convert(site, doc, isTemplate, child, state, ns);
if (!current["@value"].IsEmpty) {
current.Replace("{{" + current["@value"].AsText + "}}");
} else {
switch (current["@function"].AsText) {
case "math":
current.Replace(new XDoc("pre").Attr("class", "script").Attr("function", "math.formula").Value(current.AsText));
break;
case "kbd":
case "abbr":
case "object":
current.Rename(current["@function"].AsText.ToLowerInvariant());
current.RemoveAttr("function");
break;
case "rss": {
StringBuilder code = new StringBuilder();
string[] rssParams = current.Contents.Split('|');
code.Append("ajaxrss{");
code.AppendFormat(" feed: '{0}' ", rssParams[0]);
for (int i = 1; i < rssParams.Length; i++) {
string rssParam = rssParams[i].Trim();
int index = rssParam.IndexOf('=');
if (index >= 0) {
code.AppendFormat(", {0}: {1}", rssParam.Substring(0, index), QuoteString(rssParam.Substring(index + 1)));
} else {
code.AppendFormat(", {0}: true", rssParam);
}
}
code.Append(" }");
current.Replace(new XDoc("span").Attr("class", "script").Value(code.ToString()));
}
break;
case "title-override":
case "breadcrumbs":
current.Remove();
break;
default:
current.Replace(child.OuterXml);
break;
}
}
break;
case "magic": {
string code = null;
switch(current["@name"].AsText) {
case "CONTENTLANGUAGE":
code = "site.language";
break;
case "CURRENTDAY":
code = "date.format(date.now, '%d')";
break;
case "CURRENTDAY2":
code = "date.format(date.now, 'dd')";
break;
case "CURRENTDAYNAME":
code = "date.dayname(date.now)";
break;
case "CURRENTDOW":
code = "date.dayofweek(date.now)";
break;
case "CURRENTMONTH":
code = "date.month(date.now)";
break;
case "CURRENTMONTHABBREV":
code = "date.format(date.now, 'MMM')";
break;
case "CURRENTMONTHNAME":
code = "date.monthname(date.now)";
break;
case "CURRENTTIME":
code = "date.time(date.now)";
break;
case "CURRENTHOUR":
code = "date.format(date.now, 'HH')";
break;
case "CURRENTWEEK":
code = "date.week(date.now)";
break;
case "CURRENTYEAR":
code = "date.year(date.now)";
break;
case "CURRENTTIMESTAMP":
code = "date.format(date.now, 'yyyyMMddHHmmss')";
break;
case "PAGENAME":
case "PAGENAMEE":
code = "page.unprefixedpath";
break;
case "NUMBEROFARTICLES":
code = "site.pagecount";
break;
case "NUMBEROFUSERS":
code = "site.usercount";
break;
case "NAMESPACE":
code = "page.namespace";
break;
case "REVISIONDAY":
code = "date.format(page.date, '%d')";
break;
case "REVISIONDAY2":
code = "date.format(page.date, 'dd')";
break;
case "REVISIONMONTH":
code = "date.month(page.date)";
break;
case "REVISIONYEAR":
code = "date.year(page.date)";
break;
case "REVISIONTIMESTAMP":
code = "date.format(page.date, 'yyyyMMddHHmmss')";
break;
case "SITENAME":
code = "site.name";
break;
case "SERVER":
code = "site.uri";
break;
case "SERVERNAME":
code = "site.host";
break;
default:
// unrecognized magic word - use the mediawiki magicword extension
code = String.Format("mediawiki.variable('{0}')", DekiScriptString.EscapeString(current["@name"].AsText));
break;
}
current.Replace(Scripted(code, state, true));
}
break;
case "interwiki": {
string code = String.Format("mediawiki.interwiki('{0}', '{1}', '{2}')",
DekiScriptString.EscapeString(child.Attributes["prefix"].Value),
DekiScriptString.EscapeString(child.Attributes["path"].Value + (((XmlElement)child).HasAttribute("fragment") ? ("#" + child.Attributes["fragment"].Value) : string.Empty)),
DekiScriptString.EscapeString(child.InnerText));
current.Replace(Scripted(code, state, true));
break;
}
case "function": {
Convert(site, doc, isTemplate, child, ContextState.Argument, ns);
StringBuilder code = new StringBuilder();
bool withLang = false;
switch (current["@name"].AsText) {
case "formatnum": {
code.Append("num.format");
// add one more parameter
XmlElement arg = child.OwnerDocument.CreateElement("arg", "#mediawiki");
arg.AppendChild(child.OwnerDocument.CreateTextNode(QuoteString("N")));
child.AppendChild(arg);
}
break;
case "fullurl":
code.Append("wiki.uri");
break;
case "lc":
code.Append("string.tolower");
break;
case "lcfirst":
code.Append("string.tolowerfirst");
break;
case "padleft":
code.Append("string.padleft");
break;
case "padright":
code.Append("string.padright");
break;
case "uc":
code.Append("string.toupper");
break;
case "ucfirst":
code.Append("string.toupperfirst");
break;
case "urlencode":
code.Append("web.uriencode");
break;
case "int":
code.Append("wiki.page");
break;
case "localurl":
case "localurle":
withLang = true;
code.Append(At("mediawiki", current["@name"].AsText));
break;
default:
code.Append(At("mediawiki", current["@name"].AsText));
break;
}
// append parameters
code.Append("(");
if (withLang) {
code.Append(null == site.Language ? "_" : DekiScriptString.QuoteString(site.Language));
}
bool first = true && !withLang;
foreach(XDoc arg in current.AtPath("m:arg", ns)) {
if(!first) {
code.Append(", ");
}
first = false;
code.Append(AsArgument(arg.AsXmlNode));
}
code.Append(")");
current.Replace(Scripted(code.ToString(), state, true));
}
break;
case "expression": {
StringBuilder code = new StringBuilder();
switch(current["@name"].AsText) {
case "#expr":
Convert(site, doc, isTemplate, child, ContextState.Expression, ns);
code.Append(AsExpression(current.AtPath("m:arg", ns).AsXmlNode));
break;
case "#if": {
Convert(site, doc, isTemplate, child, ContextState.Argument, ns);
code.Append("string.trim(");
code.Append(AsArgument(current.AtPath("m:arg[1]", ns).AsXmlNode));
code.Append(") !== '' ? ");
code.Append(WebHtml(current.AtPath("m:arg[2]", ns).AsXmlNode));
code.Append(" : ");
code.Append(WebHtml(current.AtPath("m:arg[3]", ns).AsXmlNode));
}
break;
case "#ifeq": {
Convert(site, doc, isTemplate, child, ContextState.Argument, ns);
code.Append(AsArgument(current.AtPath("m:arg[1]", ns).AsXmlNode));
code.Append(" == ");
code.Append(AsArgument(current.AtPath("m:arg[2]", ns).AsXmlNode));
code.Append(" ? ");
code.Append(WebHtml(current.AtPath("m:arg[3]", ns).AsXmlNode));
code.Append(" : ");
code.Append(WebHtml(current.AtPath("m:arg[4]", ns).AsXmlNode));
}
break;
case "#ifexpr": {
Convert(site, doc, isTemplate, child, ContextState.FirstExpressionThenArgument, ns);
code.Append(AsExpression(current.AtPath("m:arg[1]", ns).AsXmlNode));
code.Append(" ? ");
code.Append(WebHtml(current.AtPath("m:arg[2]", ns).AsXmlNode));
code.Append(" : ");
code.Append(WebHtml(current.AtPath("m:arg[3]", ns).AsXmlNode));
}
break;
case "#ifexist": {
bool simple;
Convert(site, doc, isTemplate, child, ContextState.Argument, ns);
code.Append("wiki.pageexists(");
string title = AsPathArgument(site, current.AtPath("m:arg[1]", ns), false, out simple);
code.Append(simple ? ("'" + title + "'") : title);
code.Append(") ? ");
code.Append(WebHtml(current.AtPath("m:arg[2]", ns).AsXmlNode));
code.Append(" : ");
code.Append(WebHtml(current.AtPath("m:arg[3]", ns).AsXmlNode));
}
break;
case "#switch":
case "#time":
case "#rel2abs":
case "#titleparts":
case "#iferror":
// TODO (steveb): missing code, falling through to default case
default:
code.Append(At("mediawiki", current["@name"].AsText));
// append parameters
code.Append("(");
bool first = true;
foreach(XDoc arg in current.AtPath("m:arg", ns)) {
if(!first) {
code.Append(", ");
}
first = false;
code.Append(AsArgument(arg.AsXmlNode));
}
code.Append(")");
break;
}
current.Replace(Scripted(code.ToString(), state, false));
}
break;
case "template": {
Convert(site, doc, isTemplate, child, ContextState.Argument, ns);
StringBuilder code = new StringBuilder();
// check if we need to decode the page name
bool simpleTitle;
bool simpleArgs;
string title = AsPathArgument(site, current.AtPath("m:name", ns), true, out simpleTitle);
XDoc args = current.AtPath("m:arg", ns);
string argCode = AppendTemplateArguments(args, out simpleArgs);
// append parameters
if(simpleTitle && simpleArgs) {
code.Append("template.");
code.Append(title.Substring(1, title.Length - 2));
if(string.IsNullOrEmpty(argCode)) {
code.Append("()");
} else if(argCode.StartsWith("[") && argCode.EndsWith("]")) {
code.Append("(" + argCode.Substring(2, argCode.Length - 4) + ")");
} else {
code.Append(argCode);
}
} else {
code.Append("wiki.template").Append("(");
code.Append(title);
if(!string.IsNullOrEmpty(argCode)) {
code.Append(", ");
code.Append(argCode);
}
code.Append(")");
}
current.Replace(Scripted(code.ToString(), state, true));
}
break;
case "arg":
Convert(site, doc, isTemplate, child, state, ns);
break;
case "name":
Convert(site, doc, isTemplate, child, state, ns);
break;
case "ref": {
if(isTemplate || (state != ContextState.None)) {
Convert(site, doc, isTemplate, child, state, ns);
string code;
int? index = current["@index"].AsInt;
if(index != null) {
code = "$" + (index.Value - 1);
} else {
code = "$" + current["@name"].AsText;
}
switch(state) {
case ContextState.None:
if(current["@alt"].IsEmpty) {
current.Replace(Scripted("web.html(" + code + ")", state, true));
} else {
current.Replace(Scripted("web.html(" + code + " ?? " + AsArgument(current.AsXmlNode) + ")", state, true));
}
break;
default:
if(current["@alt"].IsEmpty) {
current.Replace(Scripted(code, state, true));
} else {
current.Replace(Scripted(code + " ?? " + AsArgument(current.AsXmlNode), state, false));
}
break;
}
} else {
string code = current["@index"].AsText ?? current["@name"].AsText;
if(!current["@alt"].IsEmpty) {
code += "|" + current["@alt"].AsText;
}
current.Replace(new XDoc("span").Attr("class", "plain").Value("{{{" + code + "}}}"));
}
}
break;
}
} else if(child.NodeType == XmlNodeType.Element) {
Convert(site, doc, isTemplate, child, state, ns);
// loop over attribute nodes
foreach(XDoc attribute in current.AtPath("@m:*", ns)) {
XDoc code = XDocFactory.From("<code xmlns:mediawiki=\"#mediawiki\">" + attribute.Contents + "</code>", MimeType.XML);
Convert(site, code, isTemplate, code.AsXmlNode, ContextState.Argument, ns);
attribute.Parent.Attr(attribute.Name, "{{" + AsArgument(code.AsXmlNode) + "}}");
attribute.Remove();
}
} else {
Convert(site, doc, isTemplate, child, state, ns);
if((state == ContextState.Argument) && ((child.NodeType == XmlNodeType.Text) || (child.NodeType == XmlNodeType.Whitespace) || (child.NodeType == XmlNodeType.SignificantWhitespace))) {
if(!string.IsNullOrEmpty(child.Value)) {
double value;
if(double.TryParse(child.Value, out value)) {
current.Replace(child.Value);
} else {
current.Replace(QuoteString(child.Value));
}
} else {
current.Remove();
}
}
}
}
}
private static string QuoteString(string text) {
return "'" + DekiScriptString.EscapeString(text) + "'";
}
private static DekiScriptExpression SafeParse(string code) {
DekiScriptExpression expr = null;
try {
expr = DekiScriptParser.Parse(Location.Start, code);
} catch { }
return expr;
}
private static string WebHtml(XmlNode node) {
string arg = AsArgument(node);
DekiScriptExpression expr = SafeParse(arg);
if((expr is DekiScriptNumber)) {
return arg;
} else if((expr is DekiScriptString) && !((DekiScriptString)expr).Value.Contains("<")) {
return arg;
} else {
return "web.html(" + arg + ")";
}
}
private static string AsArgument(XmlNode node) {
if(node == null) {
return "''";
}
StringBuilder arg = new StringBuilder();
AsStringArgument(node, arg);
return arg.ToString().Replace("' .. '", "");
}
private static void AsStringArgument(XmlNode node, StringBuilder arg) {
if(node.ChildNodes.Count > 0) {
foreach(XmlNode child in node.ChildNodes) {
switch(child.NodeType) {
case XmlNodeType.Element:
if(arg.Length > 0) {
arg.Append(" .. ");
}
arg.Append("'<");
arg.Append(DekiScriptString.EscapeString(child.LocalName));
foreach(XmlAttribute attribute in ((XmlElement)child).Attributes) {
arg.Append(" ");
// check if attribute contains dekiscript code
if(StringUtil.StartsWithInvariant(attribute.Value, "{{") && StringUtil.EndsWithInvariant(attribute.Value, "}}")) {
arg.Append(attribute.LocalName);
arg.Append("=\"' .. ");
arg.Append(Scripted(attribute.Value.Substring(2, attribute.Value.Length - 4), ContextState.Argument, false));
arg.Append(" .. '\"");
} else {
arg.Append(DekiScriptString.EscapeString(attribute.OuterXml));
}
}
if(child.ChildNodes.Count > 0) {
arg.Append(">'");
AsStringArgument(child, arg);
arg.Append(" .. ");
arg.Append("'</");
arg.Append(DekiScriptString.EscapeString(child.LocalName));
arg.Append(">'");
} else {
arg.Append("/>'");
}
break;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if(!string.IsNullOrEmpty(child.Value)) {
if(arg.Length > 0) {
arg.Append(" .. ");
}
arg.Append(child.Value);
}
break;
}
}
} else {
arg.Append("''");
}
}
private static string AsExpression(XmlNode node) {
if(node == null) {
return "_";
}
StringBuilder arg = new StringBuilder();
AsExpression(node, arg);
return arg.ToString();
}
private static void AsExpression(XmlNode node, StringBuilder arg) {
if(node.ChildNodes.Count > 0) {
foreach(XmlNode child in node.ChildNodes) {
switch(child.NodeType) {
case XmlNodeType.Element:
arg.Append("'<");
arg.Append(DekiScriptString.EscapeString(child.LocalName));
foreach(XmlAttribute attribute in ((XmlElement)child).Attributes) {
arg.Append(" ");
// check if attribute contains dekiscript code
if(StringUtil.StartsWithInvariant(attribute.Value, "{{") && StringUtil.EndsWithInvariant(attribute.Value, "}}")) {
arg.Append(attribute.LocalName);
arg.Append("=\"' .. ");
arg.Append(Scripted(attribute.Value.Substring(2, attribute.Value.Length - 4), ContextState.Argument, false));
arg.Append(" .. '\"");
} else {
arg.Append(DekiScriptString.EscapeString(attribute.OuterXml));
}
}
if(child.ChildNodes.Count > 0) {
arg.Append(">'");
AsExpression(child, arg);
arg.Append(" .. ");
arg.Append("'</");
arg.Append(DekiScriptString.EscapeString(child.LocalName));
arg.Append(">'");
} else {
arg.Append("/>'");
}
break;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if(!string.IsNullOrEmpty(child.Value)) {
arg.Append(child.Value);
}
break;
}
}
} else {
arg.Append("''");
}
}
private static string Scripted(string code, ContextState state, bool isAtomic) {
if(state == ContextState.None) {
code = "{{" + code + "}}";
} else if(!isAtomic) {
DekiScriptExpression expr = SafeParse(code);
if((expr == null) || (expr is DekiScriptBinary) || (expr is DekiScriptTernary)) {
code = "(" + code + ")";
}
}
return code;
}
private static string At(string container, string key) {
if(ID_REGEX.IsMatch(key)) {
return string.Format("{0}.{1}", container, key);
} else {
int i;
if(int.TryParse(key, out i)) {
return string.Format("{0}[{1}]", container, key);
} else {
return string.Format("{0}[{1}]", container, QuoteString(key));
}
}
}
private static void DetectWikiTextLinks(XmlNode node) {
Stack<XmlNode> stack = new Stack<XmlNode>();
ParserState state = ParserState.Text;
XmlNode start = null;
XmlNode current = node;
bool first = false;
while(current != null) {
if(current is XmlText) {
// parse characters
string text = current.Value;
int startIndex = (first ? ((state == ParserState.Internal) ? 2 : 1) : 0);
first = false;
for(int i = startIndex; i < text.Length; ++i) {
first = false;
switch(text[i]) {
case '[':
switch(state) {
case ParserState.Internal:
// restart internal link
case ParserState.External:
// restart external link
case ParserState.Text:
if((StringAt(text, i + 1) == '[') && (StringAt(text, i + 2) != '[')) {
state = ParserState.Internal;
// split the current text node
current = ((XmlText)current).SplitText(i + 2);
first = true;
start = current;
goto continue_while_loop;
} else if(StringAt(text, i + 1) != '[') {
state = ParserState.External;
// split the current text node
current = ((XmlText)current).SplitText(i + 1);
first = true;
start = current;
goto continue_while_loop;
} else {
// reset state
state = ParserState.Text;
start = null;
}
break;
}
break;
case ']':
switch(state) {
case ParserState.Text:
// nothing to do
break;
case ParserState.Internal:
// check if link is structurally sound
if(object.ReferenceEquals(current.ParentNode, start.ParentNode)) {
XmlNode next;
bool external;
if(StringAt(text, i + 1) == ']') {
// make an internal link
next = ((XmlText)current).SplitText(i);
external = false;
} else {
// make an external link
next = ((XmlText)current).SplitText(i);
external = true;
}
WrapNodes(external, start, next);
// reset state
state = ParserState.Text;
start = null;
current = next;
goto continue_while_loop;
}
// reset state
state = ParserState.Text;
start = null;
break;
case ParserState.External:
// check if the external link is structurally sound
if(object.ReferenceEquals(current.ParentNode, start.ParentNode)) {
// make an external link
XmlNode next = ((XmlText)current).SplitText(i);
WrapNodes(true, start, next);
// reset state
state = ParserState.Text;
start = null;
current = next;
goto continue_while_loop;
}
// reset state
state = ParserState.Text;
start = null;
break;
}
break;
}
}
} else {
// check if we are on an element that doesn't require conversion
if(!IsExcluded(current) && current.HasChildNodes) {
stack.Push(current);
current = current.FirstChild;
continue;
}
}
// move to next node
current = current.NextSibling;
while((current == null) && (stack.Count > 0)) {
current = stack.Pop().NextSibling;
}
continue_while_loop:
continue;
}
}
private static void WrapNodes(bool external, XmlNode start, XmlNode end) {
// remove '[[' or '[' depending if it's an internal or external linnk
if(external) {
start.PreviousSibling.Value = start.PreviousSibling.Value.Substring(0, start.PreviousSibling.Value.Length - 1);
end.Value = end.Value.Substring(1);
} else {
start.PreviousSibling.Value = start.PreviousSibling.Value.Substring(0, start.PreviousSibling.Value.Length - 2);
end.Value = end.Value.Substring(2);
}
// create wrapper node
XmlNode wrapper = start.OwnerDocument.CreateElement("mediawiki", external ? "external" : "internal", "#mediawiki");
start.ParentNode.InsertBefore(wrapper, start);
// move nodes
for(XmlNode current = start; current != end; ) {
XmlNode tmp = current;
current = current.NextSibling;
wrapper.AppendChild(tmp);
}
}
private static bool IsExcluded(XmlNode node) {
return (node.NodeType != XmlNodeType.Element) || ExcludedTags.Contains(node);
}
private static char StringAt(string text, int index) {
if(index >= text.Length) {
return char.MinValue;
}
return text[index];
}
private static string AsPathArgument(Site site, XDoc arg, bool useTemplateNamespace, out bool simple) {
simple = false;
string name = AsArgument(arg.AsXmlNode);
if((name.Length >= 3) && (SafeParse(name.Substring(1, name.Length - 2)) is DekiScriptVar)) {
simple = true;
return name;
}
if(SafeParse(name) is DekiScriptString) {
if(useTemplateNamespace && name.Substring(1).StartsWith("Template:")) {
name = "'" + name.Substring(10, name.Length - 11) + "'";
if(SafeParse(name.Substring(1, name.Length - 2)) is DekiScriptVar) {
simple = true;
return name;
}
}
return name;
}
if(useTemplateNamespace) {
if(string.IsNullOrEmpty(site.Language)) {
return "mediawiki.path(" + name + ")";
} else {
return "mediawiki.path(" + name + ", " + DekiScriptString.QuoteString(site.Language) + ")";
}
} else {
return "mediawiki.localurl(" + (string.IsNullOrEmpty(site.Language) ? "_" : DekiScriptString.QuoteString(site.Language)) + ", " + name + ")";
}
}
private static string AppendTemplateArguments(XDoc args, out bool simple) {
StringBuilder code = new StringBuilder();
if(args.IsEmpty) {
simple = true;
} else {
List<XDoc> list = args.ToList();
simple = true;
// check if arguments are neither strings nor numbers
foreach(XDoc arg in list) {
string value = AsArgument(arg.AsXmlNode);
DekiScriptExpression expr = SafeParse(value);
if(!(expr is DekiScriptString) && !(expr is DekiScriptNumber)) {
simple = false;
break;
}
}
// check if all entries are simple strings
if(simple) {
bool listOnly = true;
Hashtable map = new Hashtable();
for(int i = 0; i < list.Count; i++) {
DekiScriptExpression expr = SafeParse(AsArgument(list[i].AsXmlNode));
if(expr is DekiScriptString) {
string arg = ((DekiScriptString)expr).Value;
int equalIndex = arg.IndexOf("=");
if(equalIndex > 0) {
string id = arg.Substring(0, equalIndex).Trim();
if(ARG_REGEX.IsMatch(id)) {
listOnly = false;
string value = arg.Substring(equalIndex + 1, arg.Length - equalIndex - 1);
double number;
if(double.TryParse(value, out number)) {
map[id] = number;
} else {
map[id] = value;
}
} else {
map[i.ToString()] = arg;
}
} else {
map[i.ToString()] = arg;
}
} else if(expr is DekiScriptNumber) {
double arg = ((DekiScriptNumber)expr).Value;
map[i.ToString()] = arg;
} else {
throw new Exception("should never happen");
}
}
// check if all indices are simple numbers
if(listOnly) {
ArrayList items = new ArrayList();
for(int i = 0; i < map.Count; ++i) {
items.Add(map[i.ToString()]);
}
code.Append(new DekiScriptList(items).ToString());
} else {
code.Append(new DekiScriptMap(map).ToString());
}
} else {
code.Append("mediawiki.args([");
bool first = true;
foreach(XDoc arg in args) {
if(!first) {
code.Append(", ");
}
first = false;
code.Append(AsArgument(arg.AsXmlNode));
}
code.Append("])");
}
}
return code.ToString();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Monitor.Query.Models;
namespace Azure.Monitor.Query
{
/// <summary>
/// The <see cref="MetricsQueryClient"/> allows you to query the Azure Monitor Metrics service.
/// </summary>
public class MetricsQueryClient
{
private static readonly Uri _defaultEndpoint = new Uri("https://management.azure.com");
private readonly MetricDefinitionsRestClient _metricDefinitionsClient;
private readonly MetricsRestClient _metricsRestClient;
private readonly MetricNamespacesRestClient _namespacesRestClient;
private readonly ClientDiagnostics _clientDiagnostics;
/// <summary>
/// Initializes a new instance of <see cref="MetricsQueryClient"/>. Uses the default 'https://management.azure.com' endpoint.
/// <code snippet="Snippet:CreateMetricsClient" language="csharp">
/// var metricsClient = new MetricsQueryClient(new DefaultAzureCredential());
/// </code>
/// </summary>
/// <param name="credential">The <see cref="TokenCredential"/> instance to use for authentication.</param>
public MetricsQueryClient(TokenCredential credential) : this(credential, null)
{
}
/// <summary>
/// Initializes a new instance of <see cref="MetricsQueryClient"/>. Uses the default 'https://management.azure.com' endpoint.
/// </summary>
/// <param name="credential">The <see cref="TokenCredential"/> instance to use for authentication.</param>
/// <param name="options">The <see cref="MetricsQueryClientOptions"/> instance to as client configuration.</param>
public MetricsQueryClient(TokenCredential credential, MetricsQueryClientOptions options) : this(_defaultEndpoint, credential, options)
{
}
/// <summary>
/// Initializes a new instance of <see cref="MetricsQueryClient"/>.
/// </summary>
/// <param name="endpoint">The resource manager service endpoint to use. For example <c>https://management.azure.com/</c> for public cloud.</param>
/// <param name="credential">The <see cref="TokenCredential"/> instance to use for authentication.</param>
/// <param name="options">The <see cref="MetricsQueryClientOptions"/> instance to as client configuration.</param>
public MetricsQueryClient(Uri endpoint, TokenCredential credential, MetricsQueryClientOptions options = null)
{
Argument.AssertNotNull(credential, nameof(credential));
options ??= new MetricsQueryClientOptions();
_clientDiagnostics = new ClientDiagnostics(options);
var scope = $"{endpoint.AbsoluteUri}/.default";
Endpoint = endpoint;
var pipeline = HttpPipelineBuilder.Build(options,
new BearerTokenAuthenticationPolicy(credential, scope));
_metricDefinitionsClient = new MetricDefinitionsRestClient(_clientDiagnostics, pipeline, endpoint);
_metricsRestClient = new MetricsRestClient(_clientDiagnostics, pipeline, endpoint);
_namespacesRestClient = new MetricNamespacesRestClient(_clientDiagnostics, pipeline, endpoint);
}
/// <summary>
/// Initializes a new instance of <see cref="MetricsQueryClient"/> for mocking.
/// </summary>
protected MetricsQueryClient()
{
}
/// <summary>
/// Gets the endpoint used by the client.
/// </summary>
public Uri Endpoint { get; }
/// <summary>
/// Queries metrics for a resource.
/// <code snippet="Snippet:QueryMetrics" language="csharp">
/// string resourceId =
/// "/subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/<resource_provider>/<resource>";
///
/// var metricsClient = new MetricsQueryClient(new DefaultAzureCredential());
///
/// Response<MetricsQueryResult> results = await metricsClient.QueryResourceAsync(
/// resourceId,
/// new[] {"Microsoft.OperationalInsights/workspaces"}
/// );
///
/// foreach (var metric in results.Value.Metrics)
/// {
/// Console.WriteLine(metric.Name);
/// foreach (var element in metric.TimeSeries)
/// {
/// Console.WriteLine("Dimensions: " + string.Join(",", element.Metadata));
///
/// foreach (var metricValue in element.Values)
/// {
/// Console.WriteLine(metricValue);
/// }
/// }
/// }
/// </code>
/// </summary>
/// <param name="resourceId">The resource name.
/// For example:
/// <c>/subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/<resource_provider>/<resource></c>,<br/>
/// <c>/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/resource-group/providers/Microsoft.Storage/storageAccounts/mystorage</c>,<br/>
/// <c>/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/myvm</c><br/>
/// </param>
/// <param name="metrics">The list of metrics to query.</param>
/// <param name="options">The additional request options.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
/// <returns>The <see cref="MetricsQueryResult"/> instance containing the query results.</returns>
public virtual Response<MetricsQueryResult> QueryResource(string resourceId, IEnumerable<string> metrics, MetricsQueryOptions options = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(MetricsQueryClient)}.{nameof(QueryResource)}");
scope.Start();
try
{
return _metricsRestClient.List(resourceId,
timespan: options?.TimeRange?.ToIsoString(),
interval: options?.Granularity,
filter: options?.Filter,
top: options?.Size,
aggregation: GetAggregation(options),
metricnames: string.Join(",", metrics),
orderby: options?.OrderBy,
metricnamespace: options?.MetricNamespace,
cancellationToken: cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Queries metrics for a resource.
/// <code snippet="Snippet:QueryMetrics" language="csharp">
/// string resourceId =
/// "/subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/<resource_provider>/<resource>";
///
/// var metricsClient = new MetricsQueryClient(new DefaultAzureCredential());
///
/// Response<MetricsQueryResult> results = await metricsClient.QueryResourceAsync(
/// resourceId,
/// new[] {"Microsoft.OperationalInsights/workspaces"}
/// );
///
/// foreach (var metric in results.Value.Metrics)
/// {
/// Console.WriteLine(metric.Name);
/// foreach (var element in metric.TimeSeries)
/// {
/// Console.WriteLine("Dimensions: " + string.Join(",", element.Metadata));
///
/// foreach (var metricValue in element.Values)
/// {
/// Console.WriteLine(metricValue);
/// }
/// }
/// }
/// </code>
/// </summary>
/// <param name="resourceId">The resource name.
/// For example:
/// <c>/subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/<resource_provider>/<resource></c>,<br/>
/// <c>/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/resource-group/providers/Microsoft.Storage/storageAccounts/mystorage</c>,<br/>
/// <c>/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/myvm</c><br/>
/// </param>
/// <param name="metrics">The list of metrics to query.</param>
/// <param name="options">The additional request options.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
/// <returns>The <see cref="MetricsQueryResult"/> instance with query results.</returns>
public virtual async Task<Response<MetricsQueryResult>> QueryResourceAsync(string resourceId, IEnumerable<string> metrics, MetricsQueryOptions options = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(MetricsQueryClient)}.{nameof(QueryResource)}");
scope.Start();
try
{
return await _metricsRestClient.ListAsync(resourceId,
timespan: options?.TimeRange?.ToIsoString(),
interval: options?.Granularity,
filter: options?.Filter,
top: options?.Size,
aggregation: GetAggregation(options),
metricnames: string.Join(",", metrics),
orderby: options?.OrderBy,
metricnamespace: options?.MetricNamespace,
cancellationToken: cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets metric definitions for a particular resource and metric namespace.
/// </summary>
/// <param name="resourceId">The resource name.
/// For example:
/// <c>/subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/<resource_provider>/<resource></c>,<br/>
/// <c>/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/resource-group/providers/Microsoft.Storage/storageAccounts/mystorage</c>,<br/>
/// <c>/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/myvm</c><br/>
/// </param>
/// <param name="metricsNamespace">The metric namespace.
/// For example: <c>Microsoft.OperationalInsights/workspaces</c>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
/// <returns>A pageable collection of metric definitions.</returns>
public virtual Pageable<MetricDefinition> GetMetricDefinitions(string resourceId, string metricsNamespace, CancellationToken cancellationToken = default)
{
return PageResponseEnumerator.CreateEnumerable(_ =>
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(MetricsQueryClient)}.{nameof(GetMetricDefinitions)}");
scope.Start();
try
{
var response = _metricDefinitionsClient.List(resourceId, metricsNamespace, cancellationToken);
return Page<MetricDefinition>.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
});
}
/// <summary>
/// Gets metric definitions for a particular resource and metric namespace.
/// </summary>
/// <param name="resourceId">The resource name.
///
/// For example:
/// <c>/subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/<resource_provider>/<resource></c>,<br/>
/// <c>/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/resource-group/providers/Microsoft.Storage/storageAccounts/mystorage</c>,<br/>
/// <c>/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/myvm</c><br/>
/// </param>
/// <param name="metricsNamespace">The metric namespace.
/// For example: <c>Microsoft.OperationalInsights/workspaces</c>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
/// <returns>A pageable collection of metric definitions.</returns>
public virtual AsyncPageable<MetricDefinition> GetMetricDefinitionsAsync(string resourceId, string metricsNamespace, CancellationToken cancellationToken = default)
{
return PageResponseEnumerator.CreateAsyncEnumerable(async _ =>
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(MetricsQueryClient)}.{nameof(GetMetricDefinitions)}");
scope.Start();
try
{
var response = await _metricDefinitionsClient.ListAsync(resourceId, metricsNamespace, cancellationToken).ConfigureAwait(false);
return Page<MetricDefinition>.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
});
}
/// <summary>
/// Gets metric namespaces for a particular resource.
/// </summary>
/// <param name="resourceId">The resource name.
/// For example:
/// <c>/subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/<resource_provider>/<resource></c>,<br/>
/// <c>/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/resource-group/providers/Microsoft.Storage/storageAccounts/mystorage</c>,<br/>
/// <c>/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/myvm</c><br/>
/// </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
/// <returns>A pageable collection of metric namespaces.</returns>
public virtual Pageable<MetricNamespace> GetMetricNamespaces(string resourceId, CancellationToken cancellationToken = default)
{
return PageResponseEnumerator.CreateEnumerable(_ =>
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(MetricsQueryClient)}.{nameof(GetMetricNamespaces)}");
scope.Start();
try
{
var response = _namespacesRestClient.List(resourceId, cancellationToken: cancellationToken);
return Page<MetricNamespace>.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
});
}
/// <summary>
/// Gets metric namespaces for a particular resource.
/// </summary>
/// <param name="resourceId">The resource name.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
/// <returns>A pageable collection of metric namespaces.</returns>
public virtual AsyncPageable<MetricNamespace> GetMetricNamespacesAsync(string resourceId, CancellationToken cancellationToken = default)
{
return PageResponseEnumerator.CreateAsyncEnumerable(async _ =>
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(MetricsQueryClient)}.{nameof(GetMetricNamespaces)}");
scope.Start();
try
{
var response = await _namespacesRestClient.ListAsync(resourceId, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page<MetricNamespace>.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
});
}
private static string GetAggregation(MetricsQueryOptions options)
{
if (options?.Aggregations == null ||
options.Aggregations.Count == 0)
{
return null;
}
return string.Join(",", options.Aggregations);
}
}
}
| |
/*
* Copyright 2010-2014 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.
*/
/*
* Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.RDS.Model
{
/// <summary>
/// Container for the parameters to the DescribeReservedDBInstancesOfferings operation.
/// Lists available reserved DB instance offerings.
/// </summary>
public partial class DescribeReservedDBInstancesOfferingsRequest : AmazonRDSRequest
{
private string _dbInstanceClass;
private string _duration;
private List<Filter> _filters = new List<Filter>();
private string _marker;
private int? _maxRecords;
private bool? _multiAZ;
private string _offeringType;
private string _productDescription;
private string _reservedDBInstancesOfferingId;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public DescribeReservedDBInstancesOfferingsRequest() { }
/// <summary>
/// Gets and sets the property DBInstanceClass.
/// <para>
/// The DB instance class filter value. Specify this parameter to show only the available
/// offerings matching the specified DB instance class.
/// </para>
/// </summary>
public string DBInstanceClass
{
get { return this._dbInstanceClass; }
set { this._dbInstanceClass = value; }
}
// Check to see if DBInstanceClass property is set
internal bool IsSetDBInstanceClass()
{
return this._dbInstanceClass != null;
}
/// <summary>
/// Gets and sets the property Duration.
/// <para>
/// Duration filter value, specified in years or seconds. Specify this parameter to show
/// only reservations for this duration.
/// </para>
///
/// <para>
/// Valid Values: <code>1 | 3 | 31536000 | 94608000</code>
/// </para>
/// </summary>
public string Duration
{
get { return this._duration; }
set { this._duration = value; }
}
// Check to see if Duration property is set
internal bool IsSetDuration()
{
return this._duration != null;
}
/// <summary>
/// Gets and sets the property Filters.
/// <para>
/// This parameter is not currently supported.
/// </para>
/// </summary>
public List<Filter> Filters
{
get { return this._filters; }
set { this._filters = value; }
}
// Check to see if Filters property is set
internal bool IsSetFilters()
{
return this._filters != null && this._filters.Count > 0;
}
/// <summary>
/// Gets and sets the property Marker.
/// <para>
/// An optional pagination token provided by a previous request. If this parameter is
/// specified, the response includes only records beyond the marker, up to the value specified
/// by <code>MaxRecords</code>.
/// </para>
/// </summary>
public string Marker
{
get { return this._marker; }
set { this._marker = value; }
}
// Check to see if Marker property is set
internal bool IsSetMarker()
{
return this._marker != null;
}
/// <summary>
/// Gets and sets the property MaxRecords.
/// <para>
/// The maximum number of records to include in the response. If more than the <code>MaxRecords</code>
/// value is available, a pagination token called a marker is included in the response
/// so that the following results can be retrieved.
/// </para>
///
/// <para>
/// Default: 100
/// </para>
///
/// <para>
/// Constraints: Minimum 20, maximum 100.
/// </para>
/// </summary>
public int MaxRecords
{
get { return this._maxRecords.GetValueOrDefault(); }
set { this._maxRecords = value; }
}
// Check to see if MaxRecords property is set
internal bool IsSetMaxRecords()
{
return this._maxRecords.HasValue;
}
/// <summary>
/// Gets and sets the property MultiAZ.
/// <para>
/// The Multi-AZ filter value. Specify this parameter to show only the available offerings
/// matching the specified Multi-AZ parameter.
/// </para>
/// </summary>
public bool MultiAZ
{
get { return this._multiAZ.GetValueOrDefault(); }
set { this._multiAZ = value; }
}
// Check to see if MultiAZ property is set
internal bool IsSetMultiAZ()
{
return this._multiAZ.HasValue;
}
/// <summary>
/// Gets and sets the property OfferingType.
/// <para>
/// The offering type filter value. Specify this parameter to show only the available
/// offerings matching the specified offering type.
/// </para>
///
/// <para>
/// Valid Values: <code>"Partial Upfront" | "All Upfront" | "No Upfront" </code>
/// </para>
/// </summary>
public string OfferingType
{
get { return this._offeringType; }
set { this._offeringType = value; }
}
// Check to see if OfferingType property is set
internal bool IsSetOfferingType()
{
return this._offeringType != null;
}
/// <summary>
/// Gets and sets the property ProductDescription.
/// <para>
/// Product description filter value. Specify this parameter to show only the available
/// offerings matching the specified product description.
/// </para>
/// </summary>
public string ProductDescription
{
get { return this._productDescription; }
set { this._productDescription = value; }
}
// Check to see if ProductDescription property is set
internal bool IsSetProductDescription()
{
return this._productDescription != null;
}
/// <summary>
/// Gets and sets the property ReservedDBInstancesOfferingId.
/// <para>
/// The offering identifier filter value. Specify this parameter to show only the available
/// offering that matches the specified reservation identifier.
/// </para>
///
/// <para>
/// Example: <code>438012d3-4052-4cc7-b2e3-8d3372e0e706</code>
/// </para>
/// </summary>
public string ReservedDBInstancesOfferingId
{
get { return this._reservedDBInstancesOfferingId; }
set { this._reservedDBInstancesOfferingId = value; }
}
// Check to see if ReservedDBInstancesOfferingId property is set
internal bool IsSetReservedDBInstancesOfferingId()
{
return this._reservedDBInstancesOfferingId != null;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace QTrkDotNet
{
[StructLayout(LayoutKind.Sequential)]
public struct Int2
{
public Int2(int x, int y)
{
this.x = x; this.y = y;
}
public int x, y;
public void Clamp(int w, int h)
{
if (x < 0) x = 0; if (x > w - 1) x = w - 1;
if (y < 0) y = 0; if (y > h - 1) y = h - 1;
}
public static Int2 operator +(Int2 a, Int2 b)
{
Int2 r;
r.x = a.x + b.x;
r.y = a.y + b.y;
return r;
}
public static Int2 operator -(Int2 a, Int2 b)
{
Int2 r;
r.x = a.x - b.x;
r.y = a.y - b.y;
return r;
}
public static Int2 operator -(Int2 a, int b)
{
Int2 r;
r.x = a.x - b;
r.y = a.y - b;
return r;
}
public static Int2 operator -(int a, Int2 b)
{
Int2 r;
r.x = a - b.x;
r.y = a - b.y;
return r;
}
public static Int2 operator +(Int2 a, int b)
{
Int2 r;
r.x = a.x + b;
r.y = a.y + b;
return r;
}
public static Int2 operator +(int a, Int2 b)
{
Int2 r;
r.x = a + b.x;
r.y = a + b.y;
return r;
}
public static Int2 operator -(Int2 a)
{
return new Int2(-a.x, -a.y);
}
public float Length
{
get { return (float)Math.Sqrt(x * x + y * y); }
}
}
public struct Int3 : IEquatable<Int3>
{
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public Int3(Int2 p)
{
this.x = p.x; this.y = p.y; this.z = 0;
}
public Int3(int x, int y, int z = 0)
{
this.x = x; this.y = y;
this.z = z;
}
public int x, y, z;
public void Clamp(int w, int h, int d)
{
if (x < 0) x = 0; if (x > w - 1) x = w - 1;
if (y < 0) y = 0; if (y > h - 1) y = h - 1;
if (z < 0) z = 0; if (z > d - 1) z = d - 1;
}
public static bool operator ==(Int3 a, Int3 b)
{
return a.x == b.x && a.y == b.y && a.z == b.z;
}
public static bool operator !=(Int3 a, Int3 b)
{
return a.x != b.x || a.y != b.y || a.z != b.z;
}
public static Int3 operator +(Int3 a, Int3 b)
{
Int3 r;
r.x = a.x + b.x;
r.y = a.y + b.y;
r.z = a.z + b.z;
return r;
}
public static Int3 operator -(Int3 a, Int3 b)
{
Int3 r;
r.x = a.x - b.x;
r.y = a.y - b.y;
r.z = a.z - b.z;
return r;
}
public static Int3 operator -(Int3 a, int b)
{
Int3 r;
r.x = a.x - b;
r.y = a.y - b;
r.z = a.z - b;
return r;
}
public static Int3 operator -(int a, Int3 b)
{
Int3 r;
r.x = a - b.x;
r.y = a - b.y;
r.z = a - b.z;
return r;
}
public static Int3 operator +(Int3 a, int b)
{
Int3 r;
r.x = a.x + b;
r.y = a.y + b;
r.z = a.z + b;
return r;
}
public static Int3 operator +(int a, Int3 b)
{
Int3 r;
r.x = a + b.x;
r.y = a + b.y;
r.z = a + b.z;
return r;
}
public static Int3 operator -(Int3 a)
{
return new Int3(-a.x, -a.y, -a.z);
}
public float Length
{
get { return (float)Math.Sqrt(x * x + y * y + z * z); }
}
public override string ToString()
{
return string.Format("Int3({0},{1},{2})", x, y, z);
}
public Int2 XY
{
get { return new Int2(x, y); }
set { x = value.x; y = value.y; }
}
public bool Equals(Int3 other)
{
return other == this;
}
bool IEquatable<Int3>.Equals(Int3 other)
{
return other == this;
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Pathfinding;
// Empty namespace declaration to avoid errors in the free version
// Which does not have any classes in the RVO namespace
namespace Pathfinding.RVO {}
namespace Pathfinding {
using Pathfinding.Util;
using Pathfinding.Serialization;
#if UNITY_5_0
/** Used in Unity 5.0 since the HelpURLAttribute was first added in Unity 5.1 */
public class HelpURLAttribute : Attribute {}
#endif
[System.Serializable]
/** Stores editor colors */
public class AstarColor {
public Color _NodeConnection;
public Color _UnwalkableNode;
public Color _BoundsHandles;
public Color _ConnectionLowLerp;
public Color _ConnectionHighLerp;
public Color _MeshEdgeColor;
public Color _MeshColor;
/** Holds user set area colors.
* Use GetAreaColor to get an area color */
public Color[] _AreaColors;
public static Color NodeConnection = new Color(1, 1, 1, 0.9F);
public static Color UnwalkableNode = new Color(1, 0, 0, 0.5F);
public static Color BoundsHandles = new Color(0.29F, 0.454F, 0.741F, 0.9F);
public static Color ConnectionLowLerp = new Color(0, 1, 0, 0.5F);
public static Color ConnectionHighLerp = new Color(1, 0, 0, 0.5F);
public static Color MeshEdgeColor = new Color(0, 0, 0, 0.5F);
public static Color MeshColor = new Color(0, 0, 0, 0.5F);
/** Holds user set area colors.
* Use GetAreaColor to get an area color */
private static Color[] AreaColors;
/** Returns an color for an area, uses both user set ones and calculated.
* If the user has set a color for the area, it is used, but otherwise the color is calculated using Mathfx.IntToColor
* \see #AreaColors */
public static Color GetAreaColor (uint area) {
if (AreaColors == null || area >= AreaColors.Length) {
return AstarMath.IntToColor((int)area, 1F);
}
return AreaColors[(int)area];
}
/** Pushes all local variables out to static ones */
public void OnEnable () {
NodeConnection = _NodeConnection;
UnwalkableNode = _UnwalkableNode;
BoundsHandles = _BoundsHandles;
ConnectionLowLerp = _ConnectionLowLerp;
ConnectionHighLerp = _ConnectionHighLerp;
MeshEdgeColor = _MeshEdgeColor;
MeshColor = _MeshColor;
AreaColors = _AreaColors;
}
public AstarColor () {
_NodeConnection = new Color(1, 1, 1, 0.9F);
_UnwalkableNode = new Color(1, 0, 0, 0.5F);
_BoundsHandles = new Color(0.29F, 0.454F, 0.741F, 0.9F);
_ConnectionLowLerp = new Color(0, 1, 0, 0.5F);
_ConnectionHighLerp = new Color(1, 0, 0, 0.5F);
_MeshEdgeColor = new Color(0, 0, 0, 0.5F);
_MeshColor = new Color(0.125F, 0.686F, 0, 0.19F);
}
}
/** Returned by graph ray- or linecasts containing info about the hit. This will only be set up if something was hit. */
public struct GraphHitInfo {
/** Start of the line/ray */
public Vector3 origin;
/** Hit point */
public Vector3 point;
/** Node which contained the edge which was hit */
public GraphNode node;
/** Where the tangent starts. tangentOrigin and tangent together actually describes the edge which was hit */
public Vector3 tangentOrigin;
/** Tangent of the edge which was hit */
public Vector3 tangent;
public float distance {
get {
return (point-origin).magnitude;
}
}
public GraphHitInfo (Vector3 point) {
tangentOrigin = Vector3.zero;
origin = Vector3.zero;
this.point = point;
node = null;
tangent = Vector3.zero;
//this.distance = distance;
}
}
/** Nearest node constraint. Constrains which nodes will be returned by the GetNearest function */
public class NNConstraint {
/** Graphs treated as valid to search on.
* This is a bitmask meaning that bit 0 specifies whether or not the first graph in the graphs list should be able to be included in the search,
* bit 1 specifies whether or not the second graph should be included and so on.
* \code
* //Enables the first and third graphs to be included, but not the rest
* myNNConstraint.graphMask = (1 << 0) | (1 << 2);
* \endcode
* \note This does only affect which nodes are returned from a GetNearest call, if an invalid graph is linked to from a valid graph, it might be searched anyway.
*
* \see AstarPath.GetNearest */
public int graphMask = -1;
/** Only treat nodes in the area #area as suitable. Does not affect anything if #area is less than 0 (zero) */
public bool constrainArea;
/** Area ID to constrain to. Will not affect anything if less than 0 (zero) or if #constrainArea is false */
public int area = -1;
/** Only treat nodes with the walkable flag set to the same as #walkable as suitable */
public bool constrainWalkability = true;
/** What must the walkable flag on a node be for it to be suitable. Does not affect anything if #constrainWalkability if false */
public bool walkable = true;
/** if available, do an XZ check instead of checking on all axes. The RecastGraph supports this */
public bool distanceXZ;
/** Sets if tags should be constrained */
public bool constrainTags = true;
/** Nodes which have any of these tags set are suitable. This is a bitmask, i.e bit 0 indicates that tag 0 is good, bit 3 indicates tag 3 is good etc. */
public int tags = -1;
/** Constrain distance to node.
* Uses distance from AstarPath.maxNearestNodeDistance.
* If this is false, it will completely ignore the distance limit.
* \note This value is not used in this class, it is used by the AstarPath.GetNearest function.
*/
public bool constrainDistance = true;
/** Returns whether or not the graph conforms to this NNConstraint's rules.
* Note that only the first 31 graphs are considered using this function.
* If the graphMask has bit 31 set (i.e the last graph possible to fit in the mask), all graphs
* above index 31 will also be considered suitable.
*/
public virtual bool SuitableGraph (int graphIndex, NavGraph graph) {
return ((graphMask >> graphIndex) & 1) != 0;
}
/** Returns whether or not the node conforms to this NNConstraint's rules */
public virtual bool Suitable (GraphNode node) {
if (constrainWalkability && node.Walkable != walkable) return false;
if (constrainArea && area >= 0 && node.Area != area) return false;
if (constrainTags && ((tags >> (int)node.Tag) & 0x1) == 0) return false;
return true;
}
/** The default NNConstraint.
* Equivalent to new NNConstraint ().
* This NNConstraint has settings which works for most, it only finds walkable nodes
* and it constrains distance set by A* Inspector -> Settings -> Max Nearest Node Distance */
public static NNConstraint Default {
get {
return new NNConstraint();
}
}
/** Returns a constraint which will not filter the results */
public static NNConstraint None {
get {
var n = new NNConstraint();
n.constrainWalkability = false;
n.constrainArea = false;
n.constrainTags = false;
n.constrainDistance = false;
n.graphMask = -1;
return n;
}
}
/** Default constructor. Equals to the property #Default */
public NNConstraint () {
}
}
/** A special NNConstraint which can use different logic for the start node and end node in a path.
* A PathNNConstraint can be assigned to the Path.nnConstraint field, the path will first search for the start node, then it will call #SetStart and proceed with searching for the end node (nodes in the case of a MultiTargetPath).\n
* The default PathNNConstraint will constrain the end point to lie inside the same area as the start point.
*/
public class PathNNConstraint : NNConstraint {
public static new PathNNConstraint Default {
get {
var n = new PathNNConstraint();
n.constrainArea = true;
return n;
}
}
/** Called after the start node has been found. This is used to get different search logic for the start and end nodes in a path */
public virtual void SetStart (GraphNode node) {
if (node != null) {
area = (int)node.Area;
} else {
constrainArea = false;
}
}
}
public struct NNInfo {
/** Closest node found.
* This node is not necessarily accepted by any NNConstraint passed.
* \see constrainedNode
*/
public GraphNode node;
/** Optional to be filled in.
* If the search will be able to find the constrained node without any extra effort it can fill it in. */
public GraphNode constrainedNode;
/** The position clamped to the closest point on the #node.
*/
public Vector3 clampedPosition;
/** Clamped position for the optional constrainedNode */
public Vector3 constClampedPosition;
public NNInfo (GraphNode node) {
this.node = node;
constrainedNode = null;
clampedPosition = Vector3.zero;
constClampedPosition = Vector3.zero;
UpdateInfo();
}
/** Sets the constrained node */
public void SetConstrained (GraphNode constrainedNode, Vector3 clampedPosition) {
this.constrainedNode = constrainedNode;
constClampedPosition = clampedPosition;
}
/** Updates #clampedPosition and #constClampedPosition from node positions */
public void UpdateInfo () {
clampedPosition = node != null ? (Vector3)node.position : Vector3.zero;
constClampedPosition = constrainedNode != null ? (Vector3)constrainedNode.position : Vector3.zero;
}
public static explicit operator Vector3 (NNInfo ob) {
return ob.clampedPosition;
}
public static explicit operator GraphNode (NNInfo ob) {
return ob.node;
}
public static explicit operator NNInfo (GraphNode ob) {
return new NNInfo(ob);
}
}
/** Progress info for e.g a progressbar.
* Used by the scan functions in the project
* \see AstarPath.ScanLoop
*/
public struct Progress {
public float progress;
public string description;
public Progress (float p, string d) {
progress = p;
description = d;
}
}
/** Graphs which can be updated during runtime */
public interface IUpdatableGraph {
/** Updates an area using the specified GraphUpdateObject.
*
* Notes to implementators.
* This function should (in order):
* -# Call o.WillUpdateNode on the GUO for every node it will update, it is important that this is called BEFORE any changes are made to the nodes.
* -# Update walkabilty using special settings such as the usePhysics flag used with the GridGraph.
* -# Call Apply on the GUO for every node which should be updated with the GUO.
* -# Update eventual connectivity info if appropriate (GridGraphs updates connectivity, but most other graphs don't since then the connectivity cannot be recovered later).
*/
void UpdateArea (GraphUpdateObject o);
void UpdateAreaInit (GraphUpdateObject o);
GraphUpdateThreading CanUpdateAsync (GraphUpdateObject o);
}
[System.Serializable]
/** Holds a tagmask.
* This is used to store which tags to change and what to set them to in a Pathfinding.GraphUpdateObject.
* All variables are bitmasks.\n
* I wanted to make it a struct, but due to technical limitations when working with Unity's GenericMenu, I couldn't.
* So be wary of this when passing it as it will be passed by reference, not by value as e.g LayerMask.
*
* \deprecated This class is being phased out
*/
public class TagMask {
public int tagsChange;
public int tagsSet;
public TagMask () {}
public TagMask (int change, int set) {
tagsChange = change;
tagsSet = set;
}
public override string ToString () {
return ""+System.Convert.ToString(tagsChange, 2)+"\n"+System.Convert.ToString(tagsSet, 2);
}
}
/** Represents a collection of settings used to update nodes in a specific region of a graph.
* \see AstarPath.UpdateGraphs
* \see \ref graph-updates
*/
public class GraphUpdateObject {
/** The bounds to update nodes within.
* Defined in world space.
*/
public Bounds bounds;
/** Controlls if a flood fill will be carried out after this GUO has been applied.
* Disabling this can be used to gain a performance boost, but use with care.
* If you are sure that a GUO will not modify walkability or connections. You can set this to false.
* For example when only updating penalty values it can save processing power when setting this to false. Especially on large graphs.
* \note If you set this to false, even though it does change e.g walkability, it can lead to paths returning that they failed even though there is a path,
* or the try to search the whole graph for a path even though there is none, and will in the processes use wast amounts of processing power.
*
* If using the basic GraphUpdateObject (not a derived class), a quick way to check if it is going to need a flood fill is to check if #modifyWalkability is true or #updatePhysics is true.
*
*/
public bool requiresFloodFill = true;
/** Use physics checks to update nodes.
* When updating a grid graph and this is true, the nodes' position and walkability will be updated using physics checks
* with settings from "Collision Testing" and "Height Testing".
*
* When updating a PointGraph, setting this to true will make it re-evaluate all connections in the graph which passes through the #bounds.
* This has no effect when updating GridGraphs if #modifyWalkability is turned on.
*
* On RecastGraphs, having this enabled will trigger a complete recalculation of all tiles intersecting the bounds.
* This is quite slow (but powerful). If you only want to update e.g penalty on existing nodes, leave it disabled.
*/
public bool updatePhysics = true;
/** When #updatePhysics is true, GridGraphs will normally reset penalties, with this option you can override it.
* Good to use when you want to keep old penalties even when you update the graph.
*
* The images below shows two overlapping graph update objects, the right one happened to be applied before the left one. They both have updatePhysics = true and are
* set to increase the penalty of the nodes by some amount.
*
* The first image shows the result when resetPenaltyOnPhysics is false. Both penalties are added correctly.
* \shadowimage{resetPenaltyOnPhysics_False.png}
*
* This second image shows when resetPenaltyOnPhysics is set to true. The first GUO is applied correctly, but then the second one (the left one) is applied
* and during its updating, it resets the penalties first and then adds penalty to the nodes. The result is that the penalties from both GUOs are not added together.
* The green patch in at the border is there because physics recalculation (recalculation of the position of the node, checking for obstacles etc.) affects a slightly larger
* area than the original GUO bounds because of the Grid Graph -> Collision Testing -> Diameter setting (it is enlarged by that value). So some extra nodes have their penalties reset.
*
* \shadowimage{resetPenaltyOnPhysics_True.png}
*/
public bool resetPenaltyOnPhysics = true;
/** Update Erosion for GridGraphs.
* When enabled, erosion will be recalculated for grid graphs
* after the GUO has been applied.
*
* In the below image you can see the different effects you can get with the different values.\n
* The first image shows the graph when no GUO has been applied. The blue box is not identified as an obstacle by the graph, the reason
* there are unwalkable nodes around it is because there is a height difference (nodes are placed on top of the box) so erosion will be applied (an erosion value of 2 is used in this graph).
* The orange box is identified as an obstacle, so the area of unwalkable nodes around it is a bit larger since both erosion and collision has made
* nodes unwalkable.\n
* The GUO used simply sets walkability to true, i.e making all nodes walkable.
*
* \shadowimage{updateErosion.png}
*
* When updateErosion=True, the reason the blue box still has unwalkable nodes around it is because there is still a height difference
* so erosion will still be applied. The orange box on the other hand has no height difference and all nodes are set to walkable.\n
* \n
* When updateErosion=False, all nodes walkability are simply set to be walkable in this example.
*
* \see Pathfinding.GridGraph
*/
public bool updateErosion = true;
/** NNConstraint to use.
* The Pathfinding.NNConstraint.SuitableGraph function will be called on the NNConstraint to enable filtering of which graphs to update.\n
* \note As the Pathfinding.NNConstraint.SuitableGraph function is A* Pathfinding Project Pro only, this variable doesn't really affect anything in the free version.
*
*
* \astarpro */
public NNConstraint nnConstraint = NNConstraint.None;
/** Penalty to add to the nodes.
* A penalty of 1000 is equivalent to the cost of moving 1 world unit.
*/
public int addPenalty;
/** If true, all nodes' \a walkable variable will be set to #setWalkability */
public bool modifyWalkability;
/** If #modifyWalkability is true, the nodes' \a walkable variable will be set to this value */
public bool setWalkability;
/** If true, all nodes' \a tag will be set to #setTag */
public bool modifyTag;
/** If #modifyTag is true, all nodes' \a tag will be set to this value */
public int setTag;
/** Track which nodes are changed and save backup data.
* Used internally to revert changes if needed.
*/
public bool trackChangedNodes;
/** Nodes which were updated by this GraphUpdateObject.
* Will only be filled if #trackChangedNodes is true.
* \note It might take a few frames for graph update objects to be applied.
* If you need this info directly, use AstarPath.FlushGraphUpdates.
*/
public List<GraphNode> changedNodes;
private List<uint> backupData;
private List<Int3> backupPositionData;
/** A shape can be specified if a bounds object does not give enough precision.
* Note that if you set this, you should set the bounds so that it encloses the shape
* because the bounds will be used as an initial fast check for which nodes that should
* be updated.
*/
public GraphUpdateShape shape;
/** Should be called on every node which is updated with this GUO before it is updated.
* \param node The node to save fields for. If null, nothing will be done
* \see #trackChangedNodes
*/
public virtual void WillUpdateNode (GraphNode node) {
if (trackChangedNodes && node != null) {
if (changedNodes == null) { changedNodes = ListPool<GraphNode>.Claim(); backupData = ListPool<uint>.Claim(); backupPositionData = ListPool<Int3>.Claim(); }
changedNodes.Add(node);
backupPositionData.Add(node.position);
backupData.Add(node.Penalty);
backupData.Add(node.Flags);
var gg = node as GridNode;
if (gg != null) backupData.Add(gg.InternalGridFlags);
}
}
/** Reverts penalties and flags (which includes walkability) on every node which was updated using this GUO.
* Data for reversion is only saved if #trackChangedNodes is true */
public virtual void RevertFromBackup () {
if (trackChangedNodes) {
if (changedNodes == null) return;
int counter = 0;
for (int i = 0; i < changedNodes.Count; i++) {
changedNodes[i].Penalty = backupData[counter];
counter++;
changedNodes[i].Flags = backupData[counter];
counter++;
var gg = changedNodes[i] as GridNode;
if (gg != null) {
gg.InternalGridFlags = (ushort)backupData[counter];
counter++;
}
changedNodes[i].position = backupPositionData[i];
}
ListPool<GraphNode>.Release(changedNodes);
ListPool<uint>.Release(backupData);
ListPool<Int3>.Release(backupPositionData);
} else {
throw new System.InvalidOperationException("Changed nodes have not been tracked, cannot revert from backup");
}
}
/** Updates the specified node using this GUO's settings */
public virtual void Apply (GraphNode node) {
if (shape == null || shape.Contains(node)) {
//Update penalty and walkability
node.Penalty = (uint)(node.Penalty+addPenalty);
if (modifyWalkability) {
node.Walkable = setWalkability;
}
//Update tags
if (modifyTag) node.Tag = (uint)setTag;
}
}
public GraphUpdateObject () {
}
/** Creates a new GUO with the specified bounds */
public GraphUpdateObject (Bounds b) {
bounds = b;
}
}
public interface IRaycastableGraph {
bool Linecast (Vector3 start, Vector3 end);
bool Linecast (Vector3 start, Vector3 end, GraphNode hint);
bool Linecast (Vector3 start, Vector3 end, GraphNode hint, out GraphHitInfo hit);
bool Linecast (Vector3 start, Vector3 end, GraphNode hint, out GraphHitInfo hit, List<GraphNode> trace);
}
/** Holds info about one pathfinding thread.
* Mainly used to send information about how the thread should execute when starting it
*/
public struct PathThreadInfo {
public int threadIndex;
public AstarPath astar;
public PathHandler runData;
public readonly System.Object lockObject;
public PathThreadInfo (int index, AstarPath astar, PathHandler runData) {
this.threadIndex = index;
this.astar = astar;
this.runData = runData;
lockObject = new object();
}
}
/** Integer Rectangle.
* Works almost like UnityEngine.Rect but with integer coordinates
*/
public struct IntRect {
public int xmin, ymin, xmax, ymax;
public IntRect (int xmin, int ymin, int xmax, int ymax) {
this.xmin = xmin;
this.xmax = xmax;
this.ymin = ymin;
this.ymax = ymax;
}
public bool Contains (int x, int y) {
return !(x < xmin || y < ymin || x > xmax || y > ymax);
}
public int Width {
get {
return xmax-xmin+1;
}
}
public int Height {
get {
return ymax-ymin+1;
}
}
/** Returns if this rectangle is valid.
* An invalid rect could have e.g xmin > xmax.
* Rectamgles with a zero area area invalid.
*/
public bool IsValid () {
return xmin <= xmax && ymin <= ymax;
}
public static bool operator == (IntRect a, IntRect b) {
return a.xmin == b.xmin && a.xmax == b.xmax && a.ymin == b.ymin && a.ymax == b.ymax;
}
public static bool operator != (IntRect a, IntRect b) {
return a.xmin != b.xmin || a.xmax != b.xmax || a.ymin != b.ymin || a.ymax != b.ymax;
}
public override bool Equals (System.Object _b) {
var b = (IntRect)_b;
return xmin == b.xmin && xmax == b.xmax && ymin == b.ymin && ymax == b.ymax;
}
public override int GetHashCode () {
return xmin*131071 ^ xmax*3571 ^ ymin*3109 ^ ymax*7;
}
/** Returns the intersection rect between the two rects.
* The intersection rect is the area which is inside both rects.
* If the rects do not have an intersection, an invalid rect is returned.
* \see IsValid
*/
public static IntRect Intersection (IntRect a, IntRect b) {
var r = new IntRect(
System.Math.Max(a.xmin, b.xmin),
System.Math.Max(a.ymin, b.ymin),
System.Math.Min(a.xmax, b.xmax),
System.Math.Min(a.ymax, b.ymax)
);
return r;
}
/** Returns if the two rectangles intersect each other
*/
public static bool Intersects (IntRect a, IntRect b) {
return !(a.xmin > b.xmax || a.ymin > b.ymax || a.xmax < b.xmin || a.ymax < b.ymin);
}
/** Returns a new rect which contains both input rects.
* This rectangle may contain areas outside both input rects as well in some cases.
*/
public static IntRect Union (IntRect a, IntRect b) {
var r = new IntRect(
System.Math.Min(a.xmin, b.xmin),
System.Math.Min(a.ymin, b.ymin),
System.Math.Max(a.xmax, b.xmax),
System.Math.Max(a.ymax, b.ymax)
);
return r;
}
/** Returns a new IntRect which is expanded to contain the point */
public IntRect ExpandToContain (int x, int y) {
var r = new IntRect(
System.Math.Min(xmin, x),
System.Math.Min(ymin, y),
System.Math.Max(xmax, x),
System.Math.Max(ymax, y)
);
return r;
}
/** Returns a new rect which is expanded by \a range in all directions.
* \param range How far to expand. Negative values are permitted.
*/
public IntRect Expand (int range) {
return new IntRect(xmin-range,
ymin-range,
xmax+range,
ymax+range
);
}
/** Matrices for rotation.
* Each group of 4 elements is a 2x2 matrix.
* The XZ position is multiplied by this.
* So
* \code
* //A rotation by 90 degrees clockwise, second matrix in the array
* (5,2) * ((0, 1), (-1, 0)) = (2,-5)
* \endcode
*/
private static readonly int[] Rotations = {
1, 0, //Identity matrix
0, 1,
0, 1,
-1, 0,
-1, 0,
0, -1,
0, -1,
1, 0
};
/** Returns a new rect rotated around the origin 90*r degrees.
* Ensures that a valid rect is returned.
*/
public IntRect Rotate (int r) {
int mx1 = Rotations[r*4+0];
int mx2 = Rotations[r*4+1];
int my1 = Rotations[r*4+2];
int my2 = Rotations[r*4+3];
int p1x = mx1*xmin + mx2*ymin;
int p1y = my1*xmin + my2*ymin;
int p2x = mx1*xmax + mx2*ymax;
int p2y = my1*xmax + my2*ymax;
return new IntRect(
System.Math.Min(p1x, p2x),
System.Math.Min(p1y, p2y),
System.Math.Max(p1x, p2x),
System.Math.Max(p1y, p2y)
);
}
/** Returns a new rect which is offset by the specified amount.
*/
public IntRect Offset (Int2 offset) {
return new IntRect(xmin+offset.x, ymin + offset.y, xmax + offset.x, ymax + offset.y);
}
/** Returns a new rect which is offset by the specified amount.
*/
public IntRect Offset (int x, int y) {
return new IntRect(xmin+x, ymin + y, xmax + x, ymax + y);
}
public override string ToString () {
return "[x: "+xmin+"..."+xmax+", y: " + ymin +"..."+ymax+"]";
}
/** Draws some debug lines representing the rect */
public void DebugDraw (Matrix4x4 matrix, Color col) {
Vector3 p1 = matrix.MultiplyPoint3x4(new Vector3(xmin, 0, ymin));
Vector3 p2 = matrix.MultiplyPoint3x4(new Vector3(xmin, 0, ymax));
Vector3 p3 = matrix.MultiplyPoint3x4(new Vector3(xmax, 0, ymax));
Vector3 p4 = matrix.MultiplyPoint3x4(new Vector3(xmax, 0, ymin));
Debug.DrawLine(p1, p2, col);
Debug.DrawLine(p2, p3, col);
Debug.DrawLine(p3, p4, col);
Debug.DrawLine(p4, p1, col);
}
}
#region Delegates
/* Delegate with on Path object as parameter.
* This is used for callbacks when a path has finished calculation.\n
* Example function:
* \code
* public void Start () {
* //Assumes a Seeker component is attached to the GameObject
* Seeker seeker = GetComponent<Seeker>();
*
* //seeker.pathCallback is a OnPathDelegate, we add the function OnPathComplete to it so it will be called whenever a path has finished calculating on that seeker
* seeker.pathCallback += OnPathComplete;
* }
*
* public void OnPathComplete (Path p) {
* Debug.Log ("This is called when a path is completed on the seeker attached to this GameObject");
* }
* \endcode
*/
public delegate void OnPathDelegate (Path p);
public delegate void OnGraphDelegate (NavGraph graph);
public delegate void OnScanDelegate (AstarPath script);
public delegate void OnScanStatus (Progress progress);
#endregion
#region Enums
public enum GraphUpdateThreading {
UnityThread,
SeparateThread,
SeparateAndUnityInit
}
/** How path results are logged by the system */
public enum PathLog {
/** Does not log anything. This is recommended for release since logging path results has a performance overhead. */
None,
/** Logs basic info about the paths */
Normal,
/** Includes additional info */
Heavy,
/** Same as heavy, but displays the info in-game using GUI */
InGame,
/** Same as normal, but logs only paths which returned an error */
OnlyErrors
}
/** Heuristic to use. Heuristic is the estimated cost from the current node to the target */
public enum Heuristic {
Manhattan,
DiagonalManhattan,
Euclidean,
None
}
/** What data to draw the graph debugging with */
public enum GraphDebugMode {
Areas,
G,
H,
F,
Penalty,
Connections,
Tags
}
public enum ThreadCount {
AutomaticLowLoad = -1,
AutomaticHighLoad = -2,
None = 0,
One = 1,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight
}
public enum PathState {
Created = 0,
PathQueue = 1,
Processing = 2,
ReturnQueue = 3,
Returned = 4
}
public enum PathCompleteState {
NotCalculated = 0,
Error = 1,
Complete = 2,
Partial = 3
}
#endregion
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Cohorts for data aggregation Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KCOHORTDataSet : EduHubDataSet<KCOHORT>
{
/// <inheritdoc />
public override string Name { get { return "KCOHORT"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KCOHORTDataSet(EduHubContext Context)
: base(Context)
{
Index_COHORT = new Lazy<Dictionary<string, KCOHORT>>(() => this.ToDictionary(i => i.COHORT));
Index_DESCRIPTION = new Lazy<NullDictionary<string, IReadOnlyList<KCOHORT>>>(() => this.ToGroupedNullDictionary(i => i.DESCRIPTION));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KCOHORT" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KCOHORT" /> fields for each CSV column header</returns>
internal override Action<KCOHORT, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KCOHORT, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "COHORT":
mapper[i] = (e, v) => e.COHORT = v;
break;
case "DESCRIPTION":
mapper[i] = (e, v) => e.DESCRIPTION = v;
break;
case "VELS":
mapper[i] = (e, v) => e.VELS = v;
break;
case "BENCHMARK":
mapper[i] = (e, v) => e.BENCHMARK = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KCOHORT" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KCOHORT" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KCOHORT" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KCOHORT}"/> of entities</returns>
internal override IEnumerable<KCOHORT> ApplyDeltaEntities(IEnumerable<KCOHORT> Entities, List<KCOHORT> DeltaEntities)
{
HashSet<string> Index_COHORT = new HashSet<string>(DeltaEntities.Select(i => i.COHORT));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.COHORT;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_COHORT.Remove(entity.COHORT);
if (entity.COHORT.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, KCOHORT>> Index_COHORT;
private Lazy<NullDictionary<string, IReadOnlyList<KCOHORT>>> Index_DESCRIPTION;
#endregion
#region Index Methods
/// <summary>
/// Find KCOHORT by COHORT field
/// </summary>
/// <param name="COHORT">COHORT value used to find KCOHORT</param>
/// <returns>Related KCOHORT entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KCOHORT FindByCOHORT(string COHORT)
{
return Index_COHORT.Value[COHORT];
}
/// <summary>
/// Attempt to find KCOHORT by COHORT field
/// </summary>
/// <param name="COHORT">COHORT value used to find KCOHORT</param>
/// <param name="Value">Related KCOHORT entity</param>
/// <returns>True if the related KCOHORT entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByCOHORT(string COHORT, out KCOHORT Value)
{
return Index_COHORT.Value.TryGetValue(COHORT, out Value);
}
/// <summary>
/// Attempt to find KCOHORT by COHORT field
/// </summary>
/// <param name="COHORT">COHORT value used to find KCOHORT</param>
/// <returns>Related KCOHORT entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KCOHORT TryFindByCOHORT(string COHORT)
{
KCOHORT value;
if (Index_COHORT.Value.TryGetValue(COHORT, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find KCOHORT by DESCRIPTION field
/// </summary>
/// <param name="DESCRIPTION">DESCRIPTION value used to find KCOHORT</param>
/// <returns>List of related KCOHORT entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KCOHORT> FindByDESCRIPTION(string DESCRIPTION)
{
return Index_DESCRIPTION.Value[DESCRIPTION];
}
/// <summary>
/// Attempt to find KCOHORT by DESCRIPTION field
/// </summary>
/// <param name="DESCRIPTION">DESCRIPTION value used to find KCOHORT</param>
/// <param name="Value">List of related KCOHORT entities</param>
/// <returns>True if the list of related KCOHORT entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByDESCRIPTION(string DESCRIPTION, out IReadOnlyList<KCOHORT> Value)
{
return Index_DESCRIPTION.Value.TryGetValue(DESCRIPTION, out Value);
}
/// <summary>
/// Attempt to find KCOHORT by DESCRIPTION field
/// </summary>
/// <param name="DESCRIPTION">DESCRIPTION value used to find KCOHORT</param>
/// <returns>List of related KCOHORT entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KCOHORT> TryFindByDESCRIPTION(string DESCRIPTION)
{
IReadOnlyList<KCOHORT> value;
if (Index_DESCRIPTION.Value.TryGetValue(DESCRIPTION, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KCOHORT table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KCOHORT]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KCOHORT](
[COHORT] varchar(2) NOT NULL,
[DESCRIPTION] varchar(30) NULL,
[VELS] varchar(1) NULL,
[BENCHMARK] varchar(1) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KCOHORT_Index_COHORT] PRIMARY KEY CLUSTERED (
[COHORT] ASC
)
);
CREATE NONCLUSTERED INDEX [KCOHORT_Index_DESCRIPTION] ON [dbo].[KCOHORT]
(
[DESCRIPTION] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCOHORT]') AND name = N'KCOHORT_Index_DESCRIPTION')
ALTER INDEX [KCOHORT_Index_DESCRIPTION] ON [dbo].[KCOHORT] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCOHORT]') AND name = N'KCOHORT_Index_DESCRIPTION')
ALTER INDEX [KCOHORT_Index_DESCRIPTION] ON [dbo].[KCOHORT] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KCOHORT"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KCOHORT"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KCOHORT> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_COHORT = new List<string>();
foreach (var entity in Entities)
{
Index_COHORT.Add(entity.COHORT);
}
builder.AppendLine("DELETE [dbo].[KCOHORT] WHERE");
// Index_COHORT
builder.Append("[COHORT] IN (");
for (int index = 0; index < Index_COHORT.Count; index++)
{
if (index != 0)
builder.Append(", ");
// COHORT
var parameterCOHORT = $"@p{parameterIndex++}";
builder.Append(parameterCOHORT);
command.Parameters.Add(parameterCOHORT, SqlDbType.VarChar, 2).Value = Index_COHORT[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KCOHORT data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KCOHORT data set</returns>
public override EduHubDataSetDataReader<KCOHORT> GetDataSetDataReader()
{
return new KCOHORTDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KCOHORT data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KCOHORT data set</returns>
public override EduHubDataSetDataReader<KCOHORT> GetDataSetDataReader(List<KCOHORT> Entities)
{
return new KCOHORTDataReader(new EduHubDataSetLoadedReader<KCOHORT>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KCOHORTDataReader : EduHubDataSetDataReader<KCOHORT>
{
public KCOHORTDataReader(IEduHubDataSetReader<KCOHORT> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 7; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // COHORT
return Current.COHORT;
case 1: // DESCRIPTION
return Current.DESCRIPTION;
case 2: // VELS
return Current.VELS;
case 3: // BENCHMARK
return Current.BENCHMARK;
case 4: // LW_DATE
return Current.LW_DATE;
case 5: // LW_TIME
return Current.LW_TIME;
case 6: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // DESCRIPTION
return Current.DESCRIPTION == null;
case 2: // VELS
return Current.VELS == null;
case 3: // BENCHMARK
return Current.BENCHMARK == null;
case 4: // LW_DATE
return Current.LW_DATE == null;
case 5: // LW_TIME
return Current.LW_TIME == null;
case 6: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // COHORT
return "COHORT";
case 1: // DESCRIPTION
return "DESCRIPTION";
case 2: // VELS
return "VELS";
case 3: // BENCHMARK
return "BENCHMARK";
case 4: // LW_DATE
return "LW_DATE";
case 5: // LW_TIME
return "LW_TIME";
case 6: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "COHORT":
return 0;
case "DESCRIPTION":
return 1;
case "VELS":
return 2;
case "BENCHMARK":
return 3;
case "LW_DATE":
return 4;
case "LW_TIME":
return 5;
case "LW_USER":
return 6;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.IO;
using Org.BouncyCastle.Utilities.IO;
namespace Org.BouncyCastle.Bcpg
{
/// <remarks>Reader for PGP objects.</remarks>
public class BcpgInputStream : BaseInputStream
{
private readonly Stream _mIn;
private bool _next;
private int _nextB;
internal static BcpgInputStream Wrap(Stream inStr)
{
var inputStream = inStr as BcpgInputStream;
return inputStream ?? new BcpgInputStream(inStr);
}
private BcpgInputStream(Stream inputStream)
{
_mIn = inputStream;
}
public override int ReadByte()
{
if (_next)
{
_next = false;
return _nextB;
}
return _mIn.ReadByte();
}
public override int Read(byte[] buffer, int offset, int count)
{
// Strangely, when count == 0, we should still attempt to read a byte
// if (count == 0)
// return 0;
if (!_next)
return _mIn.Read(buffer, offset, count);
// We have next byte waiting, so return it
if (_nextB < 0)
return 0; // EndOfStream
if (buffer == null)
throw new ArgumentNullException("buffer");
buffer[offset] = (byte)_nextB;
_next = false;
return 1;
}
public byte[] ReadAll()
{
return Streams.ReadAll(this);
}
public void ReadFully(byte[] buffer, int off, int len)
{
if (Streams.ReadFully(this, buffer, off, len) < len)
throw new EndOfStreamException();
}
public void ReadFully(byte[] buffer)
{
ReadFully(buffer, 0, buffer.Length);
}
/// <summary>Returns the next packet tag in the stream.</summary>
public PacketTag NextPacketTag()
{
if (!_next)
{
try
{
_nextB = _mIn.ReadByte();
}
catch (EndOfStreamException)
{
_nextB = -1;
}
_next = true;
}
if (_nextB >= 0)
{
if ((_nextB & 0x40) != 0) // new
{
return (PacketTag)(_nextB & 0x3f);
}
return (PacketTag)((_nextB & 0x3f) >> 2);
}
return (PacketTag)_nextB;
}
public Packet ReadPacket()
{
var hdr = this.ReadByte();
if (hdr < 0)
{
return null;
}
if ((hdr & 0x80) == 0)
{
throw new IOException("invalid header encountered");
}
var newPacket = (hdr & 0x40) != 0;
PacketTag tag;
var bodyLen = 0;
var partial = false;
if (newPacket)
{
tag = (PacketTag)(hdr & 0x3f);
var l = this.ReadByte();
if (l < 192)
{
bodyLen = l;
}
else if (l <= 223)
{
var b = _mIn.ReadByte();
bodyLen = ((l - 192) << 8) + (b) + 192;
}
else if (l == 255)
{
bodyLen = (_mIn.ReadByte() << 24)
| (_mIn.ReadByte() << 16)
| (_mIn.ReadByte() << 8)
| _mIn.ReadByte();
}
else
{
partial = true;
bodyLen = 1 << (l & 0x1f);
}
}
else
{
var lengthType = hdr & 0x3;
tag = (PacketTag)((hdr & 0x3f) >> 2);
switch (lengthType)
{
case 0:
bodyLen = this.ReadByte();
break;
case 1:
bodyLen = (this.ReadByte() << 8) | this.ReadByte();
break;
case 2:
bodyLen = (this.ReadByte() << 24) | (this.ReadByte() << 16)
| (this.ReadByte() << 8) | this.ReadByte();
break;
case 3:
partial = true;
break;
default:
throw new IOException("unknown length type encountered");
}
}
BcpgInputStream objStream;
if (bodyLen == 0 && partial)
{
objStream = this;
}
else
{
objStream = new BcpgInputStream(new PartialInputStream(this, partial, bodyLen));
}
switch (tag)
{
case PacketTag.Reserved:
return new InputStreamPacket(objStream);
case PacketTag.PublicKeyEncryptedSession:
return new PublicKeyEncSessionPacket(objStream);
case PacketTag.Signature:
return new SignaturePacket(objStream);
case PacketTag.SymmetricKeyEncryptedSessionKey:
return new SymmetricKeyEncSessionPacket(objStream);
case PacketTag.OnePassSignature:
return new OnePassSignaturePacket(objStream);
case PacketTag.SecretKey:
return new SecretKeyPacket(objStream);
case PacketTag.PublicKey:
return new PublicKeyPacket(objStream);
case PacketTag.SecretSubkey:
return new SecretSubkeyPacket(objStream);
case PacketTag.CompressedData:
return new CompressedDataPacket(objStream);
case PacketTag.SymmetricKeyEncrypted:
return new SymmetricEncDataPacket(objStream);
case PacketTag.Marker:
return new MarkerPacket(objStream);
case PacketTag.LiteralData:
return new LiteralDataPacket(objStream);
case PacketTag.Trust:
return new TrustPacket(objStream);
case PacketTag.UserId:
return new UserIdPacket(objStream);
case PacketTag.UserAttribute:
return new UserAttributePacket(objStream);
case PacketTag.PublicSubkey:
return new PublicSubkeyPacket(objStream);
case PacketTag.SymmetricEncryptedIntegrityProtected:
return new SymmetricEncIntegrityPacket(objStream);
case PacketTag.ModificationDetectionCode:
return new ModDetectionCodePacket(objStream);
case PacketTag.Experimental1:
case PacketTag.Experimental2:
case PacketTag.Experimental3:
case PacketTag.Experimental4:
return new ExperimentalPacket(tag, objStream);
default:
throw new IOException("unknown packet type encountered: " + tag);
}
}
#if !NETFX_CORE
public override void Close()
{
_mIn.Close();
base.Close();
}
#else
protected override void Dispose(bool disposing)
{
_mIn.Dispose();
base.Dispose(disposing);
}
#endif
/// <summary>
/// A stream that overlays our input stream, allowing the user to only read a segment of it.
/// NB: dataLength will be negative if the segment length is in the upper range above 2**31.
/// </summary>
private class PartialInputStream : BaseInputStream
{
private readonly BcpgInputStream _in;
private bool _partial;
private int _dataLength;
internal PartialInputStream(BcpgInputStream bcpgIn, bool partial, int dataLength)
{
_in = bcpgIn;
_partial = partial;
_dataLength = dataLength;
}
public override int ReadByte()
{
do
{
if (_dataLength == 0)
continue;
var ch = _in.ReadByte();
if (ch < 0)
throw new EndOfStreamException("Premature end of stream in PartialInputStream");
_dataLength--;
return ch;
}
while (_partial && ReadPartialDataLength() >= 0);
return -1;
}
public override int Read(byte[] buffer, int offset, int count)
{
do
{
if (_dataLength == 0)
continue;
var readLen = (_dataLength > count || _dataLength < 0) ? count : _dataLength;
var len = _in.Read(buffer, offset, readLen);
if (len < 1)
throw new EndOfStreamException("Premature end of stream in PartialInputStream");
_dataLength -= len;
return len;
}
while (_partial && ReadPartialDataLength() >= 0);
return 0;
}
private int ReadPartialDataLength()
{
var l = _in.ReadByte();
if (l < 0)
{
return -1;
}
_partial = false;
if (l < 192)
{
_dataLength = l;
}
else if (l <= 223)
{
_dataLength = ((l - 192) << 8) + (_in.ReadByte()) + 192;
}
else if (l == 255)
{
_dataLength = (_in.ReadByte() << 24) | (_in.ReadByte() << 16)
| (_in.ReadByte() << 8) | _in.ReadByte();
}
else
{
_partial = true;
_dataLength = 1 << (l & 0x1f);
}
return 0;
}
}
}
}
| |
/* Copyright (c) 2007-2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Change history
* Oct 13 2008 Joe Feser joseph.feser@gmail.com
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
#region Using directives
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Xml;
using Google.GData.Client;
#endregion
namespace Google.GData.GoogleBase
{
//////////////////////////////////////////////////////////////////////
/// <summary>Individual statistic in Stats (impressions, clicks,
/// page views).
///
/// Most of the time, the total is all there is to individual
/// statistics, but there might be sometimes more specific
/// per-source count information.
///
/// Such objects are typically accessed through a property
/// of a <c>Stats</c> object.
/// </summary>
//////////////////////////////////////////////////////////////////////
public class Statistic
{
private int total;
/// <summary>source name(string) x count(int)</summary>
private Hashtable sourceCount;
//////////////////////////////////////////////////////////////////////
/// <summary>Total count for this statistics.</summary>
//////////////////////////////////////////////////////////////////////
public int Total
{
get
{
return total;
}
set
{
total = value;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>Per-source count (subtotal), -1 for unknown count.
/// </summary>
//////////////////////////////////////////////////////////////////////
public int this[string source]
{
get
{
if (sourceCount == null || !sourceCount.Contains(source))
{
return -1;
}
return (int)sourceCount[source];
}
set
{
if (sourceCount == null)
{
if (value == -1)
{
return;
}
sourceCount = new Hashtable();
}
if (value == -1)
{
sourceCount.Remove(source);
}
else
{
sourceCount[source] = value;
}
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>Puts the object back into its original state.</summary>
//////////////////////////////////////////////////////////////////////
private void Reset()
{
total = 0;
sourceCount = null;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Parses an XML representation and updates the object</summary>
///////////////////////////////////////////////////////////////////////
public void Parse(XmlNode xml)
{
Reset();
String value = Utilities.GetAttributeValue("total", xml);
if (value != null)
{
total = NumberFormat.ToInt(value);
}
for (XmlNode child = xml.FirstChild; child != null; child = child.NextSibling)
{
if ("source".Equals(child.LocalName) && GBaseNameTable.NSGBaseMeta.Equals(child.NamespaceURI))
{
string name = Utilities.GetAttributeValue("name", child);
string countString = Utilities.GetAttributeValue("count", child);
if (name != null && countString != null)
{
this[name] = NumberFormat.ToInt(countString);
}
}
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Generates an XML representation for this object.</summary>
///////////////////////////////////////////////////////////////////////
public void Save(string tagName, XmlWriter writer)
{
if (total > 0)
{
writer.WriteStartElement(GBaseNameTable.GBaseMetaPrefix, tagName, GBaseNameTable.NSGBaseMeta);
writer.WriteAttributeString("total", NumberFormat.ToString(total));
if (sourceCount != null)
{
foreach (string source in sourceCount.Keys)
{
int count = (int)sourceCount[source];
writer.WriteStartElement(GBaseNameTable.GBaseMetaPrefix,
"source",
GBaseNameTable.NSGBaseMeta);
writer.WriteAttributeString("name", source);
writer.WriteAttributeString("count", NumberFormat.ToString(count));
writer.WriteEndElement();
}
}
writer.WriteEndElement();
}
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>Object representation for the gm:stats tags in
/// the customer item feed.</summary>
//////////////////////////////////////////////////////////////////////
public class Stats : IExtensionElementFactory
{
private Statistic impressions = new Statistic();
private Statistic clicks = new Statistic();
private Statistic pageViews = new Statistic();
//////////////////////////////////////////////////////////////////////
/// <summary>Impressions statistics</summary>
//////////////////////////////////////////////////////////////////////
public Statistic Impressions
{
get
{
return impressions;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>Clicks statistics</summary>
//////////////////////////////////////////////////////////////////////
public Statistic Clicks
{
get
{
return clicks;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>Page views statistics</summary>
//////////////////////////////////////////////////////////////////////
public Statistic PageViews
{
get
{
return pageViews;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Parses an XML representation and creates an object</summary>
///////////////////////////////////////////////////////////////////////
public static Stats Parse(XmlNode xml)
{
Stats retval = new Stats();
for (XmlNode child = xml.FirstChild; child != null; child = child.NextSibling)
{
if (GBaseNameTable.NSGBaseMeta.Equals(child.NamespaceURI))
{
switch (child.LocalName)
{
case "impressions":
retval.Impressions.Parse(child);
break;
case "clicks":
retval.Clicks.Parse(child);
break;
case "page_views":
retval.PageViews.Parse(child);
break;
}
}
}
return retval;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Generates an XML representation for this object.</summary>
///////////////////////////////////////////////////////////////////////
public void Save(XmlWriter writer)
{
if (impressions.Total > 0 || clicks.Total > 0 || pageViews.Total > 0)
{
writer.WriteStartElement(XmlPrefix,
"stats",
XmlNameSpace);
impressions.Save("impressions", writer);
clicks.Save("clicks", writer);
pageViews.Save("page_views", writer);
writer.WriteEndElement();
}
}
#region IExtensionElementFactory Members
public string XmlName
{
get
{
return "stats";
}
}
public string XmlNameSpace
{
get
{
return GBaseNameTable.NSGBaseMeta;
}
}
public string XmlPrefix
{
get
{
return GBaseNameTable.GBaseMetaPrefix;
}
}
public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser)
{
return Parse(node);
}
#endregion
}
}
| |
/* Josip Medved <jmedved@jmedved.com> * www.medo64.com * MIT License */
//2019-03-24: Workaround for resize bugs on mono.
// Cleanup.
//2018-02-24: Added option to raise event on read/write instead of using registry.
//2010-10-31: Added option to skip registry writes (NoRegistryWrites).
//2010-10-17: Limited all loaded forms to screen's working area.
// Changed LoadNowAndSaveOnClose to use SetupOnLoadAndClose.
//2009-07-04: Compatibility with Mono 2.4.
//2008-12-27: Added LoadNowAndSaveOnClose method.
//2008-07-10: Fixed resize on load when window is maximized.
//2008-05-11: Windows with fixed borders are no longer resized.
//2008-04-11: Cleaned code to match FxCop 1.36 beta 2 (CompoundWordsShouldBeCasedCorrectly).
//2008-02-15: Fixed bug with positioning of centered forms.
//2008-01-31: Fixed bug that caused only first control to be loaded/saved.
//2008-01-10: Moved private methods to Helper class.
//2008-01-05: Removed obsoleted methods.
//2008-01-02: Calls to MoveSplitterTo method are now checked.
//2007-12-27: Added Load overloads for multiple controls.
// Obsoleted Subscribe method.
//2007-12-24: Changed SubKeyPath to include full path.
//2007-11-21: Initial version.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace Medo.Windows.Forms {
/// <summary>
/// Enables storing and loading of windows control's state.
/// It is written in State key at HKEY_CURRENT_USER branch withing SubKeyPath of Settings class.
/// This class is not thread-safe since it should be called only from one thread - one that has interface.
/// </summary>
public static class State {
private static string _subkeyPath;
/// <summary>
/// Gets/sets subkey used for registry storage.
/// </summary>
public static string SubkeyPath {
get {
if (_subkeyPath == null) {
var assembly = Assembly.GetEntryAssembly();
string company = null;
var companyAttributes = assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), true);
if ((companyAttributes != null) && (companyAttributes.Length >= 1)) {
company = ((AssemblyCompanyAttribute)companyAttributes[companyAttributes.Length - 1]).Company;
}
var productAttributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), true);
string product;
if ((productAttributes != null) && (productAttributes.Length >= 1)) {
product = ((AssemblyProductAttribute)productAttributes[productAttributes.Length - 1]).Product;
} else {
var titleAttributes = assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), true);
if ((titleAttributes != null) && (titleAttributes.Length >= 1)) {
product = ((AssemblyTitleAttribute)titleAttributes[titleAttributes.Length - 1]).Title;
} else {
product = assembly.GetName().Name;
}
}
var path = "Software";
if (!string.IsNullOrEmpty(company)) { path += "\\" + company; }
if (!string.IsNullOrEmpty(product)) { path += "\\" + product; }
_subkeyPath = path + "\\State";
}
return _subkeyPath;
}
set { _subkeyPath = value; }
}
/// <summary>
/// Gets/sets whether settings should be written to registry.
/// </summary>
public static bool NoRegistryWrites { get; set; }
#region Obsoleted
/// <summary>
/// Loads previous state.
/// Supported controls are Form, PropertyGrid, ListView and SplitContainer.
/// </summary>
/// <param name="form">Form on which's FormClosing handler this function will attach. State will not be altered for this parameter.</param>
/// <param name="controls">Controls to load and to save.</param>
/// <exception cref="ArgumentNullException">Form is null.</exception>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
/// <exception cref="ArgumentException">Form setup already done.</exception>
[Obsolete("Use Attach instead.")]
public static void SetupOnLoadAndClose(Form form, params Control[] controls) {
if (form == null) { throw new ArgumentNullException("form", "Form is null."); }
if (AttachedFormControls.ContainsKey(form)) { throw new ArgumentException("Form setup already done.", "form"); }
AttachedFormControls.Add(form, controls);
form.Load += new EventHandler(HandleLoadEvent);
form.FormClosed += new FormClosedEventHandler(HandleSaveEvent);
}
#endregion
#region Attach
/// <summary>
/// Attaches to form's events to automtically resize desired controls.
/// Supported controls are Form, PropertyGrid, ListView and SplitContainer.
/// </summary>
/// <param name="form">Form on which handlers will attach.</param>
/// <param name="controls">Controls for which dimensions will be controlled.</param>
/// <exception cref="ArgumentNullException">Form is null.</exception>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
/// <exception cref="ArgumentException">Form setup already done.</exception>
public static void Attach(Form form, params Control[] controls) {
if (form == null) { throw new ArgumentNullException("form", "Form is null."); }
if (AttachedFormControls.ContainsKey(form)) { throw new ArgumentException("Form setup already done.", "form"); }
AttachedFormControls.Add(form, controls);
form.Shown += new EventHandler(HandleLoadEvent);
form.Closed += new EventHandler(HandleSaveEvent);
}
private static readonly Dictionary<Form, Control[]> AttachedFormControls = new Dictionary<Form, Control[]>();
private static void HandleLoadEvent(object sender, EventArgs e) {
var form = sender as Form;
if (AttachedFormControls.ContainsKey(form)) {
Load(form);
Load(AttachedFormControls[form]);
}
}
private static void HandleSaveEvent(object sender, EventArgs e) {
var form = sender as Form;
if (AttachedFormControls.ContainsKey(form)) {
Save(form);
Save(AttachedFormControls[form]);
AttachedFormControls.Remove(form);
}
}
#endregion
#region Load Save - All
/// <summary>
/// Loads previous state.
/// Supported controls are Form, PropertyGrid, ListView and SplitContainer.
/// </summary>
/// <param name="controls">Controls to load.</param>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
public static void Load(params Control[] controls) {
if (controls == null) { return; }
for (var i = 0; i < controls.Length; ++i) {
if (controls[i] is Form form) {
Load(form);
} else if (controls[i] is PropertyGrid propertyGrid) {
Load(propertyGrid);
} else if (controls[i] is ListView listView) {
Load(listView);
} else if (controls[i] is SplitContainer splitContainer) {
Load(splitContainer);
}
}
}
/// <summary>
/// Saves control's state.
/// Supported controls are Form, PropertyGrid, ListView and SplitContainer.
/// </summary>
/// <param name="controls">Controls to save.</param>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
public static void Save(params Control[] controls) {
if (controls == null) { return; }
for (var i = 0; i < controls.Length; ++i) {
if (controls[i] is Form form) {
Save(form);
} else if (controls[i] is PropertyGrid propertyGrid) {
Save(propertyGrid);
} else if (controls[i] is ListView listView) {
Save(listView);
} else if (controls[i] is SplitContainer splitContainer) {
Save(splitContainer);
}
}
}
#endregion
#region Load Save - Form
/// <summary>
/// Saves Form state (Left,Top,Width,Height,WindowState).
/// </summary>
/// <param name="form">Form.</param>
/// <exception cref="ArgumentNullException">Form is null.</exception>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
public static void Save(Form form) {
if (form == null) { throw new ArgumentNullException("form", "Form is null."); }
var baseValueName = Helper.GetControlPath(form);
Write(baseValueName + ".WindowState", System.Convert.ToInt32(form.WindowState, CultureInfo.InvariantCulture));
if (form.WindowState == FormWindowState.Normal) {
Write(baseValueName + ".Left", form.Bounds.Left);
Write(baseValueName + ".Top", form.Bounds.Top);
Write(baseValueName + ".Width", form.Bounds.Width);
Write(baseValueName + ".Height", form.Bounds.Height);
} else {
Write(baseValueName + ".Left", form.RestoreBounds.Left);
Write(baseValueName + ".Top", form.RestoreBounds.Top);
Write(baseValueName + ".Width", form.RestoreBounds.Width);
Write(baseValueName + ".Height", form.RestoreBounds.Height);
}
}
/// <summary>
/// Loads previous Form state (Left,Top,Width,Height,WindowState).
/// If StartupPosition value is Manual, saved settings are used, for other types, it tryes to resemble original behaviour.
/// </summary>
/// <param name="form">Form.</param>
/// <exception cref="ArgumentNullException">Form is null.</exception>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
public static void Load(Form form) {
if (form == null) { throw new ArgumentNullException("form", "Form is null."); }
var baseValueName = Helper.GetControlPath(form);
var currWindowState = System.Convert.ToInt32(form.WindowState, CultureInfo.InvariantCulture);
int currLeft, currTop, currWidth, currHeight;
if (form.WindowState == FormWindowState.Normal) {
currLeft = form.Bounds.Left;
currTop = form.Bounds.Top;
currWidth = form.Bounds.Width;
currHeight = form.Bounds.Height;
} else {
currLeft = form.RestoreBounds.Left;
currTop = form.RestoreBounds.Top;
currWidth = form.RestoreBounds.Width;
currHeight = form.RestoreBounds.Height;
}
var newLeft = Read(baseValueName + ".Left", currLeft);
var newTop = Read(baseValueName + ".Top", currTop);
var newWidth = Read(baseValueName + ".Width", currWidth);
var newHeight = Read(baseValueName + ".Height", currHeight);
var newWindowState = Read(baseValueName + ".WindowState", currWindowState);
if ((form.FormBorderStyle == FormBorderStyle.Fixed3D) || (form.FormBorderStyle == FormBorderStyle.FixedDialog) || (form.FormBorderStyle == FormBorderStyle.FixedSingle) || (form.FormBorderStyle == FormBorderStyle.FixedToolWindow)) {
newWidth = currWidth;
newHeight = currHeight;
}
var screen = Screen.FromRectangle(new Rectangle(newLeft, newTop, newWidth, newHeight));
switch (form.StartPosition) {
case FormStartPosition.CenterParent: {
if (form.Parent != null) {
newLeft = form.Parent.Left + (form.Parent.Width - newWidth) / 2;
newTop = form.Parent.Top + (form.Parent.Height - newHeight) / 2;
} else if (form.Owner != null) {
newLeft = form.Owner.Left + (form.Owner.Width - newWidth) / 2;
newTop = form.Owner.Top + (form.Owner.Height - newHeight) / 2;
} else {
newLeft = screen.WorkingArea.Left + (screen.WorkingArea.Width - newWidth) / 2;
newTop = screen.WorkingArea.Top + (screen.WorkingArea.Height - newHeight) / 2;
}
}
break;
case FormStartPosition.CenterScreen: {
newLeft = screen.WorkingArea.Left + (screen.WorkingArea.Width - newWidth) / 2;
newTop = screen.WorkingArea.Top + (screen.WorkingArea.Height - newHeight) / 2;
}
break;
}
if (newWidth <= 0) { newWidth = currWidth; }
if (newHeight <= 0) { newHeight = currHeight; }
if (newWidth > screen.WorkingArea.Width) { newWidth = screen.WorkingArea.Width; }
if (newHeight > screen.WorkingArea.Height) { newHeight = screen.WorkingArea.Height; }
if (newLeft + newWidth > screen.WorkingArea.Right) { newLeft = screen.WorkingArea.Left + (screen.WorkingArea.Width - newWidth); }
if (newTop + newHeight > screen.WorkingArea.Bottom) { newTop = screen.WorkingArea.Top + (screen.WorkingArea.Height - newHeight); }
if (newLeft < screen.WorkingArea.Left) { newLeft = screen.WorkingArea.Left; }
if (newTop < screen.WorkingArea.Top) { newTop = screen.WorkingArea.Top; }
form.Location = new Point(newLeft, newTop);
form.Size = new Size(newWidth, newHeight);
if (newWindowState == System.Convert.ToInt32(FormWindowState.Maximized, CultureInfo.InvariantCulture)) {
form.WindowState = FormWindowState.Maximized;
} //no need for any code - it is already either in normal state or minimized (will be restored to normal).
}
#endregion
#region Load Save - PropertyGrid
/// <summary>
/// Loads previous PropertyGrid state (LabelWidth, PropertySort).
/// </summary>
/// <param name="control">PropertyGrid.</param>
/// <exception cref="ArgumentNullException">Control is null.</exception>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "PropertyGrid is passed because of reflection upon its member.")]
public static void Load(PropertyGrid control) {
if (control == null) { throw new ArgumentNullException("control", "Control is null."); }
var baseValueName = Helper.GetControlPath(control);
try {
control.PropertySort = (PropertySort)(Read(baseValueName + ".PropertySort", System.Convert.ToInt32(control.PropertySort, CultureInfo.InvariantCulture)));
} catch (InvalidEnumArgumentException) { }
var fieldGridView = control.GetType().GetField("gridView", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);
var gridViewObject = fieldGridView.GetValue(control);
if (gridViewObject != null) {
var currentlabelWidth = 0;
var propertyInternalLabelWidth = gridViewObject.GetType().GetProperty("InternalLabelWidth", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance);
if (propertyInternalLabelWidth != null) {
var val = propertyInternalLabelWidth.GetValue(gridViewObject, null);
if (val is int) {
currentlabelWidth = (int)val;
}
}
var labelWidth = Read(baseValueName + ".LabelWidth", currentlabelWidth);
if ((labelWidth > 0) && (labelWidth < control.Width)) {
var methodMoveSplitterToFlags = BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance;
var methodMoveSplitterTo = gridViewObject.GetType().GetMethod("MoveSplitterTo", methodMoveSplitterToFlags);
if (methodMoveSplitterTo != null) {
methodMoveSplitterTo.Invoke(gridViewObject, methodMoveSplitterToFlags, null, new object[] { labelWidth }, CultureInfo.CurrentCulture);
}
}
}
}
/// <summary>
/// Saves PropertyGrid state (LabelWidth).
/// </summary>
/// <param name="control">PropertyGrid.</param>
/// <exception cref="ArgumentNullException">Control is null.</exception>
/// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "PropertyGrid is passed because of reflection upon its member.")]
public static void Save(PropertyGrid control) {
if (control == null) { throw new ArgumentNullException("control", "Control is null."); }
var baseValueName = Helper.GetControlPath(control);
Write(baseValueName + ".PropertySort", System.Convert.ToInt32(control.PropertySort, CultureInfo.InvariantCulture));
var fieldGridView = control.GetType().GetField("gridView", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);
var gridViewObject = fieldGridView.GetValue(control);
if (gridViewObject != null) {
var propertyInternalLabelWidth = gridViewObject.GetType().GetProperty("InternalLabelWidth", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance);
if (propertyInternalLabelWidth != null) {
var val = propertyInternalLabelWidth.GetValue(gridViewObject, null);
if (val is int) {
Write(baseValueName + ".LabelWidth", (int)val);
}
}
}
}
#endregion
#region Load Save - ListView
/// <summary>
/// Loads previous ListView state (Column header width).
/// </summary>
/// <param name="control">ListView.</param>
/// <exception cref="ArgumentNullException">Control is null.</exception>
public static void Load(ListView control) {
if (control == null) { throw new ArgumentNullException("control", "Control is null."); }
var baseValueName = Helper.GetControlPath(control);
for (var i = 0; i < control.Columns.Count; i++) {
var width = Read(baseValueName + ".ColumnHeaderWidth[" + i.ToString(CultureInfo.InvariantCulture) + "]", control.Columns[i].Width);
if (width > control.ClientRectangle.Width) { width = control.ClientRectangle.Width; }
control.Columns[i].Width = width;
}
}
/// <summary>
/// Saves ListView state (Column header width).
/// </summary>
/// <param name="control">ListView.</param>
/// <exception cref="ArgumentNullException">Control is null.</exception>
public static void Save(ListView control) {
if (control == null) { throw new ArgumentNullException("control", "Control is null."); }
var baseValueName = Helper.GetControlPath(control);
for (var i = 0; i < control.Columns.Count; i++) {
Write(baseValueName + ".ColumnHeaderWidth[" + i.ToString(CultureInfo.InvariantCulture) + "]", control.Columns[i].Width);
}
}
#endregion
#region Load Save - SplitContainer
/// <summary>
/// Loads previous SplitContainer state.
/// </summary>
/// <param name="control">SplitContainer.</param>
/// <exception cref="ArgumentNullException">Control is null.</exception>
public static void Load(SplitContainer control) {
if (control == null) { throw new ArgumentNullException("control", "Control is null."); }
var baseValueName = Helper.GetControlPath(control);
try {
control.Orientation = (Orientation)(Read(baseValueName + ".Orientation", System.Convert.ToInt32(control.Orientation, CultureInfo.InvariantCulture)));
} catch (InvalidEnumArgumentException) { }
try {
var distance = Read(baseValueName + ".SplitterDistance", control.SplitterDistance);
try {
control.SplitterDistance = distance;
} catch (ArgumentOutOfRangeException) { }
} catch (InvalidEnumArgumentException) { }
}
/// <summary>
/// Saves SplitContainer state.
/// </summary>
/// <param name="control">SplitContainer.</param>
/// <exception cref="ArgumentNullException">Control is null.</exception>
public static void Save(SplitContainer control) {
if (control == null) { throw new ArgumentNullException("control", "Control is null."); }
var baseValueName = Helper.GetControlPath(control);
Write(baseValueName + ".Orientation", System.Convert.ToInt32(control.Orientation, CultureInfo.InvariantCulture));
Write(baseValueName + ".SplitterDistance", control.SplitterDistance);
}
#endregion
#region Store
/// <summary>
/// Event handler used to read state.
/// If used, registry is not read.
/// </summary>
public static event EventHandler<StateReadEventArgs> ReadState;
/// <summary>
/// Event handler used to write state.
/// If used, registry is not written to.
/// </summary>
public static event EventHandler<StateWriteEventArgs> WriteState;
private static void Write(string valueName, int value) {
var ev = WriteState;
if (ev != null) {
ev.Invoke(null, new StateWriteEventArgs(valueName, value));
} else {
Helper.RegistryWrite(valueName, value);
}
}
private static int Read(string valueName, int defaultValue) {
var ev = ReadState;
if (ev != null) {
var state = new StateReadEventArgs(valueName, defaultValue);
ev.Invoke(null, state);
return state.Value;
} else {
return Helper.RegistryRead(valueName, defaultValue);
}
}
#endregion Store
private static class Helper {
internal static void RegistryWrite(string valueName, int value) {
if (State.NoRegistryWrites == false) {
try {
if (State.SubkeyPath.Length == 0) { return; }
using (var rk = Registry.CurrentUser.CreateSubKey(State.SubkeyPath)) {
if (rk != null) {
rk.SetValue(valueName, value, RegistryValueKind.DWord);
}
}
} catch (IOException) { //key is deleted.
} catch (UnauthorizedAccessException) { } //key is write protected.
}
}
internal static int RegistryRead(string valueName, int defaultValue) {
try {
using (var rk = Registry.CurrentUser.OpenSubKey(State.SubkeyPath, false)) {
if (rk != null) {
var value = rk.GetValue(valueName, null);
if (value == null) { return defaultValue; }
var valueKind = RegistryValueKind.DWord;
if (!State.Helper.IsRunningOnMono) { valueKind = rk.GetValueKind(valueName); }
if ((value != null) && (valueKind == RegistryValueKind.DWord)) {
return (int)value;
}
}
}
} catch (SecurityException) { }
return defaultValue;
}
internal static string GetControlPath(Control control) {
var sbPath = new StringBuilder();
var currControl = control;
while (true) {
var parentControl = currControl.Parent;
if (parentControl == null) {
if (sbPath.Length > 0) { sbPath.Insert(0, "."); }
sbPath.Insert(0, currControl.GetType().FullName);
break;
} else {
if (string.IsNullOrEmpty(currControl.Name)) {
throw new NotSupportedException("This control's parents cannot be resolved using Name property.");
} else {
if (sbPath.Length > 0) { sbPath.Insert(0, "."); }
sbPath.Insert(0, currControl.Name);
}
}
currControl = parentControl;
}
return sbPath.ToString();
}
private static bool IsRunningOnMono {
get {
return (Type.GetType("Mono.Runtime") != null);
}
}
}
}
/// <summary>
/// State read event arguments.
/// </summary>
public class StateReadEventArgs : EventArgs {
/// <summary>
/// Create a new instance.
/// </summary>
/// <param name="name">Property name.</param>
/// <param name="defaultValue">Default property value.</param>
public StateReadEventArgs(string name, int defaultValue) {
if (name == null) { throw new ArgumentNullException(nameof(name), "Name cannot be null."); }
if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentOutOfRangeException(nameof(name), "Name cannot be empty."); }
Name = name;
DefaultValue = defaultValue;
Value = defaultValue;
}
/// <summary>
/// Gets property name.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets default property value.
/// </summary>
public int DefaultValue { get; }
/// <summary>
/// Gets/sets property value.
/// </summary>
public int Value { get; set; }
}
/// <summary>
/// State write event arguments.
/// </summary>
public class StateWriteEventArgs : EventArgs {
/// <summary>
/// Create a new instance.
/// </summary>
/// <param name="name">Property name.</param>
/// <param name="value">Property value.</param>
public StateWriteEventArgs(string name, int value) {
if (name == null) { throw new ArgumentNullException(nameof(name), "Name cannot be null."); }
if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentOutOfRangeException(nameof(name), "Name cannot be empty."); }
Name = name;
Value = value;
}
/// <summary>
/// Gets property name.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets property value.
/// </summary>
public int Value { get; }
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Monitor.Management
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Monitor;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// DiagnosticSettingsOperations operations.
/// </summary>
internal partial class DiagnosticSettingsOperations : IServiceOperations<MonitorManagementClient>, IDiagnosticSettingsOperations
{
/// <summary>
/// Initializes a new instance of the DiagnosticSettingsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DiagnosticSettingsOperations(MonitorManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the MonitorManagementClient
/// </summary>
public MonitorManagementClient Client { get; private set; }
/// <summary>
/// Gets the active diagnostic settings for the specified resource.
/// </summary>
/// <param name='resourceUri'>
/// The identifier of the resource.
/// </param>
/// <param name='name'>
/// The name of the diagnostic setting.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DiagnosticSettingsResource>> GetWithHttpMessagesAsync(string resourceUri, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceUri == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
string apiVersion = "2017-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/diagnosticSettings/{name}").ToString();
_url = _url.Replace("{resourceUri}", System.Uri.EscapeDataString(resourceUri));
_url = _url.Replace("{name}", System.Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DiagnosticSettingsResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<DiagnosticSettingsResource>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates diagnostic settings for the specified resource.
/// </summary>
/// <param name='resourceUri'>
/// The identifier of the resource.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the operation.
/// </param>
/// <param name='name'>
/// The name of the diagnostic setting.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DiagnosticSettingsResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceUri, DiagnosticSettingsResource parameters, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceUri == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
string apiVersion = "2017-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/diagnosticSettings/{name}").ToString();
_url = _url.Replace("{resourceUri}", System.Uri.EscapeDataString(resourceUri));
_url = _url.Replace("{name}", System.Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DiagnosticSettingsResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<DiagnosticSettingsResource>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes existing diagnostic settings for the specified resource.
/// </summary>
/// <param name='resourceUri'>
/// The identifier of the resource.
/// </param>
/// <param name='name'>
/// The name of the diagnostic setting.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceUri, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceUri == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
string apiVersion = "2017-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/diagnosticSettings/{name}").ToString();
_url = _url.Replace("{resourceUri}", System.Uri.EscapeDataString(resourceUri));
_url = _url.Replace("{name}", System.Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the active diagnostic settings list for the specified resource.
/// </summary>
/// <param name='resourceUri'>
/// The identifier of the resource.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DiagnosticSettingsResourceCollection>> ListWithHttpMessagesAsync(string resourceUri, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceUri == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri");
}
string apiVersion = "2017-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/diagnosticSettings").ToString();
_url = _url.Replace("{resourceUri}", System.Uri.EscapeDataString(resourceUri));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DiagnosticSettingsResourceCollection>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<DiagnosticSettingsResourceCollection>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable warnings
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Components.Rendering
{
[DebuggerDisplay("{_state,nq}")]
internal class RendererSynchronizationContext : SynchronizationContext
{
private static readonly ContextCallback ExecutionContextThunk = (object state) =>
{
var item = (WorkItem)state;
item.SynchronizationContext.ExecuteSynchronously(null, item.Callback, item.State);
};
private static readonly Action<Task, object> BackgroundWorkThunk = (Task task, object state) =>
{
var item = (WorkItem)state;
item.SynchronizationContext.ExecuteBackground(item);
};
private readonly State _state;
public event UnhandledExceptionEventHandler UnhandledException;
public RendererSynchronizationContext()
: this(new State())
{
}
private RendererSynchronizationContext(State state)
{
_state = state;
}
public Task InvokeAsync(Action action)
{
var completion = new RendererSynchronizationTaskCompletionSource<Action, object>(action);
ExecuteSynchronouslyIfPossible((state) =>
{
var completion = (RendererSynchronizationTaskCompletionSource<Action, object>)state;
try
{
completion.Callback();
completion.SetResult(null);
}
catch (OperationCanceledException)
{
completion.SetCanceled();
}
catch (Exception exception)
{
completion.SetException(exception);
}
}, completion);
return completion.Task;
}
public Task InvokeAsync(Func<Task> asyncAction)
{
var completion = new RendererSynchronizationTaskCompletionSource<Func<Task>, object>(asyncAction);
ExecuteSynchronouslyIfPossible(async (state) =>
{
var completion = (RendererSynchronizationTaskCompletionSource<Func<Task>, object>)state;
try
{
await completion.Callback();
completion.SetResult(null);
}
catch (OperationCanceledException)
{
completion.SetCanceled();
}
catch (Exception exception)
{
completion.SetException(exception);
}
}, completion);
return completion.Task;
}
public Task<TResult> InvokeAsync<TResult>(Func<TResult> function)
{
var completion = new RendererSynchronizationTaskCompletionSource<Func<TResult>, TResult>(function);
ExecuteSynchronouslyIfPossible((state) =>
{
var completion = (RendererSynchronizationTaskCompletionSource<Func<TResult>, TResult>)state;
try
{
var result = completion.Callback();
completion.SetResult(result);
}
catch (OperationCanceledException)
{
completion.SetCanceled();
}
catch (Exception exception)
{
completion.SetException(exception);
}
}, completion);
return completion.Task;
}
public Task<TResult> InvokeAsync<TResult>(Func<Task<TResult>> asyncFunction)
{
var completion = new RendererSynchronizationTaskCompletionSource<Func<Task<TResult>>, TResult>(asyncFunction);
ExecuteSynchronouslyIfPossible(async (state) =>
{
var completion = (RendererSynchronizationTaskCompletionSource<Func<Task<TResult>>, TResult>)state;
try
{
var result = await completion.Callback();
completion.SetResult(result);
}
catch (OperationCanceledException)
{
completion.SetCanceled();
}
catch (Exception exception)
{
completion.SetException(exception);
}
}, completion);
return completion.Task;
}
// asynchronously runs the callback
//
// NOTE: this must always run async. It's not legal here to execute the work item synchronously.
public override void Post(SendOrPostCallback d, object state)
{
lock (_state.Lock)
{
_state.Task = Enqueue(_state.Task, d, state, forceAsync: true);
}
}
// synchronously runs the callback
public override void Send(SendOrPostCallback d, object state)
{
Task antecedent;
var completion = new TaskCompletionSource<object>();
lock (_state.Lock)
{
antecedent = _state.Task;
_state.Task = completion.Task;
}
// We have to block. That's the contract of Send - we don't expect this to be used
// in many scenarios in Components.
//
// Using Wait here is ok because the antecedent task will never throw.
antecedent.Wait();
ExecuteSynchronously(completion, d, state);
}
// shallow copy
public override SynchronizationContext CreateCopy()
{
return new RendererSynchronizationContext(_state);
}
// Similar to Post, but it can runs the work item synchronously if the context is not busy.
//
// This is the main code path used by components, we want to be able to run async work but only dispatch
// if necessary.
private void ExecuteSynchronouslyIfPossible(SendOrPostCallback d, object state)
{
TaskCompletionSource<object> completion;
lock (_state.Lock)
{
if (!_state.Task.IsCompleted)
{
_state.Task = Enqueue(_state.Task, d, state);
return;
}
// We can execute this synchronously because nothing is currently running
// or queued.
completion = new TaskCompletionSource<object>();
_state.Task = completion.Task;
}
ExecuteSynchronously(completion, d, state);
}
private Task Enqueue(Task antecedent, SendOrPostCallback d, object state, bool forceAsync = false)
{
// If we get here is means that a callback is being explicitly queued. Let's instead add it to the queue and yield.
//
// We use our own queue here to maintain the execution order of the callbacks scheduled here. Also
// we need a queue rather than just scheduling an item in the thread pool - those items would immediately
// block and hurt scalability.
//
// We need to capture the execution context so we can restore it later. This code is similar to
// the call path of ThreadPool.QueueUserWorkItem and System.Threading.QueueUserWorkItemCallback.
ExecutionContext executionContext = null;
if (!ExecutionContext.IsFlowSuppressed())
{
executionContext = ExecutionContext.Capture();
}
var flags = forceAsync ? TaskContinuationOptions.RunContinuationsAsynchronously : TaskContinuationOptions.None;
return antecedent.ContinueWith(BackgroundWorkThunk, new WorkItem()
{
SynchronizationContext = this,
ExecutionContext = executionContext,
Callback = d,
State = state,
}, CancellationToken.None, flags, TaskScheduler.Current);
}
private void ExecuteSynchronously(
TaskCompletionSource<object> completion,
SendOrPostCallback d,
object state)
{
var original = Current;
try
{
SetSynchronizationContext(this);
_state.IsBusy = true;
d(state);
}
finally
{
_state.IsBusy = false;
SetSynchronizationContext(original);
completion?.SetResult(null);
}
}
private void ExecuteBackground(WorkItem item)
{
if (item.ExecutionContext == null)
{
try
{
ExecuteSynchronously(null, item.Callback, item.State);
}
catch (Exception ex)
{
DispatchException(ex);
}
return;
}
// Perf - using a static thunk here to avoid a delegate allocation.
try
{
ExecutionContext.Run(item.ExecutionContext, ExecutionContextThunk, item);
}
catch (Exception ex)
{
DispatchException(ex);
}
}
private void DispatchException(Exception ex)
{
var handler = UnhandledException;
if (handler != null)
{
handler(this, new UnhandledExceptionEventArgs(ex, isTerminating: false));
}
}
private class State
{
public bool IsBusy; // Just for debugging
public object Lock = new object();
public Task Task = Task.CompletedTask;
public override string ToString()
{
return $"{{ Busy: {IsBusy}, Pending Task: {Task} }}";
}
}
private class WorkItem
{
public RendererSynchronizationContext SynchronizationContext;
public ExecutionContext ExecutionContext;
public SendOrPostCallback Callback;
public object State;
}
private class RendererSynchronizationTaskCompletionSource<TCallback, TResult> : TaskCompletionSource<TResult>
{
public RendererSynchronizationTaskCompletionSource(TCallback callback)
{
Callback = callback;
}
public TCallback Callback { get; }
}
}
}
| |
using Discord;
using Discord.Commands;
using Microsoft.Extensions.Configuration;
using MoreLinq;
using NoAdsHere.Commands.Blocks;
using NoAdsHere.Common;
using NoAdsHere.Common.Preconditions;
using NoAdsHere.Database.Entities.Guild;
using NoAdsHere.Database.UnitOfWork;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NoAdsHere.Commands.Ignores
{
[Name("Ignores"), Alias("Ignore"), Group("Ignores")]
public class IgnoreModule : ModuleBase<SocketCommandContext>
{
private readonly IConfigurationRoot _config;
private readonly IUnitOfWork _unit;
public IgnoreModule(IConfigurationRoot config, IUnitOfWork unit)
{
_config = config;
_unit = unit;
}
[Command("Add")]
[RequirePermission(AccessLevel.HighModerator)]
[Priority(-2)]
#pragma warning disable RECS0154 // Parameter is never used
public async Task AddHelp([Remainder] string remainder = null)
{
await ReplyAsync($"Correct Usage is: `{_config["Prefixes:Main"]} Ignore Add <Type> <Target>`");
}
[Command("Remove")]
[RequirePermission(AccessLevel.HighModerator)]
[Priority(-2)]
public async Task RemoveHelp([Remainder] string remainder = null)
#pragma warning restore RECS0154 // Parameter is never used
{
await ReplyAsync($"Correct Usage is: `{_config["Prefixes:Main"]} Ignore Remove <Type> <Target>`");
}
[Command("Add All")]
[RequirePermission(AccessLevel.HighModerator)]
public async Task AddAll(IGuildUser guildUser)
{
var newignores = new List<Ignore>();
foreach (BlockType type in Enum.GetValues(typeof(BlockType)))
{
newignores.Add(new Ignore(Context.Guild, guildUser, type));
}
var ignores = _unit.Ignores.Get(guildUser);
newignores = newignores.ExceptBy(ignores, ignore => ignore.BlockType).ToList();
if (newignores.Count != 0)
{
await _unit.Ignores.AddRangeAsync(newignores);
_unit.SaveChanges();
await ReplyAsync($":white_check_mark: Added missing whitelist entries for User {guildUser}`({guildUser.Id})`" +
$"\n`{string.Join(", ", newignores.Select(ignore => ignore.BlockType))}`");
}
else
{
await ReplyAsync($":exclamation: User {guildUser}`({guildUser.Id})` is already whitelisted for all blocktypes!");
}
}
[Command("Add All")]
[RequirePermission(AccessLevel.HighModerator)]
public async Task AddAll(IRole role)
{
var newignores = new List<Ignore>();
foreach (BlockType type in Enum.GetValues(typeof(BlockType)))
{
newignores.Add(new Ignore(Context.Guild, role, type));
}
var ignores = _unit.Ignores.Get(role);
newignores = newignores.ExceptBy(ignores, ignore => ignore.BlockType).ToList();
if (newignores.Count != 0)
{
await _unit.Ignores.AddRangeAsync(newignores);
_unit.SaveChanges();
await ReplyAsync($":white_check_mark: Added missing whitelist entries for Role {role}`(ID: {role.Id})`" +
$"\n`{string.Join(", ", newignores.Select(ignore => ignore.BlockType))}`");
}
else
{
await ReplyAsync($":exclamation: Role {role}`(ID: {role.Id})` is already whitelisted for all blocktypes!");
}
}
[Command("Remove All")]
[RequirePermission(AccessLevel.HighModerator)]
public async Task RemoveAll(IGuildUser guildUser)
{
var ignores = _unit.Ignores.Get(guildUser).ToList();
if (ignores.Any())
{
_unit.Ignores.RemoveRange(ignores);
_unit.SaveChanges();
await ReplyAsync($":white_check_mark: Removed User {guildUser}`(ID: {guildUser.Id})` from whitelist for" +
$"\n`{string.Join(", ", ignores.Select(ignore => ignore.BlockType))}`");
}
else
{
await ReplyAsync($":exclamation: User {guildUser}`(ID: {guildUser.Id})` is not whitelisted anywhere!");
}
}
[Command("Remove All")]
[RequirePermission(AccessLevel.HighModerator)]
public async Task RemoveAll(IRole role)
{
var ignores = _unit.Ignores.Get(role).ToList();
if (ignores.Any())
{
_unit.Ignores.RemoveRange(ignores);
_unit.SaveChanges();
await ReplyAsync($":white_check_mark: Removed Role {role}`(ID: {role.Id})` from whitelist for" +
$"\n`{string.Join(", ", ignores.Select(ignore => ignore.BlockType))}`");
}
else
{
await ReplyAsync($":exclamation: Role {role}`(ID: {role.Id})` is not whitelisted anywhere!");
}
}
[Command("Add")]
[RequirePermission(AccessLevel.HighModerator)]
public async Task Add(string blocktype, IGuildUser guildUser)
{
var type = BlockModule.ParseBlockType(blocktype.ToLower());
var ignores = _unit.Ignores.Get(guildUser);
if (ignores.All(ignore => ignore.BlockType != type))
{
var ignore = new Ignore(Context.Guild, guildUser, type);
await _unit.Ignores.AddAsync(ignore);
_unit.SaveChanges();
await ReplyAsync($":white_check_mark: Added User {guildUser}`(ID: {guildUser.Id})` to whitelist for blocktype `{type}`");
}
else
{
await ReplyAsync($":exclamation: User {guildUser}`(ID: {guildUser.Id})` is already whitelisted for blocktype `{type}`!");
}
}
[Command("Add")]
[RequirePermission(AccessLevel.HighModerator)]
public async Task Add(string blocktype, IRole role)
{
var type = BlockModule.ParseBlockType(blocktype.ToLower());
var ignores = _unit.Ignores.Get(role);
if (ignores.All(ignore => ignore.BlockType != type))
{
var ignore = new Ignore(Context.Guild, role, type);
await _unit.Ignores.AddAsync(ignore);
_unit.SaveChanges();
await ReplyAsync($":white_check_mark: Added Role {role}`(ID: {role.Id})` to whitelist for blocktype `{type}`");
}
else
{
await ReplyAsync($":exclamation: Role {role}`(ID: {role.Id})` is already whitelisted for blocktype `{type}`!");
}
}
[Command("Remove")]
[RequirePermission(AccessLevel.HighModerator)]
public async Task Remove(string blocktype, IGuildUser guildUser)
{
var type = BlockModule.ParseBlockType(blocktype.ToLower());
var ignore = _unit.Ignores.Get(guildUser).FirstOrDefault(ig => ig.BlockType == type);
if (ignore != null)
{
_unit.Ignores.Remove(ignore);
_unit.SaveChanges();
await ReplyAsync($":white_check_mark: Removed User {guildUser}`(ID: {guildUser.Id})` from whitelist for blocktype `{type}`");
}
else
{
await ReplyAsync($":exclamation: User {guildUser}`(ID: {guildUser.Id})` is not whitelisted for blocktype `{type}`!");
}
}
[Command("Remove")]
[RequirePermission(AccessLevel.HighModerator)]
public async Task Remove(string blocktype, IRole role)
{
var type = BlockModule.ParseBlockType(blocktype.ToLower());
var ignore = _unit.Ignores.Get(role).FirstOrDefault(ig => ig.BlockType == type);
if (ignore != null)
{
_unit.Ignores.Remove(ignore);
_unit.SaveChanges();
await ReplyAsync($":white_check_mark: Removed User {role}`(ID: {role.Id})` from whitelist for blocktype `{type}`");
}
else
{
await ReplyAsync($":exclamation: User {role}`(ID: {role.Id})` is not whitelisted for blocktype `{type}`!");
}
}
[Command("List")]
[RequirePermission(AccessLevel.Moderator)]
public async Task List()
{
var sb = new StringBuilder();
var ignores = await _unit.Ignores.GetAllAsync(Context.Guild);
sb.AppendLine("```");
foreach (var ignore in ignores.OrderBy(i => i.IgnoreType).GroupBy(i => i.IgnoredId))
{
switch (ignore.First().IgnoreType)
{
case IgnoreType.User:
sb.Append("USER: ");
var user = Context.Guild.GetUser(ignore.Key);
sb.Append(user != null ? user.ToString() : "USER LEFT");
sb.Append(" => ");
sb.AppendLine($"{string.Join(", ", ignore.Select(i => i.BlockType))} ");
break;
case IgnoreType.Role:
sb.Append("USER: ");
var role = Context.Guild.GetRole(ignore.Key);
sb.Append(role != null ? role.ToString() : "USER LEFT" + " ");
sb.Append(" => ");
sb.AppendLine($"{string.Join(", ", ignore.Select(i => i.BlockType))} ");
break;
}
}
sb.AppendLine("```");
if (sb.Length > 6)
await ReplyAsync(sb.ToString());
else
await ReplyAsync("Currently no ignores");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Joins;
using System.Reactive.Subjects;
using System.Threading;
namespace System.Reactive.Linq
{
public static partial class Observable
{
public static IObservable<IObservable<TSource>> Window<TSource> (
this IObservable<TSource> source,
int count)
{
return source.Window (TimeSpan.MaxValue, count);
}
public static IObservable<IObservable<TSource>> Window<TSource> (
this IObservable<TSource> source,
TimeSpan timeSpan)
{
return source.Window (timeSpan, int.MaxValue);
}
struct SubjectCountContext<TSource>
{
public SubjectCountContext (int start, ISubject<TSource> subject)
{
this.start = start;
this.subject = subject;
}
readonly int start;
readonly ISubject<TSource> subject;
public int Start {
get { return start; }
}
public ISubject<TSource> Subject {
get { return subject; }
}
}
public static IObservable<IObservable<TSource>> Window<TSource> (
this IObservable<TSource> source,
int count,
int skip)
{
if (source == null)
throw new ArgumentNullException ("source");
if (count < 0)
throw new ArgumentOutOfRangeException ("timeSpan");
if (skip < 0)
throw new ArgumentOutOfRangeException ("timeShift");
return new ColdObservableEach<IObservable<TSource>> (sub => {
// ----
var subjects = new List<SubjectCountContext<TSource>> ();
int nextStart = 0;
int current = 0;
var dis = source.Subscribe (Observer.Create<TSource> (v => {
if (nextStart == current) {
var sc = new SubjectCountContext<TSource> (nextStart, new ReplaySubject<TSource> ());
subjects.Add (sc);
sub.OnNext (sc.Subject);
nextStart += skip;
}
for (int x = 0; x < subjects.Count; ) {
if (current - subjects [x].Start == count) {
subjects [x].Subject.OnCompleted ();
subjects.RemoveAt (x);
}
else
subjects [x++].Subject.OnNext (v);
}
current++;
}, ex => sub.OnError (ex), () => { foreach (var sc in subjects) sc.Subject.OnCompleted (); sub.OnCompleted (); }));
return dis;
// ----
}, DefaultColdScheduler);
}
public static IObservable<IObservable<TSource>> Window<TSource> (
this IObservable<TSource> source,
TimeSpan timeSpan,
int count)
{
return source.Window (timeSpan, count, Scheduler.ThreadPool);
}
public static IObservable<IObservable<TSource>> Window<TSource> (
this IObservable<TSource> source,
TimeSpan timeSpan,
IScheduler scheduler)
{
return source.Window (timeSpan, int.MaxValue, scheduler);
}
public static IObservable<IObservable<TSource>> Window<TSource> (
this IObservable<TSource> source,
TimeSpan timeSpan,
TimeSpan timeShift)
{
return source.Window (timeSpan, timeShift, Scheduler.ThreadPool);
}
public static IObservable<IObservable<TSource>> Window<TSource> (
this IObservable<TSource> source,
TimeSpan timeSpan,
int count,
IScheduler scheduler)
{
if (source == null)
throw new ArgumentNullException ("source");
if (scheduler == null)
throw new ArgumentNullException ("scheduler");
return new ColdObservableEach<IObservable<TSource>> (sub => {
// ----
var counter = new Subject<Unit> ();
var l = new Subject<TSource> ();
var dis = new CompositeDisposable ();
dis.Add (source.Subscribe (
v => { l.OnNext (v); counter.OnNext (Unit.Default); },
ex => sub.OnError (ex),
() => { sub.OnNext (l); sub.OnCompleted (); }));
var buffer = new TimeOrCountObservable (timeSpan, counter, count, scheduler);
dis.Add (buffer.Subscribe (u => {
var n = l;
l = new Subject<TSource> ();
sub.OnNext (n);
}, ex => sub.OnError (ex), () => {}));
return dis;
// ----
}, scheduler);
}
struct SubjectTimeShiftContext<TSource>
{
public SubjectTimeShiftContext (DateTimeOffset start, ISubject<TSource> sub)
{
this.start = start;
this.sub = sub;
}
readonly DateTimeOffset start;
readonly ISubject<TSource> sub;
public DateTimeOffset Start {
get { return start; }
}
public ISubject<TSource> Subject {
get { return sub; }
}
}
public static IObservable<IObservable<TSource>> Window<TSource> (
this IObservable<TSource> source,
TimeSpan timeSpan,
TimeSpan timeShift,
IScheduler scheduler)
{
if (source == null)
throw new ArgumentNullException ("source");
if (scheduler == null)
throw new ArgumentNullException ("scheduler");
if (timeSpan < TimeSpan.Zero)
throw new ArgumentOutOfRangeException ("timeSpan");
if (timeShift < TimeSpan.Zero)
throw new ArgumentOutOfRangeException ("timeShift");
return new ColdObservableEach<IObservable<TSource>> (sub => {
// ----
var subjects = new List<SubjectTimeShiftContext<TSource>> ();
DateTimeOffset nextStart = scheduler.Now;
var dis = new CompositeDisposable ();
dis.Add (source.Subscribe (Observer.Create<TSource> (v => {
if (nextStart <= scheduler.Now) {
var lc = new SubjectTimeShiftContext<TSource> (nextStart, new ReplaySubject<TSource> ());
subjects.Add (lc);
sub.OnNext (lc.Subject);
nextStart += timeShift;
var ddis = new SingleAssignmentDisposable ();
ddis.Disposable = scheduler.Schedule (timeSpan, () => {
lc.Subject.OnCompleted ();
subjects.Remove (lc);
dis.Remove (ddis);
});
}
for (int x = 0; x < subjects.Count; x++)
// This check makes sense when the event was published *at the same time* the subject ends its life time by timeSpan.
if (scheduler.Now - subjects [x].Start < timeSpan)
subjects [x].Subject.OnNext (v);
}, ex => sub.OnError (ex), () => { foreach (var sc in subjects) sc.Subject.OnCompleted (); sub.OnCompleted (); })));
return dis;
// ----
}, DefaultColdScheduler);
}
public static IObservable<IObservable<TSource>> Window<TSource, TWindowClosing> (
this IObservable<TSource> source,
Func<IObservable<TWindowClosing>> windowClosingSelector)
{
return Window<TSource, int, TWindowClosing> (source, Range (0, int.MaxValue), l => windowClosingSelector ());
}
public static IObservable<IObservable<TSource>> Window<TSource, TWindowOpening, TWindowClosing> (
this IObservable<TSource> source,
IObservable<TWindowOpening> windowOpenings,
Func<TWindowOpening, IObservable<TWindowClosing>> windowClosingSelector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (windowOpenings == null)
throw new ArgumentNullException ("windowOpenings");
if (windowClosingSelector == null)
throw new ArgumentNullException ("windowClosingSelector");
return new ColdObservableEach<IObservable<TSource>> (sub => {
// ----
var l = new Subject<TSource> ();
var dis = new CompositeDisposable ();
var disClosings = new CompositeDisposable ();
dis.Add (windowOpenings.Subscribe (s => {
var closing = windowClosingSelector (s);
disClosings.Add (closing.Subscribe (c => {
sub.OnNext (l);
l = new Subject<TSource> ();
}));
}, ex => sub.OnError (ex), () => disClosings.Dispose ()));
dis.Add (source.Subscribe (
s => l.OnNext (s), ex => sub.OnError (ex), () => {
sub.OnNext (l);
sub.OnCompleted ();
}
));
return dis;
// ----
}, DefaultColdScheduler);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Storage.Models
{
using Azure;
using Management;
using Storage;
using Rest;
using Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The storage account.
/// </summary>
[JsonTransformation]
public partial class StorageAccount : Resource
{
/// <summary>
/// Initializes a new instance of the StorageAccount class.
/// </summary>
public StorageAccount()
{
}
/// <summary>
/// Initializes a new instance of the StorageAccount class.
/// </summary>
/// <param name="id">Resource Id</param>
/// <param name="name">Resource name</param>
/// <param name="type">Resource type</param>
/// <param name="location">Resource location</param>
/// <param name="tags">Tags assigned to a resource; can be used for
/// viewing and grouping a resource (across resource groups).</param>
/// <param name="sku">Gets the SKU.</param>
/// <param name="kind">Gets the Kind. Possible values include:
/// 'Storage', 'BlobStorage'</param>
/// <param name="provisioningState">Gets the status of the storage
/// account at the time the operation was called. Possible values
/// include: 'Creating', 'ResolvingDNS', 'Succeeded'</param>
/// <param name="primaryEndpoints">Gets the URLs that are used to
/// perform a retrieval of a public blob, queue, or table object. Note
/// that Standard_ZRS and Premium_LRS accounts only return the blob
/// endpoint.</param>
/// <param name="primaryLocation">Gets the location of the primary data
/// center for the storage account.</param>
/// <param name="statusOfPrimary">Gets the status indicating whether
/// the primary location of the storage account is available or
/// unavailable. Possible values include: 'available',
/// 'unavailable'</param>
/// <param name="lastGeoFailoverTime">Gets the timestamp of the most
/// recent instance of a failover to the secondary location. Only the
/// most recent timestamp is retained. This element is not returned if
/// there has never been a failover instance. Only available if the
/// accountType is Standard_GRS or Standard_RAGRS.</param>
/// <param name="secondaryLocation">Gets the location of the
/// geo-replicated secondary for the storage account. Only available if
/// the accountType is Standard_GRS or Standard_RAGRS.</param>
/// <param name="statusOfSecondary">Gets the status indicating whether
/// the secondary location of the storage account is available or
/// unavailable. Only available if the SKU name is Standard_GRS or
/// Standard_RAGRS. Possible values include: 'available',
/// 'unavailable'</param>
/// <param name="creationTime">Gets the creation date and time of the
/// storage account in UTC.</param>
/// <param name="customDomain">Gets the custom domain the user assigned
/// to this storage account.</param>
/// <param name="secondaryEndpoints">Gets the URLs that are used to
/// perform a retrieval of a public blob, queue, or table object from
/// the secondary location of the storage account. Only available if
/// the SKU name is Standard_RAGRS.</param>
/// <param name="encryption">Gets the encryption settings on the
/// account. If unspecified, the account is unencrypted.</param>
/// <param name="accessTier">Required for storage accounts where kind =
/// BlobStorage. The access tier used for billing. Possible values
/// include: 'Hot', 'Cool'</param>
/// <param name="enableHttpsTrafficOnly">Allows https traffic only to
/// storage service if sets to true.</param>
public StorageAccount(string id = default(string), string name = default(string), string type = default(string), string location = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), Sku sku = default(Sku), Kind? kind = default(Kind?), ProvisioningState? provisioningState = default(ProvisioningState?), Endpoints primaryEndpoints = default(Endpoints), string primaryLocation = default(string), AccountStatus? statusOfPrimary = default(AccountStatus?), System.DateTime? lastGeoFailoverTime = default(System.DateTime?), string secondaryLocation = default(string), AccountStatus? statusOfSecondary = default(AccountStatus?), System.DateTime? creationTime = default(System.DateTime?), CustomDomain customDomain = default(CustomDomain), Endpoints secondaryEndpoints = default(Endpoints), Encryption encryption = default(Encryption), AccessTier? accessTier = default(AccessTier?), bool? enableHttpsTrafficOnly = default(bool?))
: base(id, name, type, location, tags)
{
Sku = sku;
Kind = kind;
ProvisioningState = provisioningState;
PrimaryEndpoints = primaryEndpoints;
PrimaryLocation = primaryLocation;
StatusOfPrimary = statusOfPrimary;
LastGeoFailoverTime = lastGeoFailoverTime;
SecondaryLocation = secondaryLocation;
StatusOfSecondary = statusOfSecondary;
CreationTime = creationTime;
CustomDomain = customDomain;
SecondaryEndpoints = secondaryEndpoints;
Encryption = encryption;
AccessTier = accessTier;
EnableHttpsTrafficOnly = enableHttpsTrafficOnly;
}
/// <summary>
/// Gets the SKU.
/// </summary>
[JsonProperty(PropertyName = "sku")]
public Sku Sku { get; protected set; }
/// <summary>
/// Gets the Kind. Possible values include: 'Storage', 'BlobStorage'
/// </summary>
[JsonProperty(PropertyName = "kind")]
public Kind? Kind { get; protected set; }
/// <summary>
/// Gets the status of the storage account at the time the operation
/// was called. Possible values include: 'Creating', 'ResolvingDNS',
/// 'Succeeded'
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public ProvisioningState? ProvisioningState { get; protected set; }
/// <summary>
/// Gets the URLs that are used to perform a retrieval of a public
/// blob, queue, or table object. Note that Standard_ZRS and
/// Premium_LRS accounts only return the blob endpoint.
/// </summary>
[JsonProperty(PropertyName = "properties.primaryEndpoints")]
public Endpoints PrimaryEndpoints { get; protected set; }
/// <summary>
/// Gets the location of the primary data center for the storage
/// account.
/// </summary>
[JsonProperty(PropertyName = "properties.primaryLocation")]
public string PrimaryLocation { get; protected set; }
/// <summary>
/// Gets the status indicating whether the primary location of the
/// storage account is available or unavailable. Possible values
/// include: 'available', 'unavailable'
/// </summary>
[JsonProperty(PropertyName = "properties.statusOfPrimary")]
public AccountStatus? StatusOfPrimary { get; protected set; }
/// <summary>
/// Gets the timestamp of the most recent instance of a failover to the
/// secondary location. Only the most recent timestamp is retained.
/// This element is not returned if there has never been a failover
/// instance. Only available if the accountType is Standard_GRS or
/// Standard_RAGRS.
/// </summary>
[JsonProperty(PropertyName = "properties.lastGeoFailoverTime")]
public System.DateTime? LastGeoFailoverTime { get; protected set; }
/// <summary>
/// Gets the location of the geo-replicated secondary for the storage
/// account. Only available if the accountType is Standard_GRS or
/// Standard_RAGRS.
/// </summary>
[JsonProperty(PropertyName = "properties.secondaryLocation")]
public string SecondaryLocation { get; protected set; }
/// <summary>
/// Gets the status indicating whether the secondary location of the
/// storage account is available or unavailable. Only available if the
/// SKU name is Standard_GRS or Standard_RAGRS. Possible values
/// include: 'available', 'unavailable'
/// </summary>
[JsonProperty(PropertyName = "properties.statusOfSecondary")]
public AccountStatus? StatusOfSecondary { get; protected set; }
/// <summary>
/// Gets the creation date and time of the storage account in UTC.
/// </summary>
[JsonProperty(PropertyName = "properties.creationTime")]
public System.DateTime? CreationTime { get; protected set; }
/// <summary>
/// Gets the custom domain the user assigned to this storage account.
/// </summary>
[JsonProperty(PropertyName = "properties.customDomain")]
public CustomDomain CustomDomain { get; protected set; }
/// <summary>
/// Gets the URLs that are used to perform a retrieval of a public
/// blob, queue, or table object from the secondary location of the
/// storage account. Only available if the SKU name is Standard_RAGRS.
/// </summary>
[JsonProperty(PropertyName = "properties.secondaryEndpoints")]
public Endpoints SecondaryEndpoints { get; protected set; }
/// <summary>
/// Gets the encryption settings on the account. If unspecified, the
/// account is unencrypted.
/// </summary>
[JsonProperty(PropertyName = "properties.encryption")]
public Encryption Encryption { get; protected set; }
/// <summary>
/// Gets required for storage accounts where kind = BlobStorage. The
/// access tier used for billing. Possible values include: 'Hot',
/// 'Cool'
/// </summary>
[JsonProperty(PropertyName = "properties.accessTier")]
public AccessTier? AccessTier { get; protected set; }
/// <summary>
/// Gets or sets allows https traffic only to storage service if sets
/// to true.
/// </summary>
[JsonProperty(PropertyName = "properties.supportsHttpsTrafficOnly")]
public bool? EnableHttpsTrafficOnly { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Sku != null)
{
Sku.Validate();
}
if (CustomDomain != null)
{
CustomDomain.Validate();
}
}
}
}
| |
using System;
using Csla;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERCLevel;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H09_Region_Child (editable child object).<br/>
/// This is a generated base class of <see cref="H09_Region_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="H08_Region"/> collection.
/// </remarks>
[Serializable]
public partial class H09_Region_Child : BusinessBase<H09_Region_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Cities Child Name");
/// <summary>
/// Gets or sets the Cities Child Name.
/// </summary>
/// <value>The Cities Child Name.</value>
public string Region_Child_Name
{
get { return GetProperty(Region_Child_NameProperty); }
set { SetProperty(Region_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H09_Region_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H09_Region_Child"/> object.</returns>
internal static H09_Region_Child NewH09_Region_Child()
{
return DataPortal.CreateChild<H09_Region_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="H09_Region_Child"/> object, based on given parameters.
/// </summary>
/// <param name="region_ID1">The Region_ID1 parameter of the H09_Region_Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="H09_Region_Child"/> object.</returns>
internal static H09_Region_Child GetH09_Region_Child(int region_ID1)
{
return DataPortal.FetchChild<H09_Region_Child>(region_ID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H09_Region_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 H09_Region_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="H09_Region_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="H09_Region_Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="region_ID1">The Region ID1.</param>
protected void Child_Fetch(int region_ID1)
{
var args = new DataPortalHookArgs(region_ID1);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var dal = dalManager.GetProvider<IH09_Region_ChildDal>();
var data = dal.Fetch(region_ID1);
Fetch(data);
}
OnFetchPost(args);
}
/// <summary>
/// Loads a <see cref="H09_Region_Child"/> object from the given <see cref="H09_Region_ChildDto"/>.
/// </summary>
/// <param name="data">The H09_Region_ChildDto to use.</param>
private void Fetch(H09_Region_ChildDto data)
{
// Value properties
LoadProperty(Region_Child_NameProperty, data.Region_Child_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="H09_Region_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(H08_Region parent)
{
var dto = new H09_Region_ChildDto();
dto.Parent_Region_ID = parent.Region_ID;
dto.Region_Child_Name = Region_Child_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IH09_Region_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H09_Region_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(H08_Region parent)
{
if (!IsDirty)
return;
var dto = new H09_Region_ChildDto();
dto.Parent_Region_ID = parent.Region_ID;
dto.Region_Child_Name = Region_Child_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IH09_Region_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="H09_Region_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(H08_Region parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IH09_Region_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Region_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
}
}
| |
// Prexonite
//
// Copyright (c) 2014, Christian Klauser
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// The names of the 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.Diagnostics;
using JetBrains.Annotations;
using Prexonite.Compiler.Symbolic;
using Prexonite.Properties;
namespace Prexonite.Compiler.Internal
{
public class SymbolMExprParser
{
[NotNull] private readonly ISymbolView<Symbol> _symbols;
[NotNull] private readonly ISymbolView<Symbol> _topLevelSymbols;
[NotNull] private readonly IMessageSink _messageSink;
public SymbolMExprParser([NotNull] ISymbolView<Symbol> symbols,[NotNull] IMessageSink messageSink, [NotNull]ISymbolView<Symbol> topLevelSymbols = null)
{
if (symbols == null)
throw new ArgumentNullException("symbols");
if (messageSink == null)
throw new ArgumentNullException("messageSink");
_symbols = symbols;
_messageSink = messageSink;
_topLevelSymbols = topLevelSymbols ?? symbols;
}
public const string HerePositionHead = "here";
public const string AbsoluteModifierHead = "absolute";
private bool _tryParseCrossReference(MExpr expr, [NotNull] ISymbolView<Symbol> symbols, out Symbol symbol)
{
symbol = null;
List<MExpr> elements;
if (!expr.TryMatchHead(SymbolMExprSerializer.CrossReferenceHead, out elements))
return false;
var currentScope = symbols;
for (var i = 0; i < elements.Count; i++)
{
var element = elements[i];
string symbolName;
if (!element.TryMatchStringAtom(out symbolName))
throw new ErrorMessageException(Message.Error(
string.Format("Symbolic reference must be consist only of symbol names. Found {0} {1} instead.", (element != null ? element.GetType().ToString() : ""), element),
element.Position, MessageClasses.SymbolNotResolved));
if (!currentScope.TryGet(symbolName, out symbol))
throw new ErrorMessageException(
Message.Error(
String.Format("Cannot find symbol {0} referred to by delcaration {1}.", symbolName, expr),
expr.Position, MessageClasses.SymbolNotResolved));
// If this is not the last element in the sequence, it must refer to a namespace symbol
if (i < elements.Count - 1)
{
var errors = new List<Message>();
var nsSym = NamespaceSymbol.UnwrapNamespaceSymbol(symbol, element.Position, _messageSink, errors);
Message abortMessage = null;
foreach (var error in errors)
{
if (abortMessage == null)
abortMessage = error;
else
_messageSink.ReportMessage(error);
}
if (abortMessage != null)
throw new ErrorMessageException(abortMessage);
// Impossible. Condition required to convey that fact to null-analysis
if (nsSym == null)
throw new PrexoniteException("Namespace symbol was expected to exist. Internal error (\"impossible condition\").");
currentScope = nsSym.Namespace;
}
}
if (symbol == null)
throw new ErrorMessageException(Message.Error(
Resources.SymbolMExprParser_EmptySymbolicReference, expr.Position,
MessageClasses.SymbolNotResolved));
return true;
}
[NotNull]
public Symbol Parse( [NotNull] MExpr expr)
{
MExpr innerSymbolExpr;
Symbol innerSymbol;
List<MExpr> elements;
object raw;
if (expr.TryMatchHead(SymbolMExprSerializer.DereferenceHead, out innerSymbolExpr))
{
innerSymbol = Parse(innerSymbolExpr);
return Symbol.CreateDereference(innerSymbol, expr.Position);
}
else if (_tryParseCrossReference(expr, _symbols, out innerSymbol))
{
return innerSymbol;
}
else if (expr.TryMatchHead(AbsoluteModifierHead, out innerSymbolExpr) && _tryParseCrossReference(innerSymbolExpr,_topLevelSymbols,out innerSymbol))
{
return innerSymbol;
}
else if (expr.TryMatchHead(SymbolMExprSerializer.ErrorHead, out elements) && elements.Count == 4)
{
return _parseMessage(MessageSeverity.Error, expr, elements);
}
else if (expr.TryMatchHead(SymbolMExprSerializer.WarningHead, out elements) && elements.Count == 4)
{
return _parseMessage(MessageSeverity.Warning, expr, elements);
}
else if (expr.TryMatchHead(SymbolMExprSerializer.InfoHead, out elements) && elements.Count == 4)
{
return _parseMessage(MessageSeverity.Info, expr, elements);
}
else if (expr.TryMatchHead(SymbolMExprSerializer.ExpandHead, out innerSymbolExpr))
{
innerSymbol = Parse(innerSymbolExpr);
return Symbol.CreateExpand(innerSymbol, expr.Position);
}
else if (expr.TryMatchAtom(out raw) && raw == null)
{
return Symbol.CreateNil(expr.Position);
}
else
{
// must be a reference
return Symbol.CreateReference(EntityRefMExprParser.Parse(expr), expr.Position);
}
}
[NotNull]
private Symbol _parseMessage(MessageSeverity severity,
[NotNull] MExpr expr, [NotNull] List<MExpr> elements)
{
Debug.Assert(elements[0] != null);
Debug.Assert(elements[1] != null);
Debug.Assert(elements[2] != null);
Debug.Assert(elements[3] != null);
var position = _parsePosition(elements[0]);
object rawMessageClass;
string messageText;
if (elements[1].TryMatchAtom(out rawMessageClass) && elements[2].TryMatchStringAtom(out messageText))
{
var message = Message.Create(severity, messageText, position,
(rawMessageClass == null ? null : rawMessageClass.ToString()));
return Symbol.CreateMessage(message, Parse(elements[3]), expr.Position);
}
else
{
throw new ErrorMessageException(
Message.Error(String.Format(Resources.Parser_Cannot_parse_message_symbol, expr),
expr.Position, MessageClasses.CannotParseMExpr));
}
}
[NotNull]
private static ISourcePosition _parsePosition([NotNull] MExpr expr)
{
MExpr fileExpr;
MExpr lineExpr;
MExpr columnExpr;
string file;
int line;
int column;
List<MExpr> hereArgs;
if (expr.TryMatchHead(SymbolMExprSerializer.SourcePositionHead, out fileExpr, out lineExpr,
out columnExpr)
&& fileExpr.TryMatchStringAtom(out file)
&& lineExpr.TryMatchIntAtom(out line)
&& columnExpr.TryMatchIntAtom(out column))
{
return new SourcePosition(file, line, column);
}
else if(expr.TryMatchHead(HerePositionHead, out hereArgs))
{
return expr.Position;
}
else
{
throw new ErrorMessageException(
Message.Error(String.Format(Resources.Parser_Cannot_parse_source_position, expr), expr.Position,
MessageClasses.CannotParseMExpr));
}
}
}
}
| |
// Copyright 2012 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NodaTime.Extensions;
using NodaTime.TimeZones;
using NUnit.Framework;
namespace NodaTime.Test.TimeZones
{
[TestFixture]
public class TzdbDateTimeZoneSourceTest
{
private static readonly List<TimeZoneInfo> SystemTimeZones = TimeZoneInfo.GetSystemTimeZones().ToList();
[Test]
[TestCase("UTC", "Etc/GMT")]
[TestCase("GMT Standard Time", "Europe/London")]
// Standard name differs from ID under Windows
[TestCase("Israel Standard Time", "Asia/Jerusalem")]
public void ZoneMapping(string bclId, string tzdbId)
{
try
{
var source = TzdbDateTimeZoneSource.Default;
var bclZone = TimeZoneInfo.FindSystemTimeZoneById(bclId);
Assert.AreEqual(tzdbId, source.MapTimeZoneId(bclZone));
}
catch (TimeZoneNotFoundException)
{
// This may occur on Mono, for example.
Assert.Ignore("Test assumes existence of BCL zone with ID: " + bclId);
}
}
/// <summary>
/// Tests that we can load (and exercise) the binary Tzdb resource file distributed with Noda Time 1.1.0.
/// This is effectively a black-box regression test that ensures that the stream format has not changed in a
/// way such that a custom tzdb compiled with ZoneInfoCompiler from 1.1 would become unreadable.
/// </summary>
[Test]
public void CanLoadNodaTimeResourceFromOnePointOneRelease()
{
var assembly = typeof(TzdbDateTimeZoneSourceTest).Assembly;
TzdbDateTimeZoneSource source;
using (Stream stream = assembly.GetManifestResourceStream("NodaTime.Test.TestData.Tzdb2013bFromNodaTime1.1.nzd"))
{
source = TzdbDateTimeZoneSource.FromStream(stream);
}
Assert.AreEqual("TZDB: 2013b (mapping: 8274)", source.VersionId);
var utc = Instant.FromUtc(2007, 8, 24, 9, 30, 0);
// Test a regular zone with rules.
var london = source.ForId("Europe/London");
var inLondon = new ZonedDateTime(utc, london);
var expectedLocal = new LocalDateTime(2007, 8, 24, 10, 30);
Assert.AreEqual(expectedLocal, inLondon.LocalDateTime);
// Test a fixed-offset zone.
var utcFixed = source.ForId("Etc/UTC");
var inUtcFixed = new ZonedDateTime(utc, utcFixed);
expectedLocal = new LocalDateTime(2007, 8, 24, 9, 30);
Assert.AreEqual(expectedLocal, inUtcFixed.LocalDateTime);
// Test an alias.
var jersey = source.ForId("Japan"); // Asia/Tokyo
var inJersey = new ZonedDateTime(utc, jersey);
expectedLocal = new LocalDateTime(2007, 8, 24, 18, 30);
Assert.AreEqual(expectedLocal, inJersey.LocalDateTime);
// Test ZoneLocations.
var france = source.ZoneLocations.Single(g => g.CountryName == "France");
// Tolerance of about 2 seconds
Assert.AreEqual(48.86666, france.Latitude, 0.00055);
Assert.AreEqual(2.3333, france.Longitude, 0.00055);
Assert.AreEqual("Europe/Paris", france.ZoneId);
Assert.AreEqual("FR", france.CountryCode);
Assert.AreEqual("", france.Comment);
}
/// <summary>
/// Simply tests that every ID in the built-in database can be fetched. This is also
/// helpful for diagnostic debugging when we want to check that some potential
/// invariant holds for all time zones...
/// </summary>
[Test]
public void ForId_AllIds()
{
var source = TzdbDateTimeZoneSource.Default;
foreach (string id in source.GetIds())
{
Assert.IsNotNull(source.ForId(id));
}
}
[Test]
public void ForId_Null()
{
Assert.Throws<ArgumentNullException>(() => TzdbDateTimeZoneSource.Default.ForId(null));
}
[Test]
public void ForId_Unknown()
{
Assert.Throws<ArgumentException>(() => TzdbDateTimeZoneSource.Default.ForId("unknown"));
}
[Test]
public void UtcEqualsBuiltIn()
{
var zone = TzdbDateTimeZoneSource.Default.ForId("UTC");
Assert.AreEqual(DateTimeZone.Utc, zone);
}
// The following tests all make assumptions about the built-in TZDB data.
// This is simpler than constructing fake data, and validates that the creation
// mechanism matches the reading mechanism, too.
[Test]
public void Aliases()
{
var aliases = TzdbDateTimeZoneSource.Default.Aliases;
CollectionAssert.AreEqual(new[] { "Europe/Belfast", "Europe/Guernsey", "Europe/Isle_of_Man", "Europe/Jersey", "GB", "GB-Eire" },
aliases["Europe/London"].ToArray()); // ToArray call makes diagnostics more useful
CollectionAssert.IsOrdered(aliases["Europe/London"]);
CollectionAssert.IsEmpty(aliases["Europe/Jersey"]);
}
[Test]
public void CanonicalIdMap_Contents()
{
var map = TzdbDateTimeZoneSource.Default.CanonicalIdMap;
Assert.AreEqual("Europe/London", map["Europe/Jersey"]);
Assert.AreEqual("Europe/London", map["Europe/London"]);
}
[Test]
public void CanonicalIdMap_IsReadOnly()
{
var map = TzdbDateTimeZoneSource.Default.CanonicalIdMap;
Assert.Throws<NotSupportedException>(() => map.Add("Foo", "Bar"));
}
// Sample zone location checks to ensure we've serialized and deserialized correctly
// Input line: FR +4852+00220 Europe/Paris
[Test]
public void ZoneLocations_ContainsFrance()
{
var zoneLocations = TzdbDateTimeZoneSource.Default.ZoneLocations;
var france = zoneLocations.Single(g => g.CountryName == "France");
// Tolerance of about 2 seconds
Assert.AreEqual(48.86666, france.Latitude, 0.00055);
Assert.AreEqual(2.3333, france.Longitude, 0.00055);
Assert.AreEqual("Europe/Paris", france.ZoneId);
Assert.AreEqual("FR", france.CountryCode);
Assert.AreEqual("", france.Comment);
}
// Sample zone location checks to ensure we've serialized and deserialized correctly
// Input line: GB,GG,IM,JE +513030-0000731 Europe/London
[Test]
public void Zone1970Locations_ContainsBritain()
{
var zoneLocations = TzdbDateTimeZoneSource.Default.Zone1970Locations;
var britain = zoneLocations.Single(g => g.ZoneId == "Europe/London");
// Tolerance of about 2 seconds
Assert.AreEqual(51.5083, britain.Latitude, 0.00055);
Assert.AreEqual(-0.1253, britain.Longitude, 0.00055);
Assert.AreEqual("Europe/London", britain.ZoneId);
CollectionAssert.AreEqual(
new[]
{
new TzdbZone1970Location.Country("Britain (UK)", "GB"),
new TzdbZone1970Location.Country("Guernsey", "GG"),
new TzdbZone1970Location.Country("Isle of Man", "IM"),
new TzdbZone1970Location.Country("Jersey", "JE")
},
britain.Countries.ToArray());
Assert.AreEqual("", britain.Comment);
}
// Input line: CA +744144-0944945 America/Resolute Central Time - Resolute, Nunavut
// (Note: prior to 2014f, this was "Central Standard Time - Resolute, Nunavut".)
[Test]
public void ZoneLocations_ContainsResolute()
{
var zoneLocations = TzdbDateTimeZoneSource.Default.ZoneLocations;
var resolute = zoneLocations.Single(g => g.ZoneId == "America/Resolute");
// Tolerance of about 2 seconds
Assert.AreEqual(74.69555, resolute.Latitude, 0.00055);
Assert.AreEqual(-94.82916, resolute.Longitude, 0.00055);
Assert.AreEqual("Canada", resolute.CountryName);
Assert.AreEqual("CA", resolute.CountryCode);
Assert.AreEqual("Central Time - Resolute, Nunavut", resolute.Comment);
}
[Test]
public void TzdbVersion()
{
var source = TzdbDateTimeZoneSource.Default;
StringAssert.StartsWith("201", source.TzdbVersion);
}
[Test]
public void FixedDateTimeZoneName()
{
var zulu = DateTimeZoneProviders.Tzdb["Etc/Zulu"];
Assert.AreEqual("UTC", zulu.GetZoneInterval(NodaConstants.UnixEpoch).Name);
}
[Test]
public void VersionId()
{
var source = TzdbDateTimeZoneSource.Default;
StringAssert.StartsWith("TZDB: " + source.TzdbVersion, source.VersionId);
}
// Note: this test doesn't check that the intervals are right; it checks that they haven't changed since
// we last generated them, typically in response to a TZDB update. It means we can change the time zone code
// with more confidence.
[Test]
public void CheckDump()
{
List<string> expected;
var assembly = typeof(TzdbDateTimeZoneSourceTest).Assembly;
using (Stream stream = assembly.GetManifestResourceStream("NodaTime.Test.TestData.tzdb-dump.txt"))
{
using (var reader = new StreamReader(stream))
{
expected = ReadLines(reader);
}
}
List<string> actual;
using (var writer = new StringWriter())
{
DateTimeZoneProviders.Tzdb.Dump(writer);
actual = ReadLines(new StringReader(writer.ToString()));
}
// We can improve the diagnostics here if and when we need to. Given that Collections.Assert
// says which index (i.e. line - 1) the inputs differ on, it's not hard to then look at tzdb-dump.txt for context.
CollectionAssert.AreEqual(expected, actual);
}
private static List<string> ReadLines(TextReader reader)
{
var ret = new List<string>();
string line;
while ((line = reader.ReadLine()) != null)
{
ret.Add(line);
}
return ret;
}
// We should be able to use TestCaseSource to call TimeZoneInfo.GetSystemTimeZones directly,
// but that appears to fail under Mono.
[Test]
[TestCaseSource(nameof(SystemTimeZones))]
public void GuessZoneIdByTransitionsUncached(TimeZoneInfo bclZone)
{
// As of October 17th 2013, the Windows time zone database hasn't noticed that
// Morocco delayed the DST transition in 2013, so we end up with UTC. It's
// annoying, but it's not actually a code issue. Just ignore it for now. We
// should check this periodically and remove the hack when it works again.
// Likewise Libya has somewhat odd representation in the BCL. Worth looking at more closely later.
if (bclZone.Id == "Morocco Standard Time" || bclZone.Id == "Libya Standard Time")
{
return;
}
string id = TzdbDateTimeZoneSource.Default.GuessZoneIdByTransitionsUncached(bclZone);
// Unmappable zones may not be mapped, or may be mapped to something reasonably accurate.
// We don't mind either way.
if (!TzdbDateTimeZoneSource.Default.WindowsMapping.PrimaryMapping.ContainsKey(bclZone.Id))
{
return;
}
Assert.IsNotNull(id);
var tzdbZone = TzdbDateTimeZoneSource.Default.ForId(id);
var thisYear = SystemClock.Instance.GetCurrentInstant().InUtc().Year;
LocalDate? lastIncorrectDate = null;
Offset? lastIncorrectBclOffset = null;
Offset? lastIncorrectTzdbOffset = null;
int total = 0;
int correct = 0;
// From the start of this year to the end of next year, we should have an 80% hit rate or better.
// That's stronger than the 70% we limit to in the code, because if it starts going between 70% and 80% we
// should have another look at the algorithm. (And this is dealing with 80% of days, not 80% of transitions,
// so it's not quite equivalent anyway.)
for (var date = new LocalDate(thisYear, 1, 1); date.Year < thisYear + 2; date = date.PlusDays(1))
{
Instant startOfUtcDay = date.AtMidnight().InUtc().ToInstant();
Offset tzdbOffset = tzdbZone.GetUtcOffset(startOfUtcDay);
Offset bclOffset = Offset.FromTimeSpan(bclZone.GetUtcOffset(startOfUtcDay.ToDateTimeOffset()));
if (tzdbOffset == bclOffset)
{
correct++;
}
else
{
// Useful for debugging (by having somewhere to put a breakpoint) as well as for the message.
lastIncorrectDate = date;
lastIncorrectBclOffset = bclOffset;
lastIncorrectTzdbOffset = tzdbOffset;
}
total++;
}
Assert.That(correct * 100.0 / total, Is.GreaterThanOrEqualTo(75.0),
"Last incorrect date for {0} vs {1}: {2} (BCL: {3}; TZDB: {4})",
bclZone.Id,
id,
lastIncorrectDate, lastIncorrectBclOffset, lastIncorrectTzdbOffset);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Threading.Tasks;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Phone.Info;
using Put.io.Api.UrlHelper;
using Put.io.Core.Common;
using Put.io.Core.InvokeSynchronising;
using Put.io.Core.ProgressTracking;
using Put.io.Core.Storage;
namespace Put.io.Core.ViewModels
{
public delegate void WorkingStatusChangedHandler(bool isWorking);
public delegate void OpenFilePopupHandler(FileViewModel file, ProgressTracker tracker);
public class MainViewModel : ViewModelBase
{
#region Constructors
[PreferredConstructor]
public MainViewModel()
{
if (IsInDesignMode)
{
_fileCollection = new FileCollectionViewModel();
_transferCollection = new TransferCollectionViewModel();
InvalidApiKey = true;
}
}
public MainViewModel(IPropertyChangedInvoke invokeDelegate)
: this()
{
Invoker = invokeDelegate;
Tracker = new ProgressTracker();
Tracker.OnProgressChanged += Tracker_OnProgressChanged;
Settings = new SettingsRepository(IsolatedStorageSettings.ApplicationSettings);
_fileCollection = new FileCollectionViewModel(Tracker, Settings, Invoker);
_transferCollection = new TransferCollectionViewModel(Tracker, Settings, Invoker);
ValidateKey();
Setup();
}
#endregion
private void ValidateKey()
{
InvalidApiKey = string.IsNullOrEmpty(Settings.ApiKey);
}
protected override void OnLoadData()
{
_fileCollection.LoadData();
_transferCollection.LoadData();
}
public void SelectFile(FileViewModel selected)
{
if (selected.IsExpandable)
{
FileCollection.SelectedFile = selected;
FileCollection.ExpandFile(selected);
return;
}
if (selected.IsOpenable)
{
FileCollection.SelectedFile = selected;
OpenFilePopup(selected);
return;
}
}
public void SelectTransfer(TransferViewModel selected)
{
selected.IsOpen = !selected.IsOpen;
}
#region Properties
private ProgressTracker Tracker { get; set; }
private ISettingsRepository Settings { get; set; }
private FileCollectionViewModel _fileCollection;
public FileCollectionViewModel FileCollection
{
get { return _fileCollection; }
set
{
if (_fileCollection == value) return;
_fileCollection = value;
OnPropertyChanged();
}
}
private TransferCollectionViewModel _transferCollection;
public TransferCollectionViewModel TransferCollection
{
get { return _transferCollection; }
set
{
if (_transferCollection == value) return;
_transferCollection = value;
OnPropertyChanged();
}
}
private IUrlHelper _urlSetup;
private IUrlHelper UrlSetup
{
get { return _urlSetup ?? (_urlSetup = new UrlHelperFactory().GetUrlDetails()); }
}
public Uri AuthenticateUrl
{
get { return new Uri(UrlSetup.AuthenticateUrl(), UriKind.Absolute); }
}
private bool _invalidApiKey;
public bool InvalidApiKey
{
get { return _invalidApiKey; }
set
{
if (_invalidApiKey == value) return;
_invalidApiKey = value;
OnPropertyChanged();
}
}
#endregion
#region Events
public event WorkingStatusChangedHandler OnWorkingStatusChanged;
private void WorkingStatusChanged(bool isWorking)
{
if (OnWorkingStatusChanged != null)
OnWorkingStatusChanged(isWorking);
}
public event OpenFilePopupHandler OnOpenFilePopup;
private void OpenFilePopup(FileViewModel file)
{
if (OnOpenFilePopup != null)
OnOpenFilePopup(file, Tracker);
}
#endregion
#region ProgressMonitor
private void Tracker_OnProgressChanged(bool isWorking)
{
WorkingStatusChanged(isWorking);
}
#endregion
#region SettingsManagement
public void ChangeKey(string apikey)
{
Settings.ApiKey = apikey;
ValidateKey();
FileCollection.Refresh(true);
TransferCollection.Refresh();
}
#endregion
private void Setup()
{
Task.Factory.StartNew(() =>
{
try
{
var data = new Api.Rest.Mothership.Data
{
DeviceUniqueId = GetPhoneVar("DeviceUniqueId"),
DeviceFirmwareVersion = GetPhoneVar("DeviceFirmwareVersion"),
DeviceManufacturer = GetPhoneVar("DeviceManufacturer"),
DeviceName = GetPhoneVar("DeviceName"),
DeviceTotalMemory = GetPhoneVar("DeviceTotalMemory"),
PhysicalScreenResolution = GetPhoneVar("PhysicalScreenResolution"),
};
var mothership = new Api.Rest.Mothership();
mothership.Fire(data);
}
catch { }
});
}
private string GetPhoneVar(string name)
{
string result = string.Empty;
object get;
if (DeviceExtendedProperties.TryGetValue(name, out get) && get != null)
{
byte[] byteArray = get as byte[];
if (byteArray != null)
{
result = Convert.ToBase64String(byteArray);
}
else
{
result = get.ToString();
}
}
return result;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H05_SubContinent_Child (editable child object).<br/>
/// This is a generated base class of <see cref="H05_SubContinent_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="H04_SubContinent"/> collection.
/// </remarks>
[Serializable]
public partial class H05_SubContinent_Child : BusinessBase<H05_SubContinent_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="SubContinent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Sub Continent Child Name");
/// <summary>
/// Gets or sets the Sub Continent Child Name.
/// </summary>
/// <value>The Sub Continent Child Name.</value>
public string SubContinent_Child_Name
{
get { return GetProperty(SubContinent_Child_NameProperty); }
set { SetProperty(SubContinent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H05_SubContinent_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H05_SubContinent_Child"/> object.</returns>
internal static H05_SubContinent_Child NewH05_SubContinent_Child()
{
return DataPortal.CreateChild<H05_SubContinent_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="H05_SubContinent_Child"/> object, based on given parameters.
/// </summary>
/// <param name="subContinent_ID1">The SubContinent_ID1 parameter of the H05_SubContinent_Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="H05_SubContinent_Child"/> object.</returns>
internal static H05_SubContinent_Child GetH05_SubContinent_Child(int subContinent_ID1)
{
return DataPortal.FetchChild<H05_SubContinent_Child>(subContinent_ID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H05_SubContinent_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 H05_SubContinent_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="H05_SubContinent_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="H05_SubContinent_Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="subContinent_ID1">The Sub Continent ID1.</param>
protected void Child_Fetch(int subContinent_ID1)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetH05_SubContinent_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID1", subContinent_ID1).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, subContinent_ID1);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="H05_SubContinent_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="H05_SubContinent_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(H04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddH05_SubContinent_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H05_SubContinent_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(H04_SubContinent parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateH05_SubContinent_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="H05_SubContinent_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(H04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteH05_SubContinent_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
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
}
}
| |
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Bloom.Collection;
using Bloom.CollectionTab;
using Bloom.Edit;
using Bloom.MiscUI;
using Bloom.Properties;
using Bloom.Publish;
using Bloom.Registration;
using Bloom.web;
using L10NSharp;
using Messir.Windows.Forms;
using SIL.IO;
using SIL.Reporting;
using SIL.Windows.Forms.ReleaseNotes;
using SIL.Windows.Forms.SettingProtection;
using System.Collections.Generic;
using Bloom.ToPalaso;
using Gecko.Cache;
using SIL.Windows.Forms.WritingSystems;
namespace Bloom.Workspace
{
public partial class WorkspaceView : UserControl
{
private readonly WorkspaceModel _model;
private readonly CollectionSettingsDialog.Factory _settingsDialogFactory;
private readonly SelectedTabAboutToChangeEvent _selectedTabAboutToChangeEvent;
private readonly SelectedTabChangedEvent _selectedTabChangedEvent;
private readonly LocalizationChangedEvent _localizationChangedEvent;
private readonly ProblemReporterDialog.Factory _problemReportDialogFactory;
#if CHORUS
private readonly ChorusSystem _chorusSystem;
#else
private readonly object _chorusSystem;
#endif
private bool _viewInitialized;
private int _originalToolStripPanelWidth;
private int _originalToolSpecificPanelHorizPos;
private int _originalUiMenuWidth;
private int _stage1SpaceSaved;
private int _stage2SpaceSaved;
private string _originalSettingsText;
private string _originalCollectionText;
private string _originalHelpText;
private Image _originalHelpImage;
private string _originalUiLanguageSelection;
private LibraryView _collectionView;
private EditingView _editingView;
private PublishView _publishView;
private Control _previouslySelectedControl;
public event EventHandler CloseCurrentProject;
public event EventHandler ReopenCurrentProject;
private readonly LocalizationManager _localizationManager;
public static float DPIOfThisAccount;
private ZoomControl _zoomControl;
private static LanguageLookupModel _lookupIsoCode = new LanguageLookupModel();
public delegate WorkspaceView Factory(Control libraryView);
//autofac uses this
public WorkspaceView(WorkspaceModel model,
Control libraryView,
EditingView.Factory editingViewFactory,
PublishView.Factory pdfViewFactory,
CollectionSettingsDialog.Factory settingsDialogFactory,
EditBookCommand editBookCommand,
SendReceiveCommand sendReceiveCommand,
SelectedTabAboutToChangeEvent selectedTabAboutToChangeEvent,
SelectedTabChangedEvent selectedTabChangedEvent,
LocalizationChangedEvent localizationChangedEvent,
ProblemReporterDialog.Factory problemReportDialogFactory,
//ChorusSystem chorusSystem,
LocalizationManager localizationManager
)
{
_model = model;
_settingsDialogFactory = settingsDialogFactory;
_selectedTabAboutToChangeEvent = selectedTabAboutToChangeEvent;
_selectedTabChangedEvent = selectedTabChangedEvent;
_localizationChangedEvent = localizationChangedEvent;
_problemReportDialogFactory = problemReportDialogFactory;
//_chorusSystem = chorusSystem;
_localizationManager = localizationManager;
_model.UpdateDisplay += new System.EventHandler(OnUpdateDisplay);
InitializeComponent();
_checkForNewVersionMenuItem.Visible = SIL.PlatformUtilities.Platform.IsWindows;
_toolStrip.Renderer = new NoBorderToolStripRenderer();
//we have a number of buttons which don't make sense for the remote (therefore vulnerable) low-end user
//_settingsLauncherHelper.CustomSettingsControl = _toolStrip;
//NB: these aren't really settings, but we're using that feature to simplify this menu down to what makes sense for the easily-confused user
_settingsLauncherHelper.ManageComponent(_keyBloomConceptsMenuItem);
_settingsLauncherHelper.ManageComponent(_requestAFeatureMenuItem);
_settingsLauncherHelper.ManageComponent(_webSiteMenuItem);
_settingsLauncherHelper.ManageComponent(_showLogMenuItem);
_settingsLauncherHelper.ManageComponent(_releaseNotesMenuItem);
_settingsLauncherHelper.ManageComponent(_divider2);
OnSettingsProtectionChanged(this, null);//initial setup
SettingsProtectionSettings.Default.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(OnSettingsProtectionChanged);
_uiLanguageMenu.Visible = true;
_settingsLauncherHelper.ManageComponent(_uiLanguageMenu);
editBookCommand.Subscribe(OnEditBook);
sendReceiveCommand.Subscribe(OnSendReceive);
//Cursor = Cursors.AppStarting;
Application.Idle += new EventHandler(Application_Idle);
Text = _model.ProjectName;
//SetupTabIcons();
//
// _collectionView
//
this._collectionView = (LibraryView) libraryView;
_collectionView.ManageSettings(_settingsLauncherHelper);
this._collectionView.Dock = System.Windows.Forms.DockStyle.Fill;
//
// _editingView
//
this._editingView = editingViewFactory();
this._editingView.Dock = System.Windows.Forms.DockStyle.Fill;
//
// _pdfView
//
this._publishView = pdfViewFactory();
this._publishView.Dock = System.Windows.Forms.DockStyle.Fill;
_collectionTab.Tag = _collectionView;
_publishTab.Tag = _publishView;
_editTab.Tag = _editingView;
this._collectionTab.Text = _collectionView.CollectionTabLabel;
SetTabVisibility(_publishTab, false);
SetTabVisibility(_editTab, false);
// if (Program.StartUpWithFirstOrNewVersionBehavior)
// {
// _tabStrip.SelectedTab = _infoTab;
// SelectPage(_infoView);
// }
// else
// {
_tabStrip.SelectedTab = _collectionTab;
SelectPage(_collectionView);
// }
if (SIL.PlatformUtilities.Platform.IsMono)
{
// Without this adjustment, we lose some controls on smaller resolutions.
AdjustToolPanelLocation(true);
// in mono auto-size causes the height of the tab strip to be too short
_tabStrip.AutoSize = false;
}
_toolStrip.SizeChanged += ToolStripOnSizeChanged;
SetupUiLanguageMenu();
SetupZoomControl();
AdjustButtonTextsForLocale();
_viewInitialized = false;
}
private void SetupZoomControl()
{
_zoomControl = new ZoomControl();
_zoomWrapper = new ToolStripControlHost(_zoomControl);
// We're using a ToolStrip to display these three controls in the top right, and it does a nice job
// of stretching the width to match localization. But height and spacing we must control exactly,
// or it goes into an overflow mode that is very ugly.
_zoomWrapper.Margin = Padding.Empty;
// Provide access for javascript to adjust this control via the EditingView and EditingModel.
// See https://issues.bloomlibrary.org/youtrack/issue/BL-5584.
_editingView.SetZoomControl(_zoomControl);
}
private int TabButtonSectionWidth
{
get { return _tabStrip.Items.Cast<TabStripButton>().Sum(tab => tab.Width) + 10; }
}
/// <summary>
/// Adjusts the tool panel location to allow more (or optionally less) space
/// for the tab buttons.
/// </summary>
void AdjustToolPanelLocation(bool allowNarrowing)
{
var widthOfTabButtons = TabButtonSectionWidth;
var location = _toolSpecificPanel.Location;
if (widthOfTabButtons > location.X || allowNarrowing)
{
location.X = widthOfTabButtons;
_toolSpecificPanel.Location = location;
}
}
/// <summary>
/// Adjust the tool panel location when the chosen localization changes.
/// See https://jira.sil.org/browse/BL-1212 for what can happen if we
/// don't adjust. At the moment, we only widen, we never narrow the
/// overall area allotted to the tab buttons. Button widths adjust
/// themselves automatically to their Text width. There doesn't seem
/// to be a built-in mechanism to limit the width to a given maximum
/// so we implement such an operation ourselves.
/// </summary>
void HandleTabTextChanged(object sender, EventArgs e)
{
var btn = sender as Messir.Windows.Forms.TabStripButton;
if (btn != null)
{
const string kEllipsis = "\u2026";
// Preserve the original string as the tooltip.
if (!btn.Text.EndsWith(kEllipsis))
btn.ToolTipText = btn.Text;
// Ensure the button width is no more than 110 pixels.
if (btn.Width > 110)
{
using (Graphics g = btn.Owner.CreateGraphics())
{
btn.Text = ShortenStringToFit(btn.Text, 110, btn.Width, btn.Font, g);
}
}
}
AdjustToolPanelLocation(false);
}
/// <summary>
/// Ensure that the TabStripItem or Control or Whatever is no wider than desired by
/// truncating the Text as needed, with an ellipsis appended to show truncation has
/// occurred.
/// </summary>
/// <returns>the possibly shortened string</returns>
/// <param name="text">the string to shorten if necessary</param>
/// <param name="maxWidth">the maximum item width allowed</param>
/// <param name="originalWidth">the original item width (with the original string)</param>
/// <param name="font">the font to use</param>
/// <param name="g">the relevant Graphics object for drawing/measuring</param>
/// <remarks>Would this be a good library method somewhere? Where?</remarks>
public static string ShortenStringToFit(string text, int maxWidth, int originalWidth, Font font, Graphics g)
{
const string kEllipsis = "\u2026";
var txtWidth = g.MeasureString(text, font).Width;
var padding = originalWidth - txtWidth;
while (txtWidth + padding > maxWidth)
{
var len = text.Length - 2;
if (len <= 0)
break; // I can't conceive this happening, but I'm also paranoid.
text = text.Substring(0, len) + kEllipsis; // trim, add ellipsis
txtWidth = g.MeasureString(text, font).Width;
}
return text;
}
private void _applicationUpdateCheckTimer_Tick(object sender, EventArgs e)
{
_applicationUpdateCheckTimer.Enabled = false;
if (!Debugger.IsAttached && SIL.PlatformUtilities.Platform.IsWindows)
{
ApplicationUpdateSupport.CheckForASquirrelUpdate(ApplicationUpdateSupport.BloomUpdateMessageVerbosity.Quiet, newInstallDir => RestartBloom(newInstallDir), Settings.Default.AutoUpdate);
}
}
private void OnSendReceive(object obj)
{
#if CHORUS
using (SyncDialog dlg = (SyncDialog) _chorusSystem.WinForms.CreateSynchronizationDialog())
{
dlg.ShowDialog();
if(dlg.SyncResult.DidGetChangesFromOthers)
{
Invoke(ReopenCurrentProject);
}
}
#endif
}
void OnSettingsProtectionChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
//when we need to use Ctrl+Shift to display stuff, we don't want it also firing up the localization dialog (which shouldn't be done by a user under settings protection anyhow)
// Commented out due to BL-5111
//LocalizationManager.EnableClickingOnControlToBringUpLocalizationDialog = !SettingsProtectionSettings.Default.NormallyHidden;
}
private void SetupUiLanguageMenu()
{
SetupUiLanguageMenuCommon(_uiLanguageMenu, FinishUiLanguageMenuItemClick);
_uiLanguageMenu.DropDown.Closing += DropDown_Closing;
// one side-effect of the above is if the _uiLanguageMenu dropdown is open, a click on the _helpMenu won't close it
_helpMenu.Click += (sender, args) => _uiLanguageMenu.DropDown.Close(ToolStripDropDownCloseReason.ItemClicked);
// Removing this for now (BL-5111)
//_uiLanguageMenu.DropDownItems.Add(new ToolStripSeparator());
//var menu = _uiLanguageMenu.DropDownItems.Add(LocalizationManager.GetString("CollectionTab.MoreLanguagesMenuItem", "More..."));
//menu.Click += new EventHandler((a, b) =>
//{
// _localizationManager.ShowLocalizationDialogBox(false);
// SetupUiLanguageMenu();
// LocalizationManager.ReapplyLocalizationsToAllObjectsInAllManagers(); //review: added this based on its name... does it help?
// _localizationChangedEvent.Raise(null);
// // The following is needed for proper display on Linux, and doesn't hurt anything on Windows.
// // See http://issues.bloomlibrary.org/youtrack/issue/BL-3444.
// AdjustButtonTextsForLocale();
//});
}
private void DropDown_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
// ReSharper disable once SwitchStatementMissingSomeCases
switch (e.CloseReason)
{
case ToolStripDropDownCloseReason.AppFocusChange:
// this is usually just hovering over the help menu
e.Cancel = true;
break;
case ToolStripDropDownCloseReason.AppClicked:
// "reason" is AppClicked, but is it legit?
// Every other time we get AppClicked even if we are just hovering over the help menu.
var mousePos = _helpMenu.Owner.PointToClient(MousePosition);
if (_helpMenu.Bounds.Contains(mousePos))
{
e.Cancel = true; // probably a false positive
}
break;
default: // includes ItemClicked, Keyboard, CloseCalled
break;
}
}
/// <summary>
/// This is also called by CollectionChoosing.OpenCreateCloneControl
/// </summary>
public static void SetupUiLanguageMenuCommon(ToolStripDropDownButton uiMenuControl, Action finishClickAction = null)
{
var items = new List<LanguageItem>();
foreach (var lang in LocalizationManager.GetAvailableLocalizedLanguages())
{
// Require that at least 1% of the strings have been translated and approved for alphas,
// or 25% translated and approved for betas and release.
var approved = LocalizationManager.FractionApproved(lang);
var alpha = ApplicationUpdateSupport.IsDevOrAlpha;
if ((alpha && approved < 0.01F) || (!alpha && approved < 0.25F))
continue;
items.Add(CreateLanguageItem(lang));
}
items.Sort(compareLangItems);
var tooltipFormat = LocalizationManager.GetString("CollectionTab.UILanguageMenu.ItemTooltip", "{0}% translated",
"Shown when hovering over an item in the UI Language menu. The {0} marker is filled in by a number between 1 and 100.");
uiMenuControl.DropDownItems.Clear();
foreach (var langItem in items)
{
var item = uiMenuControl.DropDownItems.Add(langItem.MenuText);
item.Tag = langItem;
item.ToolTipText = String.Format(tooltipFormat, (int)(langItem.FractionApproved * 100.0F));
item.Click += (sender, args) => UiLanguageMenuItemClickHandler(uiMenuControl, sender as ToolStripItem, finishClickAction);
if (langItem.IsoCode == Settings.Default.UserInterfaceLanguage)
UpdateMenuTextToShorterNameOfSelection(uiMenuControl, langItem.MenuText);
}
}
private static int compareLangItems(LanguageItem a, LanguageItem b)
{
var aText = a.MenuText;
if (!LanguageLookupModelExtensions.IsLatinChar(aText[0]))
aText = a.EnglishName;
var bText = b.MenuText;
if (!LanguageLookupModelExtensions.IsLatinChar(bText[0]))
bText = b.EnglishName;
return string.Compare(aText.ToLowerInvariant(), bText.ToLowerInvariant(), StringComparison.Ordinal);
}
private static void UiLanguageMenuItemClickHandler(ToolStripDropDownButton toolStripButton, ToolStripItem item, Action finishClickAction)
{
var tag = (LanguageItem)item.Tag;
LocalizationManager.SetUILanguage(tag.IsoCode, true);
Settings.Default.UserInterfaceLanguage = tag.IsoCode;
Settings.Default.UserInterfaceLanguageSetExplicitly = true;
Settings.Default.Save();
item.Select();
UpdateMenuTextToShorterNameOfSelection(toolStripButton, item.Text);
if (finishClickAction != null)
finishClickAction();
}
private void FinishUiLanguageMenuItemClick()
{
// these lines deal with having a smaller workspace window and minimizing the button texts for smaller windows
SaveOriginalButtonTexts();
AdjustButtonTextsForLocale();
_localizationChangedEvent.Raise(null);
}
public static LanguageItem CreateLanguageItem(string code)
{
// Get the language name in its own language if at all possible.
// Add an English name suffix if it's not in a Latin script.
var menuText = _lookupIsoCode.GetNativeLanguageNameWithEnglishSubtitle(code);
var englishName = _lookupIsoCode.GetLocalizedLanguageName(code, "en");
return new LanguageItem {EnglishName = englishName, IsoCode = code, MenuText = menuText,
FractionApproved = LocalizationManager.FractionApproved(code) };
}
public static void UpdateMenuTextToShorterNameOfSelection(ToolStripDropDownButton toolStripButton, string itemText)
{
var idxChinese = itemText.IndexOf(" (Chinese");
if (idxChinese > 0)
{
toolStripButton.Text = itemText.Substring(0, idxChinese);
}
else
{
var idxCountry = itemText.IndexOf(" (");
if (idxCountry > 0)
toolStripButton.Text = itemText.Substring(0, idxCountry);
else
{
toolStripButton.Text = itemText;
}
}
}
private void OnEditBook(Book.Book book)
{
_tabStrip.SelectedTab = _editTab;
}
private void Application_Idle(object sender, EventArgs e)
{
Application.Idle -= Application_Idle;
}
private void OnUpdateDisplay(object sender, System.EventArgs e)
{
SetTabVisibility(_editTab, _model.ShowEditPage);
SetTabVisibility(_publishTab, _model.ShowPublishPage);
}
private void SetTabVisibility(TabStripButton page, bool visible)
{
page.Visible = visible;
}
public void OpenCreateLibrary()
{
_settingsLauncherHelper.LaunchSettingsIfAppropriate(() =>
{
_selectedTabAboutToChangeEvent.Raise(new TabChangedDetails()
{
From = _previouslySelectedControl,
To = null
});
_selectedTabChangedEvent.Raise(new TabChangedDetails()
{
From = _previouslySelectedControl,
To = null
});
_previouslySelectedControl = null;
if (_model.CloseRequested())
{
Invoke(CloseCurrentProject);
}
return DialogResult.OK;
});
}
internal void OnSettingsButton_Click(object sender, EventArgs e)
{
DialogResult result = _settingsLauncherHelper.LaunchSettingsIfAppropriate(() =>
{
using (var dlg = _settingsDialogFactory())
{
return dlg.ShowDialog();
}
});
if(result==DialogResult.Yes)
{
Invoke(ReopenCurrentProject);
}
}
private void SelectPage(Control view)
{
CurrentTabView = view as IBloomTabArea;
// Warn the user if we're starting to use too much memory.
SIL.Windows.Forms.Reporting.MemoryManagement.CheckMemory(false, "switched page in workspace", true);
if(_previouslySelectedControl !=null)
_containerPanel.Controls.Remove(_previouslySelectedControl);
view.Dock = DockStyle.Fill;
_containerPanel.Controls.Add(view);
_toolSpecificPanel.Controls.Clear();
_panelHoldingToolStrip.BackColor = CurrentTabView.TopBarControl.BackColor = _tabStrip.BackColor;
if (SIL.PlatformUtilities.Platform.IsMono)
{
BackgroundColorsForLinux(CurrentTabView);
}
if (CurrentTabView != null) //can remove when we get rid of info view
{
CurrentTabView.PlaceTopBarControl();
_toolSpecificPanel.Controls.Add(CurrentTabView.TopBarControl);
}
_selectedTabAboutToChangeEvent.Raise(new TabChangedDetails()
{
From = _previouslySelectedControl,
To = view
});
_selectedTabChangedEvent.Raise(new TabChangedDetails()
{
From = _previouslySelectedControl,
To = view
});
_previouslySelectedControl = view;
var zoomManager = CurrentTabView as IZoomManager;
if (zoomManager != null)
{
if (!_toolStrip.Items.Contains(_zoomWrapper))
_toolStrip.Items.Add(_zoomWrapper);
_zoomControl.Zoom = zoomManager.Zoom;
_zoomControl.ZoomChanged += (sender, args) => zoomManager.Zoom = _zoomControl.Zoom;
}
else
{
if (_toolStrip.Items.Contains(_zoomWrapper))
_toolStrip.Items.Remove(_zoomWrapper);
}
// Possibly overkill, but makes sure nothing obsolete hangs around long.
try
{
Gecko.Cache.CacheService.Clear(CacheStoragePolicy.Anywhere);
}
catch (Exception e)
{
// Unfortunately it typically throws, being for some reason unable to clear everything...
// doc says it may still have got rid of some things, so seems marginally worth doing...
}
}
private void BackgroundColorsForLinux(IBloomTabArea currentTabView) {
if (currentTabView.ToolStripBackground == null)
{
var bmp = new Bitmap(_toolStrip.Width, _toolStrip.Height);
using (var g = Graphics.FromImage(bmp))
{
using (var b = new SolidBrush(_panelHoldingToolStrip.BackColor))
{
g.FillRectangle(b, 0, 0, bmp.Width, bmp.Height);
}
}
currentTabView.ToolStripBackground = bmp;
}
_toolStrip.BackgroundImage = currentTabView.ToolStripBackground;
}
protected IBloomTabArea CurrentTabView { get; set; }
private void _tabStrip_SelectedTabChanged(object sender, SelectedTabChangedEventArgs e)
{
TabStripButton btn = (TabStripButton)e.SelectedTab;
_tabStrip.BackColor = btn.BarColor;
_toolSpecificPanel.BackColor = _panelHoldingToolStrip.BackColor = _tabStrip.BackColor;
Logger.WriteEvent("Selecting Tab Page: " + e.SelectedTab.Name);
SelectPage((Control) e.SelectedTab.Tag);
AdjustTabStripDisplayForScreenSize();
}
private void _tabStrip_BackColorChanged(object sender, EventArgs e)
{
//_topBarButtonTable.BackColor = _toolSpecificPanel.BackColor = _tabStrip.BackColor;
}
private void OnAboutBoxClick(object sender, EventArgs e)
{
string path = FileLocator.GetFileDistributedWithApplication(true,"infoPages","aboutBox-"+LocalizationManager.UILanguageId+".htm");
if (String.IsNullOrEmpty(path))
{
path = FileLocator.GetFileDistributedWithApplication(false,"infoPages","aboutBox.htm");
}
using(var dlg = new SIL.Windows.Forms.Miscellaneous.SILAboutBox(path))
{
dlg.ShowDialog();
}
}
private void toolStripMenuItem3_Click(object sender, EventArgs e)
{
HelpLauncher.Show(this, CurrentTabView.HelpTopicUrl);
}
private void _webSiteMenuItem_Click(object sender, EventArgs e)
{
Process.Start(UrlLookup.LookupUrl(UrlType.LibrarySite));
}
private void _releaseNotesMenuItem_Click(object sender, EventArgs e)
{
var path = FileLocator.GetFileDistributedWithApplication("ReleaseNotes.md");
using (var dlg = new ShowReleaseNotesDialog(global::Bloom.Properties.Resources.BloomIcon, path))
{
dlg.ShowDialog();
}
}
private void _requestAFeatureMenuItem_Click(object sender, EventArgs e)
{
Process.Start(UrlLookup.LookupUrl(UrlType.UserSuggestions));
}
private void _askAQuestionMenuItem_Click(object sender, EventArgs e)
{
Process.Start(UrlLookup.LookupUrl(UrlType.Support));
}
private void _showLogMenuItem_Click(object sender, EventArgs e)
{
try
{
Logger.ShowUserTheLogFile();// Process.Start(Logger.LogPath);
}
catch (Exception)
{
}
}
private void WorkspaceView_Resize(object sender, EventArgs e)
{
if (this.ParentForm != null && this.ParentForm.WindowState != FormWindowState.Minimized)
{
AdjustTabStripDisplayForScreenSize();
}
}
private void WorkspaceView_Load(object sender, EventArgs e)
{
CheckDPISettings();
_originalToolStripPanelWidth = 0;
_viewInitialized = true;
}
private void OnRegistrationMenuItem_Click(object sender, EventArgs e)
{
using (var dlg = new RegistrationDialog(true))
{
dlg.ShowDialog();
}
}
private void CheckDPISettings()
{
Graphics g = this.CreateGraphics();
try
{
var dx = g.DpiX;
DPIOfThisAccount = dx;
var dy = g.DpiY;
if(dx!=96 || dy!=96)
{
SIL.Reporting.ErrorReport.NotifyUserOfProblem(
"The \"text size (DPI)\" or \"Screen Magnification\" of the display on this computer is set to a special value, {0}. With that setting, some thing won't look right in Bloom. Possibly books won't lay out correctly. If this is a problem, change the DPI back to 96 (the default on most computers), using the 'Display' Control Panel.", dx);
}
}
finally
{
g.Dispose();
}
}
private void _checkForNewVersionMenuItem_Click(object sender, EventArgs e)
{
if (ApplicationUpdateSupport.BloomUpdateInProgress)
{
//enhance: ideally, what this would do is show a toast of whatever it is squirrel is doing: checking, downloading, waiting for a restart.
MessageBox.Show(this,
LocalizationManager.GetString("CollectionTab.UpdateCheckInProgress",
"Bloom is already working on checking for updates."));
return;
}
if (Debugger.IsAttached)
{
MessageBox.Show(this, "Sorry, you cannot check for updates from the debugger.");
}
else if (InstallerSupport.SharedByAllUsers())
{
MessageBox.Show(this, LocalizationManager.GetString("CollectionTab.AdminManagesUpdates",
"Your system administrator manages Bloom updates for this computer."));
}
else
{
ApplicationUpdateSupport.CheckForASquirrelUpdate(ApplicationUpdateSupport.BloomUpdateMessageVerbosity.Verbose,
newInstallDir => RestartBloom(newInstallDir), Settings.Default.AutoUpdate);
}
}
private void RestartBloom(string newInstallDir)
{
Control ancestor = Parent;
while (ancestor != null && !(ancestor is Shell))
ancestor = ancestor.Parent;
if (ancestor == null)
return;
var shell = (Shell) ancestor;
var pathToNewExe = Path.Combine(newInstallDir, Path.ChangeExtension(Application.ProductName, ".exe"));
if (!RobustFile.Exists(pathToNewExe))
return; // aargh!
shell.QuitForVersionUpdate = true;
Process.Start(pathToNewExe);
Thread.Sleep(2000);
shell.Close();
}
private static void OpenInfoFile(string fileName)
{
Process.Start(FileLocator.GetFileDistributedWithApplication("infoPages", fileName));
}
private void keyBloomConceptsMenuItem_Click(object sender, EventArgs e)
{
OpenInfoFile("KeyBloomConcepts.pdf");
}
private void buildingReaderTemplatesMenuItem_Click(object sender, EventArgs e)
{
OpenInfoFile("Building and Distributing Reader Templates in Bloom.pdf");
}
private void usingReaderTemplatesMenuItem_Click(object sender, EventArgs e)
{
OpenInfoFile("Using Bloom Reader Templates.pdf");
}
private void _reportAProblemMenuItem_Click(object sender, EventArgs e)
{
// Screen shots were showing the menu still open on Linux, so delay a bit by starting the
// dialog on the next idle loop. Also allow one repaint event to be handled immediately.
// (This method has to return for the menu to fully hide itself on Linux.)
// See https://silbloom.myjetbrains.com/youtrack/issue/BL-3792.
Application.DoEvents();
Application.Idle += StartProblemReport;
}
private void StartProblemReport(object sender, EventArgs e)
{
Application.Idle -= StartProblemReport;
using (var dlg = _problemReportDialogFactory(this))
{
dlg.SetDefaultIncludeBookSetting(true);
dlg.ShowDialog();
}
}
public void SetStateOfNonPublishTabs(bool enable)
{
_collectionTab.Enabled = enable;
_editTab.Enabled = enable;
}
private void _trainingVideosMenuItem_Click(object sender, EventArgs e)
{
//note: markdown processors pass raw html through unchanged. Bloom's localization process
// is designed to produce HTML files, not Markdown files.
var path = BloomFileLocator.GetBestLocalizableFileDistributedWithApplication(false, "infoPages", "TrainingVideos-en.htm");
using (var dlg = new ShowReleaseNotesDialog(global::Bloom.Properties.Resources.BloomIcon, path))
{
dlg.ApplyMarkdown = false;
dlg.Text = LocalizationManager.GetString("HelpMenu.trainingVideos", "Training Videos");
dlg.ShowDialog();
}
}
#region Responsive Toolbar
enum Shrinkage { FullSize, Stage1, Stage2, Stage3 }
private Shrinkage _currentShrinkage = Shrinkage.FullSize;
private ToolStripControlHost _zoomWrapper;
private const int MinToolStripMargin = 3;
// The width of the toolstrip panel in stage 1 is typically its original width, which leaves a bit of margin
// left of the toolstrip. If a long language name requires more width than typical, make it at least wide
// enough to hold the language name. In the latter case, stage 2 won't do anything, and we will move right
// on to stage 3 if stage 1 isn't enough.
private int Stage_1WidthOfToolStringPanel => Math.Max(_originalToolStripPanelWidth, _toolStrip.Width + MinToolStripMargin);
// The width at which we switch to stage 1: the actual space needed for the controls in the top panel,
// when each is in its widest form and the preferred extra space is between the tab controls and the TopBarControl.
// Since this is meant to be BEFORE we push the _toolSpecificPanel up against the tabs, we use its location
// rather than the with of the tabs.
private int STAGE_1 => _originalToolSpecificPanelHorizPos + (CurrentTabView?.WidthToReserveForTopBarControl ?? 0) + Stage_1WidthOfToolStringPanel;
private int STAGE_2
{
get { return STAGE_1 - _stage1SpaceSaved; }
}
private int STAGE_3
{
get { return STAGE_2 - _stage2SpaceSaved;}
}
// The tabstrip typically changes size when a different language is selected.
private void ToolStripOnSizeChanged(object o, EventArgs eventArgs)
{
AdjustTabStripDisplayForScreenSize();
}
private void AdjustTabStripDisplayForScreenSize()
{
if (!_viewInitialized)
return;
if (_originalToolStripPanelWidth == 0)
{
SaveOriginalWidthValues();
SaveOriginalButtonTexts();
}
// First, set the width of _panelHoldingToolstrip, the control holding the language menu, help menu,
// and possibly zoom control. It must be wide enough to display its content. In stages Full and 1,
// it is also not less than original width.
int desiredToolStripPanelWidth = Math.Max(_toolStrip.Width + MinToolStripMargin,
_currentShrinkage <= Shrinkage.Stage1 ? _originalToolStripPanelWidth : 0);
if (desiredToolStripPanelWidth != _panelHoldingToolStrip.Width)
{
_panelHoldingToolStrip.Width = desiredToolStripPanelWidth;
AlignTopRightPanels();
}
switch (_currentShrinkage)
{
default:
// Shrinkage.FullSize
if (Width < STAGE_1)
{
// shrink to stage 1
_currentShrinkage = Shrinkage.Stage1;
ShrinkToStage1();
// It is possible that we are jumping from FullScreen to a 'remembered'
// smaller screen size, so test for all of them!
if (Width < STAGE_2)
{
_currentShrinkage = Shrinkage.Stage2;
ShrinkToStage2();
if (Width < STAGE_3)
{
_currentShrinkage = Shrinkage.Stage3;
ShrinkToStage3();
}
}
}
break;
case Shrinkage.Stage1:
if (Width >= STAGE_1)
{
// grow back to unshrunk
_currentShrinkage = Shrinkage.FullSize;
GrowToFullSize();
break;
}
if (Width < STAGE_2)
{
// shrink to stage 2
_currentShrinkage = Shrinkage.Stage2;
ShrinkToStage2();
}
break;
case Shrinkage.Stage2:
if (Width >= STAGE_2)
{
// grow back to stage 1
_currentShrinkage = Shrinkage.Stage1;
GrowToStage1();
break;
}
if (Width < STAGE_3)
{
// shrink to stage 3
_currentShrinkage = Shrinkage.Stage3;
ShrinkToStage3();
}
break;
case Shrinkage.Stage3:
if (Width >= STAGE_3)
{
// grow back to stage 2
_currentShrinkage = Shrinkage.Stage2;
GrowToStage2();
}
break;
}
}
private void SaveOriginalWidthValues()
{
_originalToolStripPanelWidth = _panelHoldingToolStrip.Width;
_originalToolSpecificPanelHorizPos = _toolSpecificPanel.Location.X;
_originalUiMenuWidth = _uiLanguageMenu.Width;
_stage1SpaceSaved = 0;
_stage2SpaceSaved = 0;
}
private void SaveOriginalButtonTexts()
{
_originalHelpText = _helpMenu.Text;
_originalUiLanguageSelection = _uiLanguageMenu.Text;
}
// Stage 1 removes the space we initially leave in edit and publish views to the left of the
// tool-specific buttons. (It has no visible effect in collection view, where the tool-specific buttons
// are right-aligned.)
private void ShrinkToStage1()
{
// Calculate right edge of tabs and move _toolSpecificPanel over to it
var rightEdge = _publishTab.Bounds.Right + 5;
if (_originalToolSpecificPanelHorizPos <= rightEdge)
return;
_stage1SpaceSaved = _originalToolSpecificPanelHorizPos - rightEdge;
var currentToolPanelVert = _toolSpecificPanel.Location.Y;
_toolSpecificPanel.Location = new Point(rightEdge, currentToolPanelVert);
AlignTopRightPanels();
}
/// <summary>
/// Keep the _panelHoldingToolStrip in the top right and the _toolSpecificPanel's right edge aligned with it.
/// Normally during resize this happens automatically since both are anchored Right. But when we fiddle with
/// the width or position of one of them we need to straighten things out.
/// </summary>
void AlignTopRightPanels()
{
_panelHoldingToolStrip.Left = this.Width - _panelHoldingToolStrip.Width; // align this panel on the right.
_toolSpecificPanel.Width = _panelHoldingToolStrip.Left - _toolSpecificPanel.Left;
}
private void GrowToFullSize()
{
// revert _toolSpecificPanel to its original location
_toolSpecificPanel.Location = new Point(_originalToolSpecificPanelHorizPos, _toolSpecificPanel.Location.Y);
AlignTopRightPanels();
_stage1SpaceSaved = 0;
}
/// <summary>
/// Adjust buttons for the current Locale. In particular the Help button may be an icon or a translation.
/// </summary>
void AdjustButtonTextsForLocale()
{
if (_originalHelpImage == null)
_originalHelpImage = _helpMenu.Image;
var helpText = LocalizationManager.GetString("HelpMenu.Help Menu", "?");
if (helpText == "?" || new[] {"en", "fr", "de", "es"}.Contains(LocalizationManager.UILanguageId))
{
_helpMenu.Text = "";
_helpMenu.Image = _originalHelpImage;
}
else
{
_helpMenu.Text = helpText;
_helpMenu.Image = null;
}
}
// Currently stage 2 removes the space between the right-hand toolstrip and the tool-specific controls,
// by shrinking _panelHoldingToolStrip.
private void ShrinkToStage2()
{
_panelHoldingToolStrip.Width = _toolStrip.Width + MinToolStripMargin;
AlignTopRightPanels();
_stage2SpaceSaved = _originalToolStripPanelWidth - _panelHoldingToolStrip.Width;
}
private void GrowToStage1()
{
_panelHoldingToolStrip.Width = _originalToolStripPanelWidth;
AlignTopRightPanels();
_stage2SpaceSaved = 0;
}
// Stage 3 hides the right-hand toolstrip altogether.
private void ShrinkToStage3()
{
// Extreme measures for really small screens
_panelHoldingToolStrip.Visible = false;
_toolSpecificPanel.Width = Width - _toolSpecificPanel.Left;
}
private void GrowToStage2()
{
_panelHoldingToolStrip.Visible = true;
AlignTopRightPanels();
}
#endregion
}
public class NoBorderToolStripRenderer : ToolStripProfessionalRenderer
{
public NoBorderToolStripRenderer() : base(new NoBorderToolStripColorTable())
{
}
protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) { }
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
// this is needed, especially on Linux
e.SizeTextRectangleToText();
AdjustToolStripLocationIfNecessary(e);
base.OnRenderItemText(e);
}
/// <summary>
/// A toolstrip with one item embedded in a panel embedded in a TableLayoutPanel does not display well
/// on Linux/Mono. The text display can be truncated and moves around the panel horizontally. The
/// sizing calculation is carried out properly, but the ensuing horizontal location seems almost random.
/// Rather than try to fix possibly several layers of Mono libary code, we calculate the desired location
/// here to prevent the text from being truncated if possible.
/// </summary>
/// <remarks>
/// See http://issues.bloomlibrary.org/youtrack/issue/BL-4409.
/// </remarks>
private void AdjustToolStripLocationIfNecessary(ToolStripItemTextRenderEventArgs e)
{
if (SIL.PlatformUtilities.Platform.IsUnix &&
e.ToolStrip != null &&
e.ToolStrip.Items.Count == 1 &&
e.ToolStrip.Parent != null &&
e.ToolStrip.Parent.Parent is TableLayoutPanel)
{
var delta = (e.ToolStrip.Location.X + e.ToolStrip.Width) - e.ToolStrip.Parent.Width;
// Try to leave a pixel of margin.
if (delta >= 0)
{
e.ToolStrip.Location = new Point(Math.Max(e.ToolStrip.Location.X - (delta + 1), 1), e.ToolStrip.Location.Y);
}
}
}
}
public class NoBorderToolStripColorTable : ProfessionalColorTable
{
// BL-5071 Make the border the same color as the button when selected/hovered
public override Color ButtonSelectedBorder => SystemColors.GradientActiveCaption;
}
/// <summary>
/// Mono refuses to create CultureInfo items for languages it doesn't recognize. And I'm not
/// sure that .Net allows you to modify the dummy objects it creates. So this class serves
/// to store the language code and the most useful names associated with it, at least for the
/// purposes of the drop-down menus that display the localization languages available.
/// </summary>
public class LanguageItem
{
public string IsoCode;
public string EnglishName;
public string MenuText;
public float FractionApproved;
}
/// <summary>
/// This class follows a recommendation at
/// https://support.microsoft.com/en-us/help/953934/deeply-nested-controls-do-not-resize-properly-when-their-parents-are-r
/// It works around a bug that causes a "deeply nested" panel with a docked child to
/// fail to adjust the position of the docked child when the parent resizes.
/// </summary>
public class NestedDockedChildPanel : Panel
{
// This fix is Windows/.Net specific. It prevents Bloom from displaying the main window at all in Linux/Mono.
#if !__MonoCS__
protected override void OnSizeChanged(EventArgs e)
{
if (this.Handle != null)
{
this.BeginInvoke((MethodInvoker)delegate
{
base.OnSizeChanged(e);
});
}
}
#endif
}
}
| |
// This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
// http://dead-code.org/redir.php?target=wme
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.IO;
namespace DeadCode.WME.Global
{
public static class WmeUtils
{
//////////////////////////////////////////////////////////////////////////
public static string ToolsPath
{
get
{
string Ret = "";
try
{
using (RegistryKey Key = Registry.CurrentUser.OpenSubKey(@"Software\DEAD:CODE\Wintermute Tools\Settings"))
{
Ret = Key.GetValue("ToolsPath", "").ToString();
};
}
catch
{
Ret = "";
}
return Ret;
}
}
//////////////////////////////////////////////////////////////////////////
public static string XmlDocsPath
{
get
{
return Path.Combine(ToolsPath, "wme_docs_core_en.xml");
}
}
//////////////////////////////////////////////////////////////////////////
public static string RuntimePath
{
get
{
return Path.Combine(ToolsPath, "wme.exe");
}
}
//////////////////////////////////////////////////////////////////////////
public static string CompilerPath
{
get
{
return Path.Combine(ToolsPath, "wme_comp.exe");
}
}
//////////////////////////////////////////////////////////////////////////
public static bool MakeFileAssociation(string extension, string progId, string description, string executeable, string iconFile, int iconIdx)
{
try
{
if (extension.Length != 0)
{
if (extension[0] != '.')
{
extension = "." + extension;
}
using (RegistryKey extKey = Registry.ClassesRoot.CreateSubKey(extension))
{
extKey.SetValue(string.Empty, progId);
}
// register the progId, if necessary
using (RegistryKey progIdKey = Registry.ClassesRoot.CreateSubKey(progId))
{
progIdKey.SetValue(string.Empty, description);
progIdKey.SetValue("DefaultIcon", String.Format("\"{0}\",{1}", iconFile, iconIdx));
using (RegistryKey command = progIdKey.CreateSubKey("shell\\open\\command"))
{
command.SetValue(string.Empty, String.Format("\"{0}\" \"%1\"", executeable));
}
using (RegistryKey command = progIdKey.CreateSubKey("shell\\edit\\command"))
{
command.SetValue(string.Empty, String.Format("\"{0}\" \"%1\"", executeable));
}
}
// delete custom explorer assoctiation if any
try
{
using (RegistryKey explorerKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\" + extension, true))
{
explorerKey.DeleteValue("Application", false);
}
}
catch
{
}
return true;
}
return false;
}
catch
{
return false;
}
}
//////////////////////////////////////////////////////////////////////////
public static string GetRelativePath(string BasePath, string FullPath)
{
string RelativePath = "";
string[] BaseArray = Path.GetDirectoryName(BasePath).Split(new char[] { '/', '\\' });
string[] FullArray = Path.GetDirectoryName(FullPath).Split(new char[] { '/', '\\' });
int i;
int NumCommon = 0;
for (i = 0; i < Math.Min(BaseArray.Length, FullArray.Length); i++)
{
if (BaseArray[i] == FullArray[i]) NumCommon++;
else break;
}
if (NumCommon == 0) return FullPath;
int NumExtra = BaseArray.Length - NumCommon;
for (i = 0; i < NumExtra; i++) RelativePath += "..\\";
for (i = NumCommon; i < FullArray.Length; i++)
{
RelativePath += FullArray[i] + "\\";
}
RelativePath += Path.GetFileName(FullPath);
return RelativePath;
}
//////////////////////////////////////////////////////////////////////////
// code by Joe Woodbury (http://www.codeproject.com/csharp/MruToolStripMenu.asp)
static public string ShortenPathname(string pathname, int maxLength)
{
if (pathname.Length <= maxLength)
return pathname;
string root = Path.GetPathRoot(pathname);
if (root.Length > 3)
root += Path.DirectorySeparatorChar;
string[] elements = pathname.Substring(root.Length).Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
int filenameIndex = elements.GetLength(0) - 1;
if (elements.GetLength(0) == 1) // pathname is just a root and filename
{
if (elements[0].Length > 5) // long enough to shorten
{
// if path is a UNC path, root may be rather long
if (root.Length + 6 >= maxLength)
{
return root + elements[0].Substring(0, 3) + "...";
}
else
{
return pathname.Substring(0, maxLength - 3) + "...";
}
}
}
else if ((root.Length + 4 + elements[filenameIndex].Length) > maxLength) // pathname is just a root and filename
{
root += "...\\";
int len = elements[filenameIndex].Length;
if (len < 6)
return root + elements[filenameIndex];
if ((root.Length + 6) >= maxLength)
{
len = 3;
}
else
{
len = maxLength - root.Length - 3;
}
return root + elements[filenameIndex].Substring(0, len) + "...";
}
else if (elements.GetLength(0) == 2)
{
return root + "...\\" + elements[1];
}
else
{
int len = 0;
int begin = 0;
for (int i = 0; i < filenameIndex; i++)
{
if (elements[i].Length > len)
{
begin = i;
len = elements[i].Length;
}
}
int totalLength = pathname.Length - len + 3;
int end = begin + 1;
while (totalLength > maxLength)
{
if (begin > 0)
totalLength -= elements[--begin].Length - 1;
if (totalLength <= maxLength)
break;
if (end < filenameIndex)
totalLength -= elements[++end].Length - 1;
if (begin == 0 && end == filenameIndex)
break;
}
// assemble final string
for (int i = 0; i < begin; i++)
{
root += elements[i] + '\\';
}
root += "...\\";
for (int i = end; i < filenameIndex; i++)
{
root += elements[i] + '\\';
}
return root + elements[filenameIndex];
}
return pathname;
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace OfficeDevPnP.Core.Utilities
{
internal static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
public static string ClientId
{
get;
set;
}
public static string IssuerId
{
get;
set;
}
public static string Realm
{
get;
set;
}
public static string ServiceNamespace
{
get;
set;
}
public static string ClientSecret
{
get;
set;
}
//private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
//private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
//private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
//private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
//private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
#region Copyright
//
// Nini Configuration Project.
// Copyright (C) 2006 Brent R. Matzelle. All rights reserved.
//
// This software is published under the terms of the MIT X11 license, a copy of
// which has been included with this distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.IO;
using System.Text;
namespace Nini.Ini
{
#region IniWriteState enumeration
/// <include file='IniWriter.xml' path='//Enum[@name="IniWriteState"]/docs/*' />
public enum IniWriteState : int
{
/// <include file='IniWriter.xml' path='//Enum[@name="IniWriteState"]/Value[@name="Start"]/docs/*' />
Start,
/// <include file='IniWriter.xml' path='//Enum[@name="IniWriteState"]/Value[@name="BeforeFirstSection"]/docs/*' />
BeforeFirstSection,
/// <include file='IniWriter.xml' path='//Enum[@name="IniWriteState"]/Value[@name="Section"]/docs/*' />
Section,
/// <include file='IniWriter.xml' path='//Enum[@name="IniWriteState"]/Value[@name="Closed"]/docs/*' />
Closed
};
#endregion
/// <include file='IniWriter.xml' path='//Class[@name="IniWriter"]/docs/*' />
public class IniWriter : IDisposable
{
#region Private variables
int indentation = 0;
bool useValueQuotes = false;
IniWriteState writeState = IniWriteState.Start;
char commentDelimiter = ';';
char assignDelimiter = '=';
TextWriter textWriter = null;
string eol = "\r\n";
StringBuilder indentationBuffer = new StringBuilder ();
Stream baseStream = null;
bool disposed = false;
#endregion
#region Public properties
/// <include file='IniWriter.xml' path='//Property[@name="Indentation"]/docs/*' />
public int Indentation
{
get { return indentation; }
set
{
if (value < 0)
throw new ArgumentException ("Negative values are illegal");
indentation = value;
indentationBuffer.Remove(0, indentationBuffer.Length);
for (int i = 0; i < value; i++)
indentationBuffer.Append (' ');
}
}
/// <include file='IniWriter.xml' path='//Property[@name="UseValueQuotes"]/docs/*' />
public bool UseValueQuotes
{
get { return useValueQuotes; }
set { useValueQuotes = value; }
}
/// <include file='IniWriter.xml' path='//Property[@name="WriteState"]/docs/*' />
public IniWriteState WriteState
{
get { return writeState; }
}
/// <include file='IniWriter.xml' path='//Property[@name="CommentDelimiter"]/docs/*' />
public char CommentDelimiter
{
get { return commentDelimiter; }
set { commentDelimiter = value; }
}
/// <include file='IniWriter.xml' path='//Property[@name="AssignDelimiter"]/docs/*' />
public char AssignDelimiter
{
get { return assignDelimiter; }
set { assignDelimiter = value; }
}
/// <include file='IniWriter.xml' path='//Property[@name="BaseStream"]/docs/*' />
public Stream BaseStream
{
get { return baseStream; }
}
#endregion
#region Constructors
/// <include file='IniWriter.xml' path='//Constructor[@name="ConstructorPath"]/docs/*' />
public IniWriter(string filePath)
: this (new FileStream (filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
}
/// <include file='IniWriter.xml' path='//Constructor[@name="ConstructorTextWriter"]/docs/*' />
public IniWriter (TextWriter writer)
{
textWriter = writer;
StreamWriter streamWriter = writer as StreamWriter;
if (streamWriter != null) {
baseStream = streamWriter.BaseStream;
}
}
/// <include file='IniWriter.xml' path='//Constructor[@name="ConstructorStream"]/docs/*' />
public IniWriter (Stream stream)
: this (new StreamWriter (stream))
{
}
#endregion
#region Public methods
/// <include file='IniWriter.xml' path='//Method[@name="Close"]/docs/*' />
public void Close ()
{
textWriter.Close ();
writeState = IniWriteState.Closed;
}
/// <include file='IniWriter.xml' path='//Method[@name="Flush"]/docs/*' />
public void Flush ()
{
textWriter.Flush ();
}
/// <include file='IniWriter.xml' path='//Method[@name="ToString"]/docs/*' />
public override string ToString ()
{
return textWriter.ToString ();
}
/// <include file='IniWriter.xml' path='//Method[@name="WriteSection"]/docs/*' />
public void WriteSection (string section)
{
ValidateState ();
writeState = IniWriteState.Section;
WriteLine ("[" + section + "]");
}
/// <include file='IniWriter.xml' path='//Method[@name="WriteSectionComment"]/docs/*' />
public void WriteSection (string section, string comment)
{
ValidateState ();
writeState = IniWriteState.Section;
WriteLine ("[" + section + "]" + Comment(comment));
}
/// <include file='IniWriter.xml' path='//Method[@name="WriteKey"]/docs/*' />
public void WriteKey (string key, string value)
{
ValidateStateKey ();
WriteLine (key + " " + assignDelimiter + " " + GetKeyValue (value));
}
/// <include file='IniWriter.xml' path='//Method[@name="WriteKeyComment"]/docs/*' />
public void WriteKey (string key, string value, string comment)
{
ValidateStateKey ();
WriteLine (key + " " + assignDelimiter + " " + GetKeyValue (value) + Comment (comment));
}
/// <include file='IniWriter.xml' path='//Method[@name="WriteEmpty"]/docs/*' />
public void WriteEmpty ()
{
ValidateState ();
if (writeState == IniWriteState.Start) {
writeState = IniWriteState.BeforeFirstSection;
}
WriteLine ("");
}
/// <include file='IniWriter.xml' path='//Method[@name="WriteEmptyComment"]/docs/*' />
public void WriteEmpty (string comment)
{
ValidateState ();
if (writeState == IniWriteState.Start) {
writeState = IniWriteState.BeforeFirstSection;
}
if (comment == null) {
WriteLine ("");
} else {
WriteLine (commentDelimiter + " " + comment);
}
}
/// <include file='IniWriter.xml' path='//Method[@name="Dispose"]/docs/*' />
public void Dispose ()
{
Dispose (true);
}
#endregion
#region Protected methods
/// <include file='IniWriter.xml' path='//Method[@name="DisposeBoolean"]/docs/*' />
protected virtual void Dispose (bool disposing)
{
if (!disposed)
{
if (textWriter != null)
textWriter.Close ();
if (baseStream != null)
baseStream.Close ();
disposed = true;
if (disposing)
{
GC.SuppressFinalize (this);
}
}
}
#endregion
#region Private methods
/// <summary>
/// Destructor.
/// </summary>
~IniWriter ()
{
Dispose (false);
}
/// <summary>
/// Returns the value of a key.
/// </summary>
private string GetKeyValue (string text)
{
string result;
if (useValueQuotes) {
result = MassageValue ('"' + text + '"');
} else {
result = MassageValue (text);
}
return result;
}
/// <summary>
/// Validates whether a key can be written.
/// </summary>
private void ValidateStateKey ()
{
ValidateState ();
switch (writeState)
{
case IniWriteState.BeforeFirstSection:
case IniWriteState.Start:
throw new InvalidOperationException ("The WriteState is not Section");
case IniWriteState.Closed:
throw new InvalidOperationException ("The writer is closed");
}
}
/// <summary>
/// Validates the state to determine if the item can be written.
/// </summary>
private void ValidateState ()
{
if (writeState == IniWriteState.Closed) {
throw new InvalidOperationException ("The writer is closed");
}
}
/// <summary>
/// Returns a formatted comment.
/// </summary>
private string Comment (string text)
{
return (text == null) ? "" : (" " + commentDelimiter + " " + text);
}
/// <summary>
/// Writes data to the writer.
/// </summary>
private void Write (string value)
{
textWriter.Write (indentationBuffer.ToString () + value);
}
/// <summary>
/// Writes a full line to the writer.
/// </summary>
private void WriteLine (string value)
{
Write (value + eol);
}
/// <summary>
/// Fixes the incoming value to prevent illegal characters from
/// hurting the integrity of the INI file.
/// </summary>
private string MassageValue (string text)
{
return text.Replace ("\n", "");
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#region Assembly mscorlib.dll, v4.0.0.0
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\mscorlib.dll
#endregion
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime;
using System.Security;
namespace System.Diagnostics.Tracing
{
#if !SILVERLIGHT_4_0_WP && !SILVERLIGHT && !SILVERLIGHT_3_0 && !SILVERLIGHT_5_0 && !NETFRAMEWORK_3_5 && !NETFRAMEWORK_4_0
// Summary:
// Provides the ability to create events for event tracing for Windows (ETW).
public class EventSource // : IDisposable
{
// Summary:
// Creates a new instance of the System.Diagnostics.Tracing.EventSource class.
protected EventSource() { }
//
// Summary:
// Creates a new instance of the System.Diagnostics.Tracing.EventSource class
// and specifies whether to throw an exception when an error occurs in the underlying
// Windows code.
//
// Parameters:
// throwOnEventWriteErrors:
// true to throw an exception when an error occurs in the underlying Windows
// code; otherwise, false.
protected EventSource(bool throwOnEventWriteErrors) { }
// Summary:
// The unique identifier for the event source.
//
// Returns:
// A unique identifier for the event source.
extern public Guid Guid { get; }
//
// Summary:
// The friendly name of the class that is derived from the event source.
//
// Returns:
// The friendly name of the derived class. The default is the simple name of
// the class.
extern public string Name { get; }
// Summary:
// Returns a string of the XML manifest that is associated with the current
// event source.
//
// Parameters:
// eventSourceType:
// The type of the event source.
//
// assemblyPathToIncludeInManifest:
// The path to the .dll file to include in the manifest.
//
// Returns:
// The XML data string.
public static string GenerateManifest(Type eventSourceType, string assemblyPathToIncludeInManifest) { return null; }
//
// Summary:
// Gets the unique identifier for this implementation of the event source.
//
// Parameters:
// eventSourceType:
// The type of the event source.
//
// Returns:
// A unique identifier for this event source type.
public static Guid GetGuid(Type eventSourceType) { return default(Guid); }
//
// Summary:
// Gets the friendly name of the event source.
//
// Parameters:
// eventSourceType:
// The type of the event source.
//
// Returns:
// The friendly name of the event source. The default is the simple name of
// the class.
public static string GetName(Type eventSourceType) { { return null; } }
//
// Summary:
// Gets a snapshot of all the event sources for the application domain.
//
// Returns:
// An enumeration of all the event sources in the application domain.
public static IEnumerable<EventSource> GetSources() { return null; }
//
// Summary:
// Determines whether the current event source is enabled.
//
// Returns:
// true if the current event source is enabled; otherwise, false.
public bool IsEnabled() { return false; }
//
// Summary:
// Determines whether the current event source that has the specified level
// and keyword is enabled.
//
// Parameters:
// level:
// The level of the event source.
//
// keywords:
// The keyword of the event source.
//
// Returns:
// true if the event source is enabled; otherwise, false.
// public bool IsEnabled(EventLevel level, EventKeywords keywords);
//
// Summary:
// Called when the current event source is updated by the controller.
//
// Parameters:
// command:
// The arguments for the event.
// protected virtual void OnEventCommand(EventCommandEventArgs command);
//
// Summary:
// Sends a command to a specified event source.
//
// Parameters:
// eventSource:
// The event source to send the command to.
//
// command:
// The event command to send.
//
// commandArguments:
// The arguments for the event command.
//public static void SendCommand(EventSource eventSource, EventCommand command, IDictionary<string, string> commandArguments);
//
// Summary:
// Writes an event by using the provided event identifier.
//
// Parameters:
// eventId:
// The event identifier.
protected void WriteEvent(int eventId) { }
//
// Summary:
// Writes an event by using the provided event identifier and 32-bit integer
// argument.
//
// Parameters:
// eventId:
// The event identifier.
//
// arg1:
// An integer argument.
protected void WriteEvent(int eventId, int arg1) { }
//
// Summary:
// Writes an event by using the provided event identifier and 64-bit integer
// argument.
//
// Parameters:
// eventId:
// The event identifier.
//
// arg1:
// A 64 bit integer argument.
protected void WriteEvent(int eventId, long arg1) { }
//
// Summary:
// Writes an event by using the provided event identifier and array of arguments.
//
// Parameters:
// eventId:
// The event identifier.
//
// args:
// An array of objects.
protected void WriteEvent(int eventId, params object[] args) { }
//
// Summary:
// Writes an event by using the provided event identifier and string argument.
//
// Parameters:
// eventId:
// The event identifier.
//
// arg1:
// A string argument.
protected void WriteEvent(int eventId, string arg1) { }
//
// Summary:
// Writes an event by using the provided event identifier and 32-bit integer
// arguments.
//
// Parameters:
// eventId:
// The event identifier.
//
// arg1:
// An integer argument.
//
// arg2:
// An integer argument.
protected void WriteEvent(int eventId, int arg1, int arg2) { }
//
// Summary:
// Writes an event by using the provided event identifier and 64-bit arguments.
//
// Parameters:
// eventId:
// The event identifier.
//
// arg1:
// A 64 bit integer argument.
//
// arg2:
// A 64 bit integer argument.
protected void WriteEvent(int eventId, long arg1, long arg2) { }
//
// Summary:
// Writes an event by using the provided event identifier and arguments.
//
// Parameters:
// eventId:
// The event identifier.
//
// arg1:
// A string argument.
//
// arg2:
// A 32 bit integer argument.
protected void WriteEvent(int eventId, string arg1, int arg2) { }
//
// Summary:
// Writes an event by using the provided event identifier and arguments.
//
// Parameters:
// eventId:
// The event identifier.
//
// arg1:
// A string argument.
//
// arg2:
// A 64 bit integer argument.
protected void WriteEvent(int eventId, string arg1, long arg2) { }
//
// Summary:
// Writes an event by using the provided event identifier and string arguments.
//
// Parameters:
// eventId:
// The event identifier.
//
// arg1:
// A string argument.
//
// arg2:
// A string argument.
protected void WriteEvent(int eventId, string arg1, string arg2) { }
//
// Summary:
// Writes an event by using the provided event identifier and 32-bit integer
// arguments.
//
// Parameters:
// eventId:
// The event identifier.
//
// arg1:
// An integer argument.
//
// arg2:
// An integer argument.
//
// arg3:
// An integer argument.
protected void WriteEvent(int eventId, int arg1, int arg2, int arg3) { }
//
// Summary:
// Writes an event by using the provided event identifier and 64-bit arguments.
//
// Parameters:
// eventId:
// The event identifier.
//
// arg1:
// A 64 bit integer argument.
//
// arg2:
// A 64 bit integer argument.
//
// arg3:
// A 64 bit integer argument.
protected void WriteEvent(int eventId, long arg1, long arg2, long arg3) { }
//
// Summary:
// Writes an event by using the provided event identifier and arguments.
//
// Parameters:
// eventId:
// The event identifier.
//
// arg1:
// A string argument.
//
// arg2:
// A 32 bit integer argument.
//
// arg3:
// A 32 bit integer argument.
protected void WriteEvent(int eventId, string arg1, int arg2, int arg3) { }
//
// Summary:
// Writes an event by using the provided event identifier and string arguments.
//
// Parameters:
// eventId:
// The event identifier.
//
// arg1:
// A string argument.
//
// arg2:
// A string argument.
//
// arg3:
// A string argument.
protected void WriteEvent(int eventId, string arg1, string arg2, string arg3) { }
//
// Summary:
// Creates a new Overload:System.Diagnostics.Tracing.EventSource.WriteEvent
// overload by using the provided event identifier and event data.
//
// Parameters:
// eventId:
// The event identifier.
//
// eventDataCount:
// The number of event data items.
//
// data:
// The structure that contains the event data.
//protected void WriteEventCore(int eventId, int eventDataCount, EventSource.EventData* data) { }
// Summary:
// Provides the event data for creating fast Overload:System.Diagnostics.Tracing.EventSource.WriteEvent
// overloads by using the System.Diagnostics.Tracing.EventSource.WriteEventCore(System.Int32,System.Int32,System.Diagnostics.Tracing.EventSource.EventData*)
// method.
protected internal struct EventData
{
// Summary:
// Gets or sets the pointer to the data for the new Overload:System.Diagnostics.Tracing.EventSource.WriteEvent
// overload.
//
// Returns:
// The pointer to the data.
public IntPtr DataPointer { get; set; }
//
// Summary:
// Gets or sets the number of payload items in the new Overload:System.Diagnostics.Tracing.EventSource.WriteEvent
// overload.
//
// Returns:
// The number of payload items in the new overload.
public int Size { get; set; }
}
}
#endif
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Reflection;
using Microsoft.Win32;
using System.Diagnostics;
using UnrealBuildTool;
using System.Text.RegularExpressions;
namespace AutomationTool
{
/// <summary>
/// Defines the environment variable names that will be used to setup the environemt.
/// </summary>
static class EnvVarNames
{
// Command Environment
static public readonly string LocalRoot = "uebp_LOCAL_ROOT";
static public readonly string LogFolder = "uebp_LogFolder";
static public readonly string CSVFile = "uebp_CSVFile";
static public readonly string EngineSavedFolder = "uebp_EngineSavedFolder";
static public readonly string NETFrameworkDir = "FrameworkDir";
static public readonly string NETFrameworkVersion = "FrameworkVersion";
// Perforce Environment
static public readonly string P4Port = "uebp_PORT";
static public readonly string ClientRoot = "uebp_CLIENT_ROOT";
static public readonly string Changelist = "uebp_CL";
static public readonly string User = "uebp_USER";
static public readonly string Client = "uebp_CLIENT";
static public readonly string BuildRootP4 = "uebp_BuildRoot_P4";
static public readonly string BuildRootEscaped = "uebp_BuildRoot_Escaped";
static public readonly string LabelToSync = "uebp_LabelToSync";
static public readonly string P4Password = "uebp_PASS";
}
/// <summary>
/// Environment to allow access to commonly used environment variables.
/// </summary>
public class CommandEnvironment
{
/// <summary>
/// Path to a file we know to always exist under the UE4 root directory.
/// </summary>
public static readonly string KnownFileRelativeToRoot = @"Engine/Config/BaseEngine.ini";
#region Command Environment properties
public string LocalRoot { get; protected set; }
public string EngineSavedFolder { get; protected set; }
public string LogFolder { get; protected set; }
public string CSVFile { get; protected set; }
public string RobocopyExe { get; protected set; }
public string MountExe { get; protected set; }
public string CmdExe { get; protected set; }
public string UATExe { get; protected set; }
public string TimestampAsString { get; protected set; }
public bool HasCapabilityToCompile { get; protected set; }
public string MsBuildExe { get; protected set; }
public string MsDevExe { get; protected set; }
#endregion
internal CommandEnvironment()
{
InitEnvironment();
}
/// <summary>
/// Sets the location of the exe.
/// </summary>
protected void SetUATLocation()
{
if (String.IsNullOrEmpty(UATExe))
{
UATExe = CommandUtils.CombinePaths(Path.GetFullPath(InternalUtils.ExecutingAssemblyLocation));
}
if (!CommandUtils.FileExists_NoExceptions(UATExe))
{
throw new AutomationException("Could not find AutomationTool.exe. Reflection indicated it was here: {0}", UATExe);
}
}
/// <summary>
/// Sets the location of the AutomationTool/Saved directory
/// </summary>
protected void SetUATSavedPath()
{
var LocalRootPath = CommandUtils.GetEnvVar(EnvVarNames.LocalRoot);
var SavedPath = CommandUtils.CombinePaths(PathSeparator.Slash, LocalRootPath, "Engine", "Programs", "AutomationTool", "Saved");
CommandUtils.SetEnvVar(EnvVarNames.EngineSavedFolder, SavedPath);
}
/// <summary>
/// Initializes the environement.
/// </summary>
protected virtual void InitEnvironment()
{
SetUATLocation();
LocalRoot = CommandUtils.GetEnvVar(EnvVarNames.LocalRoot);
if (String.IsNullOrEmpty(CommandUtils.GetEnvVar(EnvVarNames.EngineSavedFolder)))
{
SetUATSavedPath();
}
if (LocalRoot.EndsWith(":"))
{
LocalRoot += Path.DirectorySeparatorChar;
}
EngineSavedFolder = CommandUtils.GetEnvVar(EnvVarNames.EngineSavedFolder);
CSVFile = CommandUtils.GetEnvVar(EnvVarNames.CSVFile);
LogFolder = CommandUtils.GetEnvVar(EnvVarNames.LogFolder);
RobocopyExe = GetSystemExePath("robocopy.exe");
MountExe = GetSystemExePath("mount.exe");
CmdExe = Utils.IsRunningOnMono ? "/bin/sh" : GetSystemExePath("cmd.exe");
if (String.IsNullOrEmpty(LogFolder))
{
throw new AutomationException("Environment is not set up correctly: LogFolder is not set!");
}
if (String.IsNullOrEmpty(LocalRoot))
{
throw new AutomationException("Environment is not set up correctly: LocalRoot is not set!");
}
if (String.IsNullOrEmpty(EngineSavedFolder))
{
throw new AutomationException("Environment is not set up correctly: EngineSavedFolder is not set!");
}
// Make sure that the log folder exists
var LogFolderInfo = new DirectoryInfo(LogFolder);
if (!LogFolderInfo.Exists)
{
LogFolderInfo.Create();
}
// Setup the timestamp string
DateTime LocalTime = DateTime.Now;
string TimeStamp = LocalTime.Year + "-"
+ LocalTime.Month.ToString("00") + "-"
+ LocalTime.Day.ToString("00") + "_"
+ LocalTime.Hour.ToString("00") + "."
+ LocalTime.Minute.ToString("00") + "."
+ LocalTime.Second.ToString("00");
TimestampAsString = TimeStamp;
SetupBuildEnvironment();
LogSettings();
}
/// <summary>
/// Returns the path to an executable in the System Directory.
/// To help support running 32-bit assemblies on a 64-bit operating system, if the executable
/// can't be found in System32, we also search Sysnative.
/// </summary>
/// <param name="ExeName">The name of the executable to find</param>
/// <returns>The path to the executable within the system folder</returns>
string GetSystemExePath(string ExeName)
{
var Result = CommandUtils.CombinePaths(Environment.SystemDirectory, ExeName);
if (!CommandUtils.FileExists(Result))
{
// Use Regex.Replace so we can do a case-insensitive replacement of System32
var SysNativeDirectory = Regex.Replace(Environment.SystemDirectory, "System32", "Sysnative", RegexOptions.IgnoreCase);
var SysNativeExe = CommandUtils.CombinePaths(SysNativeDirectory, ExeName);
if (CommandUtils.FileExists(SysNativeExe))
{
Result = SysNativeExe;
}
}
return Result;
}
void LogSettings()
{
Log.TraceVerbose("Command Environment settings:");
Log.TraceVerbose("CmdExe={0}", CmdExe);
Log.TraceVerbose("EngineSavedFolder={0}", EngineSavedFolder);
Log.TraceVerbose("HasCapabilityToCompile={0}", HasCapabilityToCompile);
Log.TraceVerbose("LocalRoot={0}", LocalRoot);
Log.TraceVerbose("LogFolder={0}", LogFolder);
Log.TraceVerbose("MountExe={0}", MountExe);
Log.TraceVerbose("MsBuildExe={0}", MsBuildExe);
Log.TraceVerbose("MsDevExe={0}", MsDevExe);
Log.TraceVerbose("RobocopyExe={0}", RobocopyExe);
Log.TraceVerbose("TimestampAsString={0}", TimestampAsString);
Log.TraceVerbose("UATExe={0}", UATExe);
}
#region Compiler Setup
/// <summary>
/// Initializes build environemnt: finds the path to msbuild.exe
/// </summary>
void SetupBuildEnvironment()
{
// Assume we have the capability co compile.
HasCapabilityToCompile = true;
try
{
HostPlatform.Current.SetFrameworkVars();
}
catch (Exception)
{
// Something went wrong, we can't compile.
Log.WriteLine(TraceEventType.Warning, "SetFrameworkVars failed. Assuming no compilation capability.");
HasCapabilityToCompile = false;
}
if (HasCapabilityToCompile)
{
try
{
MsBuildExe = HostPlatform.Current.GetMsBuildExe();
}
catch (Exception Ex)
{
Log.WriteLine(TraceEventType.Warning, Ex.Message);
Log.WriteLine(TraceEventType.Warning, "Assuming no compilation capability.");
HasCapabilityToCompile = false;
MsBuildExe = "";
}
}
if (HasCapabilityToCompile)
{
try
{
MsDevExe = HostPlatform.Current.GetMsDevExe();
}
catch (Exception Ex)
{
Log.WriteLine(TraceEventType.Warning, Ex.Message);
Log.WriteLine(TraceEventType.Warning, "Assuming no solution compilation capability.");
MsDevExe = "";
}
}
Log.TraceVerbose("CompilationEvironment.HasCapabilityToCompile={0}", HasCapabilityToCompile);
Log.TraceVerbose("CompilationEvironment.MsBuildExe={0}", MsBuildExe);
Log.TraceVerbose("CompilationEvironment.MsDevExe={0}", MsDevExe);
}
#endregion
}
}
| |
using Content.Server.Atmos.EntitySystems;
using Content.Server.Body.Components;
using Content.Server.Explosion.EntitySystems;
using Content.Server.UserInterface;
using Content.Shared.Actions;
using Content.Shared.Actions.ActionTypes;
using Content.Shared.Atmos;
using Content.Shared.Atmos.Components;
using Content.Shared.Audio;
using Content.Shared.Examine;
using Content.Shared.Interaction;
using Content.Shared.Sound;
using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.Player;
using Robust.Shared.Utility;
namespace Content.Server.Atmos.Components
{
[RegisterComponent]
[ComponentReference(typeof(IActivate))]
#pragma warning disable 618
public sealed class GasTankComponent : Component, IExamine, IGasMixtureHolder, IDropped, IActivate
#pragma warning restore 618
{
[Dependency] private readonly IEntityManager _entMan = default!;
private const float MaxExplosionRange = 14f;
private const float DefaultOutputPressure = Atmospherics.OneAtmosphere;
private int _integrity = 3;
[Dependency] private readonly IEntityManager _entityManager = default!;
[ViewVariables] private BoundUserInterface? _userInterface;
[DataField("ruptureSound")] private SoundSpecifier _ruptureSound = new SoundPathSpecifier("Audio/Effects/spray.ogg");
[DataField("air")] [ViewVariables] public GasMixture Air { get; set; } = new();
/// <summary>
/// Distributed pressure.
/// </summary>
[DataField("outputPressure")]
[ViewVariables]
public float OutputPressure { get; private set; } = DefaultOutputPressure;
/// <summary>
/// Tank is connected to internals.
/// </summary>
[ViewVariables] public bool IsConnected { get; set; }
/// <summary>
/// Represents that tank is functional and can be connected to internals.
/// </summary>
public bool IsFunctional => GetInternalsComponent() != null;
/// <summary>
/// Pressure at which tanks start leaking.
/// </summary>
[DataField("tankLeakPressure")]
public float TankLeakPressure { get; set; } = 30 * Atmospherics.OneAtmosphere;
/// <summary>
/// Pressure at which tank spills all contents into atmosphere.
/// </summary>
[DataField("tankRupturePressure")]
public float TankRupturePressure { get; set; } = 40 * Atmospherics.OneAtmosphere;
/// <summary>
/// Base 3x3 explosion.
/// </summary>
[DataField("tankFragmentPressure")]
public float TankFragmentPressure { get; set; } = 50 * Atmospherics.OneAtmosphere;
/// <summary>
/// Increases explosion for each scale kPa above threshold.
/// </summary>
[DataField("tankFragmentScale")]
public float TankFragmentScale { get; set; } = 10 * Atmospherics.OneAtmosphere;
[DataField("toggleAction", required: true)]
public InstantAction ToggleAction = new();
protected override void Initialize()
{
base.Initialize();
_userInterface = Owner.GetUIOrNull(SharedGasTankUiKey.Key);
if (_userInterface != null)
{
_userInterface.OnReceiveMessage += UserInterfaceOnOnReceiveMessage;
}
}
public void OpenInterface(IPlayerSession session)
{
_userInterface?.Open(session);
UpdateUserInterface(true);
}
public void Examine(FormattedMessage message, bool inDetailsRange)
{
message.AddMarkup(Loc.GetString("comp-gas-tank-examine", ("pressure", Math.Round(Air?.Pressure ?? 0))));
if (IsConnected)
{
message.AddText("\n");
message.AddMarkup(Loc.GetString("comp-gas-tank-connected"));
}
}
protected override void Shutdown()
{
base.Shutdown();
DisconnectFromInternals();
}
public GasMixture? RemoveAir(float amount)
{
var gas = Air?.Remove(amount);
CheckStatus();
return gas;
}
public GasMixture RemoveAirVolume(float volume)
{
if (Air == null)
return new GasMixture(volume);
var tankPressure = Air.Pressure;
if (tankPressure < OutputPressure)
{
OutputPressure = tankPressure;
UpdateUserInterface();
}
var molesNeeded = OutputPressure * volume / (Atmospherics.R * Air.Temperature);
var air = RemoveAir(molesNeeded);
if (air != null)
air.Volume = volume;
else
return new GasMixture(volume);
return air;
}
void IActivate.Activate(ActivateEventArgs eventArgs)
{
if (!_entMan.TryGetComponent(eventArgs.User, out ActorComponent? actor)) return;
OpenInterface(actor.PlayerSession);
}
public void ConnectToInternals()
{
if (IsConnected || !IsFunctional) return;
var internals = GetInternalsComponent();
if (internals == null) return;
IsConnected = internals.TryConnectTank(Owner);
EntitySystem.Get<SharedActionsSystem>().SetToggled(ToggleAction, IsConnected);
UpdateUserInterface();
}
public void DisconnectFromInternals(EntityUid? owner = null)
{
if (!IsConnected) return;
IsConnected = false;
EntitySystem.Get<SharedActionsSystem>().SetToggled(ToggleAction, false);
GetInternalsComponent(owner)?.DisconnectTank();
UpdateUserInterface();
}
public void UpdateUserInterface(bool initialUpdate = false)
{
var internals = GetInternalsComponent();
_userInterface?.SetState(
new GasTankBoundUserInterfaceState
{
TankPressure = Air?.Pressure ?? 0,
OutputPressure = initialUpdate ? OutputPressure : null,
InternalsConnected = IsConnected,
CanConnectInternals = IsFunctional && internals != null
});
}
private void UserInterfaceOnOnReceiveMessage(ServerBoundUserInterfaceMessage message)
{
switch (message.Message)
{
case GasTankSetPressureMessage msg:
OutputPressure = msg.Pressure;
break;
case GasTankToggleInternalsMessage _:
ToggleInternals();
break;
}
}
internal void ToggleInternals()
{
if (IsConnected)
{
DisconnectFromInternals();
return;
}
ConnectToInternals();
}
private InternalsComponent? GetInternalsComponent(EntityUid? owner = null)
{
if (_entMan.Deleted(Owner)) return null;
if (owner != null) return _entMan.GetComponentOrNull<InternalsComponent>(owner.Value);
return Owner.TryGetContainer(out var container)
? _entMan.GetComponentOrNull<InternalsComponent>(container.Owner)
: null;
}
public void AssumeAir(GasMixture giver)
{
EntitySystem.Get<AtmosphereSystem>().Merge(Air, giver);
CheckStatus();
}
public void CheckStatus()
{
if (Air == null)
return;
var atmosphereSystem = EntitySystem.Get<AtmosphereSystem>();
var pressure = Air.Pressure;
if (pressure > TankFragmentPressure)
{
// Give the gas a chance to build up more pressure.
for (var i = 0; i < 3; i++)
{
atmosphereSystem.React(Air, this);
}
pressure = Air.Pressure;
var range = (pressure - TankFragmentPressure) / TankFragmentScale;
// Let's cap the explosion, yeah?
if (range > MaxExplosionRange)
{
range = MaxExplosionRange;
}
EntitySystem.Get<ExplosionSystem>().SpawnExplosion(Owner, (int) (range * 0.25f), (int) (range * 0.5f), (int) (range * 1.5f), 1);
_entMan.QueueDeleteEntity(Owner);
return;
}
if (pressure > TankRupturePressure)
{
if (_integrity <= 0)
{
var environment = atmosphereSystem.GetTileMixture(_entMan.GetComponent<TransformComponent>(Owner).Coordinates, true);
if(environment != null)
atmosphereSystem.Merge(environment, Air);
SoundSystem.Play(Filter.Pvs(Owner), _ruptureSound.GetSound(), _entMan.GetComponent<TransformComponent>(Owner).Coordinates, AudioHelpers.WithVariation(0.125f));
_entMan.QueueDeleteEntity(Owner);
return;
}
_integrity--;
return;
}
if (pressure > TankLeakPressure)
{
if (_integrity <= 0)
{
var environment = atmosphereSystem.GetTileMixture(_entMan.GetComponent<TransformComponent>(Owner).Coordinates, true);
if (environment == null)
return;
var leakedGas = Air.RemoveRatio(0.25f);
atmosphereSystem.Merge(environment, leakedGas);
}
else
{
_integrity--;
}
return;
}
if (_integrity < 3)
_integrity++;
}
void IDropped.Dropped(DroppedEventArgs eventArgs)
{
DisconnectFromInternals(eventArgs.User);
}
}
}
| |
// 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.Runtime.InteropServices;
namespace OpenLiveWriter.Interop.Com
{
/*
/// <summary>
/// Generic COM/OLE command dispatching interface
/// </summary>
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("b722bccb-4e68-101b-a2bc-00aa00404770")]
public interface IOleCommandTargetTest
{
/// <summary>
/// Queries the object for the status of one or more commands generated by user
/// interface events. Note that because we couldn't get COM interop to correctly
/// marshall the array of OLECMDs, our declaration of this interface supports
/// only querying for status on a single-command. This is not a problem as almost
/// all instances where you would implement IOleCommandTarget are for a single
/// command. Implementations should ASSERT that cCmds is 1
/// </summary>
/// <param name="pguidCmdGroup"> Unique identifier of the command group; can be NULL to
/// specify the standard group. All the commands that are passed in the prgCmds
/// array must belong to the group specified by pguidCmdGroup</param>
/// <param name="cCmds">The number of commands in the prgCmds array. For this
/// interface declaration (which doesn't support arrays of OLECMD) this value
/// MUST always be 1.</param>
/// <param name="prgCmds">Reference to the command that is being queried for
/// its status -- this parameter should be filled in with the appropriate
/// values.</param>
/// <param name="pCmdText">Pointer to an OLECMDTEXT structure in which to return
/// name and/or status information of a single command. Can be NULL to indicate
/// that the caller does not need this information. Note that because of
/// marshalling issues w/ the OLECMDTEXT structure (can't figure out how to
/// marshall it correctly) we required that this parameter be NULL (implementations
/// should Assert on this). Note that IE currently passes NULL for this parameter
/// for custom toolbar button implementations.</param>
void QueryStatus(
IntPtr pguidCmdGroup,
uint cCmds,
IntPtr prgCmds,
IntPtr pCmdText);
/// <summary>
/// Executes a specified command or displays help for a command
/// </summary>
/// <param name="pguidCmdGroup">Pointer to unique identifier of the command group; can be
/// NULL to specify the standard group</param>
/// <param name="nCmdID">The command to be executed. This command must belong to the
/// group specified with pguidCmdGroup</param>
/// <param name="nCmdexecopt">Values taken from the OLECMDEXECOPT enumeration, which
/// describe how the object should execute the command</param>
/// <param name="pvaIn">Pointer to a VARIANTARG structure containing input arguments.
/// Can be NULL</param>
/// <param name="pvaOut">Pointer to a VARIANTARG structure to receive command output.
/// Can be NULL.</param>
void Exec(
IntPtr pguidCmdGroup,
uint nCmdID,
OLECMDEXECOPT nCmdexecopt,
IntPtr pvaIn,
IntPtr pvaOut ) ;
}
*/
/// <summary>
/// Generic COM/OLE command dispatching interface
/// </summary>
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("b722bccb-4e68-101b-a2bc-00aa00404770")]
public interface IOleCommandTarget
{
/// <summary>
/// Queries the object for the status of one or more commands generated by user
/// interface events.
/// </summary>
/// <param name="pguidCmdGroup"> Unique identifier of the command group; can be NULL to
/// specify the standard group. All the commands that are passed in the prgCmds
/// array must belong to the group specified by pguidCmdGroup</param>
/// <param name="cCmds">The number of commands in the prgCmds array.</param>
/// <param name="prgCmds">Reference to the command that is being queried for
/// its status -- this parameter should be filled in with the appropriate
/// values.</param>
/// <param name="pCmdText">Pointer to an OLECMDTEXT structure in which to return
/// name and/or status information of a single command. Can be NULL to indicate
/// that the caller does not need this information. Note that because of
/// marshalling issues w/ the OLECMDTEXT structure (can't figure out how to
/// marshall it correctly) we required that this parameter be NULL (implementations
/// should Assert on this). Note that IE currently passes NULL for this parameter
/// for custom toolbar button implementations.</param>
[PreserveSig]
int QueryStatus(
[In] ref Guid pguidCmdGroup,
[In] uint cCmds,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] OLECMD[] prgCmds,
[In, Out] IntPtr pCmdText);
/// <summary>
/// Executes a specified command or displays help for a command
/// </summary>
/// <param name="pguidCmdGroup">Pointer to unique identifier of the command group; can be
/// NULL to specify the standard group</param>
/// <param name="nCmdID">The command to be executed. This command must belong to the
/// group specified with pguidCmdGroup</param>
/// <param name="nCmdexecopt">Values taken from the OLECMDEXECOPT enumeration, which
/// describe how the object should execute the command</param>
/// <param name="pvaIn">Pointer to a VARIANTARG structure containing input arguments.
/// Can be NULL</param>
/// <param name="pvaOut">Pointer to a VARIANTARG structure to receive command output.
/// Can be NULL.</param>
[PreserveSig]
int Exec(
[In] ref Guid pguidCmdGroup,
[In] uint nCmdID,
[In] OLECMDEXECOPT nCmdexecopt,
[In] IntPtr pvaIn,
[In, Out] IntPtr pvaOut);
}
/// <summary>
/// Generic COM/OLE command dispatching interface. This version of the declaration
/// declares the two optional Exec parameters as ref object to allow for passing
/// parameters to the Exec method. The reason we need to do this is that these
/// parameters are defined as VARIANTARG* however the value passed can be NULL. If
/// we declare them as object and the caller passes NULL then the runtime blows up.
/// We therefore need two separate declarations for the interface depending upon
/// its use.
/// </summary>
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("b722bccb-4e68-101b-a2bc-00aa00404770")]
public interface IOleCommandTargetWithExecParams
{
/// <summary>
/// Queries the object for the status of one or more commands generated by user
/// interface events. Note that because we couldn't get COM interop to correctly
/// marshall the array of OLECMDs, our declaration of this interface supports
/// only querying for status on a single-command. This is not a problem as almost
/// all instances where you would implement IOleCommandTarget are for a single
/// command. Implementations should ASSERT that cCmds is 1
/// </summary>
/// <param name="pguidCmdGroup"> Unique identifier of the command group; can be NULL to
/// specify the standard group. All the commands that are passed in the prgCmds
/// array must belong to the group specified by pguidCmdGroup</param>
/// <param name="cCmds">The number of commands in the prgCmds array. For this
/// interface declaration (which doesn't support arrays of OLECMD) this value
/// MUST always be 1.</param>
/// <param name="prgCmds">Reference to the command that is being queried for
/// its status -- this parameter should be filled in with the appropriate
/// values.</param>
/// <param name="pCmdText">Pointer to an OLECMDTEXT structure in which to return
/// name and/or status information of a single command. Can be NULL to indicate
/// that the caller does not need this information. Note that because of
/// marshalling issues w/ the OLECMDTEXT structure (can't figure out how to
/// marshall it correctly) we required that this parameter be NULL (implementations
/// should Assert on this). Note that IE currently passes NULL for this parameter
/// for custom toolbar button implementations.</param>
void QueryStatus(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid pguidCmdGroup,
[In] uint cCmds,
[In, Out] ref OLECMD prgCmds,
[In, Out] IntPtr pCmdText);
/// <summary>
/// Executes a specified command or displays help for a command
/// </summary>
/// <param name="pguidCmdGroup">Pointer to unique identifier of the command group; can be
/// NULL to specify the standard group</param>
/// <param name="nCmdID">The command to be executed. This command must belong to the
/// group specified with pguidCmdGroup</param>
/// <param name="nCmdexecopt">Values taken from the OLECMDEXECOPT enumeration, which
/// describe how the object should execute the command</param>
/// <param name="pvaIn">Variant input parameter</param>
/// <param name="pvaOut">Variant out parameter</param>
void Exec(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid pguidCmdGroup,
[In] uint nCmdID,
[In] OLECMDEXECOPT nCmdexecopt,
[In] ref object pvaIn,
[In, Out] ref object pvaOut);
}
/// <summary>
/// Generic COM/OLE command dispatching interface. This version of the declaration
/// allows for the passing of NULL for the input parmaeter and object for the
/// output parameter, thereby making it compatible with implementations that expect
/// a NULL input parameter as an indicator that a command value request is occurring.
/// </summary>
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("b722bccb-4e68-101b-a2bc-00aa00404770")]
public interface IOleCommandTargetGetCommandValue
{
/// <summary>
/// Queries the object for the status of one or more commands generated by user
/// interface events. Note that because we couldn't get COM interop to correctly
/// marshall the array of OLECMDs, our declaration of this interface supports
/// only querying for status on a single-command. This is not a problem as almost
/// all instances where you would implement IOleCommandTarget are for a single
/// command. Implementations should ASSERT that cCmds is 1
/// </summary>
/// <param name="pguidCmdGroup"> Unique identifier of the command group; can be NULL to
/// specify the standard group. All the commands that are passed in the prgCmds
/// array must belong to the group specified by pguidCmdGroup</param>
/// <param name="cCmds">The number of commands in the prgCmds array. For this
/// interface declaration (which doesn't support arrays of OLECMD) this value
/// MUST always be 1.</param>
/// <param name="prgCmds">Reference to the command that is being queried for
/// its status -- this parameter should be filled in with the appropriate
/// values.</param>
/// <param name="pCmdText">Pointer to an OLECMDTEXT structure in which to return
/// name and/or status information of a single command. Can be NULL to indicate
/// that the caller does not need this information. Note that because of
/// marshalling issues w/ the OLECMDTEXT structure (can't figure out how to
/// marshall it correctly) we required that this parameter be NULL (implementations
/// should Assert on this). Note that IE currently passes NULL for this parameter
/// for custom toolbar button implementations.</param>
void QueryStatus(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid pguidCmdGroup,
[In] uint cCmds,
[In, Out] ref OLECMD prgCmds,
[In, Out] IntPtr pCmdText);
/// <summary>
/// Executes a specified command or displays help for a command
/// </summary>
/// <param name="pguidCmdGroup">Pointer to unique identifier of the command group; can be
/// NULL to specify the standard group</param>
/// <param name="nCmdID">The command to be executed. This command must belong to the
/// group specified with pguidCmdGroup</param>
/// <param name="nCmdexecopt">Values taken from the OLECMDEXECOPT enumeration, which
/// describe how the object should execute the command</param>
/// <param name="pvaIn">Variant input parameter</param>
/// <param name="pvaOut">Variant out parameter</param>
void Exec(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid pguidCmdGroup,
[In] uint nCmdID,
[In] OLECMDEXECOPT nCmdexecopt,
[In] IntPtr pvaIn,
[In, Out] ref object pvaOut);
}
/// <summary>
/// Generic COM/OLE command dispatching interface. This version of the declaration
/// allows for the passing of NULL for the input parmaeter and object for the
/// output parameter, thereby making it compatible with implementations that expect
/// a NULL input parameter as an indicator that a command value request is occurring.
/// </summary>
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("b722bccb-4e68-101b-a2bc-00aa00404770")]
public interface IOleCommandTargetNullOutputParam
{
/// <summary>
/// Queries the object for the status of one or more commands generated by user
/// interface events. Note that because we couldn't get COM interop to correctly
/// marshall the array of OLECMDs, our declaration of this interface supports
/// only querying for status on a single-command. This is not a problem as almost
/// all instances where you would implement IOleCommandTarget are for a single
/// command. Implementations should ASSERT that cCmds is 1
/// </summary>
/// <param name="pguidCmdGroup"> Unique identifier of the command group; can be NULL to
/// specify the standard group. All the commands that are passed in the prgCmds
/// array must belong to the group specified by pguidCmdGroup</param>
/// <param name="cCmds">The number of commands in the prgCmds array. For this
/// interface declaration (which doesn't support arrays of OLECMD) this value
/// MUST always be 1.</param>
/// <param name="prgCmds">Reference to the command that is being queried for
/// its status -- this parameter should be filled in with the appropriate
/// values.</param>
/// <param name="pCmdText">Pointer to an OLECMDTEXT structure in which to return
/// name and/or status information of a single command. Can be NULL to indicate
/// that the caller does not need this information. Note that because of
/// marshalling issues w/ the OLECMDTEXT structure (can't figure out how to
/// marshall it correctly) we required that this parameter be NULL (implementations
/// should Assert on this). Note that IE currently passes NULL for this parameter
/// for custom toolbar button implementations.</param>
void QueryStatus(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid pguidCmdGroup,
[In] uint cCmds,
[In, Out] ref OLECMD prgCmds,
[In, Out] IntPtr pCmdText);
/// <summary>
/// Executes a specified command or displays help for a command
/// </summary>
/// <param name="pguidCmdGroup">Pointer to unique identifier of the command group; can be
/// NULL to specify the standard group</param>
/// <param name="nCmdID">The command to be executed. This command must belong to the
/// group specified with pguidCmdGroup</param>
/// <param name="nCmdexecopt">Values taken from the OLECMDEXECOPT enumeration, which
/// describe how the object should execute the command</param>
/// <param name="pvaIn">Variant input parameter</param>
/// <param name="pvaOut">Variant out parameter</param>
void Exec(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid pguidCmdGroup,
[In] uint nCmdID,
[In] OLECMDEXECOPT nCmdexecopt,
[In] ref object pvaIn,
[In, Out] IntPtr pvaOut);
}
/// <summary>
///
/// </summary>
public enum OLECMDF : uint
{
None = 0,
/// <summary>
/// The command is supported by this object
/// </summary>
SUPPORTED = 1,
/// <summary>
/// The command is available and enabled
/// </summary>
ENABLED = 2,
/// <summary>
/// The command is an on-off toggle and is currently on
/// </summary>
LATCHED = 4,
/// <summary>
/// Reserved for future use
/// </summary>
NINCHED = 8
}
/// <summary>
///
/// </summary>
public enum OLECMDTEXTF : uint
{
/// <summary>
/// No extra information is requested
/// </summary>
NONE = 0,
/// <summary>
/// The object should provide the localized name of the command
/// </summary>
NAME = 1,
/// <summary>
/// The object should provide a localized status string for the command
/// </summary>
STATUS = 2
}
/// <summary>
///
/// </summary>
public enum OLECMDEXECOPT : uint
{
/// <summary>
/// Prompt the user for input or not, whichever is the default behavior
/// </summary>
DODEFAULT = 0,
/// <summary>
/// Execute the command after obtaining user input
/// </summary>
PROMPTUSER = 1,
/// <summary>
/// Execute the command without prompting the user. For example, clicking the Print
/// toolbar button causes a document to be immediately printed without user input
/// </summary>
DONTPROMPTUSER = 2,
/// <summary>
/// Show help for the corresponding command, but do not execute
/// </summary>
SHOWHELP = 3
}
/// <summary>
///
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct OLECMD
{
/// <summary>
/// A command identifier; taken from the OLECMDID enumeration
/// </summary>
public uint cmdID;
/// <summary>
/// Flags associated with cmdID; taken from the OLECMDF enumeration
/// </summary>
public OLECMDF cmdf;
}
public static class OLECMDID
{
// public const uint OPEN = 1;
// public const uint NEW = 2;
// public const uint SAVE = 3;
// public const uint SAVEAS = 4;
// public const uint SAVECOPYAS = 5;
// public const uint PRINT = 6;
// public const uint PRINTPREVIEW = 7;
// public const uint PAGESETUP = 8;
// public const uint SPELL = 9;
// public const uint PROPERTIES = 10;
// public const uint CUT = 11;
// public const uint COPY = 12;
// public const uint PASTE = 13;
// public const uint PASTESPECIAL = 14;
// public const uint UNDO = 15;
// public const uint REDO = 16;
// public const uint SELECTALL = 17;
// public const uint CLEARSELECTION = 18;
// public const uint ZOOM = 19;
// public const uint GETZOOMRANGE = 20;
// public const uint UPDATECOMMANDS = 21;
// public const uint REFRESH = 22;
// public const uint STOP = 23;
// public const uint HIDETOOLBARS = 24;
// public const uint SETPROGRESSMAX = 25;
// public const uint SETPROGRESSPOS = 26;
// public const uint SETPROGRESSTEXT = 27;
// public const uint SETTITLE = 28;
// public const uint SETDOWNLOADSTATE = 29;
// public const uint STOPDOWNLOAD = 30;
// public const uint ONTOOLBARACTIVATED = 31;
// public const uint FIND = 32;
// public const uint DELETE = 33;
// public const uint HTTPEQUIV = 34;
// public const uint HTTPEQUIV_DONE = 35;
// public const uint ENABLE_INTERACTION = 36;
// public const uint ONUNLOAD = 37;
// public const uint PROPERTYBAG2 = 38;
// public const uint PREREFRESH = 39;
public const uint SHOWSCRIPTERROR = 40;
public const uint SHOWMESSAGE = 41;
// public const uint SHOWFIND = 42;
// public const uint SHOWPAGESETUP = 43;
// public const uint SHOWPRINT = 44;
// public const uint CLOSE = 45;
// public const uint ALLOWUILESSSAVEAS = 46;
// public const uint DONTDOWNLOADCSS = 47;
// public const uint UPDATEPAGESTATUS = 48;
// public const uint PRINT2 = 49;
// public const uint PRINTPREVIEW2 = 50;
// public const uint SETPRINTTEMPLATE = 51;
// public const uint GETPRINTTEMPLATE = 52;
// public const uint PAGEACTIONBLOCKED = 55;
// public const uint PAGEACTIONUIQUERY = 56;
// public const uint FOCUSVIEWCONTROLS = 57;
// public const uint FOCUSVIEWCONTROLSQUERY = 58;
// public const uint SHOWPAGEACTIONMENU = 59;
}
/// <summary>
/// Parameter pCmdtext to QueryStatus method but currently unused
/// since IE passes NULL pointer. Note that if we want to start
/// using this structure we will need to get the marshalling right
/// (rgwz currently doesn't work as needed)
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct OLECMDTEXT
{
/// <summary>
/// A value from the OLECMDTEXTF enumeration describing whether the rgwz parameter
/// contains a command name or status text
/// </summary>
public OLECMDTEXTF cmdtextf;
/// <summary>
/// The number of characters actually written into the rgwz buffer before QueryStatus
/// returns
/// </summary>
public uint cwActual;
/// <summary>
/// The number of elements in the rgwz arr
/// </summary>
public uint cwBuf;
/// <summary>
/// A caller-allocated array of wide characters to receive the command name or
/// status text
/// </summary>
public char[] rgwz;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Net.Mail;
using System.Text;
namespace System.Net.Http.Headers
{
internal static class HeaderUtilities
{
private const string qualityName = "q";
internal const string ConnectionClose = "close";
internal static readonly TransferCodingHeaderValue TransferEncodingChunked =
new TransferCodingHeaderValue("chunked");
internal static readonly NameValueWithParametersHeaderValue ExpectContinue =
new NameValueWithParametersHeaderValue("100-continue");
internal const string BytesUnit = "bytes";
// Validator
internal static readonly Action<HttpHeaderValueCollection<string>, string> TokenValidator = ValidateToken;
internal static void SetQuality(ICollection<NameValueHeaderValue> parameters, double? value)
{
Contract.Requires(parameters != null);
NameValueHeaderValue qualityParameter = NameValueHeaderValue.Find(parameters, qualityName);
if (value.HasValue)
{
// Note that even if we check the value here, we can't prevent a user from adding an invalid quality
// value using Parameters.Add(). Even if we would prevent the user from adding an invalid value
// using Parameters.Add() he could always add invalid values using HttpHeaders.AddWithoutValidation().
// So this check is really for convenience to show users that they're trying to add an invalid
// value.
if ((value < 0) || (value > 1))
{
throw new ArgumentOutOfRangeException("value");
}
string qualityString = ((double)value).ToString("0.0##", NumberFormatInfo.InvariantInfo);
if (qualityParameter != null)
{
qualityParameter.Value = qualityString;
}
else
{
parameters.Add(new NameValueHeaderValue(qualityName, qualityString));
}
}
else
{
// Remove quality parameter
if (qualityParameter != null)
{
parameters.Remove(qualityParameter);
}
}
}
internal static double? GetQuality(ICollection<NameValueHeaderValue> parameters)
{
Contract.Requires(parameters != null);
NameValueHeaderValue qualityParameter = NameValueHeaderValue.Find(parameters, qualityName);
if (qualityParameter != null)
{
// Note that the RFC requires decimal '.' regardless of the culture. I.e. using ',' as decimal
// separator is considered invalid (even if the current culture would allow it).
double qualityValue = 0;
if (double.TryParse(qualityParameter.Value, NumberStyles.AllowDecimalPoint,
NumberFormatInfo.InvariantInfo, out qualityValue))
{
return qualityValue;
}
// If the stored value is an invalid quality value, just return null and log a warning.
if (Logging.On) Logging.PrintError(Logging.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_headers_invalid_quality, qualityParameter.Value));
}
return null;
}
internal static void CheckValidToken(string value, string parameterName)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
if (HttpRuleParser.GetTokenLength(value, 0) != value.Length)
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
internal static void CheckValidComment(string value, string parameterName)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
int length = 0;
if ((HttpRuleParser.GetCommentLength(value, 0, out length) != HttpParseResult.Parsed) ||
(length != value.Length)) // no trailing spaces allowed
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
internal static void CheckValidQuotedString(string value, string parameterName)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
int length = 0;
if ((HttpRuleParser.GetQuotedStringLength(value, 0, out length) != HttpParseResult.Parsed) ||
(length != value.Length)) // no trailing spaces allowed
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
internal static bool AreEqualCollections<T>(ICollection<T> x, ICollection<T> y)
{
return AreEqualCollections(x, y, null);
}
internal static bool AreEqualCollections<T>(ICollection<T> x, ICollection<T> y, IEqualityComparer<T> comparer)
{
if (x == null)
{
return (y == null) || (y.Count == 0);
}
if (y == null)
{
return (x.Count == 0);
}
if (x.Count != y.Count)
{
return false;
}
if (x.Count == 0)
{
return true;
}
// We have two unordered lists. So comparison is an O(n*m) operation which is expensive. Usually
// headers have 1-2 parameters (if any), so this comparison shouldn't be too expensive.
bool[] alreadyFound = new bool[x.Count];
int i = 0;
foreach (var xItem in x)
{
Debug.Assert(xItem != null);
i = 0;
bool found = false;
foreach (var yItem in y)
{
if (!alreadyFound[i])
{
if (((comparer == null) && xItem.Equals(yItem)) ||
((comparer != null) && comparer.Equals(xItem, yItem)))
{
alreadyFound[i] = true;
found = true;
break;
}
}
i++;
}
if (!found)
{
return false;
}
}
// Since we never re-use a "found" value in 'y', we expect 'alreadyFound' to have all fields set to 'true'.
// Otherwise the two collections can't be equal and we should not get here.
Debug.Assert(Contract.ForAll(alreadyFound, value => { return value; }),
"Expected all values in 'alreadyFound' to be true since collections are considered equal.");
return true;
}
internal static int GetNextNonEmptyOrWhitespaceIndex(string input, int startIndex, bool skipEmptyValues,
out bool separatorFound)
{
Contract.Requires(input != null);
Contract.Requires(startIndex <= input.Length); // it's OK if index == value.Length.
separatorFound = false;
int current = startIndex + HttpRuleParser.GetWhitespaceLength(input, startIndex);
if ((current == input.Length) || (input[current] != ','))
{
return current;
}
// If we have a separator, skip the separator and all following whitespaces. If we support
// empty values, continue until the current character is neither a separator nor a whitespace.
separatorFound = true;
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
if (skipEmptyValues)
{
while ((current < input.Length) && (input[current] == ','))
{
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
}
return current;
}
internal static DateTimeOffset? GetDateTimeOffsetValue(string headerName, HttpHeaders store)
{
Contract.Requires(store != null);
object storedValue = store.GetParsedValues(headerName);
if (storedValue != null)
{
return (DateTimeOffset)storedValue;
}
return null;
}
internal static TimeSpan? GetTimeSpanValue(string headerName, HttpHeaders store)
{
Contract.Requires(store != null);
object storedValue = store.GetParsedValues(headerName);
if (storedValue != null)
{
return (TimeSpan)storedValue;
}
return null;
}
internal static bool TryParseInt32(string value, out int result)
{
return int.TryParse(value, NumberStyles.None, NumberFormatInfo.InvariantInfo, out result);
}
internal static bool TryParseInt64(string value, out long result)
{
return long.TryParse(value, NumberStyles.None, NumberFormatInfo.InvariantInfo, out result);
}
internal static string DumpHeaders(params HttpHeaders[] headers)
{
// Return all headers as string similar to:
// {
// HeaderName1: Value1
// HeaderName1: Value2
// HeaderName2: Value1
// ...
// }
StringBuilder sb = new StringBuilder();
sb.Append("{\r\n");
for (int i = 0; i < headers.Length; i++)
{
if (headers[i] != null)
{
foreach (var header in headers[i])
{
foreach (var headerValue in header.Value)
{
sb.Append(" ");
sb.Append(header.Key);
sb.Append(": ");
sb.Append(headerValue);
sb.Append("\r\n");
}
}
}
}
sb.Append('}');
return sb.ToString();
}
internal static bool IsValidEmailAddress(string value)
{
try
{
#if NETNative
new MailAddress(value);
#else
MailAddressParser.ParseAddress(value);
#endif
return true;
}
catch (FormatException e)
{
if (Logging.On) Logging.PrintError(Logging.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_headers_wrong_email_format, value, e.Message));
}
return false;
}
private static void ValidateToken(HttpHeaderValueCollection<string> collection, string value)
{
CheckValidToken(value, "item");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Collections.Specialized;
namespace System.Net
{
//
// This internal class implements a static multi-threaded dictionary for user-registered SPNs.
// An SPN is mapped based on a Uri prefix that contains scheme, host and port.
//
// TODO #3114: Replace by Dictionary or ConcurrentDictionary
internal class SpnDictionary : StringDictionary
{
// A Hashtable can support one writer and multiple readers concurrently.
// Maps Uri keys to SpnToken values. The SpnTokens should not be exposed publicly.
private Hashtable _syncTable = Hashtable.Synchronized(new Hashtable());
private ValueCollection _valuesWrapper;
public override int Count
{
get
{
return _syncTable.Count;
}
}
//
// We are thread safe
//
public override bool IsSynchronized
{
get
{
return true;
}
}
//
// Internal lookup, bypasses security checks
//
internal SpnToken InternalGet(string canonicalKey)
{
int lastLength = 0;
string key = null;
// This lock is required to avoid getting InvalidOperationException
// because the collection was modified during enumeration. By design
// a Synchronized Hashtable throws if modifications occur while an
// enumeration is in progress. Manually locking the Hashtable to
// prevent modification during enumeration is the best solution.
// Catching the exception and retrying could potentially never
// succeed in the face of significant updates.
lock (_syncTable.SyncRoot)
{
foreach (object o in _syncTable.Keys)
{
string s = (string)o;
if (s != null && s.Length > lastLength)
{
if (String.Compare(s, 0, canonicalKey, 0, s.Length, StringComparison.OrdinalIgnoreCase) == 0)
{
lastLength = s.Length;
key = s;
}
}
}
}
return (key != null) ? (SpnToken)_syncTable[key] : null;
}
internal void InternalSet(string canonicalKey, SpnToken spnToken)
{
_syncTable[canonicalKey] = spnToken;
}
//
// Public lookup method
//
public override string this[string key]
{
get
{
key = GetCanonicalKey(key);
SpnToken token = InternalGet(key);
return (token == null ? null : token.Spn);
}
set
{
key = GetCanonicalKey(key);
// Value may be null
InternalSet(key, new SpnToken(value));
}
}
public override ICollection Keys
{
get
{
return _syncTable.Keys;
}
}
public override object SyncRoot
{
get
{
return _syncTable;
}
}
public override ICollection Values
{
get
{
if (_valuesWrapper == null)
{
_valuesWrapper = new ValueCollection(this);
}
return _valuesWrapper;
}
}
public override void Add(string key, string value)
{
key = GetCanonicalKey(key);
_syncTable.Add(key, new SpnToken(value));
}
public override void Clear()
{
_syncTable.Clear();
}
public override bool ContainsKey(string key)
{
key = GetCanonicalKey(key);
return _syncTable.ContainsKey(key);
}
public override bool ContainsValue(string value)
{
foreach (SpnToken spnToken in _syncTable.Values)
{
if (spnToken.Spn == value)
{
return true;
}
}
return false;
}
// We have to unwrap the SpnKey and just expose the Spn
public override void CopyTo(Array array, int index)
{
CheckCopyToArguments(array, index, Count);
int offset = 0;
foreach (object entry in this)
{
array.SetValue(entry, offset + index);
offset++;
}
}
public override IEnumerator GetEnumerator()
{
foreach (string key in _syncTable.Keys)
{
// We must unwrap the SpnToken and not expose it publicly
SpnToken spnToken = (SpnToken)_syncTable[key];
yield return new DictionaryEntry(key, spnToken.Spn);
}
}
public override void Remove(string key)
{
key = GetCanonicalKey(key);
_syncTable.Remove(key);
}
//
// We want to serialize on updates on one thread.
//
private static string GetCanonicalKey(string key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
try
{
Uri uri = new Uri(key);
key = uri.GetComponents(UriComponents.Scheme | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.SafeUnescaped);
}
catch (UriFormatException e)
{
throw new ArgumentException(SR.Format(SR.net_mustbeuri, "key"), "key", e);
}
return key;
}
private static void CheckCopyToArguments(Array array, int index, int count)
{
// Copied from HashTable.CopyTo
if (array == null)
{
throw new ArgumentNullException("array");
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if ((array.Length - index) < count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
}
// Wrap HashTable.Values so we can unwrap the SpnTokens.
private class ValueCollection : ICollection
{
private SpnDictionary _spnDictionary;
internal ValueCollection(SpnDictionary spnDictionary)
{
_spnDictionary = spnDictionary;
}
public void CopyTo(Array array, int index)
{
CheckCopyToArguments(array, index, Count);
int offset = 0;
foreach (object entry in this)
{
array.SetValue(entry, offset + index);
offset++;
}
}
public int Count
{
get { return _spnDictionary._syncTable.Values.Count; }
}
public bool IsSynchronized
{
get { return true; }
}
public object SyncRoot
{
get { return _spnDictionary._syncTable.SyncRoot; }
}
public IEnumerator GetEnumerator()
{
foreach (SpnToken spnToken in _spnDictionary._syncTable.Values)
{
yield return (spnToken != null ? spnToken.Spn : null);
}
}
}
}
internal class SpnToken
{
private readonly string _spn;
internal string Spn
{
get { return _spn; }
}
internal SpnToken(string spn)
{
_spn = spn;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Internal;
using System.Text.Unicode;
namespace Microsoft.Framework.WebEncoders
{
internal unsafe abstract class UnicodeEncoderBase
{
// A bitmap of characters which are allowed to be returned unescaped.
private AllowedCharactersBitmap _allowedCharacters;
// The worst-case number of output chars generated for any input char.
private readonly int _maxOutputCharsPerInputChar;
/// <summary>
/// Instantiates an encoder using a custom allow list of characters.
/// </summary>
protected UnicodeEncoderBase(TextEncoderSettings filter, int maxOutputCharsPerInputChar)
{
_maxOutputCharsPerInputChar = maxOutputCharsPerInputChar;
_allowedCharacters = filter.GetAllowedCharacters();
// Forbid characters that are special in HTML.
// Even though this is a common encoder used by everybody (including URL
// and JavaScript strings), it's unfortunately common for developers to
// forget to HTML-encode a string once it has been URL-encoded or
// JavaScript string-escaped, so this offers extra protection.
ForbidCharacter('<');
ForbidCharacter('>');
ForbidCharacter('&');
ForbidCharacter('\''); // can be used to escape attributes
ForbidCharacter('\"'); // can be used to escape attributes
ForbidCharacter('+'); // technically not HTML-specific, but can be used to perform UTF7-based attacks
// Forbid codepoints which aren't mapped to characters or which are otherwise always disallowed
// (includes categories Cc, Cs, Co, Cn, Zs [except U+0020 SPACE], Zl, Zp)
_allowedCharacters.ForbidUndefinedCharacters();
}
// Marks a character as forbidden (must be returned encoded)
protected void ForbidCharacter(char c)
{
_allowedCharacters.ForbidCharacter(c);
}
/// <summary>
/// Entry point to the encoder.
/// </summary>
public void Encode(char[] value, int startIndex, int characterCount, TextWriter output)
{
// Input checking
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
ValidateInputs(startIndex, characterCount, actualInputLength: value.Length);
if (characterCount != 0)
{
fixed (char* pChars = value)
{
int indexOfFirstCharWhichRequiresEncoding = GetIndexOfFirstCharWhichRequiresEncoding(&pChars[startIndex], characterCount);
if (indexOfFirstCharWhichRequiresEncoding < 0)
{
// All chars are valid - just copy the buffer as-is.
output.Write(value, startIndex, characterCount);
}
else
{
// Flush all chars which are known to be valid, then encode the remainder individually
if (indexOfFirstCharWhichRequiresEncoding > 0)
{
output.Write(value, startIndex, indexOfFirstCharWhichRequiresEncoding);
}
EncodeCore(&pChars[startIndex + indexOfFirstCharWhichRequiresEncoding], (uint)(characterCount - indexOfFirstCharWhichRequiresEncoding), output);
}
}
}
}
/// <summary>
/// Entry point to the encoder.
/// </summary>
public string Encode(string value)
{
if (String.IsNullOrEmpty(value))
{
return value;
}
// Quick check: does the string need to be encoded at all?
// If not, just return the input string as-is.
for (int i = 0; i < value.Length; i++)
{
if (!IsCharacterAllowed(value[i]))
{
return EncodeCore(value, idxOfFirstCharWhichRequiresEncoding: i);
}
}
return value;
}
/// <summary>
/// Entry point to the encoder.
/// </summary>
public void Encode(string value, int startIndex, int characterCount, TextWriter output)
{
// Input checking
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
ValidateInputs(startIndex, characterCount, actualInputLength: value.Length);
if (characterCount != 0)
{
fixed (char* pChars = value)
{
if (characterCount == value.Length)
{
// Optimize for the common case: we're being asked to encode the entire input string
// (not just a subset). If all characters are safe, we can just spit it out as-is.
int indexOfFirstCharWhichRequiresEncoding = GetIndexOfFirstCharWhichRequiresEncoding(pChars, characterCount);
if (indexOfFirstCharWhichRequiresEncoding < 0)
{
output.Write(value);
}
else
{
// Flush all chars which are known to be valid, then encode the remainder individually
for (int i = 0; i < indexOfFirstCharWhichRequiresEncoding; i++)
{
output.Write(pChars[i]);
}
EncodeCore(&pChars[indexOfFirstCharWhichRequiresEncoding], (uint)(characterCount - indexOfFirstCharWhichRequiresEncoding), output);
}
}
else
{
// We're being asked to encode a subset, so we need to go through the slow path of appending
// each character individually.
EncodeCore(&pChars[startIndex], (uint)characterCount, output);
}
}
}
}
private string EncodeCore(string input, int idxOfFirstCharWhichRequiresEncoding)
{
Debug.Assert(idxOfFirstCharWhichRequiresEncoding >= 0);
Debug.Assert(idxOfFirstCharWhichRequiresEncoding < input.Length);
int numCharsWhichMayRequireEncoding = input.Length - idxOfFirstCharWhichRequiresEncoding;
int sbCapacity = checked(idxOfFirstCharWhichRequiresEncoding + EncoderCommon.GetCapacityOfOutputStringBuilder(numCharsWhichMayRequireEncoding, _maxOutputCharsPerInputChar));
Debug.Assert(sbCapacity >= input.Length);
// Allocate the StringBuilder with the first (known to not require encoding) part of the input string,
// then begin encoding from the last (potentially requiring encoding) part of the input string.
StringBuilder builder = new StringBuilder(input, 0, idxOfFirstCharWhichRequiresEncoding, sbCapacity);
Writer writer = new Writer(builder);
fixed (char* pInput = input)
{
EncodeCore(ref writer, &pInput[idxOfFirstCharWhichRequiresEncoding], (uint)numCharsWhichMayRequireEncoding);
}
return builder.ToString();
}
private void EncodeCore(char* input, uint charsRemaining, TextWriter output)
{
Writer writer = new Writer(output);
EncodeCore(ref writer, input, charsRemaining);
}
private void EncodeCore(ref Writer writer, char* input, uint charsRemaining)
{
while (charsRemaining != 0)
{
int nextScalar = UnicodeHelpers.GetScalarValueFromUtf16(input, endOfString: (charsRemaining == 1));
if (UnicodeHelpers.IsSupplementaryCodePoint(nextScalar))
{
// Supplementary characters should always be encoded numerically.
WriteEncodedScalar(ref writer, (uint)nextScalar);
// We consume two UTF-16 characters for a single supplementary character.
input += 2;
charsRemaining -= 2;
}
else
{
// Otherwise, this was a BMP character.
input++;
charsRemaining--;
char c = (char)nextScalar;
if (IsCharacterAllowed(c))
{
writer.Write(c);
}
else
{
WriteEncodedScalar(ref writer, (uint)nextScalar);
}
}
}
}
private int GetIndexOfFirstCharWhichRequiresEncoding(char* input, int inputLength)
{
for (int i = 0; i < inputLength; i++)
{
if (!IsCharacterAllowed(input[i]))
{
return i;
}
}
return -1; // no characters require encoding
}
// Determines whether the given character can be returned unencoded.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool IsCharacterAllowed(char c)
{
return _allowedCharacters.IsCharacterAllowed(c);
}
private static void ValidateInputs(int startIndex, int characterCount, int actualInputLength)
{
if (startIndex < 0 || startIndex > actualInputLength)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
if (characterCount < 0 || characterCount > (actualInputLength - startIndex))
{
throw new ArgumentOutOfRangeException(nameof(characterCount));
}
}
protected abstract void WriteEncodedScalar(ref Writer writer, uint value);
/// <summary>
/// Provides an abstraction over both StringBuilder and TextWriter.
/// Declared as a struct so we can allocate on the stack and pass by
/// reference. Eliminates chatty virtual dispatches on hot paths.
/// </summary>
protected struct Writer
{
private readonly StringBuilder _innerBuilder;
private readonly TextWriter _innerWriter;
public Writer(StringBuilder innerBuilder)
{
_innerBuilder = innerBuilder;
_innerWriter = null;
}
public Writer(TextWriter innerWriter)
{
_innerBuilder = null;
_innerWriter = innerWriter;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(char value)
{
if (_innerBuilder != null)
{
_innerBuilder.Append(value);
}
else
{
_innerWriter.Write(value);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(string value)
{
if (_innerBuilder != null)
{
_innerBuilder.Append(value);
}
else
{
_innerWriter.Write(value);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using System.Reflection.Internal;
using System.Text;
using Xunit;
namespace System.Reflection.Metadata.Tests
{
public class MemoryBlockTests
{
[Fact]
public unsafe void Utf8NullTerminatedStringStartsWithAsciiPrefix()
{
byte[] heap;
fixed (byte* heapPtr = (heap = new byte[] { 0 }))
{
Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(0, ""));
}
fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes("Hello World!\0")))
{
Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix("Hello ".Length, "World"));
Assert.False(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix("Hello ".Length, "World?"));
}
fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes("x\0")))
{
Assert.False(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(0, "xyz"));
Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(0, "x"));
}
// bad metadata (#String heap is not nul-terminated):
fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes("abcx")))
{
Assert.True(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(3, "x"));
Assert.False(new MemoryBlock(heapPtr, heap.Length).Utf8NullTerminatedStringStartsWithAsciiPrefix(3, "xyz"));
}
}
[Fact]
public unsafe void EncodingLightUpHasSucceededAndTestsStillPassWithPortableFallbackAsWell()
{
Assert.True(EncodingHelper.TestOnly_LightUpEnabled); // tests run on desktop only right now.
try
{
// Re-run them with forced portable implementation.
EncodingHelper.TestOnly_LightUpEnabled = false;
DefaultDecodingFallbackMatchesBcl();
DecodingSuccessMatchesBcl();
DecoderIsUsedCorrectly();
LightUpTrickFromDifferentAssemblyWorks();
}
finally
{
EncodingHelper.TestOnly_LightUpEnabled = true;
}
}
[Fact]
public unsafe void DefaultDecodingFallbackMatchesBcl()
{
byte[] buffer;
int bytesRead;
var decoder = MetadataStringDecoder.DefaultUTF8;
// dangling lead byte
fixed (byte* ptr = (buffer = new byte[] { 0xC0 }))
{
string s = new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, null, decoder, out bytesRead);
Assert.Equal("\uFFFD", new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, null, decoder, out bytesRead));
Assert.Equal(s, Encoding.UTF8.GetString(buffer));
Assert.Equal(buffer.Length, bytesRead);
s = new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, Encoding.UTF8.GetBytes("Hello"), decoder, out bytesRead);
Assert.Equal("Hello\uFFFD", s);
Assert.Equal(s, "Hello" + Encoding.UTF8.GetString(buffer));
Assert.Equal(buffer.Length, bytesRead);
Assert.Equal("\uFFFD", new MemoryBlock(ptr, buffer.Length).PeekUtf8(0, buffer.Length));
}
// overlong encoding
fixed (byte* ptr = (buffer = new byte[] { (byte)'a', 0xC0, 0xAF, (byte)'b', 0x0 }))
{
var block = new MemoryBlock(ptr, buffer.Length);
Assert.Equal("a\uFFFD\uFFFDb", block.PeekUtf8NullTerminated(0, null, decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
}
// TODO: There are a bunch more error cases of course, but this is enough to break the old code
// and we now just call the BCL, so from a white box perspective, we needn't get carried away.
}
[Fact]
public unsafe void DecodingSuccessMatchesBcl()
{
var utf8 = Encoding.GetEncoding("utf-8", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
byte[] buffer;
int bytesRead;
string str = "\u4F60\u597D. Comment \u00E7a va?";
var decoder = MetadataStringDecoder.DefaultUTF8;
fixed (byte* ptr = (buffer = utf8.GetBytes(str)))
{
Assert.Equal(str, new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, null, decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
Assert.Equal(str + str, new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, buffer, decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
Assert.Equal(str, new MemoryBlock(ptr, buffer.Length).PeekUtf8(0, buffer.Length));
}
// To cover to big to pool case.
str = String.Concat(Enumerable.Repeat(str, 10000));
fixed (byte* ptr = (buffer = utf8.GetBytes(str)))
{
Assert.Equal(str, new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, null, decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
Assert.Equal(str + str, new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, buffer, decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
Assert.Equal(str, new MemoryBlock(ptr, buffer.Length).PeekUtf8(0, buffer.Length));
}
}
[Fact]
public unsafe void LightUpTrickFromDifferentAssemblyWorks()
{
// This is a trick to use our portable light up outside the reader assembly (that
// I will use in Roslyn). Check that it works with encoding other than UTF8 and that it
// validates arguments like the the real thing.
var decoder = new MetadataStringDecoder(Encoding.Unicode);
Assert.Throws<ArgumentNullException>(() => decoder.GetString(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => decoder.GetString((byte*)1, -1));
byte[] bytes;
fixed (byte* ptr = (bytes = Encoding.Unicode.GetBytes("\u00C7a marche tr\u00E8s bien.")))
{
Assert.Equal("\u00C7a marche tr\u00E8s bien.", decoder.GetString(ptr, bytes.Length));
}
}
unsafe delegate string GetString(byte* bytes, int count);
sealed class CustomDecoder : MetadataStringDecoder
{
private GetString _getString;
public CustomDecoder(Encoding encoding, GetString getString)
: base(encoding)
{
_getString = getString;
}
public override unsafe string GetString(byte* bytes, int byteCount)
{
return _getString(bytes, byteCount);
}
}
[Fact]
public unsafe void DecoderIsUsedCorrectly()
{
byte* ptr = null;
byte[] buffer = null;
int bytesRead;
bool prefixed = false;
var decoder = new CustomDecoder(
Encoding.UTF8,
(bytes, byteCount) =>
{
Assert.True(ptr != null);
Assert.True(prefixed != (ptr == bytes));
Assert.Equal(prefixed ? "PrefixTest".Length : "Test".Length, byteCount);
string s = Encoding.UTF8.GetString(bytes, byteCount);
Assert.Equal(s, prefixed ? "PrefixTest" : "Test");
return "Intercepted";
}
);
fixed (byte* fixedPtr = (buffer = Encoding.UTF8.GetBytes("Test")))
{
ptr = fixedPtr;
Assert.Equal("Intercepted", new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, null, decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
prefixed = true;
Assert.Equal("Intercepted", new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated(0, Encoding.UTF8.GetBytes("Prefix"), decoder, out bytesRead));
Assert.Equal(buffer.Length, bytesRead);
}
// decoder will fail to intercept because we don't bother calling it for empty strings.
Assert.Same(String.Empty, new MemoryBlock(null, 0).PeekUtf8NullTerminated(0, null, decoder, out bytesRead));
Assert.Equal(0, bytesRead);
Assert.Same(String.Empty, new MemoryBlock(null, 0).PeekUtf8NullTerminated(0, new byte[0], decoder, out bytesRead));
Assert.Equal(0, bytesRead);
}
private unsafe void TestComparisons(string heapValue, int offset, string value, bool unicode = false)
{
byte[] heap;
MetadataStringDecoder decoder = MetadataStringDecoder.DefaultUTF8;
fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes(heapValue)))
{
var block = new MemoryBlock(heapPtr, heap.Length);
string heapSubstr = GetStringHeapValue(heapValue, offset);
// compare:
if (!unicode)
{
int actualCmp = block.CompareUtf8NullTerminatedStringWithAsciiString(offset, value);
int expectedCmp = StringComparer.Ordinal.Compare(heapSubstr, value);
Assert.Equal(Math.Sign(expectedCmp), Math.Sign(actualCmp));
}
// equals:
bool actualEq = block.Utf8NullTerminatedEquals(offset, value, decoder);
bool expectedEq = StringComparer.Ordinal.Equals(heapSubstr, value);
Assert.Equal(expectedEq, actualEq);
// starts with:
bool actualSW = block.Utf8NullTerminatedStartsWith(offset, value, decoder);
bool expectedSW = heapSubstr.StartsWith(value, StringComparison.Ordinal);
Assert.Equal(actualSW, expectedSW);
}
}
[Fact]
public unsafe void ComparisonToInvalidByteSequenceMatchesFallback()
{
MetadataStringDecoder decoder = MetadataStringDecoder.DefaultUTF8;
// dangling lead byte
byte[] buffer;
fixed (byte* ptr = (buffer = new byte[] { 0xC0 }))
{
var block = new MemoryBlock(ptr, buffer.Length);
Assert.False(block.Utf8NullTerminatedStartsWith(0, new string((char)0xC0, 1), decoder));
Assert.False(block.Utf8NullTerminatedEquals(0, new string((char)0xC0, 1), decoder));
Assert.True(block.Utf8NullTerminatedStartsWith(0, "\uFFFD", decoder));
Assert.True(block.Utf8NullTerminatedEquals(0, "\uFFFD", decoder));
}
// overlong encoding
fixed (byte* ptr = (buffer = new byte[] { (byte)'a', 0xC0, 0xAF, (byte)'b', 0x0 }))
{
var block = new MemoryBlock(ptr, buffer.Length);
Assert.False(block.Utf8NullTerminatedStartsWith(0, "a\\", decoder));
Assert.False(block.Utf8NullTerminatedEquals(0, "a\\b", decoder));
Assert.True(block.Utf8NullTerminatedStartsWith(0, "a\uFFFD", decoder));
Assert.True(block.Utf8NullTerminatedEquals(0, "a\uFFFD\uFFFDb", decoder));
}
}
private string GetStringHeapValue(string heapValue, int offset)
{
int heapEnd = heapValue.IndexOf('\0');
return (heapEnd < 0) ? heapValue.Substring(offset) : heapValue.Substring(offset, heapEnd - offset);
}
[Fact]
public void Utf8NullTerminatedString_Comparisons()
{
TestComparisons("\0", 0, "");
TestComparisons("Foo\0", 0, "Foo");
TestComparisons("Foo\0", 1, "oo");
TestComparisons("Foo\0", 1, "oops");
TestComparisons("Foo", 1, "oo");
TestComparisons("Foo", 1, "oops");
TestComparisons("x", 1, "");
TestComparisons("hello\0", 0, "h");
TestComparisons("hello\0", 0, "he");
TestComparisons("hello\0", 0, "hel");
TestComparisons("hello\0", 0, "hell");
TestComparisons("hello\0", 0, "hello");
TestComparisons("hello\0", 0, "hello!");
TestComparisons("IVector`1\0", 0, "IVectorView`1");
TestComparisons("IVector`1\0", 0, "IVector");
TestComparisons("IVectorView`1\0", 0, "IVector`1");
TestComparisons("Matrix\0", 0, "Matrix3D");
TestComparisons("Matrix3D\0", 0, "Matrix");
TestComparisons("\u1234\0", 0, "\u1234", unicode: true);
TestComparisons("a\u1234\0", 0, "a", unicode: true);
TestComparisons("\u1001\u1002\u1003\0", 0, "\u1001\u1002", unicode: true);
TestComparisons("\u1001a\u1002\u1003\0", 0, "\u1001a\u1002", unicode: true);
TestComparisons("\u1001\u1002\u1003\0", 0, "\u1001a\u1002", unicode: true);
TestComparisons("\uD808\uDF45abc\0", 0, "\uD808\uDF45", unicode: true);
TestComparisons("abc\u1234", 0, "abc\u1234", unicode: true);
TestComparisons("abc\u1234", 0, "abc\u1235", unicode: true);
TestComparisons("abc\u1234", 0, "abcd", unicode: true);
TestComparisons("abcd", 0, "abc\u1234", unicode: true);
}
private unsafe void TestSearch(string heapValue, int offset, string[] values)
{
byte[] heap;
fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes(heapValue)))
{
int actual = new MemoryBlock(heapPtr, heap.Length).BinarySearch(values, offset);
string heapSubstr = GetStringHeapValue(heapValue, offset);
int expected = Array.BinarySearch(values, heapSubstr);
Assert.Equal(expected, actual);
}
}
[Fact]
public void BinarySearch()
{
TestSearch("a\0", 0, new string[0]);
TestSearch("a\0", 0, new[] { "b" });
TestSearch("b\0", 0, new[] { "b" });
TestSearch("c\0", 0, new[] { "b" });
TestSearch("a\0", 0, new[] { "b", "d" });
TestSearch("b\0", 0, new[] { "b", "d" });
TestSearch("c\0", 0, new[] { "b", "d" });
TestSearch("d\0", 0, new[] { "b", "d" });
TestSearch("e\0", 0, new[] { "b", "d" });
TestSearch("a\0", 0, new[] { "b", "d", "f" });
TestSearch("b\0", 0, new[] { "b", "d", "f" });
TestSearch("c\0", 0, new[] { "b", "d", "f" });
TestSearch("d\0", 0, new[] { "b", "d", "f" });
TestSearch("e\0", 0, new[] { "b", "d", "f" });
TestSearch("f\0", 0, new[] { "b", "d", "f" });
TestSearch("g\0", 0, new[] { "b", "d", "f" });
TestSearch("a\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("b\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("c\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("d\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("e\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("f\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("g\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("m\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("n\0", 0, new[] { "b", "d", "f", "m" });
TestSearch("z\0", 0, new[] { "b", "d", "f", "m" });
}
[Fact]
public unsafe void BuildPtrTable_SmallRefs()
{
const int rowSize = 4;
const int secondColumnOffset = 2;
var table = new byte[]
{
0xAA, 0xAA, 0x05, 0x00,
0xBB, 0xBB, 0x04, 0x00,
0xCC, 0xCC, 0x02, 0x01,
0xDD, 0xDD, 0x02, 0x00,
0xEE, 0xEE, 0x01, 0x01,
};
int rowCount = table.Length / rowSize;
fixed (byte* tablePtr = table)
{
var block = new MemoryBlock(tablePtr, table.Length);
Assert.Equal(0x0004, block.PeekReference(6, smallRefSize: true));
var actual = block.BuildPtrTable(rowCount, rowSize, secondColumnOffset, isReferenceSmall: true);
var expected = new int[] { 4, 2, 1, 5, 3 };
Assert.Equal(expected, actual);
}
}
[Fact]
public unsafe void BuildPtrTable_LargeRefs()
{
const int rowSize = 6;
const int secondColumnOffset = 2;
var table = new byte[]
{
0xAA, 0xAA, 0x10, 0x00, 0x05, 0x00,
0xBB, 0xBB, 0x10, 0x00, 0x04, 0x00,
0xCC, 0xCC, 0x10, 0x00, 0x02, 0x01,
0xDD, 0xDD, 0x10, 0x00, 0x02, 0x00,
0xEE, 0xEE, 0x10, 0x00, 0x01, 0x01,
};
int rowCount = table.Length / rowSize;
fixed (byte* tablePtr = table)
{
var block = new MemoryBlock(tablePtr, table.Length);
Assert.Equal(0x00040010, block.PeekReference(8, smallRefSize: false));
var actual = block.BuildPtrTable(rowCount, rowSize, secondColumnOffset, isReferenceSmall: false);
var expected = new int[] { 4, 2, 1, 5, 3 };
Assert.Equal(expected, actual);
}
}
[Fact]
public unsafe void PeekReference()
{
var table = new byte[]
{
0xff, 0xff, 0xff, 0x00, // offset 0
0xff, 0xff, 0xff, 0x01, // offset 4
0xff, 0xff, 0xff, 0x1f, // offset 8
0xff, 0xff, 0xff, 0x2f, // offset 12
0xff, 0xff, 0xff, 0xff, // offset 16
};
fixed (byte* tablePtr = table)
{
var block = new MemoryBlock(tablePtr, table.Length);
Assert.Equal(0x0000ffff, block.PeekReference(0, smallRefSize: true));
Assert.Equal(0x0000ffff, block.PeekHeapReference(0, smallRefSize: true));
Assert.Equal(0x0000ffffu, block.PeekReferenceUnchecked(0, smallRefSize: true));
Assert.Equal(0x00ffffff, block.PeekReference(0, smallRefSize: false));
Assert.Throws<BadImageFormatException>(() => block.PeekReference(4, smallRefSize: false));
Assert.Throws<BadImageFormatException>(() => block.PeekReference(16, smallRefSize: false));
Assert.Equal(0x1fffffff, block.PeekHeapReference(8, smallRefSize: false));
Assert.Throws<BadImageFormatException>(() => block.PeekHeapReference(12, smallRefSize: false));
Assert.Throws<BadImageFormatException>(() => block.PeekHeapReference(16, smallRefSize: false));
Assert.Equal(0x01ffffffu, block.PeekReferenceUnchecked(4, smallRefSize: false));
Assert.Equal(0x1fffffffu, block.PeekReferenceUnchecked(8, smallRefSize: false));
Assert.Equal(0x2fffffffu, block.PeekReferenceUnchecked(12, smallRefSize: false));
Assert.Equal(0xffffffffu, block.PeekReferenceUnchecked(16, smallRefSize: false));
}
}
}
}
| |
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Buffers.Binary;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
namespace SixLabors.Fonts
{
/// <summary>
/// BinaryReader using big-endian encoding.
/// </summary>
[DebuggerDisplay("Start: {StartOfStream}, Position: {BaseStream.Position}")]
internal class BigEndianBinaryReader : IDisposable
{
/// <summary>
/// Buffer used for temporary storage before conversion into primitives
/// </summary>
private readonly byte[] buffer = new byte[16];
private readonly bool leaveOpen;
/// <summary>
/// Initializes a new instance of the <see cref="BigEndianBinaryReader" /> class.
/// Constructs a new binary reader with the given bit converter, reading
/// to the given stream, using the given encoding.
/// </summary>
/// <param name="stream">Stream to read data from</param>
/// <param name="leaveOpen">if set to <c>true</c> [leave open].</param>
public BigEndianBinaryReader(Stream stream, bool leaveOpen)
{
this.BaseStream = stream;
this.StartOfStream = stream.Position;
this.leaveOpen = leaveOpen;
}
private long StartOfStream { get; }
/// <summary>
/// Gets the underlying stream of the EndianBinaryReader.
/// </summary>
public Stream BaseStream { get; }
/// <summary>
/// Seeks within the stream.
/// </summary>
/// <param name="offset">Offset to seek to.</param>
/// <param name="origin">Origin of seek operation. If SeekOrigin.Begin, the offset will be set to the start of stream position.</param>
public void Seek(long offset, SeekOrigin origin)
{
// If SeekOrigin.Begin, the offset will be set to the start of stream position.
if (origin == SeekOrigin.Begin)
{
offset += this.StartOfStream;
}
this.BaseStream.Seek(offset, origin);
}
/// <summary>
/// Reads a single byte from the stream.
/// </summary>
/// <returns>The byte read</returns>
public byte ReadByte()
{
this.ReadInternal(this.buffer, 1);
return this.buffer[0];
}
/// <summary>
/// Reads a single signed byte from the stream.
/// </summary>
/// <returns>The byte read</returns>
public sbyte ReadSByte()
{
this.ReadInternal(this.buffer, 1);
return unchecked((sbyte)this.buffer[0]);
}
public float ReadF2dot14()
{
const float f2Dot14ToFloat = 16384.0f;
return this.ReadInt16() / f2Dot14ToFloat;
}
/// <summary>
/// Reads a 16-bit signed integer from the stream, using the bit converter
/// for this reader. 2 bytes are read.
/// </summary>
/// <returns>The 16-bit integer read</returns>
public short ReadInt16()
{
this.ReadInternal(this.buffer, 2);
return BinaryPrimitives.ReadInt16BigEndian(this.buffer);
}
public TEnum ReadInt16<TEnum>()
where TEnum : struct, Enum
{
TryConvert(this.ReadUInt16(), out TEnum value);
return value;
}
public short ReadFWORD() => this.ReadInt16();
public short[] ReadFWORDArray(int length) => this.ReadInt16Array(length);
public ushort ReadUFWORD() => this.ReadUInt16();
/// <summary>
/// Reads a 32-bit signed integer from the stream.
/// 4 bytes are read.
/// </summary>
/// <returns>The 32-bit integer read.</returns>
public float ReadFixed()
{
this.ReadInternal(this.buffer, 4);
int value = BinaryPrimitives.ReadInt32BigEndian(this.buffer);
return Unsafe.As<int, float>(ref value);
}
/// <summary>
/// Reads a 64-bit signed integer from the stream.
/// 8 bytes are read.
/// </summary>
/// <returns>The 64-bit integer read.</returns>
public long ReadInt64()
{
this.ReadInternal(this.buffer, 8);
return BinaryPrimitives.ReadInt64BigEndian(this.buffer);
}
/// <summary>
/// Reads a 16-bit unsigned integer from the stream.
/// 2 bytes are read.
/// </summary>
/// <returns>The 16-bit unsigned integer read.</returns>
public ushort ReadUInt16()
{
this.ReadInternal(this.buffer, 2);
return BinaryPrimitives.ReadUInt16BigEndian(this.buffer);
}
/// <summary>
/// Reads a 16-bit unsigned integer from the stream representing an offset position.
/// 2 bytes are read.
/// </summary>
/// <returns>The 16-bit unsigned integer read.</returns>
public ushort ReadOffset16() => this.ReadUInt16();
public TEnum ReadUInt16<TEnum>()
where TEnum : struct, Enum
{
TryConvert(this.ReadUInt16(), out TEnum value);
return value;
}
/// <summary>
/// Reads array of 16-bit unsigned integers from the stream.
/// </summary>
/// <param name="length">The length.</param>
/// <returns>
/// The 16-bit unsigned integer read.
/// </returns>
public ushort[] ReadUInt16Array(int length)
{
ushort[] data = new ushort[length];
for (int i = 0; i < length; i++)
{
data[i] = this.ReadUInt16();
}
return data;
}
/// <summary>
/// Reads array of 16-bit unsigned integers from the stream to the buffer.
/// </summary>
/// <param name="buffer">The buffer to read to.</param>
public void ReadUInt16Array(Span<ushort> buffer)
{
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = this.ReadUInt16();
}
}
/// <summary>
/// Reads array or 32-bit unsigned integers from the stream.
/// </summary>
/// <param name="length">The length.</param>
/// <returns>
/// The 32-bit unsigned integer read.
/// </returns>
public uint[] ReadUInt32Array(int length)
{
uint[] data = new uint[length];
for (int i = 0; i < length; i++)
{
data[i] = this.ReadUInt32();
}
return data;
}
public byte[] ReadUInt8Array(int length)
{
byte[] data = new byte[length];
this.ReadInternal(data, length);
return data;
}
/// <summary>
/// Reads array of 16-bit unsigned integers from the stream.
/// </summary>
/// <param name="length">The length.</param>
/// <returns>
/// The 16-bit signed integer read.
/// </returns>
public short[] ReadInt16Array(int length)
{
short[] data = new short[length];
for (int i = 0; i < length; i++)
{
data[i] = this.ReadInt16();
}
return data;
}
/// <summary>
/// Reads an array of 16-bit signed integers from the stream to the buffer.
/// </summary>
/// <param name="buffer">The buffer to read to.</param>
public void ReadInt16Array(Span<short> buffer)
{
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = this.ReadInt16();
}
}
/// <summary>
/// Reads a 8-bit unsigned integer from the stream, using the bit converter
/// for this reader. 1 bytes are read.
/// </summary>
/// <returns>The 8-bit unsigned integer read.</returns>
public byte ReadUInt8()
{
this.ReadInternal(this.buffer, 1);
return this.buffer[0];
}
/// <summary>
/// Reads a 24-bit unsigned integer from the stream, using the bit converter
/// for this reader. 3 bytes are read.
/// </summary>
/// <returns>The 24-bit unsigned integer read.</returns>
public int ReadUInt24()
{
byte highByte = this.ReadByte();
return (highByte << 16) | this.ReadUInt16();
}
/// <summary>
/// Reads a 32-bit unsigned integer from the stream, using the bit converter
/// for this reader. 4 bytes are read.
/// </summary>
/// <returns>The 32-bit unsigned integer read.</returns>
public uint ReadUInt32()
{
this.ReadInternal(this.buffer, 4);
return BinaryPrimitives.ReadUInt32BigEndian(this.buffer);
}
/// <summary>
/// Reads a 32-bit unsigned integer from the stream representing an offset position.
/// 4 bytes are read.
/// </summary>
/// <returns>The 32-bit unsigned integer read.</returns>
public uint ReadOffset32() => this.ReadUInt32();
/// <summary>
/// Reads the specified number of bytes, returning them in a new byte array.
/// If not enough bytes are available before the end of the stream, this
/// method will return what is available.
/// </summary>
/// <param name="count">The number of bytes to read.</param>
/// <returns>The bytes read.</returns>
public byte[] ReadBytes(int count)
{
byte[] ret = new byte[count];
int index = 0;
while (index < count)
{
int read = this.BaseStream.Read(ret, index, count - index);
// Stream has finished half way through. That's fine, return what we've got.
if (read == 0)
{
byte[] copy = new byte[index];
Buffer.BlockCopy(ret, 0, copy, 0, index);
return copy;
}
index += read;
}
return ret;
}
/// <summary>
/// Reads a string of a specific length, which specifies the number of bytes
/// to read from the stream. These bytes are then converted into a string with
/// the encoding for this reader.
/// </summary>
/// <param name="bytesToRead">The bytes to read.</param>
/// <param name="encoding">The encoding.</param>
/// <returns>
/// The string read from the stream.
/// </returns>
public string ReadString(int bytesToRead, Encoding encoding)
{
byte[] data = new byte[bytesToRead];
this.ReadInternal(data, bytesToRead);
return encoding.GetString(data, 0, data.Length);
}
/// <summary>
/// Reads the uint32 string.
/// </summary>
/// <returns>a 4 character long UTF8 encoded string.</returns>
public string ReadTag()
{
this.ReadInternal(this.buffer, 4);
return Encoding.UTF8.GetString(this.buffer, 0, 4);
}
/// <summary>
/// Reads the given number of bytes from the stream, throwing an exception
/// if they can't all be read.
/// </summary>
/// <param name="data">Buffer to read into.</param>
/// <param name="size">Number of bytes to read.</param>
private void ReadInternal(byte[] data, int size)
{
int index = 0;
while (index < size)
{
int read = this.BaseStream.Read(data, index, size - index);
if (read == 0)
{
throw new EndOfStreamException($"End of stream reached with {size - index} byte{(size - index == 1 ? "s" : string.Empty)} left to read.");
}
index += read;
}
}
public void Dispose()
{
if (!this.leaveOpen)
{
this.BaseStream?.Dispose();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryConvert<T, TEnum>(T input, out TEnum value)
where T : struct, IConvertible, IFormattable, IComparable
where TEnum : struct, Enum
{
if (Unsafe.SizeOf<T>() == Unsafe.SizeOf<TEnum>())
{
value = Unsafe.As<T, TEnum>(ref input);
return true;
}
value = default;
return false;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this sample source code is subject to the terms of the Microsoft
// license agreement under which you licensed this sample source code. If
// you did not accept the terms of the license agreement, you are not
// authorized to use this sample source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the LICENSE.RTF on your install media or the root of your tools installation.
// THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Text;
namespace Microsoft.WindowsMobile.Samples.Location
{
public delegate void LocationChangedEventHandler(object sender, LocationChangedEventArgs args);
public delegate void DeviceStateChangedEventHandler(object sender, DeviceStateChangedEventArgs args);
/// <summary>
/// Summary description for GPS.
/// </summary>
public class Gps
{
// handle to the gps device
IntPtr gpsHandle = IntPtr.Zero;
// handle to the native event that is signalled when the GPS
// devices gets a new location
IntPtr newLocationHandle = IntPtr.Zero;
// handle to the native event that is signalled when the GPS
// device state changes
IntPtr deviceStateChangedHandle = IntPtr.Zero;
// handle to the native event that we use to stop our event
// thread
IntPtr stopHandle = IntPtr.Zero;
// holds our event thread instance
System.Threading.Thread gpsEventThread = null;
event LocationChangedEventHandler locationChanged;
/// <summary>
/// Event that is raised when the GPS locaction data changes
/// </summary>
public event LocationChangedEventHandler LocationChanged
{
add
{
locationChanged += value;
// create our event thread only if the user decides to listen
CreateGpsEventThread();
}
remove
{
locationChanged -= value;
}
}
event DeviceStateChangedEventHandler deviceStateChanged;
/// <summary>
/// Event that is raised when the GPS device state changes
/// </summary>
public event DeviceStateChangedEventHandler DeviceStateChanged
{
add
{
deviceStateChanged += value;
// create our event thread only if the user decides to listen
CreateGpsEventThread();
}
remove
{
deviceStateChanged -= value;
}
}
/// <summary>
/// True: The GPS device has been opened. False: It has not been opened
/// </summary>
public bool Opened
{
get { return gpsHandle != IntPtr.Zero; }
}
public Gps()
{
}
~Gps()
{
// make sure that the GPS was closed.
Close();
}
/// <summary>
/// Opens the GPS device and prepares to receive data from it.
/// </summary>
public void Open()
{
if (!Opened)
{
// create handles for GPS events
newLocationHandle = CreateEvent(IntPtr.Zero, 0, 0, null);
deviceStateChangedHandle = CreateEvent(IntPtr.Zero, 0, 0, null);
stopHandle = CreateEvent(IntPtr.Zero, 0, 0, null);
gpsHandle = GPSOpenDevice(newLocationHandle, deviceStateChangedHandle, null, 0);
// if events were hooked up before the device was opened, we'll need
// to create the gps event thread.
if (locationChanged != null || deviceStateChanged != null)
{
CreateGpsEventThread();
}
}
}
/// <summary>
/// Closes the gps device.
/// </summary>
public void Close()
{
if (gpsHandle != IntPtr.Zero)
{
GPSCloseDevice(gpsHandle);
gpsHandle = IntPtr.Zero;
}
// Set our native stop event so we can exit our event thread.
if (stopHandle != IntPtr.Zero)
{
EventModify(stopHandle, eventSet);
}
// block until our event thread is finished before
// we close our native event handles
lock (this)
{
if (newLocationHandle != IntPtr.Zero)
{
CloseHandle(newLocationHandle);
newLocationHandle = IntPtr.Zero;
}
if (deviceStateChangedHandle != IntPtr.Zero)
{
CloseHandle(deviceStateChangedHandle);
deviceStateChangedHandle = IntPtr.Zero;
}
if (stopHandle != IntPtr.Zero)
{
CloseHandle(stopHandle);
stopHandle = IntPtr.Zero;
}
}
}
/// <summary>
/// Get the position reported by the GPS receiver
/// </summary>
/// <returns>GpsPosition class with all the position details</returns>
public GpsPosition GetPosition()
{
return GetPosition(TimeSpan.Zero);
}
/// <summary>
/// Get the position reported by the GPS receiver that is no older than
/// the maxAge passed in
/// </summary>
/// <param name="maxAge">Max age of the gps position data that you want back.
/// If there is no data within the required age, null is returned.
/// if maxAge == TimeSpan.Zero, then the age of the data is ignored</param>
/// <returns>GpsPosition class with all the position details</returns>
public GpsPosition GetPosition(TimeSpan maxAge)
{
GpsPosition gpsPosition = null;
if (Opened)
{
// allocate the necessary memory on the native side. We have a class (GpsPosition) that
// has the same memory layout as its native counterpart
IntPtr ptr = Utils.LocalAlloc(Marshal.SizeOf(typeof(GpsPosition)));
// fill in the required fields
gpsPosition = new GpsPosition();
gpsPosition.dwVersion = 1;
gpsPosition.dwSize = Marshal.SizeOf(typeof(GpsPosition));
// Marshal our data to the native pointer we allocated.
Marshal.StructureToPtr(gpsPosition, ptr, false);
// call native method passing in our native buffer
int result = GPSGetPosition(gpsHandle, ptr, 500000, 0);
if (result == 0)
{
// native call succeeded, marshal native data to our managed data
gpsPosition = (GpsPosition)Marshal.PtrToStructure(ptr, typeof(GpsPosition));
if (maxAge != TimeSpan.Zero)
{
// check to see if the data is recent enough.
if (!gpsPosition.TimeValid || DateTime.Now - maxAge > gpsPosition.Time)
{
gpsPosition = null;
}
}
}
// free our native memory
Utils.LocalFree(ptr);
}
return gpsPosition;
}
/// <summary>
/// Queries the device state.
/// </summary>
/// <returns>Device state information</returns>
public GpsDeviceState GetDeviceState()
{
GpsDeviceState device = null;
// allocate a buffer on the native side. Since the
IntPtr pGpsDevice = Utils.LocalAlloc(GpsDeviceState.GpsDeviceStructureSize);
// GPS_DEVICE structure has arrays of characters, it's easier to just
// write directly into memory rather than create a managed structure with
// the same layout.
Marshal.WriteInt32(pGpsDevice, 1); // write out GPS version of 1
Marshal.WriteInt32(pGpsDevice, 4, GpsDeviceState.GpsDeviceStructureSize); // write out dwSize of structure
int result = GPSGetDeviceState(pGpsDevice);
if (result == 0)
{
// instantiate the GpsDeviceState class passing in the native pointer
device = new GpsDeviceState(pGpsDevice);
}
// free our native memory
Utils.LocalFree(pGpsDevice);
return device;
}
/// <summary>
/// Creates our event thread that will receive native events
/// </summary>
private void CreateGpsEventThread()
{
// we only want to create the thread if we don't have one created already
// and we have opened the gps device
if (gpsEventThread == null && gpsHandle != IntPtr.Zero)
{
// Create and start thread to listen for GPS events
gpsEventThread = new System.Threading.Thread(new System.Threading.ThreadStart(WaitForGpsEvents));
gpsEventThread.Start();
}
}
/// <summary>
/// Method used to listen for native events from the GPS.
/// </summary>
private void WaitForGpsEvents()
{
lock (this)
{
bool listening = true;
// allocate 3 handles worth of memory to pass to WaitForMultipleObjects
IntPtr handles = Utils.LocalAlloc(12);
// write the three handles we are listening for.
Marshal.WriteInt32(handles, 0, stopHandle.ToInt32());
Marshal.WriteInt32(handles, 4, deviceStateChangedHandle.ToInt32());
Marshal.WriteInt32(handles, 8, newLocationHandle.ToInt32());
while (listening)
{
int obj = WaitForMultipleObjects(3, handles, 0, -1);
if (obj != waitFailed)
{
switch (obj)
{
case 0:
// we've been signalled to stop
listening = false;
break;
case 1:
// device state has changed
if (deviceStateChanged != null)
{
deviceStateChanged(this, new DeviceStateChangedEventArgs(GetDeviceState()));
}
break;
case 2:
// location has changed
if (locationChanged != null)
{
locationChanged(this, new LocationChangedEventArgs(GetPosition()));
}
break;
}
}
}
// free the memory we allocated for the native handles
Utils.LocalFree(handles);
// clear our gpsEventThread so that we can recreate this thread again
// if the events are hooked up again.
gpsEventThread = null;
}
}
#region PInvokes to gpsapi.dll
[DllImport("gpsapi.dll")]
static extern IntPtr GPSOpenDevice(IntPtr hNewLocationData, IntPtr hDeviceStateChange, string szDeviceName, int dwFlags);
[DllImport("gpsapi.dll")]
static extern int GPSCloseDevice(IntPtr hGPSDevice);
[DllImport("gpsapi.dll")]
static extern int GPSGetPosition(IntPtr hGPSDevice, IntPtr pGPSPosition, int dwMaximumAge, int dwFlags);
[DllImport("gpsapi.dll")]
static extern int GPSGetDeviceState(IntPtr pGPSDevice);
#endregion
#region PInvokes to coredll.dll
[DllImport("coredll.dll")]
static extern IntPtr CreateEvent(IntPtr lpEventAttributes, int bManualReset, int bInitialState, StringBuilder lpName);
[DllImport("coredll.dll")]
static extern int CloseHandle(IntPtr hObject);
const int waitFailed = -1;
[DllImport("coredll.dll")]
static extern int WaitForMultipleObjects(int nCount, IntPtr lpHandles, int fWaitAll, int dwMilliseconds);
const int eventSet = 3;
[DllImport("coredll.dll")]
static extern int EventModify(IntPtr hHandle, int dwFunc);
#endregion
}
}
| |
using System.ComponentModel;
using System.Collections.Specialized;
using Signum.Entities.Basics;
using Signum.Entities.Chart;
using Signum.Entities.UserAssets;
using System.Xml.Linq;
using Signum.Entities.Authorization;
using Signum.Entities.DynamicQuery;
using Signum.Entities.UserQueries;
using Signum.Entities.Scheduler;
namespace Signum.Entities.Dashboard;
[EntityKind(EntityKind.Main, EntityData.Master)]
public class DashboardEntity : Entity, IUserAssetEntity, ITaskEntity
{
public DashboardEntity()
{
RebindEvents();
}
Lite<TypeEntity>? entityType;
public Lite<TypeEntity>? EntityType
{
get { return entityType; }
set
{
if (Set(ref entityType, value) && value == null)
EmbeddedInEntity = null;
}
}
public DashboardEmbedededInEntity? EmbeddedInEntity { get; set; }
public Lite<Entity>? Owner { get; set; }
public int? DashboardPriority { get; set; }
[Unit("s"), NumberIsValidator(Entities.ComparisonType.GreaterThanOrEqualTo, 10)]
public int? AutoRefreshPeriod { get; set; }
[StringLengthValidator(Min = 2, Max = 200)]
public string DisplayName { get; set; }
public bool HideDisplayName { get; set; }
public bool CombineSimilarRows { get; set; } = true;
public CacheQueryConfigurationEmbedded? CacheQueryConfiguration { get; set; }
[NotifyCollectionChanged, NotifyChildProperty]
[NoRepeatValidator]
public MList<PanelPartEmbedded> Parts { get; set; } = new MList<PanelPartEmbedded>();
[Ignore, QueryableProperty]
public MList<TokenEquivalenceGroupEntity> TokenEquivalencesGroups { get; set; } = new MList<TokenEquivalenceGroupEntity>();
[UniqueIndex]
public Guid Guid { get; set; } = Guid.NewGuid();
[StringLengthValidator(Max = 200)]
public string? Key { get; set; }
[AutoExpressionField]
public bool ContainsContent(IPartEntity content) =>
As.Expression(() => Parts.Any(p => p.Content.Is(content)));
protected override string? ChildPropertyValidation(ModifiableEntity sender, PropertyInfo pi)
{
if (sender is PanelPartEmbedded part)
{
if (pi.Name == nameof(part.StartColumn))
{
if (part.StartColumn + part.Columns > 12)
return DashboardMessage.Part0IsTooLarge.NiceToString(part);
var other = Parts.TakeWhile(p => p != part)
.FirstOrDefault(a => a.Row == part.Row && a.ColumnInterval().Overlaps(part.ColumnInterval()));
if (other != null)
return DashboardMessage.Part0OverlapsWith1.NiceToString(part, other);
}
if (entityType != null && pi.Name == nameof(part.Content) && part.Content != null)
{
var idents = GraphExplorer.FromRoot((Entity)part.Content).OfType<Entity>();
string errorsUserQuery = idents.OfType<IHasEntitytype>()
.Where(uc => uc.EntityType != null && !uc.EntityType.Is(EntityType))
.ToString(uc => DashboardMessage._0Is1InstedOf2In3.NiceToString(NicePropertyName(() => EntityType), uc.EntityType, entityType, uc),
"\r\n");
return errorsUserQuery.DefaultText(null!);
}
}
return base.ChildPropertyValidation(sender, pi);
}
protected override void ChildCollectionChanged(object? sender, NotifyCollectionChangedEventArgs args)
{
if (sender == Parts)
foreach (var pp in Parts)
pp.NotifyRowColumn();
base.ChildCollectionChanged(sender, args);
}
internal void ParseData(Func<QueryEntity, QueryDescription?> getDescription)
{
foreach (var f in TokenEquivalencesGroups)
{
foreach (var t in f.TokenEquivalences)
{
var description = getDescription(t.Query);
if (description != null)
t.Token.ParseData(this, description, SubTokensOptions.CanElement);
}
}
}
[Ignore]
bool invalidating = false;
protected override void ChildPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (!invalidating && sender is PanelPartEmbedded && (e.PropertyName == "Row" || e.PropertyName == "Column"))
{
invalidating = true;
foreach (var pp in Parts)
pp.NotifyRowColumn();
invalidating = false;
}
base.ChildPropertyChanged(sender, e);
}
[AutoExpressionField]
public override string ToString() => As.Expression(() => DisplayName);
public DashboardEntity Clone()
{
return new DashboardEntity
{
EntityType = this.EntityType,
EmbeddedInEntity = this.EmbeddedInEntity,
Owner = Owner,
DashboardPriority = DashboardPriority,
AutoRefreshPeriod = this.AutoRefreshPeriod,
DisplayName = "Clone {0}".FormatWith(this.DisplayName),
HideDisplayName = this.HideDisplayName,
CombineSimilarRows = this.CombineSimilarRows,
CacheQueryConfiguration = this.CacheQueryConfiguration?.Clone(),
Parts = Parts.Select(p => p.Clone()).ToMList(),
Key = this.Key
};
}
public XElement ToXml(IToXmlContext ctx)
{
return new XElement("Dashboard",
new XAttribute("Guid", Guid),
new XAttribute("DisplayName", DisplayName),
EntityType == null ? null! : new XAttribute("EntityType", ctx.TypeToName(EntityType)),
Owner == null ? null! : new XAttribute("Owner", Owner.Key()),
HideDisplayName == false ? null! : new XAttribute("HideDisplayName", HideDisplayName.ToString()),
DashboardPriority == null ? null! : new XAttribute("DashboardPriority", DashboardPriority.Value.ToString()),
EmbeddedInEntity == null ? null! : new XAttribute("EmbeddedInEntity", EmbeddedInEntity.Value.ToString()),
new XAttribute("CombineSimilarRows", CombineSimilarRows),
CacheQueryConfiguration?.ToXml(ctx),
new XElement("Parts", Parts.Select(p => p.ToXml(ctx))),
new XElement(nameof(TokenEquivalencesGroups), TokenEquivalencesGroups.Select(teg => teg.ToXml(ctx)))
);
}
public void FromXml(XElement element, IFromXmlContext ctx)
{
DisplayName = element.Attribute("DisplayName")!.Value;
EntityType = element.Attribute("EntityType")?.Let(a => ctx.GetTypeLite(a.Value));
Owner = element.Attribute("Owner")?.Let(a => Lite.Parse<Entity>(a.Value));
HideDisplayName = element.Attribute("HideDisplayName")?.Let(a => bool.Parse(a.Value)) ?? false;
DashboardPriority = element.Attribute("DashboardPriority")?.Let(a => int.Parse(a.Value));
EmbeddedInEntity = element.Attribute("EmbeddedInEntity")?.Let(a => a.Value.ToEnum<DashboardEmbedededInEntity>());
CombineSimilarRows = element.Attribute("CombineSimilarRows")?.Let(a => bool.Parse(a.Value)) ?? false;
CacheQueryConfiguration = CacheQueryConfiguration.CreateOrAssignEmbedded(element.Element(nameof(CacheQueryConfiguration)), (cqc, elem) => cqc.FromXml(elem));
Parts.Synchronize(element.Element("Parts")!.Elements().ToList(), (pp, x) => pp.FromXml(x, ctx));
TokenEquivalencesGroups.Synchronize(element.Element(nameof(TokenEquivalencesGroups))?.Elements().ToList() ?? new List<XElement>(), (teg, x) => teg.FromXml(x, ctx));
ParseData(q => ctx.GetQueryDescription(q));
}
protected override string? PropertyValidation(PropertyInfo pi)
{
if (pi.Name == nameof(EmbeddedInEntity))
{
if (EmbeddedInEntity == null && EntityType != null)
return ValidationMessage._0IsNecessary.NiceToString(pi.NiceName());
if (EmbeddedInEntity != null && EntityType == null)
return ValidationMessage._0IsNotAllowed.NiceToString(pi.NiceName());
}
if(pi.Name == nameof(CacheQueryConfiguration) && CacheQueryConfiguration != null && EntityType != null)
{
return ValidationMessage._0ShouldBeNullWhen1IsSet.NiceToString(pi.NiceName(), NicePropertyName(() => EntityType));
}
if(pi.Name == nameof(TokenEquivalencesGroups))
{
var dups = TokenEquivalencesGroups
.SelectMany(a => a.TokenEquivalences).Select(a => a.Token.Token).NotNull()
.GroupCount(a => a).Where(gr => gr.Value > 1).ToString(a => a.Value + " x " + a.Key.FullKey(), "\n");
if (dups.HasText())
return "Duplicated tokens: " + dups;
}
return base.PropertyValidation(pi);
}
}
public class CacheQueryConfigurationEmbedded : EmbeddedEntity
{
[Unit("s")]
public int TimeoutForQueries { get; set; } = 5 * 60;
public int MaxRows { get; set; } = 1000 * 1000;
[Unit("m")]
public int? AutoRegenerateWhenOlderThan { get; set; }
internal CacheQueryConfigurationEmbedded Clone() => new CacheQueryConfigurationEmbedded
{
TimeoutForQueries = TimeoutForQueries,
MaxRows = MaxRows,
AutoRegenerateWhenOlderThan = AutoRegenerateWhenOlderThan,
};
internal XElement ToXml(IToXmlContext ctx) => new XElement("CacheQueryConfiguration",
new XAttribute(nameof(TimeoutForQueries), TimeoutForQueries),
new XAttribute(nameof(MaxRows), MaxRows),
AutoRegenerateWhenOlderThan == null ? null : new XAttribute(nameof(AutoRegenerateWhenOlderThan), AutoRegenerateWhenOlderThan)
);
internal void FromXml(XElement elem)
{
TimeoutForQueries = elem.Attribute(nameof(TimeoutForQueries))?.Value.ToInt() ?? 5 * 60;
MaxRows = elem.Attribute(nameof(MaxRows))?.Value.ToInt() ?? 1000 * 1000;
AutoRegenerateWhenOlderThan = elem.Attribute(nameof(AutoRegenerateWhenOlderThan))?.Value.ToInt();
}
}
[AutoInit]
public static class DashboardPermission
{
public static PermissionSymbol ViewDashboard;
}
[AutoInit]
public static class DashboardOperation
{
public static ExecuteSymbol<DashboardEntity> Save;
public static ExecuteSymbol<DashboardEntity> RegenerateCachedQueries;
public static ConstructSymbol<DashboardEntity>.From<DashboardEntity> Clone;
public static DeleteSymbol<DashboardEntity> Delete;
}
public enum DashboardMessage
{
CreateNewPart,
[Description("Title must be specified for {0}")]
DashboardDN_TitleMustBeSpecifiedFor0,
Preview,
[Description("{0} is {1} (instead of {2}) in {3}")]
_0Is1InstedOf2In3,
[Description("Part {0} is too large")]
Part0IsTooLarge,
[Description("Part {0} overlaps with {1}")]
Part0OverlapsWith1,
[Description("Row[s] selected")]
RowsSelected,
ForPerformanceReasonsThisDashboardMayShowOutdatedInformation,
[Description("Last update was on {0}")]
LasUpdateWasOn0
}
public enum DashboardEmbedededInEntity
{
None,
Top,
Bottom,
Tab
}
[EntityKind(EntityKind.Part, EntityData.Master)]
public class TokenEquivalenceGroupEntity : Entity
{
[NotNullValidator(Disabled = true)]
public Lite<DashboardEntity> Dashboard { get; set; }
public InteractionGroup? InteractionGroup { get; set; }
[PreserveOrder, NoRepeatValidator, CountIsValidator(ComparisonType.GreaterThan, 1)]
public MList<TokenEquivalenceEmbedded> TokenEquivalences { get; set; } = new MList<TokenEquivalenceEmbedded>();
internal void FromXml(XElement x, IFromXmlContext ctx)
{
InteractionGroup = x.Attribute("InteractionGroup")?.Value.ToEnum<InteractionGroup>();
TokenEquivalences.Synchronize(x.Elements("TokenEquivalence").ToList(), (teg, x) => teg.FromXml(x, ctx));
}
internal XElement ToXml(IToXmlContext ctx)
{
return new XElement("TokenEquivalenceGroup",
InteractionGroup == null ? null : new XAttribute(nameof(InteractionGroup), InteractionGroup.Value.ToString()),
TokenEquivalences.Select(te => te.ToXml(ctx)));
}
protected override string? PropertyValidation(PropertyInfo pi)
{
if(pi.Name == nameof(TokenEquivalences))
{
var list = TokenEquivalences.Select(a => a.Token.Token.Type.UnNullify().CleanType()).Distinct().ToList();
if(list.Count > 1)
{
if (!list.Any(t => list.All(t2 => t.IsAssignableFrom(t2))))
return "Types " + list.CommaAnd(t => t.TypeName()) + " are not compatible";
}
}
return base.PropertyValidation(pi);
}
}
public class TokenEquivalenceEmbedded : EmbeddedEntity
{
public QueryEntity Query { get; set; }
public QueryTokenEmbedded Token { get; set; }
internal void FromXml(XElement element, IFromXmlContext ctx)
{
Query = ctx.GetQuery(element.Attribute("Query")!.Value);
Token = new QueryTokenEmbedded(element.Attribute("Token")!.Value);
}
internal XElement ToXml(IToXmlContext ctx) => new XElement("TokenEquivalence",
new XAttribute("Query", Query.Key),
new XAttribute("Token", Token.Token.FullKey())
);
}
| |
using System;
using Csla;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERCLevel;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H03_Continent_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="H03_Continent_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="H02_Continent"/> collection.
/// </remarks>
[Serializable]
public partial class H03_Continent_ReChild : BusinessBase<H03_Continent_ReChild>
{
#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="H03_Continent_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H03_Continent_ReChild"/> object.</returns>
internal static H03_Continent_ReChild NewH03_Continent_ReChild()
{
return DataPortal.CreateChild<H03_Continent_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="H03_Continent_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID2">The Continent_ID2 parameter of the H03_Continent_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="H03_Continent_ReChild"/> object.</returns>
internal static H03_Continent_ReChild GetH03_Continent_ReChild(int continent_ID2)
{
return DataPortal.FetchChild<H03_Continent_ReChild>(continent_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H03_Continent_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public H03_Continent_ReChild()
{
// 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="H03_Continent_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="H03_Continent_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="continent_ID2">The Continent ID2.</param>
protected void Child_Fetch(int continent_ID2)
{
var args = new DataPortalHookArgs(continent_ID2);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var dal = dalManager.GetProvider<IH03_Continent_ReChildDal>();
var data = dal.Fetch(continent_ID2);
Fetch(data);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Loads a <see cref="H03_Continent_ReChild"/> object from the given <see cref="H03_Continent_ReChildDto"/>.
/// </summary>
/// <param name="data">The H03_Continent_ReChildDto to use.</param>
private void Fetch(H03_Continent_ReChildDto data)
{
// Value properties
LoadProperty(Continent_Child_NameProperty, data.Continent_Child_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="H03_Continent_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(H02_Continent parent)
{
var dto = new H03_Continent_ReChildDto();
dto.Parent_Continent_ID = parent.Continent_ID;
dto.Continent_Child_Name = Continent_Child_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IH03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H03_Continent_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(H02_Continent parent)
{
if (!IsDirty)
return;
var dto = new H03_Continent_ReChildDto();
dto.Parent_Continent_ID = parent.Continent_ID;
dto.Continent_Child_Name = Continent_Child_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IH03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="H03_Continent_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(H02_Continent parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IH03_Continent_ReChildDal>();
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
}
}
| |
using ServiceBouncer.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace ServiceBouncer
{
public sealed class ServiceViewModel : INotifyPropertyChanged
{
private readonly ServiceController controller;
public event PropertyChangedEventHandler PropertyChanged;
public string Name { get; private set; }
public string ServiceName { get; private set; }
public string Status { get; private set; }
public string StartupType { get; private set; }
public Image StatusIcon { get; private set; }
public ServiceViewModel(ServiceController controller)
{
this.controller = controller;
Name = controller.DisplayName;
ServiceName = controller.ServiceName;
Status = controller.Status.ToString();
StatusIcon = GetIcon(Status);
StartupType = controller.StartType.ToString();
}
public async Task Start()
{
if (controller.Status == ServiceControllerStatus.Stopped)
{
await Task.Run(() => controller.Start());
await Refresh();
}
else if (controller.Status == ServiceControllerStatus.Paused)
{
await Task.Run(() => controller.Continue());
await Refresh();
}
}
public async Task Restart()
{
if (controller.Status == ServiceControllerStatus.Running || controller.Status == ServiceControllerStatus.Paused)
{
await Task.Run(() =>
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(60));
if (controller.Status != ServiceControllerStatus.Stopped)
{
throw new Exception("The service did not stop within 60 seconds, you will need to start manually");
}
controller.Start();
});
await Refresh();
}
}
public async Task Stop()
{
if (controller.Status == ServiceControllerStatus.Running || controller.Status == ServiceControllerStatus.Paused)
{
await Task.Run(() => controller.Stop());
await Refresh();
}
}
public async Task Pause()
{
if (controller.Status == ServiceControllerStatus.Running)
{
if (controller.CanPauseAndContinue)
{
await Task.Run(() => controller.Pause());
await Refresh();
}
else
{
throw new Exception("Cannot pause this service");
}
}
}
public async Task Delete()
{
if (controller.Status == ServiceControllerStatus.Running)
{
await Task.Run(() => controller.Stop());
}
await Task.Run(() => Process.Start("sc.exe", "delete \"" + ServiceName + "\""));
}
public async Task SetStartupType(ServiceStartMode newType)
{
await Task.Run(() => controller.SetStartupType(newType));
await Refresh();
}
public async Task OpenServiceInExplorer()
{
await Task.Run(() =>
{
var path = controller.GetExecutablePath();
Process.Start("explorer.exe", $"/select, \"{path.FullName}\"");
});
}
public async Task<string> GetAssemblyInfo()
{
return await Task.Run(() =>
{
var path = controller.GetExecutablePath();
try
{
var assembly = Assembly.LoadFrom(path.FullName);
return BuildAssemblyInfoText(assembly);
}
catch (Exception)
{
try
{
var versionInfo = FileVersionInfo.GetVersionInfo(path.FullName);
return BuildAssemblyInfoText(versionInfo);
}
catch (Exception)
{
throw new Exception("Unable to find property values");
}
}
});
}
private string BuildAssemblyInfoText(Assembly assembly)
{
var title = assembly.GetCustomAttribute<AssemblyTitleAttribute>();
var description = assembly.GetCustomAttribute<AssemblyDescriptionAttribute>();
var company = assembly.GetCustomAttribute<AssemblyCompanyAttribute>();
var product = assembly.GetCustomAttribute<AssemblyProductAttribute>();
var copyright = assembly.GetCustomAttribute<AssemblyCopyrightAttribute>();
var version = assembly.GetCustomAttribute<AssemblyFileVersionAttribute>();
var output = new StringBuilder();
if (!string.IsNullOrWhiteSpace(title?.Title)) output.AppendLine($"* Title: {title.Title}");
if (!string.IsNullOrWhiteSpace(description?.Description)) output.AppendLine($"* Description: {description.Description}");
if (!string.IsNullOrWhiteSpace(company?.Company)) output.AppendLine($"* Company: {company.Company}");
if (!string.IsNullOrWhiteSpace(product?.Product)) output.AppendLine($"* Product: {product.Product}");
if (!string.IsNullOrWhiteSpace(copyright?.Copyright)) output.AppendLine($"* Copyright: {copyright.Copyright}");
if (!string.IsNullOrWhiteSpace(version?.Version)) output.AppendLine($"* Version: {version.Version}");
return output.ToString();
}
private string BuildAssemblyInfoText(FileVersionInfo fileVersion)
{
var output = new StringBuilder();
if (!string.IsNullOrWhiteSpace(fileVersion.FileDescription)) output.AppendLine($"* Description: {fileVersion.FileDescription}");
if (!string.IsNullOrWhiteSpace(fileVersion.CompanyName)) output.AppendLine($"* Company: {fileVersion.CompanyName}");
if (!string.IsNullOrWhiteSpace(fileVersion.ProductName)) output.AppendLine($"* Product: {fileVersion.ProductName}");
if (!string.IsNullOrWhiteSpace(fileVersion.LegalCopyright)) output.AppendLine($"* Copyright: {fileVersion.LegalCopyright}");
if (!string.IsNullOrWhiteSpace(fileVersion.FileVersion)) output.AppendLine($"* Version: {fileVersion.FileVersion}");
return output.ToString();
}
public async Task Refresh()
{
try
{
var changed = await Task.Run(() =>
{
var changedEvents = new List<string>();
try
{
controller.Refresh();
if (Name != controller.DisplayName)
{
Name = controller.DisplayName;
changedEvents.Add("Name");
}
if (ServiceName != controller.ServiceName)
{
ServiceName = controller.ServiceName;
changedEvents.Add("ServiceName");
}
var statusText = controller.Status.ToString();
if (Status != statusText)
{
Status = controller.Status.ToString();
StatusIcon = GetIcon(Status);
changedEvents.Add("Status");
changedEvents.Add("StatusIcon");
}
var startup = controller.StartType.ToString();
if (StartupType != startup)
{
StartupType = startup;
changedEvents.Add("StartupType");
}
}
catch (Exception)
{
//Ignored
}
return changedEvents;
});
foreach (var item in changed)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(item));
}
}
catch (Exception)
{
//Ignored
}
}
private Image GetIcon(string status)
{
switch (status.ToLower())
{
case "running":
return Properties.Resources.Running_State_Running;
case "stopped":
return Properties.Resources.Running_State_Stopped;
case "startpending":
return Properties.Resources.Running_State_StartPending;
case "stoppending":
return Properties.Resources.Running_State_StopPending;
case "paused":
return Properties.Resources.Running_State_Paused;
default:
return Properties.Resources.Running_State_Unknown;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Tracing;
using System.Threading;
#if !UNIX
using System.Security.Principal;
#endif
using Microsoft.Win32.SafeHandles;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting.Server
{
internal abstract class OutOfProcessMediatorBase
{
#region Protected Data
protected TextReader originalStdIn;
protected OutOfProcessTextWriter originalStdOut;
protected OutOfProcessTextWriter originalStdErr;
protected OutOfProcessServerSessionTransportManager sessionTM;
protected OutOfProcessUtils.DataProcessingDelegates callbacks;
protected static object SyncObject = new object();
protected object _syncObject = new object();
protected string _initialCommand;
protected ManualResetEvent allcmdsClosedEvent;
#if !UNIX
// Thread impersonation.
protected WindowsIdentity _windowsIdentityToImpersonate;
#endif
/// <summary>
/// Count of commands in progress.
/// </summary>
protected int _inProgressCommandsCount = 0;
protected PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource();
protected bool _exitProcessOnError;
#endregion
#region Constructor
protected OutOfProcessMediatorBase(bool exitProcessOnError)
{
_exitProcessOnError = exitProcessOnError;
// Set up data handling callbacks.
callbacks = new OutOfProcessUtils.DataProcessingDelegates();
callbacks.DataPacketReceived += new OutOfProcessUtils.DataPacketReceived(OnDataPacketReceived);
callbacks.DataAckPacketReceived += new OutOfProcessUtils.DataAckPacketReceived(OnDataAckPacketReceived);
callbacks.CommandCreationPacketReceived += new OutOfProcessUtils.CommandCreationPacketReceived(OnCommandCreationPacketReceived);
callbacks.CommandCreationAckReceived += new OutOfProcessUtils.CommandCreationAckReceived(OnCommandCreationAckReceived);
callbacks.ClosePacketReceived += new OutOfProcessUtils.ClosePacketReceived(OnClosePacketReceived);
callbacks.CloseAckPacketReceived += new OutOfProcessUtils.CloseAckPacketReceived(OnCloseAckPacketReceived);
callbacks.SignalPacketReceived += new OutOfProcessUtils.SignalPacketReceived(OnSignalPacketReceived);
callbacks.SignalAckPacketReceived += new OutOfProcessUtils.SignalAckPacketReceived(OnSignalAckPacketReceived);
allcmdsClosedEvent = new ManualResetEvent(true);
}
#endregion
#region Data Processing handlers
protected void ProcessingThreadStart(object state)
{
try
{
#if !CORECLR
// CurrentUICulture is not available in Thread Class in CSS
// WinBlue: 621775. Thread culture is not properly set
// for local background jobs causing experience differences
// between local console and local background jobs.
Thread.CurrentThread.CurrentUICulture = Microsoft.PowerShell.NativeCultureResolver.UICulture;
Thread.CurrentThread.CurrentCulture = Microsoft.PowerShell.NativeCultureResolver.Culture;
#endif
string data = state as string;
OutOfProcessUtils.ProcessData(data, callbacks);
}
catch (Exception e)
{
PSEtwLog.LogOperationalError(
PSEventId.TransportError, PSOpcode.Open, PSTask.None,
PSKeyword.UseAlwaysOperational,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
PSEtwLog.LogAnalyticError(
PSEventId.TransportError_Analytic, PSOpcode.Open, PSTask.None,
PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
// notify the remote client of any errors and fail gracefully
if (_exitProcessOnError)
{
originalStdErr.WriteLine(e.Message + e.StackTrace);
Environment.Exit(OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION);
}
}
}
protected void OnDataPacketReceived(byte[] rawData, string stream, Guid psGuid)
{
string streamTemp = System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STREAM_ID_STDIN;
if (stream.Equals(DataPriorityType.PromptResponse.ToString(), StringComparison.OrdinalIgnoreCase))
{
streamTemp = System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE;
}
if (Guid.Empty == psGuid)
{
lock (_syncObject)
{
sessionTM.ProcessRawData(rawData, streamTemp);
}
}
else
{
// this is for a command
AbstractServerTransportManager cmdTM = null;
lock (_syncObject)
{
cmdTM = sessionTM.GetCommandTransportManager(psGuid);
}
if (cmdTM != null)
{
// not throwing when there is no associated command as the command might have
// legitimately closed while the client is sending data. however the client
// should die after timeout as we are not sending an ACK back.
cmdTM.ProcessRawData(rawData, streamTemp);
}
else
{
// There is no command transport manager to process the input data.
// However, we still need to acknowledge to the client that this input data
// was received. This can happen with some cmdlets such as Select-Object -First
// where the cmdlet completes before all input data is received.
originalStdOut.WriteLine(OutOfProcessUtils.CreateDataAckPacket(psGuid));
}
}
}
protected void OnDataAckPacketReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_DATA_ACK_TAG);
}
protected void OnCommandCreationPacketReceived(Guid psGuid)
{
lock (_syncObject)
{
sessionTM.CreateCommandTransportManager(psGuid);
if (_inProgressCommandsCount == 0)
allcmdsClosedEvent.Reset();
_inProgressCommandsCount++;
tracer.WriteMessage("OutOfProcessMediator.OnCommandCreationPacketReceived, in progress command count : " + _inProgressCommandsCount + " psGuid : " + psGuid.ToString());
}
}
protected void OnCommandCreationAckReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_COMMAND_ACK_TAG);
}
protected void OnSignalPacketReceived(Guid psGuid)
{
if (psGuid == Guid.Empty)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCNoSignalForSession, RemotingErrorIdStrings.IPCNoSignalForSession,
OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_TAG);
}
else
{
// this is for a command
AbstractServerTransportManager cmdTM = null;
try
{
lock (_syncObject)
{
cmdTM = sessionTM.GetCommandTransportManager(psGuid);
}
// dont throw if there is no cmdTM as it might have legitimately closed
if (cmdTM != null)
{
cmdTM.Close(null);
}
}
finally
{
// Always send ack signal to avoid not responding in client.
originalStdOut.WriteLine(OutOfProcessUtils.CreateSignalAckPacket(psGuid));
}
}
}
protected void OnSignalAckPacketReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_ACK_TAG);
}
protected void OnClosePacketReceived(Guid psGuid)
{
PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource();
if (psGuid == Guid.Empty)
{
tracer.WriteMessage("BEGIN calling close on session transport manager");
bool waitForAllcmdsClosedEvent = false;
lock (_syncObject)
{
if (_inProgressCommandsCount > 0)
waitForAllcmdsClosedEvent = true;
}
// Wait outside sync lock if required for all cmds to be closed
//
if (waitForAllcmdsClosedEvent)
allcmdsClosedEvent.WaitOne();
lock (_syncObject)
{
tracer.WriteMessage("OnClosePacketReceived, in progress commands count should be zero : " + _inProgressCommandsCount + ", psGuid : " + psGuid.ToString());
if (sessionTM != null)
{
// it appears that when closing PowerShell ISE, therefore closing OutOfProcServerMediator, there are 2 Close command requests
// changing PSRP/IPC at this point is too risky, therefore protecting about this duplication
sessionTM.Close(null);
}
tracer.WriteMessage("END calling close on session transport manager");
sessionTM = null;
}
}
else
{
tracer.WriteMessage("Closing command with GUID " + psGuid.ToString());
// this is for a command
AbstractServerTransportManager cmdTM = null;
lock (_syncObject)
{
cmdTM = sessionTM.GetCommandTransportManager(psGuid);
}
// dont throw if there is no cmdTM as it might have legitimately closed
if (cmdTM != null)
{
cmdTM.Close(null);
}
lock (_syncObject)
{
tracer.WriteMessage("OnClosePacketReceived, in progress commands count should be greater than zero : " + _inProgressCommandsCount + ", psGuid : " + psGuid.ToString());
_inProgressCommandsCount--;
if (_inProgressCommandsCount == 0)
allcmdsClosedEvent.Set();
}
}
// send close ack
originalStdOut.WriteLine(OutOfProcessUtils.CreateCloseAckPacket(psGuid));
}
protected void OnCloseAckPacketReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_CLOSE_ACK_TAG);
}
#endregion
#region Methods
protected OutOfProcessServerSessionTransportManager CreateSessionTransportManager(string configurationName, PSRemotingCryptoHelperServer cryptoHelper)
{
PSSenderInfo senderInfo;
#if !UNIX
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
PSPrincipal userPrincipal = new PSPrincipal(new PSIdentity(string.Empty, true, currentIdentity.Name, null),
currentIdentity);
senderInfo = new PSSenderInfo(userPrincipal, "http://localhost");
#else
PSPrincipal userPrincipal = new PSPrincipal(new PSIdentity(string.Empty, true, string.Empty, null),
null);
senderInfo = new PSSenderInfo(userPrincipal, "http://localhost");
#endif
OutOfProcessServerSessionTransportManager tm = new OutOfProcessServerSessionTransportManager(originalStdOut, originalStdErr, cryptoHelper);
ServerRemoteSession srvrRemoteSession = ServerRemoteSession.CreateServerRemoteSession(senderInfo,
_initialCommand, tm, configurationName);
return tm;
}
protected void Start(string initialCommand, PSRemotingCryptoHelperServer cryptoHelper, string configurationName = null)
{
_initialCommand = initialCommand;
sessionTM = CreateSessionTransportManager(configurationName, cryptoHelper);
try
{
do
{
string data = originalStdIn.ReadLine();
lock (_syncObject)
{
if (sessionTM == null)
{
sessionTM = CreateSessionTransportManager(configurationName, cryptoHelper);
}
}
if (string.IsNullOrEmpty(data))
{
lock (_syncObject)
{
// give a chance to runspace/pipelines to close (as it looks like the client died
// intermittently)
sessionTM.Close(null);
sessionTM = null;
}
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived,
RemotingErrorIdStrings.IPCUnknownElementReceived, string.Empty);
}
// process data in a thread pool thread..this way Runspace, Command
// data can be processed concurrently.
#if !UNIX
Utils.QueueWorkItemWithImpersonation(
_windowsIdentityToImpersonate,
new WaitCallback(ProcessingThreadStart),
data);
#else
ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessingThreadStart), data);
#endif
} while (true);
}
catch (Exception e)
{
PSEtwLog.LogOperationalError(
PSEventId.TransportError, PSOpcode.Open, PSTask.None,
PSKeyword.UseAlwaysOperational,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
PSEtwLog.LogAnalyticError(
PSEventId.TransportError_Analytic, PSOpcode.Open, PSTask.None,
PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
if (_exitProcessOnError)
{
// notify the remote client of any errors and fail gracefully
originalStdErr.WriteLine(e.Message);
Environment.Exit(OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION);
}
}
}
#endregion
#region Static Methods
internal static void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs args)
{
// args can never be null.
Exception exception = (Exception)args.ExceptionObject;
// log the exception to crimson event logs
PSEtwLog.LogOperationalError(PSEventId.AppDomainUnhandledException,
PSOpcode.Close, PSTask.None,
PSKeyword.UseAlwaysOperational,
exception.GetType().ToString(), exception.Message,
exception.StackTrace);
PSEtwLog.LogAnalyticError(PSEventId.AppDomainUnhandledException_Analytic,
PSOpcode.Close, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
exception.GetType().ToString(), exception.Message,
exception.StackTrace);
}
#endregion
}
internal sealed class OutOfProcessMediator : OutOfProcessMediatorBase
{
#region Private Data
private static OutOfProcessMediator s_singletonInstance;
#endregion
#region Constructors
/// <summary>
/// The mediator will take actions from the StdIn stream and responds to them.
/// It will replace StdIn,StdOut and StdErr stream with TextWriter.Null's. This is
/// to make sure these streams are totally used by our Mediator.
/// </summary>
private OutOfProcessMediator() : base(true)
{
// Create input stream reader from Console standard input stream.
// We don't use the provided Console.In TextReader because it can have
// an incorrect encoding, e.g., Hyper-V Container console where the
// TextReader has incorrect default console encoding instead of the actual
// stream encoding. This way the stream encoding is determined by the
// stream BOM as needed.
originalStdIn = new StreamReader(Console.OpenStandardInput(), true);
// replacing StdIn with Null so that no other app messes with the
// original stream.
Console.SetIn(TextReader.Null);
// replacing StdOut with Null so that no other app messes with the
// original stream
originalStdOut = new OutOfProcessTextWriter(Console.Out);
Console.SetOut(TextWriter.Null);
// replacing StdErr with Null so that no other app messes with the
// original stream
originalStdErr = new OutOfProcessTextWriter(Console.Error);
Console.SetError(TextWriter.Null);
}
#endregion
#region Static Methods
/// <summary>
/// </summary>
internal static void Run(string initialCommand)
{
lock (SyncObject)
{
if (s_singletonInstance != null)
{
Dbg.Assert(false, "Run should not be called multiple times");
return;
}
s_singletonInstance = new OutOfProcessMediator();
}
#if !CORECLR // AppDomain is not available in CoreCLR
// Setup unhandled exception to log events
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException);
#endif
s_singletonInstance.Start(initialCommand, new PSRemotingCryptoHelperServer());
}
#endregion
}
internal sealed class SSHProcessMediator : OutOfProcessMediatorBase
{
#region Private Data
private static SSHProcessMediator s_singletonInstance;
#endregion
#region Constructors
private SSHProcessMediator() : base(true)
{
#if !UNIX
var inputHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Input);
originalStdIn = new StreamReader(
new FileStream(new SafeFileHandle(inputHandle, false), FileAccess.Read));
var outputHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Output);
originalStdOut = new OutOfProcessTextWriter(
new StreamWriter(
new FileStream(new SafeFileHandle(outputHandle, false), FileAccess.Write)));
var errorHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Error);
originalStdErr = new OutOfProcessTextWriter(
new StreamWriter(
new FileStream(new SafeFileHandle(errorHandle, false), FileAccess.Write)));
#else
originalStdIn = new StreamReader(Console.OpenStandardInput(), true);
originalStdOut = new OutOfProcessTextWriter(
new StreamWriter(Console.OpenStandardOutput()));
originalStdErr = new OutOfProcessTextWriter(
new StreamWriter(Console.OpenStandardError()));
#endif
}
#endregion
#region Static Methods
/// <summary>
/// </summary>
/// <param name="initialCommand"></param>
internal static void Run(string initialCommand)
{
lock (SyncObject)
{
if (s_singletonInstance != null)
{
Dbg.Assert(false, "Run should not be called multiple times");
return;
}
s_singletonInstance = new SSHProcessMediator();
}
PSRemotingCryptoHelperServer cryptoHelper;
#if !UNIX
cryptoHelper = new PSRemotingCryptoHelperServer();
#else
cryptoHelper = null;
#endif
s_singletonInstance.Start(initialCommand, cryptoHelper);
}
#endregion
}
internal sealed class NamedPipeProcessMediator : OutOfProcessMediatorBase
{
#region Private Data
private static NamedPipeProcessMediator s_singletonInstance;
private readonly RemoteSessionNamedPipeServer _namedPipeServer;
#endregion
#region Properties
internal bool IsDisposed
{
get { return _namedPipeServer.IsDisposed; }
}
#endregion
#region Constructors
private NamedPipeProcessMediator() : base(false) { }
private NamedPipeProcessMediator(
RemoteSessionNamedPipeServer namedPipeServer) : base(false)
{
if (namedPipeServer == null)
{
throw new PSArgumentNullException("namedPipeServer");
}
_namedPipeServer = namedPipeServer;
// Create transport reader/writers from named pipe.
originalStdIn = namedPipeServer.TextReader;
originalStdOut = new OutOfProcessTextWriter(namedPipeServer.TextWriter);
originalStdErr = new NamedPipeErrorTextWriter(namedPipeServer.TextWriter);
#if !UNIX
// Flow impersonation as needed.
Utils.TryGetWindowsImpersonatedIdentity(out _windowsIdentityToImpersonate);
#endif
}
#endregion
#region Static Methods
internal static void Run(
string initialCommand,
RemoteSessionNamedPipeServer namedPipeServer)
{
lock (SyncObject)
{
if (s_singletonInstance != null && !s_singletonInstance.IsDisposed)
{
Dbg.Assert(false, "Run should not be called multiple times, unless the singleton was disposed.");
return;
}
s_singletonInstance = new NamedPipeProcessMediator(namedPipeServer);
}
#if !CORECLR
// AppDomain is not available in CoreCLR
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException);
#endif
s_singletonInstance.Start(initialCommand, new PSRemotingCryptoHelperServer(), namedPipeServer.ConfigurationName);
}
#endregion
}
internal sealed class NamedPipeErrorTextWriter : OutOfProcessTextWriter
{
#region Private Members
private const string _errorPrepend = "__NamedPipeError__:";
#endregion
#region Properties
internal static string ErrorPrepend
{
get { return _errorPrepend; }
}
#endregion
#region Constructors
internal NamedPipeErrorTextWriter(
TextWriter textWriter) : base(textWriter)
{ }
#endregion
#region Base class overrides
internal override void WriteLine(string data)
{
string dataToWrite = (data != null) ? _errorPrepend + data : null;
base.WriteLine(dataToWrite);
}
#endregion
}
internal sealed class HyperVSocketMediator : OutOfProcessMediatorBase
{
#region Private Data
private static HyperVSocketMediator s_instance;
private readonly RemoteSessionHyperVSocketServer _hypervSocketServer;
#endregion
#region Properties
internal bool IsDisposed
{
get { return _hypervSocketServer.IsDisposed; }
}
#endregion
#region Constructors
private HyperVSocketMediator()
: base(false)
{
_hypervSocketServer = new RemoteSessionHyperVSocketServer(false);
originalStdIn = _hypervSocketServer.TextReader;
originalStdOut = new OutOfProcessTextWriter(_hypervSocketServer.TextWriter);
originalStdErr = new HyperVSocketErrorTextWriter(_hypervSocketServer.TextWriter);
}
#endregion
#region Static Methods
internal static void Run(
string initialCommand,
string configurationName)
{
lock (SyncObject)
{
s_instance = new HyperVSocketMediator();
}
#if !CORECLR
// AppDomain is not available in CoreCLR
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException);
#endif
s_instance.Start(initialCommand, new PSRemotingCryptoHelperServer(), configurationName);
}
#endregion
}
internal sealed class HyperVSocketErrorTextWriter : OutOfProcessTextWriter
{
#region Private Members
private const string _errorPrepend = "__HyperVSocketError__:";
#endregion
#region Properties
internal static string ErrorPrepend
{
get { return _errorPrepend; }
}
#endregion
#region Constructors
internal HyperVSocketErrorTextWriter(
TextWriter textWriter)
: base(textWriter)
{ }
#endregion
#region Base class overrides
internal override void WriteLine(string data)
{
string dataToWrite = (data != null) ? _errorPrepend + data : null;
base.WriteLine(dataToWrite);
}
#endregion
}
}
| |
/*
-- =============================================
-- Author: Jonathan F. Minond
-- Create date: April 2006
-- Description: Partial class containing the basic parts of an Item Object.
-- This class works in conjucntion with ItemHelpers.cs and Item.cs
-- =============================================
*/
using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Xml;
using System.Reflection;
using Content.API.Data;
using Content.API.Properties;
namespace Content.API
{
public partial class Item
{
// This should all be prefetched i suppose
#region provate Standard Item Data fields
private long _itemID = 0;
private DateTime _dateCreated;
private bool _enablePersmissioning = false;
private int _version = 0;
private List<long> _versionItemIds; // not implemented yet
private List<long> _currentVersionCultureItemIds; // not implemented yet
private long _parentItemID = 0;
private Guid _typeID;
private Settings _itemSettings = new Settings();
private Settings _originalSettings = new Settings();
private WorkFlowVersions _workflowVersion = WorkFlowVersions.Draft;
private bool _enableWorkflow = false;
private string _createdByUser = string.Empty;
private ItemCollection _childItems = null;
private bool _enableComments = false;
private bool _enableRatings = false;
private long _groupItemID = 0;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="T:Item"/> class.
/// </summary>
public Item()
{
assignEvents();
}
/// <summary>
/// Initializes a new instance of the <see cref="T:Item"/> class.
/// </summary>
/// <param name="id">The id.</param>
public Item(long id)
{
if (id >= 0)
{
_itemID = id;
FillInitialData();
}
assignEvents();
}
#endregion
/// <summary>
/// Fills the initial data.
/// Prefech data for the item should be centralized to here as much as possible.
/// Inherited objects can override thi method to fill additional properties
/// they may need on aditional access.
/// Some things like cihld nodes are lazy loaded.
/// </summary>
/// <remarks>
/// Properties which are initially loaded at instance time of the itembase
/// <list type="string">
/// <item>_itemID</item>
/// <item>_title</item>
/// <item>_dateCreated</item>
/// <item>_datePublished</item>
/// <item>_enablePersmissioning</item>
/// <item>_isDirty</item>
/// <item>_parentItemID</item>
/// <item></item>
/// </list>
/// </remarks>
protected virtual void FillInitialData()
{
#region ItemHelperMethods
LoadItemStatuses();
LoadItemCategories();
FetchItemSettings();
#endregion
}
#region Public Properties
/// <summary>
/// Gets or sets a value indicating whether [enable permissioning].
/// </summary>
/// <value><c>true</c> if [enable permissioning]; otherwise, <c>false</c>.</value>
public virtual bool EnablePermissioning
{
get
{
return _enablePersmissioning;
}
set
{
_enablePersmissioning = value;
}
}
/// <summary>
/// Gets or sets the date created.
/// </summary>
/// <value>The date created.</value>
[Bindable(true)]
public virtual DateTime DateCreated
{
get
{
return _dateCreated;
}
set
{
_dateCreated = value;
}
}
/// <summary>
/// Gets or sets the parent item ID.
/// </summary>
/// <value>The parent item ID.</value>
[Bindable(true)]
public long ParentItemID
{
get
{
return _parentItemID;
}
set
{
_parentItemID = value;
}
}
/// <summary>
/// Gets the item ID.
/// </summary>
/// <value>The item ID.</value>
[Bindable(true)]
public long ItemID
{
get
{
return _itemID;
}
set
{
if (value > 0)
_itemID = value;
else
throw new Exception("Not allowed to set ItemID to 0 or negative.");
}
}
/// <summary>
/// Gets or sets the created by user.
/// <remarks>this is the user who created the original version/culture of an item. there is
/// only one created user for an item, even for multiple versions, the original creator stays
/// the same.</remarks>
/// </summary>
/// <value>The created by user.</value>
public string CreatedByUser
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
/// <summary>
/// Gets the item settings.
/// Collection of settings for the item, stored as Setting types. Which provide
/// name, value, datatype, and a bit more.
/// </summary>
/// <value>The item settings.</value>
public Settings ItemSettings
{
get { return _itemSettings; }
set
{
throw new NotImplementedException("The method or operation is not implemented.");
//_itemID = value;
}
}
/// <summary>
/// Gets or sets the group item ID.
/// The group Item ID is the id of the item that groups a bunch of things.
/// it is different from a parent id.
/// for example pages are grouped by a portal id, but there parent is another pageid
/// </summary>
/// <value>The group item ID.</value>
public long GroupItemID
{
get { return _groupItemID; }
set { _groupItemID = value; }
}
/// <summary>
/// Gets a value indicating whether [comments enabled].
/// if enabled, features such as adding items of type comment will be enabled.
/// there will be built in data mehods for easily making ui controls to deal with comments
/// <remarks>some applications have the potential to use the comments as a full fledged
/// type, for example in a discussion scenarion, you might use comments to make a single level
/// reply. the comment type does not have have a lot of features, but they would have a parent
/// for example, text, author, date.. and some other settings which UI could use.</remarks>
/// </summary>
/// <value><c>true</c> if [comments enabled]; otherwise, <c>false</c>.</value>
public bool CommentsEnabled
{
get { return _enableComments; }
set { _enableComments = value; }
}
/// <summary>
/// Gets a value indicating whether [ratings enabled].
/// if enabled, features such as adding items of type rating will be enabled.
/// there will be built in data mehods for easily making ui controls to deal with ratings
/// such as top rated by category, or most rated items...etc.. this is mainly helper functionality
/// that a lot of conetnt is likely to use.
/// <remarks>applications could potentially use ratings on differnt types</remarks>
/// </summary>
/// <value><c>true</c> if [ratings enabled]; otherwise, <c>false</c>.</value>
public bool RatingsEnabled
{
get { return _enableRatings; }
set { _enableRatings = value; }
}
/// <summary>
/// Gets or sets the child items.
/// This is a collection of items that would be lazy loaded if the items are asked for.
/// parents who have this instance itemid as a parent will show up here.
/// </summary>
/// <value>The child items.</value>
public ItemCollection ChildItems
{
get
{
return _childItems;
}
set
{
_childItems = value;
}
}
#endregion
}
}
| |
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 WebApp.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.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Threading;
using Moscrif.IDE.Execution;
namespace Moscrif.IDE.Iface
{
public class SocketServer
{
public delegate void UpdateRichEditCallback(string text);
public static event ProcessEventHandler OutputClientChanged;
private static string m_currentmessage = "";
public static AsyncCallback pfnWorkerCallBack ;
private static System.Net.Sockets.Socket m_mainSocket;
private static System.Collections.ArrayList m_workerSocketList =
ArrayList.Synchronized(new System.Collections.ArrayList());
private static int m_clientCount = 0;
private static bool isRunning;
public static string StartListen(string IPadress,string portStr){
try
{
IPAddress ipAddress = IPAddress.Parse(IPadress);
int port = System.Convert.ToInt32(portStr);
m_mainSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork,SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(ipAddress,port); //(IPAddress.Any, port);
m_mainSocket.Bind( ipLocal );
m_mainSocket.Listen(4);
m_mainSocket.BeginAccept(new AsyncCallback (OnClientConnect), null);
isRunning = true;
return ipLocal.ToString();
}
catch(SocketException se)
{
Console.WriteLine( se.Message );
return null;
}
}
public static void OnClientConnect(IAsyncResult asyn)
{
try
{
System.Net.Sockets.Socket workerSocket = m_mainSocket.EndAccept (asyn);
Interlocked.Increment(ref m_clientCount);
m_workerSocketList.Add(workerSocket);
WaitForData(workerSocket, m_clientCount);
string msg = "Client " + m_clientCount + " Connected" + "\n";
if(OutputClientChanged != null)
OutputClientChanged(null,msg);
m_mainSocket.BeginAccept(new AsyncCallback ( OnClientConnect ),null);
}
catch(ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0,"1","\n OnClientConnection: Socket has been closed\n");
}
catch(SocketException se)
{
Console.WriteLine( se.Message );
}
}
public class SocketPacket
{
public SocketPacket(System.Net.Sockets.Socket socket, int clientNumber)
{
m_currentSocket = socket;
m_clientNumber = clientNumber;
}
public System.Net.Sockets.Socket m_currentSocket;
public int m_clientNumber;
public byte[] dataBuffer = new byte[1024];
}
private static void SendDataClient(System.Net.Sockets.Socket workerSocket){
// Send back the reply to the client
string replyMsg = "Server Reply:" + m_currentmessage;
// Convert the reply to byte array
byte[] byData = System.Text.Encoding.ASCII.GetBytes(replyMsg);
workerSocket.Send(byData);
}
public static void OnDataReceived(IAsyncResult asyn)
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState ;
try
{
int numbytes = 0;
numbytes = socketData.m_currentSocket.EndReceive (asyn);
char[] chars = new char[numbytes];
//System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
string recievedData = new String(chars);
m_currentmessage += recievedData;
if (recievedData.Contains("\n" ) && OutputClientChanged != null)
{
OutputClientChanged(null,m_currentmessage);//(spacket.Socket, node);
m_currentmessage = "";
}
WaitForData(socketData.m_currentSocket, socketData.m_clientNumber );
System.Net.Sockets.Socket workerSocket2 = ( System.Net.Sockets.Socket)socketData.m_currentSocket;
SendDataClient(workerSocket2);
}
catch (ObjectDisposedException )
{
System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed \n");
}
catch(SocketException se)
{
if(se.ErrorCode == 10054) // Error code for Connection reset by peer
{
string msg = "Client " + socketData.m_clientNumber + " Disconnected" + "\n";
if(OutputClientChanged!=null){
OutputClientChanged(null,msg);
}
m_workerSocketList[socketData.m_clientNumber - 1] = null;
}
else
{
if(OutputClientChanged!=null){
OutputClientChanged(null,se.Message);
}
}
}
}
static void SendMsgToClient(string msg, int clientNumber)
{
byte[] byData = System.Text.Encoding.ASCII.GetBytes(msg);
System.Net.Sockets.Socket workerSocket = (System.Net.Sockets.Socket)m_workerSocketList[clientNumber - 1];
workerSocket.Send(byData);
}
public static void WaitForData(System.Net.Sockets.Socket soc, int clientNumber)
{
try
{
if ( pfnWorkerCallBack == null )
{
pfnWorkerCallBack = new AsyncCallback (OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket (soc, clientNumber);
soc.BeginReceive (theSocPkt.dataBuffer, 0,
theSocPkt.dataBuffer.Length,
SocketFlags.None,
pfnWorkerCallBack,
theSocPkt);
}
catch(SocketException se)
{
Console.WriteLine(se.Message );
}
}
public static bool Running {
get{
return isRunning;
}
}
public static void CloseSockets()
{
if(m_mainSocket != null)
{
m_mainSocket.Close();
}
System.Net.Sockets.Socket workerSocket = null;
for(int i = 0; i < m_workerSocketList.Count; i++)
{
workerSocket = (System.Net.Sockets.Socket)m_workerSocketList[i];
if(workerSocket != null)
{
workerSocket.Close();
workerSocket = null;
}
}
m_currentmessage = "";
isRunning = false;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace RegPetServer.WebAPI.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Orleans.Runtime
{
// This is the public interface to be used by the consistent ring
public interface IRingRange
{
/// <summary>
/// Check if <paramref name="n"/> is our responsibility to serve
/// </summary>
/// <returns>true if the reminder is in our responsibility range, false otherwise</returns>
bool InRange(uint n);
bool InRange(GrainReference grainReference);
}
// This is the internal interface to be used only by the different range implementations.
internal interface IRingRangeInternal : IRingRange
{
long RangeSize();
double RangePercentage();
string ToFullString();
}
public interface ISingleRange : IRingRange
{
/// <summary>
/// Exclusive
/// </summary>
uint Begin { get; }
/// <summary>
/// Inclusive
/// </summary>
uint End { get; }
}
[Serializable]
[GenerateSerializer]
internal sealed class SingleRange : IRingRangeInternal, IEquatable<SingleRange>, ISingleRange
{
[Id(1)]
private readonly uint begin;
[Id(2)]
private readonly uint end;
/// <summary>
/// Exclusive
/// </summary>
public uint Begin { get { return begin; } }
/// <summary>
/// Inclusive
/// </summary>
public uint End { get { return end; } }
public SingleRange(uint begin, uint end)
{
this.begin = begin;
this.end = end;
}
public bool InRange(GrainReference grainReference)
{
return InRange(grainReference.GetUniformHashCode());
}
/// <summary>
/// checks if n is element of (Begin, End], while remembering that the ranges are on a ring
/// </summary>
/// <param name="n"></param>
/// <returns>true if n is in (Begin, End], false otherwise</returns>
public bool InRange(uint n)
{
uint num = n;
if (begin < end)
{
return num > begin && num <= end;
}
// Begin > End
return num > begin || num <= end;
}
public long RangeSize()
{
if (begin < end)
{
return end - begin;
}
return RangeFactory.RING_SIZE - (begin - end);
}
public double RangePercentage() => RangeSize() * (100.0 / RangeFactory.RING_SIZE);
public bool Equals(SingleRange other)
{
return other != null && begin == other.begin && end == other.end;
}
public override bool Equals(object obj)
{
return Equals(obj as SingleRange);
}
public override int GetHashCode()
{
return (int)(begin ^ end);
}
public override string ToString()
{
if (begin == 0 && end == 0)
{
return "<(0 0], Size=x100000000, %Ring=100%>";
}
return String.Format("<(x{0,8:X8} x{1,8:X8}], Size=x{2,8:X8}, %Ring={3:0.000}%>", begin, end, RangeSize(), RangePercentage());
}
public string ToFullString()
{
return ToString();
}
internal bool Overlaps(SingleRange other) => Equals(other) || InRange(other.begin) || other.InRange(begin);
internal SingleRange Merge(SingleRange other)
{
if ((begin | end) == 0 || (other.begin | other.end) == 0)
{
return RangeFactory.FullRange;
}
if (Equals(other))
{
return this;
}
if (InRange(other.begin))
{
return MergeEnds(other);
}
if (other.InRange(begin))
{
return other.MergeEnds(this);
}
throw new InvalidOperationException("Ranges don't overlap");
}
// other range begins inside this range, merge it based on where it ends
private SingleRange MergeEnds(SingleRange other)
{
if (begin == other.end)
{
return RangeFactory.FullRange;
}
if (!InRange(other.end))
{
return new SingleRange(begin, other.end);
}
if (other.InRange(begin))
{
return RangeFactory.FullRange;
}
return this;
}
}
public static class RangeFactory
{
public const long RING_SIZE = ((long)uint.MaxValue) + 1;
private static readonly GeneralMultiRange EmptyRange = new(new());
internal static readonly SingleRange FullRange = new(0, 0);
public static IRingRange CreateFullRange() => FullRange;
public static IRingRange CreateRange(uint begin, uint end) => new SingleRange(begin, end);
public static IRingRange CreateRange(List<IRingRange> inRanges) => inRanges.Count switch
{
0 => EmptyRange,
1 => inRanges[0],
_ => GeneralMultiRange.Create(inRanges)
};
internal static IRingRange GetEquallyDividedSubRange(IRingRange range, int numSubRanges, int mySubRangeIndex)
=> EquallyDividedMultiRange.GetEquallyDividedSubRange(range, numSubRanges, mySubRangeIndex);
public static IEnumerable<ISingleRange> GetSubRanges(IRingRange range) => range switch
{
ISingleRange single => new[] { single },
GeneralMultiRange m => m.Ranges,
_ => throw new NotSupportedException(),
};
}
[Serializable]
[GenerateSerializer]
internal sealed class GeneralMultiRange : IRingRangeInternal
{
[Id(1)]
private readonly List<SingleRange> ranges;
[Id(2)]
private readonly long rangeSize;
[Id(3)]
internal List<SingleRange> Ranges => ranges;
internal GeneralMultiRange(List<SingleRange> ranges)
{
this.ranges = ranges;
foreach (var r in ranges)
rangeSize += r.RangeSize();
}
internal static IRingRange Create(List<IRingRange> inRanges)
{
var ranges = inRanges.ConvertAll(r => (SingleRange)r);
return HasOverlaps() ? Compact() : new GeneralMultiRange(ranges);
bool HasOverlaps()
{
var last = ranges[0];
for (var i = 1; i < ranges.Count; i++)
{
if (last.Overlaps(last = ranges[i])) return true;
}
return false;
}
IRingRange Compact()
{
var lastIdx = 0;
var last = ranges[0];
for (var i = 1; i < ranges.Count; i++)
{
var r = ranges[i];
if (last.Overlaps(r)) ranges[lastIdx] = last = last.Merge(r);
else ranges[++lastIdx] = last = r;
}
if (lastIdx == 0) return last;
ranges.RemoveRange(++lastIdx, ranges.Count - lastIdx);
return new GeneralMultiRange(ranges);
}
}
public bool InRange(uint n)
{
foreach (var s in ranges)
{
if (s.InRange(n)) return true;
}
return false;
}
public bool InRange(GrainReference grainReference)
{
return InRange(grainReference.GetUniformHashCode());
}
public long RangeSize() => rangeSize;
public double RangePercentage() => RangeSize() * (100.0 / RangeFactory.RING_SIZE);
public override string ToString()
{
if (ranges.Count == 0) return "Empty MultiRange";
if (ranges.Count == 1) return ranges[0].ToString();
return String.Format("<MultiRange: Size=x{0,8:X8}, %Ring={1:0.000}%>", RangeSize(), RangePercentage());
}
public string ToFullString()
{
if (ranges.Count == 0) return "Empty MultiRange";
if (ranges.Count == 1) return ranges[0].ToString();
return String.Format("<MultiRange: Size=x{0,8:X8}, %Ring={1:0.000}%, {2} Ranges: {3}>", RangeSize(), RangePercentage(), ranges.Count, Utils.EnumerableToString(ranges, r => r.ToFullString()));
}
}
internal static class EquallyDividedMultiRange
{
private static SingleRange GetEquallyDividedSubRange(SingleRange singleRange, int numSubRanges, int mySubRangeIndex)
{
var rangeSize = singleRange.RangeSize();
uint portion = (uint)(rangeSize / numSubRanges);
uint remainder = (uint)(rangeSize - portion * numSubRanges);
uint start = singleRange.Begin;
for (int i = 0; i < numSubRanges; i++)
{
// (Begin, End]
uint end = (unchecked(start + portion));
// I want it to overflow on purpose. It will do the right thing.
if (remainder > 0)
{
end++;
remainder--;
}
if (i == mySubRangeIndex)
return new SingleRange(start, end);
start = end; // nextStart
}
throw new ArgumentException(nameof(mySubRangeIndex));
}
// Takes a range and devides it into numSubRanges equal ranges and returns the subrange at mySubRangeIndex.
public static IRingRange GetEquallyDividedSubRange(IRingRange range, int numSubRanges, int mySubRangeIndex)
{
if (numSubRanges <= 0) throw new ArgumentException(nameof(numSubRanges));
if ((uint)mySubRangeIndex >= (uint)numSubRanges) throw new ArgumentException(nameof(mySubRangeIndex));
if (numSubRanges == 1) return range;
switch (range)
{
case SingleRange singleRange:
return GetEquallyDividedSubRange(singleRange, numSubRanges, mySubRangeIndex);
case GeneralMultiRange multiRange:
switch (multiRange.Ranges.Count)
{
case 0: return multiRange;
case 1: return GetEquallyDividedSubRange(multiRange.Ranges[0], numSubRanges, mySubRangeIndex);
default:
// Take each of the single ranges in the multi range and divide each into equal sub ranges.
var singlesForThisIndex = new List<SingleRange>(multiRange.Ranges.Count);
foreach (var singleRange in multiRange.Ranges)
singlesForThisIndex.Add(GetEquallyDividedSubRange(singleRange, numSubRanges, mySubRangeIndex));
return new GeneralMultiRange(singlesForThisIndex);
}
default: throw new ArgumentException(nameof(range));
}
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Core.Settings.AuditWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#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.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
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;
using Models;
/// <summary>
/// LocalNetworkGatewaysOperations operations.
/// </summary>
internal partial class LocalNetworkGatewaysOperations : IServiceOperations<NetworkManagementClient>, ILocalNetworkGatewaysOperations
{
/// <summary>
/// Initializes a new instance of the LocalNetworkGatewaysOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal LocalNetworkGatewaysOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// The Put LocalNetworkGateway operation creates/updates a local network
/// gateway in the specified resource group through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Create or update Local Network Gateway
/// operation through Network resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<LocalNetworkGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<LocalNetworkGateway> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(
resourceGroupName, localNetworkGatewayName, parameters, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// The Put LocalNetworkGateway operation creates/updates a local network
/// gateway in the specified resource group through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Create or update Local Network Gateway
/// operation through Network resource provider.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<LocalNetworkGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localNetworkGatewayName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
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("localNetworkGatewayName", localNetworkGatewayName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{localNetworkGatewayName}", Uri.EscapeDataString(localNetworkGatewayName));
_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("PUT");
_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;
if(parameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// 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 != 201 && (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;
}
}
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<LocalNetworkGateway>();
_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 == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<LocalNetworkGateway>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<LocalNetworkGateway>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The Get LocalNetworkGateway operation retrieves information about the
/// specified local network gateway through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<LocalNetworkGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localNetworkGatewayName");
}
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("localNetworkGatewayName", localNetworkGatewayName);
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.Network/localNetworkGateways/{localNetworkGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{localNetworkGatewayName}", Uri.EscapeDataString(localNetworkGatewayName));
_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;
}
}
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<LocalNetworkGateway>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<LocalNetworkGateway>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The Delete LocalNetworkGateway operation deletes the specifed local
/// network Gateway through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(
resourceGroupName, localNetworkGatewayName, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// The Delete LocalNetworkGateway operation deletes the specifed local
/// network Gateway through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localNetworkGatewayName");
}
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("localNetworkGatewayName", localNetworkGatewayName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{localNetworkGatewayName}", Uri.EscapeDataString(localNetworkGatewayName));
_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("DELETE");
_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 != 204 && (int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The List LocalNetworkGateways opertion retrieves all the local network
/// gateways stored.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LocalNetworkGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
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("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_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;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LocalNetworkGateway>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<LocalNetworkGateway>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The List LocalNetworkGateways opertion retrieves all the local network
/// gateways stored.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LocalNetworkGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + 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;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LocalNetworkGateway>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<LocalNetworkGateway>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Data.Market;
using QuantConnect.Securities;
namespace QuantConnect.Orders.Fills
{
/// <summary>
/// Provides a base class for all fill models
/// </summary>
public class FillModel : IFillModel
{
/// <summary>
/// Default market fill model for the base security class. Fills at the last traded price.
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
/// <seealso cref="SecurityTransactionModel.StopMarketFill"/>
/// <seealso cref="SecurityTransactionModel.LimitFill"/>
public virtual OrderEvent MarketFill(Security asset, MarketOrder order)
{
//Default order event to return.
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, 0);
if (order.Status == OrderStatus.Canceled) return fill;
// make sure the exchange is open/normal market hours before filling
if (!IsExchangeOpen(asset, false)) return fill;
//Order [fill]price for a market order model is the current security price
fill.FillPrice = GetPrices(asset, order.Direction).Current;
fill.Status = OrderStatus.Filled;
//Calculate the model slippage: e.g. 0.01c
var slip = asset.SlippageModel.GetSlippageApproximation(asset, order);
//Apply slippage
switch (order.Direction)
{
case OrderDirection.Buy:
fill.FillPrice += slip;
break;
case OrderDirection.Sell:
fill.FillPrice -= slip;
break;
}
// assume the order completely filled
fill.FillQuantity = order.Quantity;
return fill;
}
/// <summary>
/// Default stop fill model implementation in base class security. (Stop Market Order Type)
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
/// <seealso cref="MarketFill(Security, MarketOrder)"/>
/// <seealso cref="SecurityTransactionModel.LimitFill"/>
public virtual OrderEvent StopMarketFill(Security asset, StopMarketOrder order)
{
//Default order event to return.
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, 0);
//If its cancelled don't need anymore checks:
if (order.Status == OrderStatus.Canceled) return fill;
// make sure the exchange is open/normal market hours before filling
if (!IsExchangeOpen(asset, false)) return fill;
//Get the range of prices in the last bar:
var prices = GetPrices(asset, order.Direction);
var pricesEndTime = prices.EndTime.ConvertToUtc(asset.Exchange.TimeZone);
// do not fill on stale data
if (pricesEndTime <= order.Time) return fill;
//Calculate the model slippage: e.g. 0.01c
var slip = asset.SlippageModel.GetSlippageApproximation(asset, order);
//Check if the Stop Order was filled: opposite to a limit order
switch (order.Direction)
{
case OrderDirection.Sell:
//-> 1.1 Sell Stop: If Price below setpoint, Sell:
if (prices.Low < order.StopPrice)
{
fill.Status = OrderStatus.Filled;
// Assuming worse case scenario fill - fill at lowest of the stop & asset price.
fill.FillPrice = Math.Min(order.StopPrice, prices.Current - slip);
// assume the order completely filled
fill.FillQuantity = order.Quantity;
}
break;
case OrderDirection.Buy:
//-> 1.2 Buy Stop: If Price Above Setpoint, Buy:
if (prices.High > order.StopPrice)
{
fill.Status = OrderStatus.Filled;
// Assuming worse case scenario fill - fill at highest of the stop & asset price.
fill.FillPrice = Math.Max(order.StopPrice, prices.Current + slip);
// assume the order completely filled
fill.FillQuantity = order.Quantity;
}
break;
}
return fill;
}
/// <summary>
/// Default stop limit fill model implementation in base class security. (Stop Limit Order Type)
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
/// <seealso cref="StopMarketFill(Security, StopMarketOrder)"/>
/// <seealso cref="SecurityTransactionModel.LimitFill"/>
/// <remarks>
/// There is no good way to model limit orders with OHLC because we never know whether the market has
/// gapped past our fill price. We have to make the assumption of a fluid, high volume market.
///
/// Stop limit orders we also can't be sure of the order of the H - L values for the limit fill. The assumption
/// was made the limit fill will be done with closing price of the bar after the stop has been triggered..
/// </remarks>
public virtual OrderEvent StopLimitFill(Security asset, StopLimitOrder order)
{
//Default order event to return.
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, 0);
//If its cancelled don't need anymore checks:
if (order.Status == OrderStatus.Canceled) return fill;
// make sure the exchange is open before filling -- allow pre/post market fills to occur
if (!IsExchangeOpen(asset, true)) return fill;
//Get the range of prices in the last bar:
var prices = GetPrices(asset, order.Direction);
var pricesEndTime = prices.EndTime.ConvertToUtc(asset.Exchange.TimeZone);
// do not fill on stale data
if (pricesEndTime <= order.Time) return fill;
//Check if the Stop Order was filled: opposite to a limit order
switch (order.Direction)
{
case OrderDirection.Buy:
//-> 1.2 Buy Stop: If Price Above Setpoint, Buy:
if (prices.High > order.StopPrice || order.StopTriggered)
{
order.StopTriggered = true;
// Fill the limit order, using closing price of bar:
// Note > Can't use minimum price, because no way to be sure minimum wasn't before the stop triggered.
if (asset.Price < order.LimitPrice)
{
fill.Status = OrderStatus.Filled;
fill.FillPrice = order.LimitPrice;
// assume the order completely filled
fill.FillQuantity = order.Quantity;
}
}
break;
case OrderDirection.Sell:
//-> 1.1 Sell Stop: If Price below setpoint, Sell:
if (prices.Low < order.StopPrice || order.StopTriggered)
{
order.StopTriggered = true;
// Fill the limit order, using minimum price of the bar
// Note > Can't use minimum price, because no way to be sure minimum wasn't before the stop triggered.
if (asset.Price > order.LimitPrice)
{
fill.Status = OrderStatus.Filled;
fill.FillPrice = order.LimitPrice; // Fill at limit price not asset price.
// assume the order completely filled
fill.FillQuantity = order.Quantity;
}
}
break;
}
return fill;
}
/// <summary>
/// Default limit order fill model in the base security class.
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
/// <seealso cref="StopMarketFill(Security, StopMarketOrder)"/>
/// <seealso cref="MarketFill(Security, MarketOrder)"/>
public virtual OrderEvent LimitFill(Security asset, LimitOrder order)
{
//Initialise;
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, 0);
//If its cancelled don't need anymore checks:
if (order.Status == OrderStatus.Canceled) return fill;
// make sure the exchange is open before filling -- allow pre/post market fills to occur
if (!IsExchangeOpen(asset, true)) return fill;
//Get the range of prices in the last bar:
var prices = GetPrices(asset, order.Direction);
var pricesEndTime = prices.EndTime.ConvertToUtc(asset.Exchange.TimeZone);
// do not fill on stale data
if (pricesEndTime <= order.Time) return fill;
//-> Valid Live/Model Order:
switch (order.Direction)
{
case OrderDirection.Buy:
//Buy limit seeks lowest price
if (prices.Low < order.LimitPrice)
{
//Set order fill:
fill.Status = OrderStatus.Filled;
// fill at the worse price this bar or the limit price, this allows far out of the money limits
// to be executed properly
fill.FillPrice = Math.Min(prices.High, order.LimitPrice);
// assume the order completely filled
fill.FillQuantity = order.Quantity;
}
break;
case OrderDirection.Sell:
//Sell limit seeks highest price possible
if (prices.High > order.LimitPrice)
{
fill.Status = OrderStatus.Filled;
// fill at the worse price this bar or the limit price, this allows far out of the money limits
// to be executed properly
fill.FillPrice = Math.Max(prices.Low, order.LimitPrice);
// assume the order completely filled
fill.FillQuantity = order.Quantity;
}
break;
}
return fill;
}
/// <summary>
/// Market on Open Fill Model. Return an order event with the fill details
/// </summary>
/// <param name="asset">Asset we're trading with this order</param>
/// <param name="order">Order to be filled</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
public OrderEvent MarketOnOpenFill(Security asset, MarketOnOpenOrder order)
{
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, 0);
if (order.Status == OrderStatus.Canceled) return fill;
// MOO should never fill on the same bar or on stale data
// Imagine the case where we have a thinly traded equity, ASUR, and another liquid
// equity, say SPY, SPY gets data every minute but ASUR, if not on fill forward, maybe
// have large gaps, in which case the currentBar.EndTime will be in the past
// ASUR | | | [order] | | | | | | |
// SPY | | | | | | | | | | | | | | | | | | | |
var currentBar = asset.GetLastData();
var localOrderTime = order.Time.ConvertFromUtc(asset.Exchange.TimeZone);
if (currentBar == null || localOrderTime >= currentBar.EndTime) return fill;
// if the MOO was submitted during market the previous day, wait for a day to turn over
if (asset.Exchange.DateTimeIsOpen(localOrderTime) && localOrderTime.Date == asset.LocalTime.Date)
{
return fill;
}
// wait until market open
// make sure the exchange is open/normal market hours before filling
if (!IsExchangeOpen(asset, false)) return fill;
fill.FillPrice = GetPrices(asset, order.Direction).Open;
fill.Status = OrderStatus.Filled;
//Calculate the model slippage: e.g. 0.01c
var slip = asset.SlippageModel.GetSlippageApproximation(asset, order);
//Apply slippage
switch (order.Direction)
{
case OrderDirection.Buy:
fill.FillPrice += slip;
// assume the order completely filled
fill.FillQuantity = order.Quantity;
break;
case OrderDirection.Sell:
fill.FillPrice -= slip;
// assume the order completely filled
fill.FillQuantity = order.Quantity;
break;
}
return fill;
}
/// <summary>
/// Market on Close Fill Model. Return an order event with the fill details
/// </summary>
/// <param name="asset">Asset we're trading with this order</param>
/// <param name="order">Order to be filled</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
public OrderEvent MarketOnCloseFill(Security asset, MarketOnCloseOrder order)
{
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, 0);
if (order.Status == OrderStatus.Canceled) return fill;
var localOrderTime = order.Time.ConvertFromUtc(asset.Exchange.TimeZone);
var nextMarketClose = asset.Exchange.Hours.GetNextMarketClose(localOrderTime, false);
// wait until market closes after the order time
if (asset.LocalTime < nextMarketClose)
{
return fill;
}
// make sure the exchange is open/normal market hours before filling
if (!IsExchangeOpen(asset, false)) return fill;
fill.FillPrice = GetPrices(asset, order.Direction).Close;
fill.Status = OrderStatus.Filled;
//Calculate the model slippage: e.g. 0.01c
var slip = asset.SlippageModel.GetSlippageApproximation(asset, order);
//Apply slippage
switch (order.Direction)
{
case OrderDirection.Buy:
fill.FillPrice += slip;
// assume the order completely filled
fill.FillQuantity = order.Quantity;
break;
case OrderDirection.Sell:
fill.FillPrice -= slip;
// assume the order completely filled
fill.FillQuantity = order.Quantity;
break;
}
return fill;
}
/// <summary>
/// Get the minimum and maximum price for this security in the last bar:
/// </summary>
/// <param name="asset">Security asset we're checking</param>
/// <param name="direction">The order direction, decides whether to pick bid or ask</param>
protected virtual Prices GetPrices(Security asset, OrderDirection direction)
{
var low = asset.Low;
var high = asset.High;
var open = asset.Open;
var close = asset.Close;
var current = asset.Price;
var endTime = asset.Cache.GetData()?.EndTime ?? DateTime.MinValue;
if (direction == OrderDirection.Hold)
{
return new Prices(endTime, current, open, high, low, close);
}
// Only fill with data types we are subscribed to
var subscriptionTypes = asset.Subscriptions.Select(x => x.Type).ToList();
// Tick
var tick = asset.Cache.GetData<Tick>();
if (subscriptionTypes.Contains(typeof(Tick)) && tick != null)
{
var price = direction == OrderDirection.Sell ? tick.BidPrice : tick.AskPrice;
if (price != 0m)
{
return new Prices(tick.EndTime, price, 0, 0, 0, 0);
}
// If the ask/bid spreads are not available for ticks, try the price
price = tick.Price;
if (price != 0m)
{
return new Prices(tick.EndTime, price, 0, 0, 0, 0);
}
}
// Quote
var quoteBar = asset.Cache.GetData<QuoteBar>();
if (subscriptionTypes.Contains(typeof(QuoteBar)) && quoteBar != null)
{
var bar = direction == OrderDirection.Sell ? quoteBar.Bid : quoteBar.Ask;
if (bar != null)
{
return new Prices(quoteBar.EndTime, bar);
}
}
// Trade
var tradeBar = asset.Cache.GetData<TradeBar>();
if (subscriptionTypes.Contains(typeof(TradeBar)) && tradeBar != null)
{
return new Prices(tradeBar);
}
return new Prices(endTime, current, open, high, low, close);
}
/// <summary>
/// Determines if the exchange is open using the current time of the asset
/// </summary>
private static bool IsExchangeOpen(Security asset, bool allowExtendedMarketHoursFills)
{
if (!asset.Exchange.DateTimeIsOpen(asset.LocalTime))
{
// if we're not open at the current time exactly, check the bar size, this handle large sized bars (hours/days)
var currentBar = asset.GetLastData();
var isExtendedMarketHours = allowExtendedMarketHoursFills && asset.IsExtendedMarketHours;
if (asset.LocalTime.Date != currentBar.EndTime.Date || !asset.Exchange.IsOpenDuringBar(currentBar.Time, currentBar.EndTime, isExtendedMarketHours))
{
return false;
}
}
return true;
}
public class Prices
{
public readonly DateTime EndTime;
public readonly decimal Current;
public readonly decimal Open;
public readonly decimal High;
public readonly decimal Low;
public readonly decimal Close;
public Prices(IBaseDataBar bar)
: this(bar.EndTime, bar.Close, bar.Open, bar.High, bar.Low, bar.Close)
{
}
public Prices(DateTime endTime, IBar bar)
: this(endTime, bar.Close, bar.Open, bar.High, bar.Low, bar.Close)
{
}
public Prices(DateTime endTime, decimal current, decimal open, decimal high, decimal low, decimal close)
{
EndTime = endTime;
Current = current;
Open = open == 0 ? current : open;
High = high == 0 ? current : high;
Low = low == 0 ? current : low;
Close = close == 0 ? current : close;
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing Subscriptions.
/// </summary>
internal partial class SubscriptionsOperations : IServiceOperations<ApiManagementClient>, ISubscriptionsOperations
{
/// <summary>
/// Initializes a new instance of the SubscriptionsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SubscriptionsOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates new product subscription.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='sid'>
/// Required. Identifier of the subscription.
/// </param>
/// <param name='parameters'>
/// Required. Create parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CreateAsync(string resourceGroupName, string serviceName, string sid, SubscriptionCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (sid == null)
{
throw new ArgumentNullException("sid");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.PrimaryKey != null && parameters.PrimaryKey.Length > 256)
{
throw new ArgumentOutOfRangeException("parameters.PrimaryKey");
}
if (parameters.ProductIdPath == null)
{
throw new ArgumentNullException("parameters.ProductIdPath");
}
if (parameters.SecondaryKey != null && parameters.SecondaryKey.Length > 256)
{
throw new ArgumentOutOfRangeException("parameters.SecondaryKey");
}
if (parameters.UserIdPath == null)
{
throw new ArgumentNullException("parameters.UserIdPath");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("sid", sid);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/subscriptions/";
url = url + Uri.EscapeDataString(sid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject subscriptionCreateParametersValue = new JObject();
requestDoc = subscriptionCreateParametersValue;
subscriptionCreateParametersValue["userId"] = parameters.UserIdPath;
subscriptionCreateParametersValue["productId"] = parameters.ProductIdPath;
subscriptionCreateParametersValue["name"] = parameters.Name;
if (parameters.PrimaryKey != null)
{
subscriptionCreateParametersValue["primaryKey"] = parameters.PrimaryKey;
}
if (parameters.SecondaryKey != null)
{
subscriptionCreateParametersValue["secondaryKey"] = parameters.SecondaryKey;
}
if (parameters.State != null)
{
subscriptionCreateParametersValue["state"] = parameters.State.Value.ToString();
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes specific subscription of the Api Management service
/// instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='sid'>
/// Required. Identifier of the subscription.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string sid, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (sid == null)
{
throw new ArgumentNullException("sid");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("sid", sid);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/subscriptions/";
url = url + Uri.EscapeDataString(sid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets specific API of the Api Management service instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='sid'>
/// Required. Identifier of the subscription.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Get Subscription operation response details.
/// </returns>
public async Task<SubscriptionGetResponse> GetAsync(string resourceGroupName, string serviceName, string sid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (sid == null)
{
throw new ArgumentNullException("sid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("sid", sid);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/subscriptions/";
url = url + Uri.EscapeDataString(sid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
SubscriptionGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new SubscriptionGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
SubscriptionContract valueInstance = new SubscriptionContract();
result.Value = valueInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
valueInstance.IdPath = idInstance;
}
JToken userIdValue = responseDoc["userId"];
if (userIdValue != null && userIdValue.Type != JTokenType.Null)
{
string userIdInstance = ((string)userIdValue);
valueInstance.UserIdPath = userIdInstance;
}
JToken productIdValue = responseDoc["productId"];
if (productIdValue != null && productIdValue.Type != JTokenType.Null)
{
string productIdInstance = ((string)productIdValue);
valueInstance.ProductIdPath = productIdInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
valueInstance.Name = nameInstance;
}
JToken stateValue = responseDoc["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
SubscriptionStateContract stateInstance = ((SubscriptionStateContract)Enum.Parse(typeof(SubscriptionStateContract), ((string)stateValue), true));
valueInstance.State = stateInstance;
}
JToken createdDateValue = responseDoc["createdDate"];
if (createdDateValue != null && createdDateValue.Type != JTokenType.Null)
{
DateTime createdDateInstance = ((DateTime)createdDateValue);
valueInstance.CreatedDate = createdDateInstance;
}
JToken startDateValue = responseDoc["startDate"];
if (startDateValue != null && startDateValue.Type != JTokenType.Null)
{
DateTime startDateInstance = ((DateTime)startDateValue);
valueInstance.StartDate = startDateInstance;
}
JToken expirationDateValue = responseDoc["expirationDate"];
if (expirationDateValue != null && expirationDateValue.Type != JTokenType.Null)
{
DateTime expirationDateInstance = ((DateTime)expirationDateValue);
valueInstance.ExpirationDate = expirationDateInstance;
}
JToken endDateValue = responseDoc["endDate"];
if (endDateValue != null && endDateValue.Type != JTokenType.Null)
{
DateTime endDateInstance = ((DateTime)endDateValue);
valueInstance.EndDate = endDateInstance;
}
JToken notificationDateValue = responseDoc["notificationDate"];
if (notificationDateValue != null && notificationDateValue.Type != JTokenType.Null)
{
DateTime notificationDateInstance = ((DateTime)notificationDateValue);
valueInstance.NotificationDate = notificationDateInstance;
}
JToken primaryKeyValue = responseDoc["primaryKey"];
if (primaryKeyValue != null && primaryKeyValue.Type != JTokenType.Null)
{
string primaryKeyInstance = ((string)primaryKeyValue);
valueInstance.PrimaryKey = primaryKeyInstance;
}
JToken secondaryKeyValue = responseDoc["secondaryKey"];
if (secondaryKeyValue != null && secondaryKeyValue.Type != JTokenType.Null)
{
string secondaryKeyInstance = ((string)secondaryKeyValue);
valueInstance.SecondaryKey = secondaryKeyInstance;
}
JToken stateCommentValue = responseDoc["stateComment"];
if (stateCommentValue != null && stateCommentValue.Type != JTokenType.Null)
{
string stateCommentInstance = ((string)stateCommentValue);
valueInstance.StateComment = stateCommentInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List all subscriptions of the Api Management service instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Subscriptions operation response details.
/// </returns>
public async Task<SubscriptionListResponse> ListAsync(string resourceGroupName, string serviceName, QueryParameters query, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("query", query);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/subscriptions";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
List<string> odataFilter = new List<string>();
if (query != null && query.Filter != null)
{
odataFilter.Add(Uri.EscapeDataString(query.Filter));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (query != null && query.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
}
if (query != null && query.Skip != null)
{
queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
SubscriptionListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new SubscriptionListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
SubscriptionPaged resultInstance = new SubscriptionPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
SubscriptionContract subscriptionContractInstance = new SubscriptionContract();
resultInstance.Values.Add(subscriptionContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
subscriptionContractInstance.IdPath = idInstance;
}
JToken userIdValue = valueValue["userId"];
if (userIdValue != null && userIdValue.Type != JTokenType.Null)
{
string userIdInstance = ((string)userIdValue);
subscriptionContractInstance.UserIdPath = userIdInstance;
}
JToken productIdValue = valueValue["productId"];
if (productIdValue != null && productIdValue.Type != JTokenType.Null)
{
string productIdInstance = ((string)productIdValue);
subscriptionContractInstance.ProductIdPath = productIdInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
subscriptionContractInstance.Name = nameInstance;
}
JToken stateValue = valueValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
SubscriptionStateContract stateInstance = ((SubscriptionStateContract)Enum.Parse(typeof(SubscriptionStateContract), ((string)stateValue), true));
subscriptionContractInstance.State = stateInstance;
}
JToken createdDateValue = valueValue["createdDate"];
if (createdDateValue != null && createdDateValue.Type != JTokenType.Null)
{
DateTime createdDateInstance = ((DateTime)createdDateValue);
subscriptionContractInstance.CreatedDate = createdDateInstance;
}
JToken startDateValue = valueValue["startDate"];
if (startDateValue != null && startDateValue.Type != JTokenType.Null)
{
DateTime startDateInstance = ((DateTime)startDateValue);
subscriptionContractInstance.StartDate = startDateInstance;
}
JToken expirationDateValue = valueValue["expirationDate"];
if (expirationDateValue != null && expirationDateValue.Type != JTokenType.Null)
{
DateTime expirationDateInstance = ((DateTime)expirationDateValue);
subscriptionContractInstance.ExpirationDate = expirationDateInstance;
}
JToken endDateValue = valueValue["endDate"];
if (endDateValue != null && endDateValue.Type != JTokenType.Null)
{
DateTime endDateInstance = ((DateTime)endDateValue);
subscriptionContractInstance.EndDate = endDateInstance;
}
JToken notificationDateValue = valueValue["notificationDate"];
if (notificationDateValue != null && notificationDateValue.Type != JTokenType.Null)
{
DateTime notificationDateInstance = ((DateTime)notificationDateValue);
subscriptionContractInstance.NotificationDate = notificationDateInstance;
}
JToken primaryKeyValue = valueValue["primaryKey"];
if (primaryKeyValue != null && primaryKeyValue.Type != JTokenType.Null)
{
string primaryKeyInstance = ((string)primaryKeyValue);
subscriptionContractInstance.PrimaryKey = primaryKeyInstance;
}
JToken secondaryKeyValue = valueValue["secondaryKey"];
if (secondaryKeyValue != null && secondaryKeyValue.Type != JTokenType.Null)
{
string secondaryKeyInstance = ((string)secondaryKeyValue);
subscriptionContractInstance.SecondaryKey = secondaryKeyInstance;
}
JToken stateCommentValue = valueValue["stateComment"];
if (stateCommentValue != null && stateCommentValue.Type != JTokenType.Null)
{
string stateCommentInstance = ((string)stateCommentValue);
subscriptionContractInstance.StateComment = stateCommentInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List all subscriptions of the Api Management service instance.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Subscriptions operation response details.
/// </returns>
public async Task<SubscriptionListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
SubscriptionListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new SubscriptionListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
SubscriptionPaged resultInstance = new SubscriptionPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
SubscriptionContract subscriptionContractInstance = new SubscriptionContract();
resultInstance.Values.Add(subscriptionContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
subscriptionContractInstance.IdPath = idInstance;
}
JToken userIdValue = valueValue["userId"];
if (userIdValue != null && userIdValue.Type != JTokenType.Null)
{
string userIdInstance = ((string)userIdValue);
subscriptionContractInstance.UserIdPath = userIdInstance;
}
JToken productIdValue = valueValue["productId"];
if (productIdValue != null && productIdValue.Type != JTokenType.Null)
{
string productIdInstance = ((string)productIdValue);
subscriptionContractInstance.ProductIdPath = productIdInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
subscriptionContractInstance.Name = nameInstance;
}
JToken stateValue = valueValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
SubscriptionStateContract stateInstance = ((SubscriptionStateContract)Enum.Parse(typeof(SubscriptionStateContract), ((string)stateValue), true));
subscriptionContractInstance.State = stateInstance;
}
JToken createdDateValue = valueValue["createdDate"];
if (createdDateValue != null && createdDateValue.Type != JTokenType.Null)
{
DateTime createdDateInstance = ((DateTime)createdDateValue);
subscriptionContractInstance.CreatedDate = createdDateInstance;
}
JToken startDateValue = valueValue["startDate"];
if (startDateValue != null && startDateValue.Type != JTokenType.Null)
{
DateTime startDateInstance = ((DateTime)startDateValue);
subscriptionContractInstance.StartDate = startDateInstance;
}
JToken expirationDateValue = valueValue["expirationDate"];
if (expirationDateValue != null && expirationDateValue.Type != JTokenType.Null)
{
DateTime expirationDateInstance = ((DateTime)expirationDateValue);
subscriptionContractInstance.ExpirationDate = expirationDateInstance;
}
JToken endDateValue = valueValue["endDate"];
if (endDateValue != null && endDateValue.Type != JTokenType.Null)
{
DateTime endDateInstance = ((DateTime)endDateValue);
subscriptionContractInstance.EndDate = endDateInstance;
}
JToken notificationDateValue = valueValue["notificationDate"];
if (notificationDateValue != null && notificationDateValue.Type != JTokenType.Null)
{
DateTime notificationDateInstance = ((DateTime)notificationDateValue);
subscriptionContractInstance.NotificationDate = notificationDateInstance;
}
JToken primaryKeyValue = valueValue["primaryKey"];
if (primaryKeyValue != null && primaryKeyValue.Type != JTokenType.Null)
{
string primaryKeyInstance = ((string)primaryKeyValue);
subscriptionContractInstance.PrimaryKey = primaryKeyInstance;
}
JToken secondaryKeyValue = valueValue["secondaryKey"];
if (secondaryKeyValue != null && secondaryKeyValue.Type != JTokenType.Null)
{
string secondaryKeyInstance = ((string)secondaryKeyValue);
subscriptionContractInstance.SecondaryKey = secondaryKeyInstance;
}
JToken stateCommentValue = valueValue["stateComment"];
if (stateCommentValue != null && stateCommentValue.Type != JTokenType.Null)
{
string stateCommentInstance = ((string)stateCommentValue);
subscriptionContractInstance.StateComment = stateCommentInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Regenerates primary key of existing subscription of the Api
/// Management service instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='sid'>
/// Required. Identifier of the subscription.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> RegeneratePrimaryKeyAsync(string resourceGroupName, string serviceName, string sid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (sid == null)
{
throw new ArgumentNullException("sid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("sid", sid);
TracingAdapter.Enter(invocationId, this, "RegeneratePrimaryKeyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/subscriptions/";
url = url + Uri.EscapeDataString(sid);
url = url + "/regeneratePrimaryKey";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Regenerates secindary key of existing subscription of the Api
/// Management service instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='sid'>
/// Required. Identifier of the subscription.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> RegenerateSecondaryKeyAsync(string resourceGroupName, string serviceName, string sid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (sid == null)
{
throw new ArgumentNullException("sid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("sid", sid);
TracingAdapter.Enter(invocationId, this, "RegenerateSecondaryKeyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/subscriptions/";
url = url + Uri.EscapeDataString(sid);
url = url + "/regenerateSecondaryKey";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates specific product subscription.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='sid'>
/// Required. Identifier of the subscription.
/// </param>
/// <param name='parameters'>
/// Required. Update parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> UpdateAsync(string resourceGroupName, string serviceName, string sid, SubscriptionUpdateParameters parameters, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (sid == null)
{
throw new ArgumentNullException("sid");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.PrimaryKey != null && parameters.PrimaryKey.Length > 256)
{
throw new ArgumentOutOfRangeException("parameters.PrimaryKey");
}
if (parameters.SecondaryKey != null && parameters.SecondaryKey.Length > 256)
{
throw new ArgumentOutOfRangeException("parameters.SecondaryKey");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("sid", sid);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/subscriptions/";
url = url + Uri.EscapeDataString(sid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject subscriptionUpdateParametersValue = new JObject();
requestDoc = subscriptionUpdateParametersValue;
if (parameters.UserIdPath != null)
{
subscriptionUpdateParametersValue["userId"] = parameters.UserIdPath;
}
if (parameters.ProductIdPath != null)
{
subscriptionUpdateParametersValue["productId"] = parameters.ProductIdPath;
}
if (parameters.ExpiresOn != null)
{
subscriptionUpdateParametersValue["expirationDate"] = parameters.ExpiresOn.Value;
}
if (parameters.Name != null)
{
subscriptionUpdateParametersValue["name"] = parameters.Name;
}
if (parameters.PrimaryKey != null)
{
subscriptionUpdateParametersValue["primaryKey"] = parameters.PrimaryKey;
}
if (parameters.SecondaryKey != null)
{
subscriptionUpdateParametersValue["secondaryKey"] = parameters.SecondaryKey;
}
if (parameters.State != null)
{
subscriptionUpdateParametersValue["state"] = parameters.State.Value.ToString();
}
if (parameters.StateComment != null)
{
subscriptionUpdateParametersValue["stateComment"] = parameters.StateComment;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
#pragma warning disable SA1633 // File should have header - This is an imported file,
// original header with license shall remain the same
using UtfUnknown.Core.Models;
namespace UtfUnknown.Core.Models.MultiByte.Chinese;
internal class BIG5SMModel : StateMachineModel
{
private static readonly int[] BIG5_cls =
{
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 00 - 07
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
0,
0), // 08 - 0f
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 10 - 17
BitPackage.Pack4bits(
1,
1,
1,
0,
1,
1,
1,
1), // 18 - 1f
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 20 - 27
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 28 - 2f
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 30 - 37
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 38 - 3f
BitPackage.Pack4bits(
2,
2,
2,
2,
2,
2,
2,
2), // 40 - 47
BitPackage.Pack4bits(
2,
2,
2,
2,
2,
2,
2,
2), // 48 - 4f
BitPackage.Pack4bits(
2,
2,
2,
2,
2,
2,
2,
2), // 50 - 57
BitPackage.Pack4bits(
2,
2,
2,
2,
2,
2,
2,
2), // 58 - 5f
BitPackage.Pack4bits(
2,
2,
2,
2,
2,
2,
2,
2), // 60 - 67
BitPackage.Pack4bits(
2,
2,
2,
2,
2,
2,
2,
2), // 68 - 6f
BitPackage.Pack4bits(
2,
2,
2,
2,
2,
2,
2,
2), // 70 - 77
BitPackage.Pack4bits(
2,
2,
2,
2,
2,
2,
2,
1), // 78 - 7f
BitPackage.Pack4bits(
4,
4,
4,
4,
4,
4,
4,
4), // 80 - 87
BitPackage.Pack4bits(
4,
4,
4,
4,
4,
4,
4,
4), // 88 - 8f
BitPackage.Pack4bits(
4,
4,
4,
4,
4,
4,
4,
4), // 90 - 97
BitPackage.Pack4bits(
4,
4,
4,
4,
4,
4,
4,
4), // 98 - 9f
BitPackage.Pack4bits(
4,
3,
3,
3,
3,
3,
3,
3), // a0 - a7
BitPackage.Pack4bits(
3,
3,
3,
3,
3,
3,
3,
3), // a8 - af
BitPackage.Pack4bits(
3,
3,
3,
3,
3,
3,
3,
3), // b0 - b7
BitPackage.Pack4bits(
3,
3,
3,
3,
3,
3,
3,
3), // b8 - bf
BitPackage.Pack4bits(
3,
3,
3,
3,
3,
3,
3,
3), // c0 - c7
BitPackage.Pack4bits(
3,
3,
3,
3,
3,
3,
3,
3), // c8 - cf
BitPackage.Pack4bits(
3,
3,
3,
3,
3,
3,
3,
3), // d0 - d7
BitPackage.Pack4bits(
3,
3,
3,
3,
3,
3,
3,
3), // d8 - df
BitPackage.Pack4bits(
3,
3,
3,
3,
3,
3,
3,
3), // e0 - e7
BitPackage.Pack4bits(
3,
3,
3,
3,
3,
3,
3,
3), // e8 - ef
BitPackage.Pack4bits(
3,
3,
3,
3,
3,
3,
3,
3), // f0 - f7
BitPackage.Pack4bits(
3,
3,
3,
3,
3,
3,
3,
0) // f8 - ff
};
private static readonly int[] BIG5_st =
{
BitPackage.Pack4bits(
ERROR,
START,
START,
3,
ERROR,
ERROR,
ERROR,
ERROR), //00-07
BitPackage.Pack4bits(
ERROR,
ERROR,
ITSME,
ITSME,
ITSME,
ITSME,
ITSME,
ERROR), //08-0f
BitPackage.Pack4bits(
ERROR,
START,
START,
START,
START,
START,
START,
START) //10-17
};
private static readonly int[] BIG5CharLenTable =
{
0,
1,
1,
2,
0
};
public BIG5SMModel()
: base(
new BitPackage(
BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS,
BIG5_cls),
5,
new BitPackage(
BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS,
BIG5_st),
BIG5CharLenTable,
CodepageName.BIG5) { }
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.ReferenceHighlighting
{
internal abstract class AbstractDocumentHighlightsService : IDocumentHighlightsService
{
public async Task<IEnumerable<DocumentHighlights>> GetDocumentHighlightsAsync(Document document, int position, IEnumerable<Document> documentsToSearch, CancellationToken cancellationToken)
{
// use speculative semantic model to see whether we are on a symbol we can do HR
var span = new TextSpan(position, 0);
var solution = document.Project.Solution;
var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
var symbol = await SymbolFinder.FindSymbolAtPositionAsync(semanticModel, position, solution.Workspace, cancellationToken).ConfigureAwait(false);
if (symbol == null)
{
return SpecializedCollections.EmptyEnumerable<DocumentHighlights>();
}
symbol = await GetSymbolToSearchAsync(document, position, semanticModel, symbol, cancellationToken).ConfigureAwait(false);
if (symbol == null)
{
return SpecializedCollections.EmptyEnumerable<DocumentHighlights>();
}
// Get unique tags for referenced symbols
return await GetTagsForReferencedSymbolAsync(symbol, ImmutableHashSet.CreateRange(documentsToSearch), solution, cancellationToken).ConfigureAwait(false);
}
private async Task<ISymbol> GetSymbolToSearchAsync(Document document, int position, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken)
{
// see whether we can use the symbol as it is
var currentSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (currentSemanticModel == semanticModel)
{
return symbol;
}
// get symbols from current document again
return await SymbolFinder.FindSymbolAtPositionAsync(currentSemanticModel, position, document.Project.Solution.Workspace, cancellationToken).ConfigureAwait(false);
}
private async Task<IEnumerable<DocumentHighlights>> GetTagsForReferencedSymbolAsync(
ISymbol symbol,
IImmutableSet<Document> documentsToSearch,
Solution solution,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(symbol);
if (ShouldConsiderSymbol(symbol))
{
var references = await SymbolFinder.FindReferencesAsync(
symbol, solution, progress: null, documents: documentsToSearch, cancellationToken: cancellationToken).ConfigureAwait(false);
return await FilterAndCreateSpansAsync(references, solution, documentsToSearch, symbol, cancellationToken).ConfigureAwait(false);
}
return SpecializedCollections.EmptyEnumerable<DocumentHighlights>();
}
private bool ShouldConsiderSymbol(ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Method:
switch (((IMethodSymbol)symbol).MethodKind)
{
case MethodKind.AnonymousFunction:
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
case MethodKind.EventAdd:
case MethodKind.EventRaise:
case MethodKind.EventRemove:
return false;
default:
return true;
}
default:
return true;
}
}
private async Task<IEnumerable<DocumentHighlights>> FilterAndCreateSpansAsync(
IEnumerable<ReferencedSymbol> references, Solution solution, IImmutableSet<Document> documentsToSearch, ISymbol symbol, CancellationToken cancellationToken)
{
references = references.FilterToItemsToShow();
references = references.FilterNonMatchingMethodNames(solution, symbol);
references = references.FilterToAliasMatches(symbol as IAliasSymbol);
if (symbol.IsConstructor())
{
references = references.Where(r => r.Definition.OriginalDefinition.Equals(symbol.OriginalDefinition));
}
var additionalReferences = new List<Location>();
foreach (var document in documentsToSearch)
{
additionalReferences.AddRange(await GetAdditionalReferencesAsync(document, symbol, cancellationToken).ConfigureAwait(false));
}
return await CreateSpansAsync(solution, symbol, references, additionalReferences, documentsToSearch, cancellationToken).ConfigureAwait(false);
}
private Task<IEnumerable<Location>> GetAdditionalReferencesAsync(
Document document, ISymbol symbol, CancellationToken cancellationToken)
{
var additionalReferenceProvider = document.Project.LanguageServices.GetService<IReferenceHighlightingAdditionalReferenceProvider>();
if (additionalReferenceProvider != null)
{
return additionalReferenceProvider.GetAdditionalReferencesAsync(document, symbol, cancellationToken);
}
return Task.FromResult(SpecializedCollections.EmptyEnumerable<Location>());
}
private async Task<IEnumerable<DocumentHighlights>> CreateSpansAsync(
Solution solution,
ISymbol symbol,
IEnumerable<ReferencedSymbol> references,
IEnumerable<Location> additionalReferences,
IImmutableSet<Document> documentToSearch,
CancellationToken cancellationToken)
{
var spanSet = new HashSet<ValueTuple<Document, TextSpan>>();
var tagMap = new MultiDictionary<Document, HighlightSpan>();
bool addAllDefinitions = true;
// Add definitions
// Filter out definitions that cannot be highlighted. e.g: alias symbols defined via project property pages.
if (symbol.Kind == SymbolKind.Alias &&
symbol.Locations.Length > 0)
{
addAllDefinitions = false;
if (symbol.Locations.First().IsInSource)
{
// For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition.
await AddLocationSpan(symbol.Locations.First(), solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false);
}
}
// Add references and definitions
foreach (var reference in references)
{
if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition))
{
foreach (var location in reference.Definition.Locations)
{
if (location.IsInSource)
{
var document = solution.GetDocument(location.SourceTree);
// GetDocument will return null for locations in #load'ed trees.
// TODO: Remove this check and add logic to fetch the #load'ed tree's
// Document once https://github.com/dotnet/roslyn/issues/5260 is fixed.
if (document == null)
{
Debug.Assert(solution.Workspace.Kind == "Interactive");
continue;
}
if (documentToSearch.Contains(document))
{
await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false);
}
}
}
}
foreach (var referenceLocation in reference.Locations)
{
var referenceKind = referenceLocation.IsWrittenTo ? HighlightSpanKind.WrittenReference : HighlightSpanKind.Reference;
await AddLocationSpan(referenceLocation.Location, solution, spanSet, tagMap, referenceKind, cancellationToken).ConfigureAwait(false);
}
}
// Add additional references
foreach (var location in additionalReferences)
{
await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Reference, cancellationToken).ConfigureAwait(false);
}
var list = new List<DocumentHighlights>(tagMap.Count);
foreach (var kvp in tagMap)
{
var spans = new List<HighlightSpan>(kvp.Value.Count);
foreach (var span in kvp.Value)
{
spans.Add(span);
}
list.Add(new DocumentHighlights(kvp.Key, spans));
}
return list;
}
private static bool ShouldIncludeDefinition(ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Namespace:
return false;
case SymbolKind.NamedType:
return !((INamedTypeSymbol)symbol).IsScriptClass;
case SymbolKind.Parameter:
// If it's an indexer parameter, we will have also cascaded to the accessor
// one that actually receives the references
var containingProperty = symbol.ContainingSymbol as IPropertySymbol;
if (containingProperty != null && containingProperty.IsIndexer)
{
return false;
}
break;
}
return true;
}
private async Task AddLocationSpan(Location location, Solution solution, HashSet<ValueTuple<Document, TextSpan>> spanSet, MultiDictionary<Document, HighlightSpan> tagList, HighlightSpanKind kind, CancellationToken cancellationToken)
{
var span = await GetLocationSpanAsync(solution, location, cancellationToken).ConfigureAwait(false);
if (span != null && !spanSet.Contains(span.Value))
{
spanSet.Add(span.Value);
tagList.Add(span.Value.Item1, new HighlightSpan(span.Value.Item2, kind));
}
}
private async Task<ValueTuple<Document, TextSpan>?> GetLocationSpanAsync(Solution solution, Location location, CancellationToken cancellationToken)
{
try
{
if (location != null && location.IsInSource)
{
var tree = location.SourceTree;
var document = solution.GetDocument(tree);
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
if (syntaxFacts != null)
{
// Specify findInsideTrivia: true to ensure that we search within XML doc comments.
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(location.SourceSpan.Start, findInsideTrivia: true);
return syntaxFacts.IsGenericName(token.Parent) || syntaxFacts.IsIndexerMemberCRef(token.Parent)
? ValueTuple.Create(document, token.Span)
: ValueTuple.Create(document, location.SourceSpan);
}
}
}
catch (NullReferenceException e) when (FatalError.ReportWithoutCrash(e))
{
// We currently are seeing a strange null references crash in this code. We have
// a strong belief that this is recoverable, but we'd like to know why it is
// happening. This exception filter allows us to report the issue and continue
// without damaging the user experience. Once we get more crash reports, we
// can figure out the root cause and address appropriately. This is preferable
// to just using conditionl access operators to be resilient (as we won't actually
// know why this is happening).
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using System.Collections.Generic;
using System;
using Xunit;
namespace System.Threading.Channels.Tests
{
public class StressTests
{
public static IEnumerable<object[]> TestData()
{
foreach (var readDelegate in new Func<ChannelReader<int>, Task<bool>>[] { ReadSynchronous, ReadAsynchronous, ReadSyncAndAsync} )
foreach (var writeDelegate in new Func<ChannelWriter<int>, int, Task>[] { WriteSynchronous, WriteAsynchronous, WriteSyncAndAsync} )
foreach (bool singleReader in new [] {false, true})
foreach (bool singleWriter in new [] {false, true})
foreach (bool allowSynchronousContinuations in new [] {false, true})
{
Func<ChannelOptions, Channel<int>> unbounded = o => Channel.CreateUnbounded<int>((UnboundedChannelOptions)o);
yield return new object[] { unbounded, new UnboundedChannelOptions
{
SingleReader = singleReader,
SingleWriter = singleWriter,
AllowSynchronousContinuations = allowSynchronousContinuations
}, readDelegate, writeDelegate
};
}
foreach (var readDelegate in new Func<ChannelReader<int>, Task<bool>>[] { ReadSynchronous, ReadAsynchronous, ReadSyncAndAsync} )
foreach (var writeDelegate in new Func<ChannelWriter<int>, int, Task>[] { WriteSynchronous, WriteAsynchronous, WriteSyncAndAsync} )
foreach (BoundedChannelFullMode bco in Enum.GetValues(typeof(BoundedChannelFullMode)))
foreach (int capacity in new [] { 1, 1000 })
foreach (bool singleReader in new [] {false, true})
foreach (bool singleWriter in new [] {false, true})
foreach (bool allowSynchronousContinuations in new [] {false, true})
{
Func<ChannelOptions, Channel<int>> bounded = o => Channel.CreateBounded<int>((BoundedChannelOptions)o);
yield return new object[] { bounded, new BoundedChannelOptions(capacity)
{
SingleReader = singleReader,
SingleWriter = singleWriter,
AllowSynchronousContinuations = allowSynchronousContinuations,
FullMode = bco
}, readDelegate, writeDelegate
};
}
}
private static async Task<bool> ReadSynchronous(ChannelReader<int> reader)
{
while (!reader.TryRead(out int value))
{
if (!await reader.WaitToReadAsync())
{
return false;
}
}
return true;
}
private static async Task<bool> ReadAsynchronous(ChannelReader<int> reader)
{
if (await reader.WaitToReadAsync())
{
await reader.ReadAsync();
return true;
}
return false;
}
private static async Task<bool> ReadSyncAndAsync(ChannelReader<int> reader)
{
if (!reader.TryRead(out int value))
{
if (await reader.WaitToReadAsync())
{
await reader.ReadAsync();
return true;
}
return false;
}
return true;
}
private static async Task WriteSynchronous(ChannelWriter<int> writer, int value)
{
while (!writer.TryWrite(value))
{
if (!await writer.WaitToWriteAsync())
{
break;
}
}
}
private static async Task WriteAsynchronous(ChannelWriter<int> writer, int value)
{
if (await writer.WaitToWriteAsync())
{
await writer.WriteAsync(value);
}
}
private static async Task WriteSyncAndAsync(ChannelWriter<int> writer, int value)
{
if (!writer.TryWrite(value))
{
if (await writer.WaitToWriteAsync())
{
await writer.WriteAsync(value);
}
}
}
const int MaxNumberToWriteToChannel = 400_000;
private static readonly int MaxTaskCounts = Math.Max(2, Environment.ProcessorCount);
[ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))]
[MemberData(nameof(TestData))]
public void RunInStressMode(
Func<ChannelOptions, Channel<int>> channelCreator,
ChannelOptions options,
Func<ChannelReader<int>, Task<bool>> readDelegate,
Func<ChannelWriter<int>, int, Task> writeDelegate)
{
Channel<int> channel = channelCreator(options);
ChannelReader<int> reader = channel.Reader;
ChannelWriter<int> writer = channel.Writer;
BoundedChannelOptions boundedOptions = options as BoundedChannelOptions;
bool shouldReadAllWrittenValues = boundedOptions == null || boundedOptions.FullMode == BoundedChannelFullMode.Wait;
List<Task> taskList = new List<Task>();
int readerTasksCount;
int writerTasksCount;
if (options.SingleReader)
{
readerTasksCount = 1;
writerTasksCount = options.SingleWriter ? 1 : MaxTaskCounts - 1;
}
else if (options.SingleWriter)
{
writerTasksCount = 1;
readerTasksCount = MaxTaskCounts - 1;
}
else
{
readerTasksCount = MaxTaskCounts / 2;
writerTasksCount = MaxTaskCounts - readerTasksCount;
}
int readCount = 0;
for (int i=0; i < readerTasksCount; i++)
{
taskList.Add(Task.Run(async delegate
{
try
{
while (true)
{
if (!await readDelegate(reader))
break;
Interlocked.Increment(ref readCount);
}
}
catch (ChannelClosedException)
{
}
}));
}
int numberToWriteToQueue = -1;
int remainingWriters = writerTasksCount;
for (int i=0; i < writerTasksCount; i++)
{
taskList.Add(Task.Run(async delegate
{
int num = Interlocked.Increment(ref numberToWriteToQueue);
while (num < MaxNumberToWriteToChannel)
{
await writeDelegate(writer, num);
num = Interlocked.Increment(ref numberToWriteToQueue);
}
if (Interlocked.Decrement(ref remainingWriters) == 0)
writer.Complete();
}));
}
Task.WaitAll(taskList.ToArray());
if (shouldReadAllWrittenValues)
{
Assert.Equal(MaxNumberToWriteToChannel, readCount);
}
else
{
Assert.InRange(readCount, 0, MaxNumberToWriteToChannel);
}
}
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.NetworkInformation
{
public partial class Ping : Component
{
private const int DefaultSendBufferSize = 32; // Same as ping.exe on Windows.
private const int DefaultTimeout = 5000; // 5 seconds: same as ping.exe on Windows.
private const int MaxBufferSize = 65500; // Artificial constraint due to win32 api limitations.
private const int MaxUdpPacket = 0xFFFF + 256; // Marshal.SizeOf(typeof(Icmp6EchoReply)) * 2 + ip header info;
private readonly ManualResetEventSlim _lockObject = new ManualResetEventSlim(initialState: true); // doubles as the ability to wait on the current operation
private SendOrPostCallback _onPingCompletedDelegate;
private bool _disposeRequested = false;
private byte[] _defaultSendBuffer = null;
private bool _canceled;
// Thread safety:
private const int Free = 0;
private const int InProgress = 1;
private new const int Disposed = 2;
private int _status = Free;
public Ping()
{
// This class once inherited a finalizer. For backward compatibility it has one so that
// any derived class that depends on it will see the behaviour expected. Since it is
// not used by this class itself, suppress it immediately if this is not an instance
// of a derived class it doesn't suffer the GC burden of finalization.
if (GetType() == typeof(Ping))
{
GC.SuppressFinalize(this);
}
}
private void CheckStart()
{
if (_disposeRequested)
{
throw new ObjectDisposedException(GetType().FullName);
}
int currentStatus;
lock (_lockObject)
{
currentStatus = _status;
if (currentStatus == Free)
{
_canceled = false;
_status = InProgress;
_lockObject.Reset();
return;
}
}
if (currentStatus == InProgress)
{
throw new InvalidOperationException(SR.net_inasync);
}
else
{
Debug.Assert(currentStatus == Disposed, $"Expected currentStatus == Disposed, got {currentStatus}");
throw new ObjectDisposedException(GetType().FullName);
}
}
private void Finish()
{
lock (_lockObject)
{
Debug.Assert(_status == InProgress, $"Invalid status: {_status}");
_status = Free;
_lockObject.Set();
}
if (_disposeRequested)
{
InternalDispose();
}
}
// Cancels pending async requests, closes the handles.
private void InternalDispose()
{
_disposeRequested = true;
lock (_lockObject)
{
if (_status != Free)
{
// Already disposed, or Finish will call Dispose again once Free.
return;
}
_status = Disposed;
}
InternalDisposeCore();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Only on explicit dispose. Otherwise, the GC can cleanup everything else.
InternalDispose();
}
}
public event PingCompletedEventHandler PingCompleted;
protected void OnPingCompleted(PingCompletedEventArgs e)
{
PingCompleted?.Invoke(this, e);
}
public PingReply Send(string hostNameOrAddress)
{
return Send(hostNameOrAddress, DefaultTimeout, DefaultSendBuffer);
}
public PingReply Send(string hostNameOrAddress, int timeout)
{
return Send(hostNameOrAddress, timeout, DefaultSendBuffer);
}
public PingReply Send(IPAddress address)
{
return Send(address, DefaultTimeout, DefaultSendBuffer);
}
public PingReply Send(IPAddress address, int timeout)
{
return Send(address, timeout, DefaultSendBuffer);
}
public PingReply Send(string hostNameOrAddress, int timeout, byte[] buffer)
{
return Send(hostNameOrAddress, timeout, buffer, null);
}
public PingReply Send(IPAddress address, int timeout, byte[] buffer)
{
return Send(address, timeout, buffer, null);
}
public PingReply Send(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options)
{
return SendPingAsync(hostNameOrAddress, timeout, buffer, options).GetAwaiter().GetResult();
}
public PingReply Send(IPAddress address, int timeout, byte[] buffer, PingOptions options)
{
return SendPingAsync(address, timeout, buffer, options).GetAwaiter().GetResult();
}
public void SendAsync(string hostNameOrAddress, object userToken)
{
SendAsync(hostNameOrAddress, DefaultTimeout, DefaultSendBuffer, userToken);
}
public void SendAsync(string hostNameOrAddress, int timeout, object userToken)
{
SendAsync(hostNameOrAddress, timeout, DefaultSendBuffer, userToken);
}
public void SendAsync(IPAddress address, object userToken)
{
SendAsync(address, DefaultTimeout, DefaultSendBuffer, userToken);
}
public void SendAsync(IPAddress address, int timeout, object userToken)
{
SendAsync(address, timeout, DefaultSendBuffer, userToken);
}
public void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, object userToken)
{
SendAsync(hostNameOrAddress, timeout, buffer, null, userToken);
}
public void SendAsync(IPAddress address, int timeout, byte[] buffer, object userToken)
{
SendAsync(address, timeout, buffer, null, userToken);
}
public void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options, object userToken)
{
TranslateTaskToEap(userToken, SendPingAsync(hostNameOrAddress, timeout, buffer, options));
}
public void SendAsync(IPAddress address, int timeout, byte[] buffer, PingOptions options, object userToken)
{
TranslateTaskToEap(userToken, SendPingAsync(address, timeout, buffer, options));
}
private void TranslateTaskToEap(object userToken, Task<PingReply> pingTask)
{
pingTask.ContinueWith((t, state) =>
{
var asyncOp = (AsyncOperation)state;
var e = new PingCompletedEventArgs(t.IsCompletedSuccessfully ? t.Result : null, t.Exception, t.IsCanceled, asyncOp.UserSuppliedState);
SendOrPostCallback callback = _onPingCompletedDelegate ?? (_onPingCompletedDelegate = new SendOrPostCallback(o => { OnPingCompleted((PingCompletedEventArgs)o); }));
asyncOp.PostOperationCompleted(callback, e);
}, AsyncOperationManager.CreateOperation(userToken), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
}
public Task<PingReply> SendPingAsync(IPAddress address)
{
return SendPingAsync(address, DefaultTimeout, DefaultSendBuffer, null);
}
public Task<PingReply> SendPingAsync(string hostNameOrAddress)
{
return SendPingAsync(hostNameOrAddress, DefaultTimeout, DefaultSendBuffer, null);
}
public Task<PingReply> SendPingAsync(IPAddress address, int timeout)
{
return SendPingAsync(address, timeout, DefaultSendBuffer, null);
}
public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout)
{
return SendPingAsync(hostNameOrAddress, timeout, DefaultSendBuffer, null);
}
public Task<PingReply> SendPingAsync(IPAddress address, int timeout, byte[] buffer)
{
return SendPingAsync(address, timeout, buffer, null);
}
public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer)
{
return SendPingAsync(hostNameOrAddress, timeout, buffer, null);
}
public Task<PingReply> SendPingAsync(IPAddress address, int timeout, byte[] buffer, PingOptions options)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (buffer.Length > MaxBufferSize)
{
throw new ArgumentException(SR.net_invalidPingBufferSize, nameof(buffer));
}
if (timeout < 0)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
// Check if address family is installed.
TestIsIpSupported(address);
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.net_invalid_ip_addr, nameof(address));
}
// Need to snapshot the address here, so we're sure that it's not changed between now
// and the operation, and to be sure that IPAddress.ToString() is called and not some override.
IPAddress addressSnapshot = (address.AddressFamily == AddressFamily.InterNetwork) ?
#pragma warning disable CS0618 // IPAddress.Address is obsoleted, but it's the most efficient way to get the Int32 IPv4 address
new IPAddress(address.Address) :
#pragma warning restore CS0618
new IPAddress(address.GetAddressBytes(), address.ScopeId);
CheckStart();
try
{
return SendPingAsyncCore(addressSnapshot, buffer, timeout, options);
}
catch (Exception e)
{
Finish();
return Task.FromException<PingReply>(new PingException(SR.net_ping, e));
}
}
public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options)
{
if (string.IsNullOrEmpty(hostNameOrAddress))
{
throw new ArgumentNullException(nameof(hostNameOrAddress));
}
IPAddress address;
if (IPAddress.TryParse(hostNameOrAddress, out address))
{
return SendPingAsync(address, timeout, buffer, options);
}
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (buffer.Length > MaxBufferSize)
{
throw new ArgumentException(SR.net_invalidPingBufferSize, nameof(buffer));
}
if (timeout < 0)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
CheckStart();
return GetAddressAndSendAsync(hostNameOrAddress, timeout, buffer, options);
}
public void SendAsyncCancel()
{
lock (_lockObject)
{
if (!_lockObject.IsSet)
{
// As in the .NET Framework, this doesn't actually cancel an in-progress operation. It just marks it such that
// when the operation completes, it's flagged as canceled.
_canceled = true;
}
}
// As in the .NET Framework, synchronously wait for the in-flight operation to complete.
// If there isn't one in flight, this event will already be set.
_lockObject.Wait();
}
private async Task<PingReply> GetAddressAndSendAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options)
{
bool requiresFinish = true;
try
{
IPAddress[] addresses = await Dns.GetHostAddressesAsync(hostNameOrAddress).ConfigureAwait(false);
Task<PingReply> pingReplyTask = SendPingAsyncCore(addresses[0], buffer, timeout, options);
requiresFinish = false;
return await pingReplyTask.ConfigureAwait(false);
}
catch (Exception e)
{
// SendPingAsyncCore will call Finish before completing the Task. If SendPingAsyncCore isn't invoked
// because an exception is thrown first, or if it throws out an exception synchronously, then
// we need to invoke Finish; otherwise, it has the responsibility to invoke Finish.
if (requiresFinish)
{
Finish();
}
throw new PingException(SR.net_ping, e);
}
}
// Tests if the current machine supports the given ip protocol family.
private void TestIsIpSupported(IPAddress ip)
{
InitializeSockets();
if (ip.AddressFamily == AddressFamily.InterNetwork && !SocketProtocolSupportPal.OSSupportsIPv4)
{
throw new NotSupportedException(SR.net_ipv4_not_installed);
}
else if ((ip.AddressFamily == AddressFamily.InterNetworkV6 && !SocketProtocolSupportPal.OSSupportsIPv6))
{
throw new NotSupportedException(SR.net_ipv6_not_installed);
}
}
static partial void InitializeSockets();
partial void InternalDisposeCore();
// Creates a default send buffer if a buffer wasn't specified. This follows the ping.exe model.
private byte[] DefaultSendBuffer
{
get
{
if (_defaultSendBuffer == null)
{
_defaultSendBuffer = new byte[DefaultSendBufferSize];
for (int i = 0; i < DefaultSendBufferSize; i++)
_defaultSendBuffer[i] = (byte)((int)'a' + i % 23);
}
return _defaultSendBuffer;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Html;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
/// <summary>
/// Select-related extensions for <see cref="IHtmlHelper"/> and <see cref="IHtmlHelper{TModel}"/>.
/// </summary>
public static class HtmlHelperSelectExtensions
{
/// <summary>
/// Returns a single-selection HTML <select> element for the <paramref name="expression"/>. Adds
/// <option> elements based on the <see cref="IHtmlHelper.ViewData"/> entry with full name. Adds a
/// "selected" attribute to an <option> if its <see cref="SelectListItem.Value"/> (if non-<c>null</c>) or
/// <see cref="SelectListItem.Text"/> matches the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name, or
/// the <paramref name="expression"/> evaluated against <see cref="ViewFeatures.ViewDataDictionary.Model"/>.
/// See <see cref="IHtmlHelper.Name"/> for more information about a "full name".
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="expression">Expression name, relative to the current model.</param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <select> element.</returns>
/// <remarks>
/// <para>
/// Combines <see cref="ViewFeatures.TemplateInfo.HtmlFieldPrefix"/> and <paramref name="expression"/> to set
/// <select> element's "name" attribute. Sanitizes <paramref name="expression"/> to set element's "id"
/// attribute.
/// </para>
/// <para>
/// The <see cref="IHtmlHelper.ViewData"/> entry with full name must be a non-<c>null</c> collection of
/// <see cref="SelectListItem"/> objects.
/// </para>
/// </remarks>
public static IHtmlContent DropDownList(this IHtmlHelper htmlHelper, string expression)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.DropDownList(expression, selectList: null, optionLabel: null, htmlAttributes: null);
}
/// <summary>
/// Returns a single-selection HTML <select> element for the <paramref name="expression"/>. Adds
/// <option> elements based on <paramref name="optionLabel"/> and the <see cref="IHtmlHelper.ViewData"/>
/// entry with full name. Adds a "selected" attribute to an <option> if its
/// <see cref="SelectListItem.Value"/> (if non-<c>null</c>) or <see cref="SelectListItem.Text"/> matches the
/// first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name, or
/// the <paramref name="expression"/> evaluated against <see cref="ViewFeatures.ViewDataDictionary.Model"/>.
/// See <see cref="IHtmlHelper.Name"/> for more information about a "full name".
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="expression">Expression name, relative to the current model.</param>
/// <param name="optionLabel">
/// The text for a default empty item. Does not include such an item if argument is <c>null</c>.
/// </param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <select> element.</returns>
/// <remarks>
/// <para>
/// Combines <see cref="ViewFeatures.TemplateInfo.HtmlFieldPrefix"/> and <paramref name="expression"/> to set
/// <select> element's "name" attribute. Sanitizes <paramref name="expression"/> to set element's "id"
/// attribute.
/// </para>
/// <para>
/// The <see cref="IHtmlHelper.ViewData"/> entry with full name must be a non-<c>null</c> collection of
/// <see cref="SelectListItem"/> objects.
/// </para>
/// </remarks>
public static IHtmlContent DropDownList(
this IHtmlHelper htmlHelper,
string expression,
string optionLabel)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.DropDownList(
expression,
selectList: null,
optionLabel: optionLabel,
htmlAttributes: null);
}
/// <summary>
/// Returns a single-selection HTML <select> element for the <paramref name="expression"/>. Adds
/// <option> elements based on <paramref name="selectList"/>. Adds a "selected" attribute to an
/// <option> if its <see cref="SelectListItem.Value"/> (if non-<c>null</c>) or
/// <see cref="SelectListItem.Text"/> matches the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name,
/// the <see cref="IHtmlHelper.ViewData"/> entry with full name (unless used instead of
/// <paramref name="selectList"/>), or
/// the <paramref name="expression"/> evaluated against <see cref="ViewFeatures.ViewDataDictionary.Model"/>.
/// See <see cref="IHtmlHelper.Name"/> for more information about a "full name".
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="expression">Expression name, relative to the current model.</param>
/// <param name="selectList">
/// A collection of <see cref="SelectListItem"/> objects used to populate the <select> element with
/// <optgroup> and <option> elements. If <c>null</c>, uses the <see cref="IHtmlHelper.ViewData"/>
/// entry with full name and that entry must be a collection of <see cref="SelectListItem"/> objects.
/// </param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <select> element.</returns>
/// <remarks>
/// Combines <see cref="ViewFeatures.TemplateInfo.HtmlFieldPrefix"/> and <paramref name="expression"/> to set
/// <select> element's "name" attribute. Sanitizes <paramref name="expression"/> to set element's "id"
/// attribute.
/// </remarks>
public static IHtmlContent DropDownList(
this IHtmlHelper htmlHelper,
string expression,
IEnumerable<SelectListItem> selectList)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.DropDownList(expression, selectList, optionLabel: null, htmlAttributes: null);
}
/// <summary>
/// Returns a single-selection HTML <select> element for the <paramref name="expression"/>. Adds
/// <option> elements based on <paramref name="selectList"/>. Adds a "selected" attribute to an
/// <option> if its <see cref="SelectListItem.Value"/> (if non-<c>null</c>) or
/// <see cref="SelectListItem.Text"/> matches the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name,
/// the <see cref="IHtmlHelper.ViewData"/> entry with full name (unless used instead of
/// <paramref name="selectList"/>), or
/// the <paramref name="expression"/> evaluated against <see cref="ViewFeatures.ViewDataDictionary.Model"/>.
/// See <see cref="IHtmlHelper.Name"/> for more information about a "full name".
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="expression">Expression name, relative to the current model.</param>
/// <param name="selectList">
/// A collection of <see cref="SelectListItem"/> objects used to populate the <select> element with
/// <optgroup> and <option> elements. If <c>null</c>, uses the <see cref="IHtmlHelper.ViewData"/>
/// entry with full name and that entry must be a collection of <see cref="SelectListItem"/> objects.
/// </param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the <select> element. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <select> element.</returns>
/// <remarks>
/// Combines <see cref="ViewFeatures.TemplateInfo.HtmlFieldPrefix"/> and <paramref name="expression"/> to set
/// <select> element's "name" attribute. Sanitizes <paramref name="expression"/> to set element's "id"
/// attribute.
/// </remarks>
public static IHtmlContent DropDownList(
this IHtmlHelper htmlHelper,
string expression,
IEnumerable<SelectListItem> selectList,
object htmlAttributes)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.DropDownList(expression, selectList, optionLabel: null, htmlAttributes: htmlAttributes);
}
/// <summary>
/// Returns a single-selection HTML <select> element for the <paramref name="expression"/>. Adds
/// <option> elements based on <paramref name="optionLabel"/> and <paramref name="selectList"/>. Adds a
/// "selected" attribute to an <option> if its <see cref="SelectListItem.Value"/> (if non-<c>null</c>) or
/// <see cref="SelectListItem.Text"/> matches the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name,
/// the <see cref="IHtmlHelper.ViewData"/> entry with full name (unless used instead of
/// <paramref name="selectList"/>), or
/// the <paramref name="expression"/> evaluated against <see cref="ViewFeatures.ViewDataDictionary.Model"/>.
/// See <see cref="IHtmlHelper.Name"/> for more information about a "full name".
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="expression">Expression name, relative to the current model.</param>
/// <param name="selectList">
/// A collection of <see cref="SelectListItem"/> objects used to populate the <select> element with
/// <optgroup> and <option> elements. If <c>null</c>, uses the <see cref="IHtmlHelper.ViewData"/>
/// entry with full name and that entry must be a collection of <see cref="SelectListItem"/> objects.
/// </param>
/// <param name="optionLabel">
/// The text for a default empty item. Does not include such an item if argument is <c>null</c>.
/// </param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <select> element.</returns>
/// <remarks>
/// Combines <see cref="ViewFeatures.TemplateInfo.HtmlFieldPrefix"/> and <paramref name="expression"/> to set
/// <select> element's "name" attribute. Sanitizes <paramref name="expression"/> to set element's "id"
/// attribute.
/// </remarks>
public static IHtmlContent DropDownList(
this IHtmlHelper htmlHelper,
string expression,
IEnumerable<SelectListItem> selectList,
string optionLabel)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.DropDownList(expression, selectList, optionLabel, htmlAttributes: null);
}
/// <summary>
/// Returns a single-selection HTML <select> element for the <paramref name="expression"/>. Adds
/// <option> elements based on <paramref name="selectList"/>. Adds a "selected" attribute to an
/// <option> if its <see cref="SelectListItem.Value"/> (if non-<c>null</c>) or
/// <see cref="SelectListItem.Text"/> matches the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name, or
/// the <paramref name="expression"/> evaluated against <see cref="ViewFeatures.ViewDataDictionary.Model"/>.
/// See <see cref="IHtmlHelper{TModel}.NameFor"/> for more information about a "full name".
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper{TModel}"/> instance this method extends.</param>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="selectList">
/// A collection of <see cref="SelectListItem"/> objects used to populate the <select> element with
/// <optgroup> and <option> elements. If <c>null</c>, uses the <see cref="IHtmlHelper.ViewData"/>
/// entry with full name and that entry must be a collection of <see cref="SelectListItem"/> objects.
/// </param>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <select> element.</returns>
/// <remarks>
/// Combines <see cref="ViewFeatures.TemplateInfo.HtmlFieldPrefix"/> and the string representation of the
/// <paramref name="expression"/> to set <select> element's "name" attribute. Sanitizes the string
/// representation of the <paramref name="expression"/> to set element's "id" attribute.
/// </remarks>
public static IHtmlContent DropDownListFor<TModel, TResult>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
IEnumerable<SelectListItem> selectList)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
return htmlHelper.DropDownListFor(expression, selectList, optionLabel: null, htmlAttributes: null);
}
/// <summary>
/// Returns a single-selection HTML <select> element for the <paramref name="expression"/>. Adds
/// <option> elements based on <paramref name="selectList"/>. Adds a "selected" attribute to an
/// <option> if its <see cref="SelectListItem.Value"/> (if non-<c>null</c>) or
/// <see cref="SelectListItem.Text"/> matches the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name, or
/// the <paramref name="expression"/> evaluated against <see cref="ViewFeatures.ViewDataDictionary.Model"/>.
/// See <see cref="IHtmlHelper{TModel}.NameFor"/> for more information about a "full name".
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper{TModel}"/> instance this method extends.</param>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="selectList">
/// A collection of <see cref="SelectListItem"/> objects used to populate the <select> element with
/// <optgroup> and <option> elements. If <c>null</c>, uses the <see cref="IHtmlHelper.ViewData"/>
/// entry with full name and that entry must be a collection of <see cref="SelectListItem"/> objects.
/// </param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the <select> element. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <select> element.</returns>
/// <remarks>
/// Combines <see cref="ViewFeatures.TemplateInfo.HtmlFieldPrefix"/> and the string representation of the
/// <paramref name="expression"/> to set <select> element's "name" attribute. Sanitizes the string
/// representation of the <paramref name="expression"/> to set element's "id" attribute.
/// </remarks>
public static IHtmlContent DropDownListFor<TModel, TResult>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
IEnumerable<SelectListItem> selectList,
object htmlAttributes)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
return htmlHelper.DropDownListFor(
expression,
selectList,
optionLabel: null,
htmlAttributes: htmlAttributes);
}
/// <summary>
/// Returns a single-selection HTML <select> element for the <paramref name="expression"/>. Adds
/// <option> elements based on <paramref name="optionLabel"/> and <paramref name="selectList"/>. Adds a
/// "selected" attribute to an <option> if its <see cref="SelectListItem.Value"/> (if non-<c>null</c>) or
/// <see cref="SelectListItem.Text"/> matches the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name, or
/// the <paramref name="expression"/> evaluated against <see cref="ViewFeatures.ViewDataDictionary.Model"/>.
/// See <see cref="IHtmlHelper{TModel}.NameFor"/> for more information about a "full name".
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper{TModel}"/> instance this method extends.</param>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="selectList">
/// A collection of <see cref="SelectListItem"/> objects used to populate the <select> element with
/// <optgroup> and <option> elements. If <c>null</c>, uses the <see cref="IHtmlHelper.ViewData"/>
/// entry with full name and that entry must be a collection of <see cref="SelectListItem"/> objects.
/// </param>
/// <param name="optionLabel">
/// The text for a default empty item. Does not include such an item if argument is <c>null</c>.
/// </param>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <select> element.</returns>
/// <remarks>
/// Combines <see cref="ViewFeatures.TemplateInfo.HtmlFieldPrefix"/> and the string representation of the
/// <paramref name="expression"/> to set <select> element's "name" attribute. Sanitizes the string
/// representation of the <paramref name="expression"/> to set element's "id" attribute.
/// </remarks>
public static IHtmlContent DropDownListFor<TModel, TResult>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
IEnumerable<SelectListItem> selectList,
string optionLabel)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
return htmlHelper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes: null);
}
/// <summary>
/// Returns a multi-selection <select> element for the <paramref name="expression"/>. Adds
/// <option> elements based on the <see cref="IHtmlHelper.ViewData"/> entry with full name. Adds a
/// "selected" attribute to an <option> if its <see cref="SelectListItem.Value"/> (if non-<c>null</c>) or
/// <see cref="SelectListItem.Text"/> matches the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name, or
/// the <paramref name="expression"/> evaluated against <see cref="ViewFeatures.ViewDataDictionary.Model"/>.
/// See <see cref="IHtmlHelper.Name"/> for more information about a "full name".
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="expression">Expression name, relative to the current model.</param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <select> element.</returns>
/// <remarks>
/// <para>
/// Combines <see cref="ViewFeatures.TemplateInfo.HtmlFieldPrefix"/> and <paramref name="expression"/> to set
/// <select> element's "name" attribute. Sanitizes <paramref name="expression"/> to set element's "id"
/// attribute.
/// </para>
/// <para>
/// The <see cref="IHtmlHelper.ViewData"/> entry with full name must be a non-<c>null</c> collection of
/// <see cref="SelectListItem"/> objects.
/// </para>
/// </remarks>
public static IHtmlContent ListBox(this IHtmlHelper htmlHelper, string expression)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.ListBox(expression, selectList: null, htmlAttributes: null);
}
/// <summary>
/// Returns a multi-selection <select> element for the <paramref name="expression"/>. Adds
/// <option> elements based on <paramref name="selectList"/>. Adds a "selected" attribute to an
/// <option> if its <see cref="SelectListItem.Value"/> (if non-<c>null</c>) or
/// <see cref="SelectListItem.Text"/> matches the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name,
/// the <see cref="IHtmlHelper.ViewData"/> entry with full name (unless used instead of
/// <paramref name="selectList"/>), or
/// the <paramref name="expression"/> evaluated against <see cref="ViewFeatures.ViewDataDictionary.Model"/>.
/// See <see cref="IHtmlHelper.Name"/> for more information about a "full name".
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper"/> instance this method extends.</param>
/// <param name="expression">Expression name, relative to the current model.</param>
/// <param name="selectList">
/// A collection of <see cref="SelectListItem"/> objects used to populate the <select> element with
/// <optgroup> and <option> elements. If <c>null</c>, uses the <see cref="IHtmlHelper.ViewData"/>
/// entry with full name and that entry must be a collection of <see cref="SelectListItem"/> objects.
/// </param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <select> element.</returns>
/// <remarks>
/// Combines <see cref="ViewFeatures.TemplateInfo.HtmlFieldPrefix"/> and <paramref name="expression"/> to set
/// <select> element's "name" attribute. Sanitizes <paramref name="expression"/> to set element's "id"
/// attribute.
/// </remarks>
public static IHtmlContent ListBox(
this IHtmlHelper htmlHelper,
string expression,
IEnumerable<SelectListItem> selectList)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.ListBox(expression, selectList, htmlAttributes: null);
}
/// <summary>
/// Returns a multi-selection <select> element for the <paramref name="expression"/>. Adds
/// <option> elements based on <paramref name="selectList"/>. Adds a "selected" attribute to an
/// <option> if its <see cref="SelectListItem.Value"/> (if non-<c>null</c>) or
/// <see cref="SelectListItem.Text"/> matches the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name, or
/// the <paramref name="expression"/> evaluated against <see cref="ViewFeatures.ViewDataDictionary.Model"/>.
/// See <see cref="IHtmlHelper.Name"/> for more information about a "full name".
/// </summary>
/// <param name="htmlHelper">The <see cref="IHtmlHelper{TModel}"/> instance this method extends.</param>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="selectList">
/// A collection of <see cref="SelectListItem"/> objects used to populate the <select> element with
/// <optgroup> and <option> elements. If <c>null</c>, uses the <see cref="IHtmlHelper.ViewData"/>
/// entry with full name and that entry must be a collection of <see cref="SelectListItem"/> objects.
/// </param>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <select> element.</returns>
/// <remarks>
/// Combines <see cref="ViewFeatures.TemplateInfo.HtmlFieldPrefix"/> and the string representation of the
/// <paramref name="expression"/> to set <select> element's "name" attribute. Sanitizes the string
/// representation of the <paramref name="expression"/> to set element's "id" attribute.
/// </remarks>
public static IHtmlContent ListBoxFor<TModel, TResult>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
IEnumerable<SelectListItem> selectList)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
return htmlHelper.ListBoxFor(expression, selectList, htmlAttributes: null);
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Originally based on the Bartok code base.
//
//#define METADATARESOLVER_DEBUG
#define METADATARESOLVER_DEBUG_OP_EQUALITY
using System;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
using System.Text;
namespace Microsoft.Zelig.MetaData
{
public interface ISymbolResolverHelper
{
Importer.PdbInfo.PdbFile ResolveAssemblySymbols( string file );
}
public interface IMetaDataResolverHelper
{
Importer.MetaData ResolveAssemblyReference( string name ,
MetaDataVersion ver );
}
public sealed class MetaDataResolver : Normalized.IMetaDataBootstrap
{
internal class AssemblyPair
{
//
// State
//
internal Importer.MetaData Imported;
internal Normalized.MetaDataAssembly Normalized;
internal MetaDataNormalizationPhase Phase;
//
// Constructor Methods
//
internal AssemblyPair( Importer.MetaData imported ,
Normalized.MetaDataAssembly normalized )
{
this.Imported = imported;
this.Normalized = normalized;
this.Phase = MetaDataNormalizationPhase.Uninitialized;
}
}
//--//
//
// State
//
private IMetaDataResolverHelper m_metaDataResolverHelper;
private List< Importer.MetaData > m_metaDataInitialSet;
private List< AssemblyPair > m_metaDataList;
private List< object > m_pendingEntries;
private Normalized.MetaDataTypeDefinition[] m_lookupBuiltin;
private GrowOnlyHashTable< String , Normalized.MetaDataTypeDefinitionBase > m_lookupTypeNames;
private GrowOnlyHashTable< Importer .IMetaDataNormalize , Normalized.IMetaDataObject > m_lookupEntries;
private GrowOnlyHashTable< Importer .IMetaDataNormalizeSignature, Normalized.MetaDataSignature > m_lookupSignatureEntries;
private GrowOnlySet < Normalized.IMetaDataUnique > m_lookupUniques;
private Normalized.MetaDataAssembly m_assemblyForDelayedParameters;
//
// Constructor Methods
//
public MetaDataResolver( IMetaDataResolverHelper metaDataResolverHelper )
{
Importer.MetaData.ObjectComparer impComparer = new Importer.MetaData.ObjectComparer ();
Importer.MetaData.SignatureComparer sigComparer = new Importer.MetaData.SignatureComparer();
m_metaDataResolverHelper = metaDataResolverHelper;
m_metaDataInitialSet = new List< Importer.MetaData >();
m_metaDataList = new List< AssemblyPair >();
m_pendingEntries = new List< object >();
m_lookupBuiltin = new Normalized.MetaDataTypeDefinition[(int)ElementTypes.MAX];
m_lookupTypeNames = HashTableFactory.New < String , Normalized.MetaDataTypeDefinitionBase >( );
m_lookupEntries = HashTableFactory.NewWithComparer< Importer .IMetaDataNormalize , Normalized.IMetaDataObject >( impComparer );
m_lookupSignatureEntries = HashTableFactory.NewWithComparer< Importer .IMetaDataNormalizeSignature, Normalized.MetaDataSignature >( sigComparer );
m_lookupUniques = SetFactory .New < Normalized.IMetaDataUnique >( );
//--//
m_assemblyForDelayedParameters = new Normalized.MetaDataAssembly( this.UniqueDictionary, 0 );
m_assemblyForDelayedParameters.m_name = "<AssemblyForDelayedParameters>";
m_assemblyForDelayedParameters.m_version = new MetaDataVersion();
AssemblyPair pair = new AssemblyPair( null, m_assemblyForDelayedParameters );
m_metaDataList.Add( pair );
}
//--//
[System.Diagnostics.Conditional( "METADATARESOLVER_DEBUG" )]
void DebugPrint( string fmt ,
params object[] args )
{
Console.WriteLine( fmt, args );
}
//--//
public void Add( Importer.MetaData metaData )
{
m_metaDataInitialSet.Add( metaData );
}
//--//
//[System.Diagnostics.DebuggerHidden]
internal void RegisterBuiltIn( Normalized.MetaDataTypeDefinition td ,
ElementTypes elementType )
{
m_lookupBuiltin[(int)elementType] = td;
td.m_elementType = elementType;
}
//[System.Diagnostics.DebuggerHidden]
internal Normalized.MetaDataTypeDefinition LookupBuiltIn( ElementTypes elementType )
{
Normalized.MetaDataTypeDefinition res = m_lookupBuiltin[(int)elementType];
if(res != null)
{
return res;
}
throw Importer.IllegalMetaDataFormatException.Create( "Cannot resolve builtin {0}", elementType );
}
//[System.Diagnostics.DebuggerHidden]
internal Normalized.MetaDataTypeDefinitionBase ResolveName( String key ,
MetaDataNormalizationContext context )
{
Normalized.MetaDataTypeDefinitionBase res;
if(m_lookupTypeNames.TryGetValue( key, out res ))
{
return res;
}
string nameSpace;
string name;
string[] nested;
string assemblyName;
string extraInfo;
Importer.MetaDataTypeDefinition.ParseName( key, out nameSpace, out name, out nested, out assemblyName, out extraInfo );
if(assemblyName != null)
{
AssemblyPair pair = FindAssembly( assemblyName, null, context );
Normalized.MetaDataTypeDefinitionBase td = ResolveName( pair, nameSpace, name, nested );
if(td != null)
{
m_lookupTypeNames[key] = td;
return td;
}
}
else
{
foreach(AssemblyPair pair in m_metaDataList)
{
Normalized.MetaDataTypeDefinitionBase td = ResolveName( pair, nameSpace, name, nested );
if(td != null)
{
m_lookupTypeNames[key] = td;
return td;
}
}
}
throw Importer.UnresolvedExternalReferenceException.Create( null, "Cannot resolve reference to type '{0}' in '{1}'", key, context );
}
private Normalized.MetaDataTypeDefinitionBase ResolveName( AssemblyPair pair ,
string nameSpace ,
string name ,
string[] nested )
{
if(pair.Normalized != null)
{
return ResolveName( pair.Normalized, nameSpace, name, nested );
}
return null;
}
private Normalized.MetaDataTypeDefinitionBase ResolveName( Normalized.MetaDataAssembly asml ,
string nameSpace ,
string name ,
string[] nested )
{
foreach(Normalized.MetaDataTypeDefinitionAbstract td in asml.Types)
{
if(td is Normalized.MetaDataTypeDefinitionBase)
{
Normalized.MetaDataTypeDefinitionBase td2 = (Normalized.MetaDataTypeDefinitionBase)td;
if(td2.IsNameMatch( nameSpace, name, nested ))
{
return td2;
}
}
}
return null;
}
//--//
private void TrackRecursion_EnterNormalization( object src )
{
if(m_pendingEntries.Contains( src ))
{
throw Importer.IllegalMetaDataFormatException.Create( "Detected recursive resolution attempt on: {0}", src );
}
DebugPrint( "Normalizing:\r\n IN :{0}", src );
m_pendingEntries.Add( src );
}
private void TrackRecursion_ExitNormalization( object src ,
object dst )
{
m_pendingEntries.Remove( src );
DebugPrint( "Normalized:\r\n IN :{0}\r\n OUT:{1}", src, dst );
}
private void TrackRecursion_EnterProcessing( object src ,
object dst )
{
if(m_pendingEntries.Contains( src ))
{
throw Importer.IllegalMetaDataFormatException.Create( "Detected recursive resolution attempt on: {0}", src );
}
DebugPrint( "Processing:\r\n IN :{0}\r\n OUT:{1}", src, dst );
m_pendingEntries.Add( src );
}
private void TrackRecursion_ExitProcessing( object src ,
object dst )
{
m_pendingEntries.Remove( src );
DebugPrint( "Processed:\r\n IN :{0}\r\n OUT:{1}", src, dst );
}
//--//
internal Normalized.MetaDataAssembly GetAssemblyForDelayedParameters()
{
return m_assemblyForDelayedParameters;
}
//--//
//[System.Diagnostics.DebuggerHidden]
internal Normalized.IMetaDataObject Lookup( Importer.IMetaDataObject key ,
MetaDataNormalizationContext context )
{
if(key != null)
{
Normalized.IMetaDataObject en;
if(m_lookupEntries.TryGetValue( (Importer.IMetaDataNormalize)key, out en ))
{
DebugPrint( "Lookup:\r\n IN :{0}\r\n OUT:{1}", key, en );
return en;
}
}
return null;
}
//[System.Diagnostics.DebuggerHidden]
internal Normalized.IMetaDataObject GetNormalizedObject( Importer.IMetaDataNormalize obj ,
MetaDataNormalizationContext context ,
MetaDataNormalizationMode mode )
{
if(obj == null)
{
return null;
}
bool fLookupExisting = (mode & MetaDataNormalizationMode.LookupExisting ) != 0;
bool fAllocate = (mode & MetaDataNormalizationMode.Allocate ) != 0;
Normalized.IMetaDataObject en;
if(m_lookupEntries.TryGetValue( obj, out en ))
{
if(fLookupExisting)
{
DebugPrint( "Lookup:\r\n IN :{0}\r\n OUT:{1}", obj, en );
return en;
}
throw Importer.IllegalMetaDataFormatException.Create( "Detected recursive allocation attempt on: {0}", obj );
}
if(!fAllocate)
{
throw Importer.IllegalMetaDataFormatException.Create( "Cannot resolve lookup: {0}", obj );
}
//--//
TrackRecursion_EnterNormalization( obj );
Normalized.IMetaDataObject res = obj.AllocateNormalizedObject( context );
if(res == null)
{
throw Unresolvable( obj );
}
TrackRecursion_ExitNormalization( obj, res );
//--//
if(m_lookupEntries.ContainsKey( obj ))
{
throw Importer.IllegalMetaDataFormatException.Create( "Internal error: MetaData object redefined => {0}", obj );
}
m_lookupEntries.Add( obj, res );
return res;
}
//[System.Diagnostics.DebuggerHidden]
internal Normalized.MetaDataSignature GetNormalizedObject( Importer.IMetaDataNormalizeSignature obj ,
MetaDataNormalizationContext context ,
MetaDataNormalizationMode mode )
{
if(obj == null)
{
return null;
}
bool fLookupExisting = (mode & MetaDataNormalizationMode.LookupExisting ) != 0;
bool fAllocate = (mode & MetaDataNormalizationMode.Allocate ) != 0;
Normalized.MetaDataSignature en;
if(m_lookupSignatureEntries.TryGetValue( obj, out en ))
{
if(fLookupExisting)
{
DebugPrint( "Lookup:\r\n IN :{0}\r\n OUT:{1}", obj, en );
return en;
}
throw Importer.IllegalMetaDataFormatException.Create( "Detected recursive allocation attempt on: {0}", obj );
}
if(!fAllocate)
{
throw Importer.IllegalMetaDataFormatException.Create( "Cannot resolve lookup: {0}", obj );
}
//--//
TrackRecursion_EnterNormalization( obj );
Normalized.MetaDataSignature res = obj.AllocateNormalizedObject( context );
if(res == null)
{
throw Unresolvable( obj );
}
TrackRecursion_ExitNormalization( obj, res );
//--//
if(m_lookupSignatureEntries.ContainsKey( obj ))
{
throw Importer.IllegalMetaDataFormatException.Create( "Internal error: MetaData object redefined => {0}", obj );
}
m_lookupSignatureEntries.Add( obj, res );
return res;
}
//[System.Diagnostics.DebuggerHidden]
internal void ProcessPhase( Importer.IMetaDataObject obj ,
MetaDataNormalizationContext context )
{
if(obj != null)
{
Importer.IMetaDataNormalize obj2 = (Importer.IMetaDataNormalize)obj;
Normalized.IMetaDataObject dst = GetNormalizedObject( obj2, context, MetaDataNormalizationMode.LookupExisting );
TrackRecursion_EnterProcessing( obj2, dst );
obj2.ExecuteNormalizationPhase( dst, context );
TrackRecursion_ExitProcessing( obj2, dst );
}
}
//--//
public Normalized.MetaDataAssembly[] NormalizedAssemblies
{
get
{
List< Normalized.MetaDataAssembly > lst = new List< Normalized.MetaDataAssembly >();
foreach(AssemblyPair pair in m_metaDataList)
{
lst.Add( pair.Normalized );
}
return lst.ToArray();
}
}
public Normalized.MetaDataMethodBase ApplicationEntryPoint
{
get
{
foreach(AssemblyPair pair in m_metaDataList)
{
Normalized.MetaDataMethodBase entryPoint = pair.Normalized.EntryPoint;
if(entryPoint != null)
{
return entryPoint;
}
}
return null;
}
}
internal GrowOnlySet< Normalized.IMetaDataUnique > UniqueDictionary
{
get
{
return m_lookupUniques;
}
}
//--//
//
// Normalized.IMetaDataBootstrap
//
Normalized.MetaDataAssembly Normalized.IMetaDataBootstrap.GetAssembly( string name )
{
List<Normalized.MetaDataTypeDefinitionAbstract> res = new List<Microsoft.Zelig.MetaData.Normalized.MetaDataTypeDefinitionAbstract>();
foreach(AssemblyPair pair in m_metaDataList)
{
Normalized.MetaDataAssembly asml = pair.Normalized;
//
// BUGBUG: We need a better check.
//
if(asml.Name == name)
{
return asml;
}
}
return null;
}
Normalized.MetaDataTypeDefinitionAbstract Normalized.IMetaDataBootstrap.ResolveType( Normalized.MetaDataAssembly asml ,
string nameSpace ,
string name )
{
return ResolveName( asml, nameSpace, name, null );
}
Normalized.MetaDataMethodBase Normalized.IMetaDataBootstrap.GetApplicationEntryPoint()
{
return this.ApplicationEntryPoint;
}
void Normalized.IMetaDataBootstrap.FilterTypesByCustomAttribute( Normalized.MetaDataTypeDefinitionAbstract filter ,
Normalized.IMetaDataBootstrap_FilterTypesByCustomAttributeCallback callback )
{
foreach(Normalized.MetaDataAssembly asml in this.NormalizedAssemblies)
{
foreach(Normalized.MetaDataTypeDefinitionAbstract td in asml.Types)
{
Normalized.MetaDataCustomAttribute[] caArray = td.CustomAttributes;
if(caArray != null)
{
foreach(Normalized.MetaDataCustomAttribute ca in caArray)
{
Normalized.MetaDataMethodBase md = ca.Constructor as Normalized.MetaDataMethodBase;
if(md != null && md.Owner == filter)
{
callback( td, ca );
}
}
}
}
}
}
//--//
public void ResolveAll()
{
MetaDataNormalizationContext context = new MetaDataNormalizationContext( this );
MetaDataNormalizationPhase phase;
#if METADATARESOLVER_DEBUG
System.IO.TextWriter orig = Console.Out;
System.IO.StreamWriter writer = new System.IO.StreamWriter( Environment.ExpandEnvironmentVariables( @"%DEPOTROOT%\ZeligUnitTestResults\MetaDataResolver.txt" ), false, System.Text.Encoding.ASCII );
Console.SetOut( writer );
#endif
for(phase = MetaDataNormalizationPhase.ResolutionOfAssemblyReferences; phase < MetaDataNormalizationPhase.Max; phase++)
//for(phase = MetaDataNormalizationPhase.ResolutionOfAssemblyReferences; phase < MetaDataNormalizationPhase.ResolutionOfCustomAttributes; phase++)
{
RunPhase( context, phase );
}
#if METADATARESOLVER_DEBUG
Console.SetOut( orig );
writer.Close();
#endif
}
private void RunPhase( MetaDataNormalizationContext context ,
MetaDataNormalizationPhase phase )
{
context.SetPhase( phase );
if(phase == MetaDataNormalizationPhase.ResolutionOfAssemblyReferences)
{
while(m_metaDataInitialSet.Count > 0)
{
Importer.MetaData md = m_metaDataInitialSet[0]; m_metaDataInitialSet.RemoveAt( 0 );
EnqueueAssembly( md, context );
}
}
else
{
bool fDone;
do
{
fDone = true;
foreach(AssemblyPair pair in m_metaDataList.ToArray())
{
Importer.MetaData imported = pair.Imported;
if(imported != null)
{
if(imported.ExecuteNormalizationPhase( pair, context ) == false)
{
fDone = false;
break;
}
}
}
} while(fDone == false);
}
context.FlushErrors();
}
//--//
private Exception Unresolvable( object obj )
{
return Importer.IllegalMetaDataFormatException.Create( "Cannot resolve reference: {0}", obj );
}
//--//
internal AssemblyPair FindAssembly( Importer.MetaData md )
{
foreach(AssemblyPair pair in m_metaDataList)
{
if(pair.Imported == md)
{
return pair;
}
}
return null;
}
internal AssemblyPair FindAssembly( string name ,
MetaDataVersion version ,
MetaDataNormalizationContext context )
{
Importer.MetaData md = FindImporterAssembly( name, version );
if(md == null)
{
md = m_metaDataResolverHelper.ResolveAssemblyReference( name, version );
if(md == null)
{
throw Importer.UnresolvedExternalReferenceException.Create( null, "Cannot resolve reference to assembly: {0} {1}", name, version );
}
}
return EnqueueAssembly( md, context );
}
private AssemblyPair EnqueueAssembly( Importer.MetaData md ,
MetaDataNormalizationContext context )
{
AssemblyPair pair = FindAssembly( md );
if(pair == null)
{
pair = new AssemblyPair( md, null );
m_metaDataList.Add( pair );
MetaDataNormalizationPhase activePhase = context.Phase;
MetaDataNormalizationPhase runPhase = MetaDataNormalizationPhase.ResolutionOfAssemblyReferences;
context.SetPhase( runPhase );
md.AllocateNormalizedObject( pair, context );
while(++runPhase < activePhase)
{
context.SetPhase( runPhase );
while(md.ExecuteNormalizationPhase( pair, context ) == false)
{
}
}
context.SetPhase( activePhase );
}
return pair;
}
private Importer.MetaData FindImporterAssembly( string name ,
MetaDataVersion version )
{
foreach(AssemblyPair pair in m_metaDataList)
{
Importer.MetaData imported = pair.Imported;
if(imported != null)
{
Importer.MetaDataAssembly asml = imported.Assembly;
if(asml.Name == name)
{
//
// BUGBUG: This version check does not cover at all the complexity of versioning...
//
if(version == null || asml.Version.IsCompatible( version, false ))
{
return pair.Imported;
}
}
}
}
for(int i = 0; i < m_metaDataInitialSet.Count; i++)
{
Importer.MetaData md = m_metaDataInitialSet[i];
if(md.Assembly.Name == name)
{
//
// BUGBUG: This version check does not cover at all the complexity of versioning...
//
if(version == null || md.Assembly.Version.IsCompatible( version, false ))
{
m_metaDataInitialSet.RemoveAt( i );
return md;
}
}
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
namespace System.Net
{
internal sealed class SafeDeleteSslContext : SafeDeleteContext
{
private SafeSslHandle _sslContext;
private Interop.AppleCrypto.SSLReadFunc _readCallback;
private Interop.AppleCrypto.SSLWriteFunc _writeCallback;
private Queue<byte> _fromConnection = new Queue<byte>();
private Queue<byte> _toConnection = new Queue<byte>();
public SafeSslHandle SslContext => _sslContext;
public SafeDeleteSslContext(SafeFreeSslCredentials credential, SslAuthenticationOptions sslAuthenticationOptions)
: base(credential)
{
Debug.Assert((null != credential) && !credential.IsInvalid, "Invalid credential used in SafeDeleteSslContext");
try
{
int osStatus;
unsafe
{
_readCallback = ReadFromConnection;
_writeCallback = WriteToConnection;
}
_sslContext = CreateSslContext(credential, sslAuthenticationOptions.IsServer);
osStatus = Interop.AppleCrypto.SslSetIoCallbacks(
_sslContext,
_readCallback,
_writeCallback);
if (osStatus != 0)
{
throw Interop.AppleCrypto.CreateExceptionForOSStatus(osStatus);
}
if (sslAuthenticationOptions.CipherSuitesPolicy != null)
{
uint[] tlsCipherSuites = sslAuthenticationOptions.CipherSuitesPolicy.Pal.TlsCipherSuites;
unsafe
{
fixed (uint* cipherSuites = tlsCipherSuites)
{
osStatus = Interop.AppleCrypto.SslSetEnabledCipherSuites(
_sslContext,
cipherSuites,
tlsCipherSuites.Length);
if (osStatus != 0)
{
throw Interop.AppleCrypto.CreateExceptionForOSStatus(osStatus);
}
}
}
}
if (sslAuthenticationOptions.ApplicationProtocols != null)
{
// On OSX coretls supports only client side. For server, we will silently ignore the option.
if (!sslAuthenticationOptions.IsServer)
{
Interop.AppleCrypto.SslCtxSetAlpnProtos(_sslContext, sslAuthenticationOptions.ApplicationProtocols);
}
}
}
catch (Exception ex)
{
Debug.Write("Exception Caught. - " + ex);
Dispose();
throw;
}
}
private static SafeSslHandle CreateSslContext(SafeFreeSslCredentials credential, bool isServer)
{
switch (credential.Policy)
{
case EncryptionPolicy.RequireEncryption:
case EncryptionPolicy.AllowNoEncryption:
// SecureTransport doesn't allow TLS_NULL_NULL_WITH_NULL, but
// since AllowNoEncryption intersect OS-supported isn't nothing,
// let it pass.
break;
default:
throw new PlatformNotSupportedException(SR.Format(SR.net_encryptionpolicy_notsupported, credential.Policy));
}
SafeSslHandle sslContext = Interop.AppleCrypto.SslCreateContext(isServer ? 1 : 0);
try
{
if (sslContext.IsInvalid)
{
// This is as likely as anything. No error conditions are defined for
// the OS function, and our shim only adds a NULL if isServer isn't a normalized bool.
throw new OutOfMemoryException();
}
// Let None mean "system default"
if (credential.Protocols != SslProtocols.None)
{
SetProtocols(sslContext, credential.Protocols);
}
if (credential.Certificate != null)
{
SetCertificate(sslContext, credential.Certificate);
}
Interop.AppleCrypto.SslBreakOnServerAuth(sslContext, true);
Interop.AppleCrypto.SslBreakOnClientAuth(sslContext, true);
}
catch
{
sslContext.Dispose();
throw;
}
return sslContext;
}
public override bool IsInvalid => _sslContext?.IsInvalid ?? true;
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (null != _sslContext)
{
_sslContext.Dispose();
_sslContext = null;
}
}
base.Dispose(disposing);
}
private unsafe int WriteToConnection(void* connection, byte* data, void** dataLength)
{
ulong toWrite = (ulong)*dataLength;
byte* readFrom = data;
lock (_toConnection)
{
while (toWrite > 0)
{
_toConnection.Enqueue(*readFrom);
readFrom++;
toWrite--;
}
}
// Since we can enqueue everything, no need to re-assign *dataLength.
const int noErr = 0;
return noErr;
}
private unsafe int ReadFromConnection(void* connection, byte* data, void** dataLength)
{
const int noErr = 0;
const int errSSLWouldBlock = -9803;
ulong toRead = (ulong)*dataLength;
if (toRead == 0)
{
return noErr;
}
uint transferred = 0;
lock (_fromConnection)
{
if (_fromConnection.Count == 0)
{
*dataLength = (void*)0;
return errSSLWouldBlock;
}
byte* writePos = data;
while (transferred < toRead && _fromConnection.Count > 0)
{
*writePos = _fromConnection.Dequeue();
writePos++;
transferred++;
}
}
*dataLength = (void*)transferred;
return noErr;
}
internal void Write(byte[] buf, int offset, int count)
{
Debug.Assert(buf != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(count <= buf.Length - offset);
lock (_fromConnection)
{
for (int i = 0; i < count; i++)
{
_fromConnection.Enqueue(buf[offset + i]);
}
}
}
internal int BytesReadyForConnection => _toConnection.Count;
internal byte[] ReadPendingWrites()
{
lock (_toConnection)
{
if (_toConnection.Count == 0)
{
return null;
}
byte[] data = _toConnection.ToArray();
_toConnection.Clear();
return data;
}
}
internal int ReadPendingWrites(byte[] buf, int offset, int count)
{
Debug.Assert(buf != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(count <= buf.Length - offset);
lock (_toConnection)
{
int limit = Math.Min(count, _toConnection.Count);
for (int i = 0; i < limit; i++)
{
buf[offset + i] = _toConnection.Dequeue();
}
return limit;
}
}
private static readonly SslProtocols[] s_orderedSslProtocols = new SslProtocols[5]
{
#pragma warning disable 0618
SslProtocols.Ssl2,
SslProtocols.Ssl3,
#pragma warning restore 0618
SslProtocols.Tls,
SslProtocols.Tls11,
SslProtocols.Tls12
};
private static void SetProtocols(SafeSslHandle sslContext, SslProtocols protocols)
{
// A contiguous range of protocols is required. Find the min and max of the range,
// or throw if it's non-contiguous or if no protocols are specified.
// First, mark all of the specified protocols.
SslProtocols[] orderedSslProtocols = s_orderedSslProtocols;
Span<bool> protocolSet = stackalloc bool[orderedSslProtocols.Length];
for (int i = 0; i < orderedSslProtocols.Length; i++)
{
protocolSet[i] = (protocols & orderedSslProtocols[i]) != 0;
}
SslProtocols minProtocolId = (SslProtocols)(-1);
SslProtocols maxProtocolId = (SslProtocols)(-1);
// Loop through them, starting from the lowest.
for (int min = 0; min < protocolSet.Length; min++)
{
if (protocolSet[min])
{
// We found the first one that's set; that's the bottom of the range.
minProtocolId = orderedSslProtocols[min];
// Now loop from there to look for the max of the range.
for (int max = min + 1; max < protocolSet.Length; max++)
{
if (!protocolSet[max])
{
// We found the first one after the min that's not set; the top of the range
// is the one before this (which might be the same as the min).
maxProtocolId = orderedSslProtocols[max - 1];
// Finally, verify that nothing beyond this one is set, as that would be
// a discontiguous set of protocols.
for (int verifyNotSet = max + 1; verifyNotSet < protocolSet.Length; verifyNotSet++)
{
if (protocolSet[verifyNotSet])
{
throw new PlatformNotSupportedException(SR.Format(SR.net_security_sslprotocol_contiguous, protocols));
}
}
break;
}
}
break;
}
}
// If no protocols were set, throw.
if (minProtocolId == (SslProtocols)(-1))
{
throw new PlatformNotSupportedException(SR.net_securityprotocolnotsupported);
}
// If we didn't find an unset protocol after the min, go all the way to the last one.
if (maxProtocolId == (SslProtocols)(-1))
{
maxProtocolId = orderedSslProtocols[orderedSslProtocols.Length - 1];
}
// Finally set this min and max.
Interop.AppleCrypto.SslSetMinProtocolVersion(sslContext, minProtocolId);
Interop.AppleCrypto.SslSetMaxProtocolVersion(sslContext, maxProtocolId);
}
private static void SetCertificate(SafeSslHandle sslContext, X509Certificate2 certificate)
{
Debug.Assert(sslContext != null, "sslContext != null");
Debug.Assert(certificate != null, "certificate != null");
Debug.Assert(certificate.HasPrivateKey, "certificate.HasPrivateKey");
X509Chain chain = TLSCertificateExtensions.BuildNewChain(
certificate,
includeClientApplicationPolicy: false);
using (chain)
{
X509ChainElementCollection elements = chain.ChainElements;
// We need to leave off the EE (first) and root (last) certificate from the intermediates.
X509Certificate2[] intermediateCerts = elements.Count < 3
? Array.Empty<X509Certificate2>()
: new X509Certificate2[elements.Count - 2];
// Build an array which is [
// SecIdentityRef for EE cert,
// SecCertificateRef for intermed0,
// SecCertificateREf for intermed1,
// ...
// ]
IntPtr[] ptrs = new IntPtr[intermediateCerts.Length + 1];
for (int i = 0; i < intermediateCerts.Length; i++)
{
X509Certificate2 intermediateCert = elements[i + 1].Certificate;
if (intermediateCert.HasPrivateKey)
{
// In the unlikely event that we get a certificate with a private key from
// a chain, clear it to the certificate.
//
// The current value of intermediateCert is still in elements, which will
// get Disposed at the end of this method. The new value will be
// in the intermediate certs array, which also gets serially Disposed.
intermediateCert = new X509Certificate2(intermediateCert.RawData);
}
intermediateCerts[i] = intermediateCert;
ptrs[i + 1] = intermediateCert.Handle;
}
ptrs[0] = certificate.Handle;
Interop.AppleCrypto.SslSetCertificate(sslContext, ptrs);
// The X509Chain created all new certs for us, so Dispose them.
// And since the intermediateCerts could have been new instances, Dispose them, too
for (int i = 0; i < elements.Count; i++)
{
elements[i].Certificate.Dispose();
if (i < intermediateCerts.Length)
{
intermediateCerts[i].Dispose();
}
}
}
}
}
}
| |
using Saga.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Saga.Shared.Definitions
{
public class SagaTestException : Exception { }
public delegate void ConsoleCommandHandler(string[] args);
public class ConsoleReader
{
#region Members
public event EventHandler Initialize;
private string _Title = "Server instance";
private SortedDictionary<string, ConsoleCommand> callback = new SortedDictionary<string, ConsoleCommand>();
#endregion Members
#region Constructor / Decontructor
public ConsoleReader()
{
try
{
Register(new ConsoleCommandHandler(Clear));
Register(new ConsoleCommandHandler(Help));
}
catch (SystemException e)
{
System.Diagnostics.Trace.TraceError(e.Message);
}
}
#endregion Constructor / Decontructor
#region Public Properties
public string Title
{
get
{
return _Title;
}
set
{
if (value == null)
_Title = string.Empty;
else
_Title = value;
}
}
#endregion Public Properties
#region Public Methods
[DebuggerNonUserCode()]
private ConsoleCommand CreateConsoleCommand(ConsoleAttribute attribute, ConsoleCommandHandler handler)
{
ConsoleCommand scommand = new ConsoleCommand();
if (attribute != null)
{
scommand.description = attribute.Description;
scommand.syntax = attribute.Syntax;
scommand.mingmlevel = attribute.GmLevel;
scommand.handler = handler;
}
return scommand;
}
[DebuggerNonUserCode()]
public void Register(ConsoleCommandHandler handler)
{
ConsoleCommand scommand;
ConsoleAttribute[] attribute = handler.Method.GetCustomAttributes(typeof(ConsoleAttribute), true) as ConsoleAttribute[];
if (attribute != null && attribute.Length > 0)
{
scommand = CreateConsoleCommand(attribute[0], handler);
callback.Add(attribute[0].Name.ToUpperInvariant(), scommand);
}
else
{
throw new SystemException("Cannot register command: no information found");
}
}
[DebuggerNonUserCode()]
public void Register(string command, ConsoleCommandHandler handler)
{
ConsoleCommand scommand;
ConsoleAttribute[] attribute = handler.Method.GetCustomAttributes(typeof(ConsoleAttribute), true) as ConsoleAttribute[];
if (attribute != null && attribute.Length > 0)
{
scommand = CreateConsoleCommand(attribute[0], handler);
callback.Add(command.ToUpperInvariant(), scommand);
}
else
{
throw new SystemException("Cannot register command: no information found");
}
}
[DebuggerNonUserCode()]
public void Register(string command, string description, ConsoleCommandHandler handler)
{
ConsoleCommand scommand;
ConsoleAttribute[] attribute = handler.Method.GetCustomAttributes(typeof(ConsoleAttribute), true) as ConsoleAttribute[];
if (attribute != null && attribute.Length > 0)
{
scommand = CreateConsoleCommand(attribute[0], handler);
scommand.description = (description == null) ? string.Empty : description;
callback.Add(command.ToUpperInvariant(), scommand);
}
else
{
throw new SystemException("Cannot register command: no information found");
}
}
[DebuggerNonUserCode()]
public void Register(string command, string description, string syntax, ConsoleCommandHandler handler)
{
ConsoleCommand scommand;
ConsoleAttribute[] attribute = handler.Method.GetCustomAttributes(typeof(ConsoleAttribute), true) as ConsoleAttribute[];
if (attribute != null && attribute.Length > 0)
{
scommand = CreateConsoleCommand(attribute[0], handler);
scommand.description = (description == null) ? string.Empty : description;
scommand.syntax = (syntax == null) ? string.Empty : syntax;
callback.Add(command.ToUpperInvariant(), scommand);
}
else
{
throw new SystemException("Cannot register command: no information found");
}
}
public void Start()
{
//Clear(null);
if (Initialize != null) Initialize.Invoke(this, EventArgs.Empty);
Read();
}
#endregion Public Methods
#region Private Methods
[DebuggerNonUserCode()]
private string[] DelemitedString(string mystring)
{
List<String> stringlist = new List<string>();
StringBuilder builder = new StringBuilder();
bool NextSpecial = false;
bool QuoteOpen = false;
for (int i = 0; i < mystring.Length; i++)
{
char current = mystring[i];
if (NextSpecial == false)
{
switch (current)
{
case ' ':
if (QuoteOpen == false)
{
stringlist.Add(builder.ToString());
builder = new StringBuilder();
}
else
{
builder.Append(current);
}
break;
case '\\':
NextSpecial = true;
break;
case '"':
QuoteOpen ^= true;
break;
default:
builder.Append(current);
break;
}
}
else
{
NextSpecial = false;
switch (current)
{
case ' ':
if (QuoteOpen == false)
{
stringlist.Add(builder.ToString());
builder = new StringBuilder();
}
else
{
builder.Append(current);
}
break;
case '"':
builder.Append(current);
break;
default:
builder.Append('\\');
builder.Append(current);
break;
}
}
}
stringlist.Add(builder.ToString());
return stringlist.ToArray();
}
[DebuggerNonUserCode()]
private void Read()
{
try
{
while (Environment.HasShutdownStarted == false)
{
string command = Console.ReadLine();
DoString(command);
}
}
catch (Exception e)
{
if (e is SagaTestException)
throw e;
//Excpeption don't process
}
}
[DebuggerNonUserCode()]
private void DoString(string command)
{
ConsoleCommand handler;
string[] commands = DelemitedString(command);
if (command.Length > 0 && commands.Length > 0)
if (!callback.TryGetValue(commands[0].ToUpperInvariant(), out handler))
{
Console.WriteLine("Command does not exists");
}
else
{
try
{
if (handler.handler != null)
handler.handler.Invoke(commands);
}
catch (Exception e)
{
if (e is SagaTestException)
throw e;
Console.WriteLine("Command did not execute it had errors");
System.Diagnostics.Trace.TraceError(e.ToString());
}
}
}
#endregion Private Methods
#region Nested Classes/Structures
protected class ConsoleCommand
{
public string description;
public string syntax;
public int mingmlevel;
public ConsoleCommandHandler handler;
}
#endregion Nested Classes/Structures
#region Built-in
[ConsoleAttribute("Clear", "Clears the console")]
public void Clear(string[] args)
{
Console.Clear();
Console.Write(Resource.AsciiHeader);
Console.WriteLine(Title);
}
[ConsoleAttribute("Help", "Lists all available commands")]
public void Help(string[] args)
{
if (args.Length == 1)
{
Console.WriteLine();
Console.WriteLine("List of available commands:");
foreach (string a in callback.Keys)
{
Console.WriteLine(" {0}", a.ToLower());
}
}
else if (args.Length == 2)
{
ConsoleCommand command;
if (callback.TryGetValue(args[1].Trim(' ', '\0').ToUpperInvariant(), out command))
{
Console.WriteLine();
Console.WriteLine("Name: {0}", args[1].ToLower());
Console.WriteLine("Description: {0}", command.description);
Console.WriteLine("Syntax: {0}", command.syntax);
Console.WriteLine();
}
else
{
Console.WriteLine("Command not found");
}
}
else
{
Console.WriteLine("Invalid argument for comamnd");
}
}
#endregion Built-in
}
}
| |
namespace Epi
{
/// <summary>
/// String constants for various commands
/// </summary>
public static class CommandNames
{
/// <summary>
/// ABS absolute value numeric function
/// </summary>
public const string ABS = "ABS";
/// <summary>
/// AND logical operator
/// </summary>
public const string AND = "AND";
/// <summary>
/// ALWAYS key word used with AUTOSEARCH command to run search on existing records as well as new.
/// </summary>
public const string ALWAYS = "ALWAYS";
/// <summary>
/// Append data when exporting
/// </summary>
public const string APPEND = "APPEND";
/// <summary>
/// Sort data in descending order
/// </summary>
public const string ASCENDING = "ASCENDING";
/// <summary>
/// Assign a value or the result of an expression to a defined variable
/// </summary>
///
public const string ASSIGN = "ASSIGN";
/// <summary>
/// Autosearches particular field(s)
/// </summary>
public const string AUTOSEARCH = "AUTOSEARCH";
/// <summary>
/// Generate a beep
/// </summary>
public const string BEEP = "BEEP";
/// <summary>
/// Calls a definded sub-routine
/// </summary>
public const string CALL = "CALL";
/// <summary>
/// Cancels the current select command
/// </summary>
public const string CANCELSELECT = "SELECT";
/// <summary>
/// Cancels the current sort command
/// </summary>
public const string CANCELSORT = "SORT";
/// <summary>
/// Clears a field(s)
/// </summary>
public const string CLEAR = "CLEAR";
/// <summary>
/// Stops routing the current output to the specified output file
/// </summary>
public const string CLOSEOUT = "CLOSEOUT";
/// <summary>
/// Column size for output of analysis command tables.
/// </summary>
public const string COLUMNSIZE = "COLUMNSIZE";
/// <summary>
/// CONTINUENEW key word used with AUTOSEARCH command to prevent user from moving to matching record.
/// </summary>
public const string CONTINUENEW = "CONTINUENEW";
/// <summary>
/// COS numeric function
/// </summary>
public const string COS = "COS";
/// <summary>
/// Cox Proportional Hazards
/// </summary>
public const string COXPH = "COXPH";
/// <summary>
/// Currency parameter of FORMAT function
/// </summary>
public const string CURRENCY_FORMAT = "\"Currency\"";
/// <summary>
/// System function returning the Current User signed in
/// </summary>
public const string CURRENTUSER = "CURRENTUSER";
/// <summary>
/// Dialog format Database list
/// </summary>
public const string DATABASES = "DATABASES";
/// <summary>
/// DAY date function
/// </summary>
public const string DAY = "DAY";
/// <summary>
/// DAYS date function
/// </summary>
public const string DAYS = "DAYS";
/// <summary>
/// Used in Dialog command
/// </summary>
public const string DBVALUES = "DBVALUES";
/// <summary>
/// Display database variables
/// </summary>
public const string DBVARIABLES = "DBVARIABLES";
/// <summary>
/// Dialog format Views list and Display Views
/// </summary>
public const string DBVIEWS = "DBVIEWS";
/// <summary>
/// Sort data in descending order
/// </summary>
public const string DESCENDING = "DESCENDING";
/// <summary>
/// Define a variable of standard, global or permanent scope
/// </summary>
public const string DEFINE = "DEFINE";
/// <summary>
/// Delete table, file or records
/// </summary>
public const string DELETE = "DELETE";
/// <summary>
/// Creates a dialog box
/// </summary>
public const string DIALOG = "DIALOG";
/// <summary>
/// Command to disable a field
/// </summary>
public const string DISABLE = "DISABLE";
/// <summary>
/// Command to send the current output file to the default Display
/// </summary>
public const string DISPLAY = "DISPLAY";
/// <summary>
/// Command to display only selected fields in AUTOSEARCH results; Used with AUTOSEARCH command
/// </summary>
public const string DISPLAYLIST = "DISPLAYLIST";
/// <summary>
/// Else of If command
/// </summary>
public const string ELSE = "ELSE";
/// <summary>
/// Command to enable a field
/// </summary>
public const string ENABLE = "ENABLE";
/// <summary>
/// End of If command
/// </summary>
public const string END = "END";
/// <summary>
/// ENVIRON system function
/// </summary>
public const string ENVIRON = "ENVIRON";
/// <summary>
/// EPIWEEK date function
/// </summary>
public const string EPIWEEK = "EPIWEEK";
/// <summary>
/// Columns excluded from the List command
/// </summary>
public const string EXCEPT = "EXCEPT";
/// <summary>
/// Executes a program
/// </summary>
public const string EXECUTE = "EXECUTE";
/// <summary>
/// EXISTS system function
/// </summary>
public const string EXISTS = "EXISTS";
/// <summary>
/// Exits Analysis
/// </summary>
public const string EXIT = "EXIT";
/// <summary>
/// EXP exponentiation numeric function
/// </summary>
public const string EXP = "EXP";
/// <summary>
/// FIELDVAR, used is DISPLAY DBVARIABLES
/// </summary>
public const string FIELDVAR = "FIELDVAR";
/// <summary>
/// FILEDATE system function
/// </summary>
public const string FILEDATE = "FILEDATE";
/// <summary>
/// FINDTEXT text function
/// </summary>
public const string FINDTEXT = "FINDTEXT";
/// <summary>
/// Fixed parameter of FORMAT function
/// </summary>
public const string FIXED_FORMAT = "\"Fixed\"";
/// <summary>
/// Computes the frequency of any column(s) in the current dataset or a user defined standard variable(s)
/// </summary>
public const string FREQ = "FREQ";
/// <summary>
/// Frequency Graph Command
/// </summary>
public const string FREQGRAPH = "FREQGRAPH";
/// <summary>
/// FORMAT text function
/// </summary>
public const string FORMAT = "FORMAT";
/// <summary>
/// General Date parameter of FORMAT function
/// </summary>
public const string GENERAL_DATE_FORMAT = "\"General Date\"";
/// <summary>
/// General Number parameter of FORMAT function
/// </summary>
public const string GENERAL_NUMBER_FORMAT = "\"General Number\"";
/// <summary>
/// Sets the focus on a page, field or new record
/// </summary>
public const string GOTO = "GOTO";
/// <summary>
/// Goes to Relate Form
/// </summary>
public const string GOTOFORM = "GOTOFORM";
/// <summary>
/// <summary>
/// </summary>
public const string GRAPH = "GRAPH";
/// <summary>
/// Type of graph to be displayed following CoxPH, KMSurvival, etc.
/// </summary>
public const string GRAPHTYPE = "GRAPHTYPE";
/// <summary>
/// Data is displayed as a grid in the List command
/// </summary>
public const string GRIDTABLE = "GRIDTABLE";
/// <summary>
/// Constant for "Define Group" Command
/// </summary>
public const string GROUPVAR = "GROUPVAR";
/// <summary>
/// Creates a header in the output .HTM document
/// </summary>
public const string HEADER = "HEADER";
/// <summary>
/// Opens a .HTM or .CHM help document
/// </summary>
public const string HELP = "HELP";
/// <summary>
/// Hides field(s)
/// </summary>
public const string HIDE = "HIDE";
/// <summary>
/// Highlight a field
/// </summary>
public const string HIGHLIGHT = "HIGHLIGHT";
/// <summary>
/// Highest value
/// </summary>
public const string HIVALUE = "HIVALUE";
/// <summary>
/// HOUR time function
/// </summary>
public const string HOUR = "HOUR";
/// <summary>
/// HOURS time function
/// </summary>
public const string HOURS = "HOURS";
/// <summary>
/// Hyperlinks Command
/// </summary>
public const string HYPERLINKS = "HYPERLINKS";
/// <summary>
/// Perform a command or a set of commands conditionally
/// </summary>
public const string IF = "IF";
/// <summary>
/// Perform a command or a set of commands conditionally
/// </summary>
public const string ISUNIQUE = "ISUNIQUE";
/// <summary>
/// Kaplan-Meier Survival
/// </summary>
public const string KMSURVIVAL = "KMSURVIVAL";
/// <summary>
/// String comparison operator LIKE that compares strings that have LIKE wildcard characters (*).
/// </summary>
public const string LIKE = "LIKE";
/// <summary>
/// Line Break text function
/// </summary>
public const string LINEBREAK = "LINEBREAK";
/// <summary>
/// Lists values of column(s) or user defined standard variable(s) in the current dataset
/// </summary>
public const string LIST = "LIST";
/// <summary>
/// LN (natural log) numeric function
/// </summary>
public const string LN = "LN";
/// <summary>
/// LOG (decimal log) numeric function
/// </summary>
public const string LOG = "LOG";
/// <summary>
/// Logistic regression command
/// </summary>
public const string LOGISTIC = "LOGISTIC";
/// <summary>
/// Long Date parameter of FORMAT function
/// </summary>
public const string LONG_DATE_FORMAT = "\"Long Date\"";
/// <summary>
/// Long Time parameter of FORMAT function
/// </summary>
public const string LONG_TIME_FORMAT = "\"Long Time\"";
/// <summary>
/// Lowest value
/// </summary>
public const string LOVALUE = "LOVALUE";
/// <summary>
/// Performs a matched analysis of specified exposure and outcome variables
/// </summary>
public const string MATCH = "MATCH";
/// <summary>
/// Matched analysis
/// </summary>
public const string MATCHVAR = "MATCHVAR";
/// <summary>
/// Means command
/// </summary>
public const string MEANS = "MEANS";
/// <summary>
/// Merge command
/// </summary>
public const string MERGE = "MERGE";
/// <summary>
/// MINUTE time function
/// </summary>
public const string MINUTE = "MINUTE";
/// <summary>
/// MINUTES time function
/// </summary>
public const string MINUTES = "MINUTES";
/// <summary>
/// Missing command
/// </summary>
public const string MISSING = "MISSING";
/// <summary>
/// MOD function (modulus or remainder)
/// </summary>
public const string MOD = "MOD";
/// <summary>
/// MONTH date function
/// </summary>
public const string MONTH = "MONTH";
/// <summary>
/// MONTHS date function
/// </summary>
public const string MONTHS = "MONTHS";
/// <summary>
/// Creates a new record
/// </summary>
public const string NEWRECORD = "NEWRECORD";
/// <summary>
/// No Intercept in Logistic Regression
/// </summary>
public const string NOINTERCEPT = "NOINTERCEPT";
/// <summary>
/// NOT logical operator
/// </summary>
public const string NOT = "NOT";
/// <summary>
/// Do not wait for program to exit
/// </summary>
public const string NOWAITFOREXIT = "NOWAITFOREXIT";
/// <summary>
/// Prevents line breaks from being inserted in Analysis output so columns as wide as longest line.
/// </summary>
public const string NOWRAP = "NOWRAP";
/// <summary>
/// NUMTODATE numeric function
/// </summary>
public const string NUMTODATE = "NUMTODATE";
/// <summary>
/// NUMTOTIME numeric function
/// </summary>
public const string NUMTOTIME = "NUMTOTIME";
/// <summary>
/// On/Off parameter of FORMAT function
/// </summary>
public const string ON_OFF_FORMAT = "\"On/Off\"";
/// <summary>
/// OR logical operator
/// </summary>
public const string OR = "OR";
/// <summary>
/// for specifying the output 'table'
/// </summary>
public const string OUTTABLE = "OUTTABLE";
/// <summary>
/// Percent number parameter of FORMAT function
/// </summary>
public const string PERCENT_FORMAT = "\"Percent\"";
/// <summary>
/// Percents command
/// </summary>
public const string PERCENTS = "PERCENTS";
/// <summary>
/// Scope of the defined variable is permanent
/// </summary>
public const string PERMANENT = "PERMANENT";
/// <summary>
/// Command to calculate the P value from the Z-score
/// </summary>
public const string PFROMZ = "PFROMZ";
/// <summary>
/// Command to send the current output file to the default printer
/// </summary>
public const string PRINTOUT = "PRINTOUT";
/// <summary>
/// For SET PROCESS = (undeleted, deleted, both) records.
/// </summary>
public const string PROCESS = "PROCESS";
/// <summary>
/// Variable for the Primary Sampling Unit (PSU) in Complex Sample commands.
/// </summary>
public const string PSUVAR = "PSUVAR";
/// <summary>
/// Variable for the Primary Sampling Unit (PSU) in Complex Sample commands.
/// </summary>
public const string PVALUE = "PVALUE";
/// <summary>
/// Command to exit Analysis module
/// </summary>
public const string QUIT = "QUIT";
/// <summary>
/// Command to read project data from an Access 97, Access 2000, SQL Server 2000 or MSDE 2000 database
/// </summary>
public const string READ = "READ";
/// <summary>
/// Translates data in a column or a standard variable to another column or standard variable
/// </summary>
public const string RECODE = "RECODE";
/// <summary>
/// Command to return the current count of saved records (not counting * new record)
/// </summary>
public const string RECORDCOUNT = "RECORDCOUNT";
/// <summary>
/// Linear regression command
/// </summary>
public const string REGRESS = "REGRESS";
/// <summary>
/// Replaces an existing output file or an output table while exporting data
/// </summary>
public const string REPLACE = "REPLACE";
/// <summary>
/// Join tables.
/// </summary>
public const string RELATE = "RELATE";
/// <summary>
/// RND (random) numeric function
/// </summary>
public const string RND = "RND";
/// <summary>
/// Report command keyword
/// </summary>
public const string REPORT = "REPORT";
/// <summary>
/// ROUND numeric function
/// </summary>
public const string ROUND = "ROUND";
/// <remarks>If no output is selected Epi Info will create a new file with a sequential number.</remarks>
/// <example>ROUTEOUT 'D:\EPIInfo\Monthly_Report.htm' REPLACE</example>
/// </summary>
public const string ROUTEOUT = "ROUTEOUT";
/// <summary>
/// Runs an existing program
/// </summary>
public const string RUNPGM = "RUNPGM";
/// <summary>
/// No confirmatory messages will be displayed
/// </summary>
public const string RUNSILENT = "RUNSILENT";
/// <summary>
/// Data tables will not be deleted
/// </summary>
public const string SAVEDATA = "SAVEDATA";
/// <summary>
/// Scientific number parameter of FORMAT function
/// </summary>
public const string SCIENTIFIC_FORMAT = "\"Scientific\"";
/// <summary>
/// SECOND time function
/// </summary>
public const string SECOND = "SECOND";
/// <summary>
/// SECONDS time function
/// </summary>
public const string SECONDS = "SECONDS";
/// <summary>
/// Selects only the records that match the specified expression
/// </summary>
public const string SELECT = "SELECT";
/// <summary>
/// Sets various options that affect the performance and output of Analysis
/// </summary>
public const string SET = "SET";
/// <summary>
/// Sets the attribute required = true for one or more fields in Check Code.
/// </summary>
public const string SET_REQUIRED = "SET-REQUIRED";
/// <summary>
/// Sets the attribute required = false for one or more fields in Check Code.
/// </summary>
public const string SET_NOT_REQUIRED = "SET-NOT-REQUIRED";
/// <summary>
/// Short Date parameter of FORMAT function
/// </summary>
public const string SHORT_DATE_FORMAT = "\"Short Date\"";
/// <summary>
/// Short Time parameter of FORMAT function
/// </summary>
public const string SHORT_TIME_FORMAT = "\"Short Time\"";
/// <summary>
/// Show prompts command
/// </summary>
public const string SHOWPROMPTS = "SHOWPROMPTS";
/// <summary>
/// SIN numeric function
/// </summary>
public const string SIN = "SIN";
/// <summary>
/// Sorts the data in the current dataset by columns or variables and sort order specified
/// </summary>
public const string SORT = "SORT";
/// <summary>
/// Standard number parameter of FORMAT function
/// </summary>
public const string STANDARD_FORMAT = "\"Standard\"";
/// <summary>
/// Statistics Command
/// </summary>
public const string STATISTICS = "STATISTICS";
/// <summary>
/// Step Command
/// </summary>
public const string STEP = "STEP";
/// <summary>
/// Stratify by the variable
/// </summary>
public const string STRATAVAR = "STRATAVAR";
///<summary>
/// STRLEN text function
///</summary>
public const string STRLEN = "STRLEN";
///<summary>
/// SUBSTRING text function
///</summary>
public const string SUBSTRING = "SUBSTRING";
/// <summary>
/// Computes the aggregates of a column in the current dataset or a standard variable
/// </summary>
public const string SUMMARIZE = "SUMMARIZE";
/// <summary>
/// SYSBARCODE system function
/// </summary>
public const string SYSBARCODE = "SYSBARCODE";
/// <summary>
/// SYSALTITUDE system function
/// </summary>
public const string SYSALTITUDE = "SYSALTITUDE";
/// <summary>
/// SYSLATITUDE system function
/// </summary>
public const string SYSLATITUDE = "SYSLATITUDE";
/// <summary>
/// SYSLONGITUDE system function
/// </summary>
public const string SYSLONGITUDE = "SYSLONGITUDE";
/// <summary>
/// SYSTEMDATE system function
/// </summary>
public const string SYSTEMDATE = "SYSTEMDATE";
/// <summary>
/// SYSTEMTIME system function
/// </summary>
public const string SYSTEMTIME = "SYSTEMTIME";
/// FIRSTSAVETIME system function
/// </summary>
/// --123
public const string FIRSTSAVETIME = "FIRSTSAVETIME";
///LASTSAVETIME system function
/// </summary>
public const string LASTSAVETIME = "LASTSAVETIME";
//---
/// <summary>
/// Performs a cross-tabulation of the specified exposure and outcome variables
/// </summary>
public const string TABLES = "TABLES";
/// <summary>
/// TAN numeric function
/// </summary>
public const string TAN = "TAN";
/// <summary>
/// A dialogs title text
/// </summary>
public const string TITLETEXT = "TITLETEXT";
/// <summary>
/// TYPEOUT Command font modifier.
/// </summary>
public const string TEXTFONT = "TEXTFONT";
/// <summary>
/// The THEN Command
/// </summary>
public const string THEN = "THEN";
/// <summary>
/// Unit of time used for graphs following CoxPH, KMSurvival, etc.
/// </summary>
public const string TIMEUNIT = "TIMEUNIT";
/// <summary>
/// In Summarize command, the table to which output is written
/// </summary>
public const string TO = "TO";
/// <summary>
/// True/False parameter of FORMAT function
/// </summary>
public const string TRUE_FALSE_FORMAT = "\"True/False\"";
/// <summary>
/// TRUNC (truncate) numeric function
/// </summary>
public const string TRUNC = "TRUNC";
/// <summary>
/// The TYPEOUT Command inserts text, either a string or the
/// contents of a file, into the output.
/// <remarks>Typical uses might include comments or boilerplate.</remarks>
/// <example>TYPEOUT 'My Fancy Logo.htm'</example>
/// </summary>
public const string TYPEOUT = "TYPEOUT";
/// <summary>
/// TXTTODATE text function
/// </summary>
public const string TXTTODATE = "TXTTODATE";
/// <summary>
/// TXTTONUM text function
/// </summary>
public const string TXTTONUM = "TXTTONUM";
/// <summary>
/// Undefine a defined variable
/// </summary>
public const string UNDEFINE = "UNDEFINE";
/// <summary>
/// Undelete records that were marked as deleted
/// </summary>
public const string UNDELETE = "UNDELETE";
/// <summary>
/// Unhide field(s)
/// </summary>
public const string UNHIDE = "UNHIDE";
/// <summary>
/// Unhighlight a field
/// </summary>
public const string UNHIGHLIGHT = "UNHIGHLIGHT";
/// <summary>
/// Allows update of data in the List command
/// </summary>
public const string UPDATE = "UPDATE";
/// <summary>
/// UPPERCASE text function
/// </summary>
public const string UPPERCASE = "UPPERCASE";
/// <summary>
/// Wait for program to exit
/// </summary>
public const string WAITFOREXIT = "WAITFOREXIT";
/// <summary>
/// Weight variable
/// </summary>
public const string WEIGHTVAR = "WEIGHTVAR";
/// <summary>
/// Export the data to an output table in the current project or a different project
/// </summary>
public const string WRITE = "WRITE";
/// <summary>
/// XOR--exclusive OR logical operator
/// </summary>
public const string XOR = "XOR";
/// <summary>
/// Yes/No number parameter of FORMAT function
/// </summary>
public const string YESNO_FORMAT = "\"Yes/No\"";
/// <summary>
/// A dialog format in Dialog command
/// </summary>
public const string YN = "YN";
/// <summary>
/// YEAR date function
/// </summary>
public const string YEAR = "YEAR";
/// <summary>
/// YEARS date function
/// </summary>
public const string YEARS = "YEARS";
/// <summary>
/// ZSCORE numeric function
/// </summary>
public const string ZSCORE = "ZSCORE";
/// <summary>
/// FieldSelector Display
/// </summary>
public const string FieldSelector = "FieldSelector";
}
}
| |
/*
* 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 Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.CoreModules.Framework;
using OpenSim.Region.CoreModules.Framework.EntityTransfer;
using OpenSim.Region.CoreModules.Framework.InventoryAccess;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.XEngine;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Xml;
namespace OpenSim.Region.CoreModules.Avatar.Attachments.Tests
{
/// <summary>
/// Attachment tests
/// </summary>
[TestFixture]
public class AttachmentsModuleTests : OpenSimTestCase
{
private AutoResetEvent m_chatEvent = new AutoResetEvent(false);
// private OSChatMessage m_osChatMessageReceived;
// Used to test whether the operations have fired the attach event. Must be reset after each test.
private int m_numberOfAttachEventsFired;
[TestFixtureSetUp]
public void FixtureInit()
{
// Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread.
Util.FireAndForgetMethod = FireAndForgetMethod.None;
}
[TestFixtureTearDown]
public void TearDown()
{
// We must set this back afterwards, otherwise later tests will fail since they're expecting multiple
// threads. Possibly, later tests should be rewritten not to worry about such things.
Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod;
}
private void OnChatFromWorld(object sender, OSChatMessage oscm)
{
// Console.WriteLine("Got chat [{0}]", oscm.Message);
// m_osChatMessageReceived = oscm;
m_chatEvent.Set();
}
private Scene CreateTestScene()
{
IConfigSource config = new IniConfigSource();
List<object> modules = new List<object>();
AddCommonConfig(config, modules);
Scene scene
= new SceneHelpers().SetupScene(
"attachments-test-scene", TestHelpers.ParseTail(999), 1000, 1000, config);
SceneHelpers.SetupSceneModules(scene, config, modules.ToArray());
scene.EventManager.OnAttach += (localID, itemID, avatarID) => m_numberOfAttachEventsFired++;
return scene;
}
private Scene CreateScriptingEnabledTestScene()
{
IConfigSource config = new IniConfigSource();
List<object> modules = new List<object>();
AddCommonConfig(config, modules);
AddScriptingConfig(config, modules);
Scene scene
= new SceneHelpers().SetupScene(
"attachments-test-scene", TestHelpers.ParseTail(999), 1000, 1000, config);
SceneHelpers.SetupSceneModules(scene, config, modules.ToArray());
scene.StartScripts();
return scene;
}
private void AddCommonConfig(IConfigSource config, List<object> modules)
{
config.AddConfig("Modules");
config.Configs["Modules"].Set("InventoryAccessModule", "BasicInventoryAccessModule");
AttachmentsModule attMod = new AttachmentsModule();
attMod.DebugLevel = 1;
modules.Add(attMod);
modules.Add(new BasicInventoryAccessModule());
}
private void AddScriptingConfig(IConfigSource config, List<object> modules)
{
IConfig startupConfig = config.AddConfig("Startup");
startupConfig.Set("DefaultScriptEngine", "XEngine");
IConfig xEngineConfig = config.AddConfig("XEngine");
xEngineConfig.Set("Enabled", "true");
xEngineConfig.Set("StartDelay", "0");
// These tests will not run with AppDomainLoading = true, at least on mono. For unknown reasons, the call
// to AssemblyResolver.OnAssemblyResolve fails.
xEngineConfig.Set("AppDomainLoading", "false");
modules.Add(new XEngine());
// Necessary to stop serialization complaining
// FIXME: Stop this being necessary if at all possible
// modules.Add(new WorldCommModule());
}
/// <summary>
/// Creates an attachment item in the given user's inventory. Does not attach.
/// </summary>
/// <remarks>
/// A user with the given ID and an inventory must already exist.
/// </remarks>
/// <returns>
/// The attachment item.
/// </returns>
/// <param name='scene'></param>
/// <param name='userId'></param>
/// <param name='attName'></param>
/// <param name='rawItemId'></param>
/// <param name='rawAssetId'></param>
private InventoryItemBase CreateAttachmentItem(
Scene scene, UUID userId, string attName, int rawItemId, int rawAssetId)
{
return UserInventoryHelpers.CreateInventoryItem(
scene,
attName,
TestHelpers.ParseTail(rawItemId),
TestHelpers.ParseTail(rawAssetId),
userId,
InventoryType.Object);
}
[Test]
public void TestAddAttachmentFromGround()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
m_numberOfAttachEventsFired = 0;
Scene scene = CreateTestScene();
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1);
string attName = "att";
SceneObjectGroup so = SceneHelpers.AddSceneObject(scene, attName, sp.UUID);
m_numberOfAttachEventsFired = 0;
scene.AttachmentsModule.AttachObject(sp, so, (uint)AttachmentPoint.Chest, false, true, false);
// Check status on scene presence
Assert.That(sp.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments[0];
Assert.That(attSo.Name, Is.EqualTo(attName));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.Chest));
Assert.That(attSo.IsAttachment);
Assert.That(attSo.UsesPhysics, Is.False);
Assert.That(attSo.IsTemporary, Is.False);
// Check item status
Assert.That(
sp.Appearance.GetAttachpoint(attSo.FromItemID),
Is.EqualTo((int)AttachmentPoint.Chest));
InventoryItemBase attachmentItem = scene.InventoryService.GetItem(new InventoryItemBase(attSo.FromItemID));
Assert.That(attachmentItem, Is.Not.Null);
Assert.That(attachmentItem.Name, Is.EqualTo(attName));
InventoryFolderBase targetFolder = scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object);
Assert.That(attachmentItem.Folder, Is.EqualTo(targetFolder.ID));
Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1));
}
[Test]
public void TestWearAttachmentFromGround()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
Scene scene = CreateTestScene();
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1);
SceneObjectGroup so2 = SceneHelpers.AddSceneObject(scene, "att2", sp.UUID);
{
SceneObjectGroup so = SceneHelpers.AddSceneObject(scene, "att1", sp.UUID);
m_numberOfAttachEventsFired = 0;
scene.AttachmentsModule.AttachObject(sp, so, (uint)AttachmentPoint.Default, false, true, false);
// Check status on scene presence
Assert.That(sp.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments[0];
Assert.That(attSo.Name, Is.EqualTo(so.Name));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand));
Assert.That(attSo.IsAttachment);
Assert.That(attSo.UsesPhysics, Is.False);
Assert.That(attSo.IsTemporary, Is.False);
// Check item status
Assert.That(
sp.Appearance.GetAttachpoint(attSo.FromItemID),
Is.EqualTo((int)AttachmentPoint.LeftHand));
InventoryItemBase attachmentItem = scene.InventoryService.GetItem(new InventoryItemBase(attSo.FromItemID));
Assert.That(attachmentItem, Is.Not.Null);
Assert.That(attachmentItem.Name, Is.EqualTo(so.Name));
InventoryFolderBase targetFolder = scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object);
Assert.That(attachmentItem.Folder, Is.EqualTo(targetFolder.ID));
Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(2));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1));
}
// Test wearing a different attachment from the ground.
{
scene.AttachmentsModule.AttachObject(sp, so2, (uint)AttachmentPoint.Default, false, true, false);
// Check status on scene presence
Assert.That(sp.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments[0];
Assert.That(attSo.Name, Is.EqualTo(so2.Name));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand));
Assert.That(attSo.IsAttachment);
Assert.That(attSo.UsesPhysics, Is.False);
Assert.That(attSo.IsTemporary, Is.False);
// Check item status
Assert.That(
sp.Appearance.GetAttachpoint(attSo.FromItemID),
Is.EqualTo((int)AttachmentPoint.LeftHand));
InventoryItemBase attachmentItem = scene.InventoryService.GetItem(new InventoryItemBase(attSo.FromItemID));
Assert.That(attachmentItem, Is.Not.Null);
Assert.That(attachmentItem.Name, Is.EqualTo(so2.Name));
InventoryFolderBase targetFolder = scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object);
Assert.That(attachmentItem.Folder, Is.EqualTo(targetFolder.ID));
Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(3));
}
// Test rewearing an already worn attachment from ground. Nothing should happen.
{
scene.AttachmentsModule.AttachObject(sp, so2, (uint)AttachmentPoint.Default, false, true, false);
// Check status on scene presence
Assert.That(sp.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments[0];
Assert.That(attSo.Name, Is.EqualTo(so2.Name));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand));
Assert.That(attSo.IsAttachment);
Assert.That(attSo.UsesPhysics, Is.False);
Assert.That(attSo.IsTemporary, Is.False);
// Check item status
Assert.That(
sp.Appearance.GetAttachpoint(attSo.FromItemID),
Is.EqualTo((int)AttachmentPoint.LeftHand));
InventoryItemBase attachmentItem = scene.InventoryService.GetItem(new InventoryItemBase(attSo.FromItemID));
Assert.That(attachmentItem, Is.Not.Null);
Assert.That(attachmentItem.Name, Is.EqualTo(so2.Name));
InventoryFolderBase targetFolder = scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object);
Assert.That(attachmentItem.Folder, Is.EqualTo(targetFolder.ID));
Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(3));
}
}
/// <summary>
/// Test that we do not attempt to attach an in-world object that someone else is sitting on.
/// </summary>
[Test]
public void TestAddSatOnAttachmentFromGround()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
m_numberOfAttachEventsFired = 0;
Scene scene = CreateTestScene();
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1);
string attName = "att";
SceneObjectGroup so = SceneHelpers.AddSceneObject(scene, attName, sp.UUID);
UserAccount ua2 = UserAccountHelpers.CreateUserWithInventory(scene, 0x2);
ScenePresence sp2 = SceneHelpers.AddScenePresence(scene, ua2);
// Put avatar within 10m of the prim so that sit doesn't fail.
sp2.AbsolutePosition = new Vector3(0, 0, 0);
sp2.HandleAgentRequestSit(sp2.ControllingClient, sp2.UUID, so.UUID, Vector3.Zero);
scene.AttachmentsModule.AttachObject(sp, so, (uint)AttachmentPoint.Chest, false, true, false);
Assert.That(sp.HasAttachments(), Is.False);
Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(0));
}
[Test]
public void TestRezAttachmentFromInventory()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
Scene scene = CreateTestScene();
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1.PrincipalID);
InventoryItemBase attItem = CreateAttachmentItem(scene, ua1.PrincipalID, "att", 0x10, 0x20);
{
scene.AttachmentsModule.RezSingleAttachmentFromInventory(
sp, attItem.ID, (uint)AttachmentPoint.Chest);
// Check scene presence status
Assert.That(sp.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments[0];
Assert.That(attSo.Name, Is.EqualTo(attItem.Name));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.Chest));
Assert.That(attSo.IsAttachment);
Assert.That(attSo.UsesPhysics, Is.False);
Assert.That(attSo.IsTemporary, Is.False);
// Check appearance status
Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1));
Assert.That(sp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));
Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1));
}
// Test attaching an already attached attachment
{
scene.AttachmentsModule.RezSingleAttachmentFromInventory(
sp, attItem.ID, (uint)AttachmentPoint.Chest);
// Check scene presence status
Assert.That(sp.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments[0];
Assert.That(attSo.Name, Is.EqualTo(attItem.Name));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.Chest));
Assert.That(attSo.IsAttachment);
Assert.That(attSo.UsesPhysics, Is.False);
Assert.That(attSo.IsTemporary, Is.False);
// Check appearance status
Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1));
Assert.That(sp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));
Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1));
}
}
/// <summary>
/// Test wearing an attachment from inventory, as opposed to explicit choosing the rez point
/// </summary>
[Test]
public void TestWearAttachmentFromInventory()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
Scene scene = CreateTestScene();
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1.PrincipalID);
InventoryItemBase attItem1 = CreateAttachmentItem(scene, ua1.PrincipalID, "att1", 0x10, 0x20);
InventoryItemBase attItem2 = CreateAttachmentItem(scene, ua1.PrincipalID, "att2", 0x11, 0x21);
{
m_numberOfAttachEventsFired = 0;
scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, attItem1.ID, (uint)AttachmentPoint.Default);
// default attachment point is currently the left hand.
Assert.That(sp.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments[0];
Assert.That(attSo.Name, Is.EqualTo(attItem1.Name));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand));
Assert.That(attSo.IsAttachment);
// Check appearance status
Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1));
Assert.That(sp.Appearance.GetAttachpoint(attItem1.ID), Is.EqualTo((int)AttachmentPoint.LeftHand));
Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1));
}
// Test wearing a second attachment at the same position
// Until multiple attachments at one point is implemented, this will remove the first attachment
// This test relies on both attachments having the same default attachment point (in this case LeftHand
// since none other has been set).
{
scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, attItem2.ID, (uint)AttachmentPoint.Default);
// default attachment point is currently the left hand.
Assert.That(sp.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments[0];
Assert.That(attSo.Name, Is.EqualTo(attItem2.Name));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand));
Assert.That(attSo.IsAttachment);
// Check appearance status
Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1));
Assert.That(sp.Appearance.GetAttachpoint(attItem2.ID), Is.EqualTo((int)AttachmentPoint.LeftHand));
Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(3));
}
// Test wearing an already attached attachment
{
scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, attItem2.ID, (uint)AttachmentPoint.Default);
// default attachment point is currently the left hand.
Assert.That(sp.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments[0];
Assert.That(attSo.Name, Is.EqualTo(attItem2.Name));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand));
Assert.That(attSo.IsAttachment);
// Check appearance status
Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1));
Assert.That(sp.Appearance.GetAttachpoint(attItem2.ID), Is.EqualTo((int)AttachmentPoint.LeftHand));
Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(3));
}
}
/// <summary>
/// Test specific conditions associated with rezzing a scripted attachment from inventory.
/// </summary>
[Test]
public void TestRezScriptedAttachmentFromInventory()
{
TestHelpers.InMethod();
Scene scene = CreateScriptingEnabledTestScene();
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1);
SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, sp.UUID, "att-name", 0x10);
TaskInventoryItem scriptItem
= TaskInventoryHelpers.AddScript(
scene,
so.RootPart,
"scriptItem",
"default { attach(key id) { if (id != NULL_KEY) { llSay(0, \"Hello World\"); } } }");
InventoryItemBase userItem = UserInventoryHelpers.AddInventoryItem(scene, so, 0x100, 0x1000);
// FIXME: Right now, we have to do a tricksy chat listen to make sure we know when the script is running.
// In the future, we need to be able to do this programatically more predicably.
scene.EventManager.OnChatFromWorld += OnChatFromWorld;
scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, userItem.ID, (uint)AttachmentPoint.Chest);
m_chatEvent.WaitOne(60000);
// TODO: Need to have a test that checks the script is actually started but this involves a lot more
// plumbing of the script engine and either pausing for events or more infrastructure to turn off various
// script engine delays/asychronicity that isn't helpful in an automated regression testing context.
SceneObjectGroup attSo = scene.GetSceneObjectGroup(so.Name);
Assert.That(attSo.ContainsScripts(), Is.True);
TaskInventoryItem reRezzedScriptItem = attSo.RootPart.Inventory.GetInventoryItem(scriptItem.Name);
IScriptModule xengine = scene.RequestModuleInterface<IScriptModule>();
Assert.That(xengine.GetScriptState(reRezzedScriptItem.ItemID), Is.True);
}
[Test]
public void TestDetachAttachmentToGround()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
Scene scene = CreateTestScene();
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1.PrincipalID);
InventoryItemBase attItem = CreateAttachmentItem(scene, ua1.PrincipalID, "att", 0x10, 0x20);
ISceneEntity so
= scene.AttachmentsModule.RezSingleAttachmentFromInventory(
sp, attItem.ID, (uint)AttachmentPoint.Chest);
m_numberOfAttachEventsFired = 0;
scene.AttachmentsModule.DetachSingleAttachmentToGround(sp, so.LocalId);
// Check scene presence status
Assert.That(sp.HasAttachments(), Is.False);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(0));
// Check appearance status
Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(0));
// Check item status
Assert.That(scene.InventoryService.GetItem(new InventoryItemBase(attItem.ID)), Is.Null);
// Check object in scene
Assert.That(scene.GetSceneObjectGroup("att"), Is.Not.Null);
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1));
}
[Test]
public void TestDetachAttachmentToInventory()
{
TestHelpers.InMethod();
Scene scene = CreateTestScene();
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1.PrincipalID);
InventoryItemBase attItem = CreateAttachmentItem(scene, ua1.PrincipalID, "att", 0x10, 0x20);
SceneObjectGroup so
= (SceneObjectGroup)scene.AttachmentsModule.RezSingleAttachmentFromInventory(
sp, attItem.ID, (uint)AttachmentPoint.Chest);
m_numberOfAttachEventsFired = 0;
scene.AttachmentsModule.DetachSingleAttachmentToInv(sp, so);
// Check status on scene presence
Assert.That(sp.HasAttachments(), Is.False);
List<SceneObjectGroup> attachments = sp.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(0));
// Check item status
Assert.That(sp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo(0));
Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(0));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1));
}
/// <summary>
/// Test specific conditions associated with detaching a scripted attachment from inventory.
/// </summary>
[Test]
public void TestDetachScriptedAttachmentToInventory()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
Scene scene = CreateScriptingEnabledTestScene();
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1);
SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, sp.UUID, "att-name", 0x10);
TaskInventoryItem scriptTaskItem
= TaskInventoryHelpers.AddScript(
scene,
so.RootPart,
"scriptItem",
"default { attach(key id) { if (id != NULL_KEY) { llSay(0, \"Hello World\"); } } }");
InventoryItemBase userItem = UserInventoryHelpers.AddInventoryItem(scene, so, 0x100, 0x1000);
// FIXME: Right now, we have to do a tricksy chat listen to make sure we know when the script is running.
// In the future, we need to be able to do this programatically more predicably.
scene.EventManager.OnChatFromWorld += OnChatFromWorld;
SceneObjectGroup rezzedSo
= scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, userItem.ID, (uint)AttachmentPoint.Chest);
// Wait for chat to signal rezzed script has been started.
m_chatEvent.WaitOne(60000);
scene.AttachmentsModule.DetachSingleAttachmentToInv(sp, rezzedSo);
InventoryItemBase userItemUpdated = scene.InventoryService.GetItem(userItem);
AssetBase asset = scene.AssetService.Get(userItemUpdated.AssetID.ToString());
// TODO: It would probably be better here to check script state via the saving and retrieval of state
// information at a higher level, rather than having to inspect the serialization.
XmlDocument soXml = new XmlDocument();
soXml.LoadXml(Encoding.UTF8.GetString(asset.Data));
XmlNodeList scriptStateNodes = soXml.GetElementsByTagName("ScriptState");
Assert.That(scriptStateNodes.Count, Is.EqualTo(1));
// Re-rez the attachment to check script running state
SceneObjectGroup reRezzedSo = scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, userItem.ID, (uint)AttachmentPoint.Chest);
// Wait for chat to signal rezzed script has been started.
m_chatEvent.WaitOne(60000);
TaskInventoryItem reRezzedScriptItem = reRezzedSo.RootPart.Inventory.GetInventoryItem(scriptTaskItem.Name);
IScriptModule xengine = scene.RequestModuleInterface<IScriptModule>();
Assert.That(xengine.GetScriptState(reRezzedScriptItem.ItemID), Is.True);
// Console.WriteLine(soXml.OuterXml);
}
/// <summary>
/// Test that attachments don't hang about in the scene when the agent is closed
/// </summary>
[Test]
public void TestRemoveAttachmentsOnAvatarExit()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
Scene scene = CreateTestScene();
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
InventoryItemBase attItem = CreateAttachmentItem(scene, ua1.PrincipalID, "att", 0x10, 0x20);
AgentCircuitData acd = SceneHelpers.GenerateAgentData(ua1.PrincipalID);
acd.Appearance = new AvatarAppearance();
acd.Appearance.SetAttachment((int)AttachmentPoint.Chest, attItem.ID, attItem.AssetID);
ScenePresence presence = SceneHelpers.AddScenePresence(scene, acd);
SceneObjectGroup rezzedAtt = presence.GetAttachments()[0];
m_numberOfAttachEventsFired = 0;
scene.CloseAgent(presence.UUID, false);
// Check that we can't retrieve this attachment from the scene.
Assert.That(scene.GetSceneObjectGroup(rezzedAtt.UUID), Is.Null);
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(0));
}
[Test]
public void TestRezAttachmentsOnAvatarEntrance()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
Scene scene = CreateTestScene();
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
InventoryItemBase attItem = CreateAttachmentItem(scene, ua1.PrincipalID, "att", 0x10, 0x20);
AgentCircuitData acd = SceneHelpers.GenerateAgentData(ua1.PrincipalID);
acd.Appearance = new AvatarAppearance();
acd.Appearance.SetAttachment((int)AttachmentPoint.Chest, attItem.ID, attItem.AssetID);
m_numberOfAttachEventsFired = 0;
ScenePresence presence = SceneHelpers.AddScenePresence(scene, acd);
Assert.That(presence.HasAttachments(), Is.True);
List<SceneObjectGroup> attachments = presence.GetAttachments();
Assert.That(attachments.Count, Is.EqualTo(1));
SceneObjectGroup attSo = attachments[0];
Assert.That(attSo.Name, Is.EqualTo(attItem.Name));
Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.Chest));
Assert.That(attSo.IsAttachment);
Assert.That(attSo.UsesPhysics, Is.False);
Assert.That(attSo.IsTemporary, Is.False);
// Check appearance status
List<AvatarAttachment> retreivedAttachments = presence.Appearance.GetAttachments();
Assert.That(retreivedAttachments.Count, Is.EqualTo(1));
Assert.That(retreivedAttachments[0].AttachPoint, Is.EqualTo((int)AttachmentPoint.Chest));
Assert.That(retreivedAttachments[0].ItemID, Is.EqualTo(attItem.ID));
Assert.That(retreivedAttachments[0].AssetID, Is.EqualTo(attItem.AssetID));
Assert.That(presence.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));
Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));
// Check events. We expect OnAttach to fire on login.
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1));
}
[Test]
public void TestUpdateAttachmentPosition()
{
TestHelpers.InMethod();
Scene scene = CreateTestScene();
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
InventoryItemBase attItem = CreateAttachmentItem(scene, ua1.PrincipalID, "att", 0x10, 0x20);
AgentCircuitData acd = SceneHelpers.GenerateAgentData(ua1.PrincipalID);
acd.Appearance = new AvatarAppearance();
acd.Appearance.SetAttachment((int)AttachmentPoint.Chest, attItem.ID, attItem.AssetID);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, acd);
SceneObjectGroup attSo = sp.GetAttachments()[0];
Vector3 newPosition = new Vector3(1, 2, 4);
m_numberOfAttachEventsFired = 0;
scene.SceneGraph.UpdatePrimGroupPosition(attSo.LocalId, newPosition, sp.ControllingClient);
Assert.That(attSo.AbsolutePosition, Is.EqualTo(sp.AbsolutePosition));
Assert.That(attSo.RootPart.AttachedPos, Is.EqualTo(newPosition));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(0));
}
[Test]
public void TestSameSimulatorNeighbouringRegionsTeleportV1()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
BaseHttpServer httpServer = new BaseHttpServer(99999);
MainServer.AddHttpServer(httpServer);
MainServer.Instance = httpServer;
AttachmentsModule attModA = new AttachmentsModule();
AttachmentsModule attModB = new AttachmentsModule();
EntityTransferModule etmA = new EntityTransferModule();
EntityTransferModule etmB = new EntityTransferModule();
LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();
IConfigSource config = new IniConfigSource();
IConfig modulesConfig = config.AddConfig("Modules");
modulesConfig.Set("EntityTransferModule", etmA.Name);
modulesConfig.Set("SimulationServices", lscm.Name);
IConfig entityTransferConfig = config.AddConfig("EntityTransfer");
// In order to run a single threaded regression test we do not want the entity transfer module waiting
// for a callback from the destination scene before removing its avatar data.
entityTransferConfig.Set("wait_for_callback", false);
modulesConfig.Set("InventoryAccessModule", "BasicInventoryAccessModule");
SceneHelpers sh = new SceneHelpers();
TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1001, 1000);
SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
SceneHelpers.SetupSceneModules(
sceneA, config, new CapabilitiesModule(), etmA, attModA, new BasicInventoryAccessModule());
SceneHelpers.SetupSceneModules(
sceneB, config, new CapabilitiesModule(), etmB, attModB, new BasicInventoryAccessModule());
// FIXME: Hack - this is here temporarily to revert back to older entity transfer behaviour
lscm.ServiceVersion = "SIMULATION/0.1";
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(sceneA, 0x1);
AgentCircuitData acd = SceneHelpers.GenerateAgentData(ua1.PrincipalID);
TestClient tc = new TestClient(acd, sceneA);
List<TestClient> destinationTestClients = new List<TestClient>();
EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients);
ScenePresence beforeTeleportSp = SceneHelpers.AddScenePresence(sceneA, tc, acd);
beforeTeleportSp.AbsolutePosition = new Vector3(30, 31, 32);
InventoryItemBase attItem = CreateAttachmentItem(sceneA, ua1.PrincipalID, "att", 0x10, 0x20);
sceneA.AttachmentsModule.RezSingleAttachmentFromInventory(
beforeTeleportSp, attItem.ID, (uint)AttachmentPoint.Chest);
Vector3 teleportPosition = new Vector3(10, 11, 12);
Vector3 teleportLookAt = new Vector3(20, 21, 22);
m_numberOfAttachEventsFired = 0;
sceneA.RequestTeleportLocation(
beforeTeleportSp.ControllingClient,
sceneB.RegionInfo.RegionHandle,
teleportPosition,
teleportLookAt,
(uint)TeleportFlags.ViaLocation);
destinationTestClients[0].CompleteMovement();
// Check attachments have made it into sceneB
ScenePresence afterTeleportSceneBSp = sceneB.GetScenePresence(ua1.PrincipalID);
// This is appearance data, as opposed to actually rezzed attachments
List<AvatarAttachment> sceneBAttachments = afterTeleportSceneBSp.Appearance.GetAttachments();
Assert.That(sceneBAttachments.Count, Is.EqualTo(1));
Assert.That(sceneBAttachments[0].AttachPoint, Is.EqualTo((int)AttachmentPoint.Chest));
Assert.That(sceneBAttachments[0].ItemID, Is.EqualTo(attItem.ID));
Assert.That(sceneBAttachments[0].AssetID, Is.EqualTo(attItem.AssetID));
Assert.That(afterTeleportSceneBSp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));
// This is the actual attachment
List<SceneObjectGroup> actualSceneBAttachments = afterTeleportSceneBSp.GetAttachments();
Assert.That(actualSceneBAttachments.Count, Is.EqualTo(1));
SceneObjectGroup actualSceneBAtt = actualSceneBAttachments[0];
Assert.That(actualSceneBAtt.Name, Is.EqualTo(attItem.Name));
Assert.That(actualSceneBAtt.AttachmentPoint, Is.EqualTo((uint)AttachmentPoint.Chest));
Assert.That(sceneB.GetSceneObjectGroups().Count, Is.EqualTo(1));
// Check attachments have been removed from sceneA
ScenePresence afterTeleportSceneASp = sceneA.GetScenePresence(ua1.PrincipalID);
// Since this is appearance data, it is still present on the child avatar!
List<AvatarAttachment> sceneAAttachments = afterTeleportSceneASp.Appearance.GetAttachments();
Assert.That(sceneAAttachments.Count, Is.EqualTo(1));
Assert.That(afterTeleportSceneASp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));
// This is the actual attachment, which should no longer exist
List<SceneObjectGroup> actualSceneAAttachments = afterTeleportSceneASp.GetAttachments();
Assert.That(actualSceneAAttachments.Count, Is.EqualTo(0));
Assert.That(sceneA.GetSceneObjectGroups().Count, Is.EqualTo(0));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(0));
}
[Test]
public void TestSameSimulatorNeighbouringRegionsTeleportV2()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
BaseHttpServer httpServer = new BaseHttpServer(99999);
MainServer.AddHttpServer(httpServer);
MainServer.Instance = httpServer;
AttachmentsModule attModA = new AttachmentsModule();
AttachmentsModule attModB = new AttachmentsModule();
EntityTransferModule etmA = new EntityTransferModule();
EntityTransferModule etmB = new EntityTransferModule();
LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();
IConfigSource config = new IniConfigSource();
IConfig modulesConfig = config.AddConfig("Modules");
modulesConfig.Set("EntityTransferModule", etmA.Name);
modulesConfig.Set("SimulationServices", lscm.Name);
modulesConfig.Set("InventoryAccessModule", "BasicInventoryAccessModule");
SceneHelpers sh = new SceneHelpers();
TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1001, 1000);
SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
SceneHelpers.SetupSceneModules(
sceneA, config, new CapabilitiesModule(), etmA, attModA, new BasicInventoryAccessModule());
SceneHelpers.SetupSceneModules(
sceneB, config, new CapabilitiesModule(), etmB, attModB, new BasicInventoryAccessModule());
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(sceneA, 0x1);
AgentCircuitData acd = SceneHelpers.GenerateAgentData(ua1.PrincipalID);
TestClient tc = new TestClient(acd, sceneA);
List<TestClient> destinationTestClients = new List<TestClient>();
EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients);
ScenePresence beforeTeleportSp = SceneHelpers.AddScenePresence(sceneA, tc, acd);
beforeTeleportSp.AbsolutePosition = new Vector3(30, 31, 32);
Assert.That(destinationTestClients.Count, Is.EqualTo(1));
Assert.That(destinationTestClients[0], Is.Not.Null);
InventoryItemBase attItem = CreateAttachmentItem(sceneA, ua1.PrincipalID, "att", 0x10, 0x20);
sceneA.AttachmentsModule.RezSingleAttachmentFromInventory(
beforeTeleportSp, attItem.ID, (uint)AttachmentPoint.Chest);
Vector3 teleportPosition = new Vector3(10, 11, 12);
Vector3 teleportLookAt = new Vector3(20, 21, 22);
// Here, we need to make clientA's receipt of SendRegionTeleport trigger clientB's CompleteMovement(). This
// is to operate the teleport V2 mechanism where the EntityTransferModule will first request the client to
// CompleteMovement to the region and then call UpdateAgent to the destination region to confirm the receipt
// Both these operations will occur on different threads and will wait for each other.
// We have to do this via ThreadPool directly since FireAndForget has been switched to sync for the V1
// test protocol, where we are trying to avoid unpredictable async operations in regression tests.
tc.OnTestClientSendRegionTeleport
+= (regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL)
=> ThreadPool.UnsafeQueueUserWorkItem(o => destinationTestClients[0].CompleteMovement(), null);
m_numberOfAttachEventsFired = 0;
sceneA.RequestTeleportLocation(
beforeTeleportSp.ControllingClient,
sceneB.RegionInfo.RegionHandle,
teleportPosition,
teleportLookAt,
(uint)TeleportFlags.ViaLocation);
// Check attachments have made it into sceneB
ScenePresence afterTeleportSceneBSp = sceneB.GetScenePresence(ua1.PrincipalID);
// This is appearance data, as opposed to actually rezzed attachments
List<AvatarAttachment> sceneBAttachments = afterTeleportSceneBSp.Appearance.GetAttachments();
Assert.That(sceneBAttachments.Count, Is.EqualTo(1));
Assert.That(sceneBAttachments[0].AttachPoint, Is.EqualTo((int)AttachmentPoint.Chest));
Assert.That(sceneBAttachments[0].ItemID, Is.EqualTo(attItem.ID));
Assert.That(sceneBAttachments[0].AssetID, Is.EqualTo(attItem.AssetID));
Assert.That(afterTeleportSceneBSp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));
// This is the actual attachment
List<SceneObjectGroup> actualSceneBAttachments = afterTeleportSceneBSp.GetAttachments();
Assert.That(actualSceneBAttachments.Count, Is.EqualTo(1));
SceneObjectGroup actualSceneBAtt = actualSceneBAttachments[0];
Assert.That(actualSceneBAtt.Name, Is.EqualTo(attItem.Name));
Assert.That(actualSceneBAtt.AttachmentPoint, Is.EqualTo((uint)AttachmentPoint.Chest));
Assert.That(sceneB.GetSceneObjectGroups().Count, Is.EqualTo(1));
// Check attachments have been removed from sceneA
ScenePresence afterTeleportSceneASp = sceneA.GetScenePresence(ua1.PrincipalID);
// Since this is appearance data, it is still present on the child avatar!
List<AvatarAttachment> sceneAAttachments = afterTeleportSceneASp.Appearance.GetAttachments();
Assert.That(sceneAAttachments.Count, Is.EqualTo(1));
Assert.That(afterTeleportSceneASp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));
// This is the actual attachment, which should no longer exist
List<SceneObjectGroup> actualSceneAAttachments = afterTeleportSceneASp.GetAttachments();
Assert.That(actualSceneAAttachments.Count, Is.EqualTo(0));
Assert.That(sceneA.GetSceneObjectGroups().Count, Is.EqualTo(0));
// Check events
Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(0));
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using AppodealAds.Unity.Common;
namespace AppodealAds.Unity.Api {
public class Appodeal {
public const int NONE = 0;
public const int INTERSTITIAL = 1;
public const int SKIPPABLE_VIDEO = 2;
public const int BANNER = 4;
public const int BANNER_BOTTOM = 8;
public const int BANNER_TOP = 16;
public const int REWARDED_VIDEO = 128;
#if UNITY_ANDROID || UNITY_EDITOR
public const int NON_SKIPPABLE_VIDEO = 128;
#elif UNITY_IPHONE
public const int NON_SKIPPABLE_VIDEO = 256;
#endif
private static IAppodealAdsClient client;
private static IAppodealAdsClient getInstance() {
if (client == null) {
client = AppodealAdsClientFactory.GetAppodealAdsClient();
}
return client;
}
public static void initialize(string appKey, int adTypes)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().initialize(appKey, adTypes);
#endif
}
public static void setInterstitialCallbacks(IInterstitialAdListener listener)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setInterstitialCallbacks (listener);
#endif
}
public static void setSkippableVideoCallbacks(ISkippableVideoAdListener listener)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setSkippableVideoCallbacks (listener);
#endif
}
public static void setNonSkippableVideoCallbacks(INonSkippableVideoAdListener listener)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setNonSkippableVideoCallbacks (listener);
#endif
}
public static void setRewardedVideoCallbacks(IRewardedVideoAdListener listener)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setRewardedVideoCallbacks (listener);
#endif
}
public static void setBannerCallbacks(IBannerAdListener listener)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setBannerCallbacks (listener);
#endif
}
public static void cache(int adTypes)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().cache (adTypes);
#endif
}
public static void cache(int adTypes, string placement)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().cache (adTypes, placement);
#endif
}
public static void confirm(int adTypes)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().confirm (adTypes);
#endif
}
public static bool isLoaded(int adTypes)
{
bool isLoaded = false;
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
isLoaded = getInstance().isLoaded (adTypes);
#endif
return isLoaded;
}
public static bool isPrecache(int adTypes)
{
bool isPrecache = false;
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
isPrecache = getInstance().isPrecache (adTypes);
#endif
return isPrecache;
}
public static bool show(int adTypes)
{
bool show = false;
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
show = getInstance().show (adTypes);
#endif
return show;
}
public static bool show(int adTypes, string placement)
{
bool show = false;
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR && !UNITY_EDITOR
show = getInstance().show (adTypes, placement);
#endif
return show;
}
public static void hide(int adTypes)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().hide (adTypes);
#endif
}
public static void orientationChange()
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().orientationChange ();
#endif
}
public static void setAutoCache(int adTypes, bool autoCache)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setAutoCache (adTypes, autoCache);
#endif
}
public static void setOnLoadedTriggerBoth(int adTypes, bool onLoadedTriggerBoth)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setOnLoadedTriggerBoth (adTypes, onLoadedTriggerBoth);
#endif
}
public static void disableNetwork(string network)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().disableNetwork (network);
#endif
}
public static void disableNetwork(string network, int adType)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().disableNetwork (network, adType);
#endif
}
public static void disableLocationPermissionCheck()
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().disableLocationPermissionCheck ();
#endif
}
public static void disableWriteExternalStoragePermissionCheck()
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().disableWriteExternalStoragePermissionCheck ();
#endif
}
public static void requestAndroidMPermissions(IPermissionGrantedListener listener)
{
#if UNITY_ANDROID && !UNITY_EDITOR
getInstance().requestAndroidMPermissions (listener);
#endif
}
public static void setTesting(bool test)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setTesting (test);
#endif
}
public static void setLogging(bool logging)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setLogging (logging);
#endif
}
public static string getVersion()
{
string version = null;
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
version = getInstance().getVersion();
#endif
return version;
}
public static void trackInAppPurchase(double amount, string currency)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().trackInAppPurchase(amount, currency);
#endif
}
public static void setCustomRule(string name, bool value)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setCustomRule(name, value);
#endif
}
public static void setCustomRule(string name, int value)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setCustomRule(name, value);
#endif
}
public static void setCustomRule(string name, double value)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setCustomRule(name, value);
#endif
}
public static void setCustomRule(string name, string value)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setCustomRule(name, value);
#endif
}
public static void setSmartBanners(Boolean value)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setSmartBanners(value);
#endif
}
public static void setBannerBackground(bool value) {
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setBannerBackground(value);
#endif
}
public static void setBannerAnimation(bool value) {
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setBannerAnimation(value);
#endif
}
}
public class UserSettings
{
private static IAppodealAdsClient client;
private static IAppodealAdsClient getInstance() {
if (client == null) {
client = AppodealAdsClientFactory.GetAppodealAdsClient();
}
return client;
}
public enum Gender {
OTHER, MALE, FEMALE
}
public enum Occupation {
OTHER, WORK, SCHOOL, UNIVERSITY
}
public enum Relation {
OTHER, SINGLE, DATING, ENGAGED, MARRIED, SEARCHING
}
public enum Smoking {
NEGATIVE, NEUTRAL, POSITIVE
}
public enum Alcohol {
NEGATIVE, NEUTRAL, POSITIVE
}
public UserSettings ()
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().getUserSettings();
#endif
}
public UserSettings setUserId(string id)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setUserId(id);
#endif
return this;
}
public UserSettings setAge(int age)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setAge(age);
#endif
return this;
}
public UserSettings setBirthday(string bDay)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setBirthday(bDay);
#endif
return this;
}
public UserSettings setEmail(string email)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setEmail(email);
#endif
return this;
}
public UserSettings setGender(Gender gender)
{
switch(gender) {
case Gender.OTHER:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setGender(1);
#endif
return this;
}
case Gender.MALE:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setGender(2);
#endif
return this;
}
case Gender.FEMALE:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setGender(3);
#endif
return this;
}
}
return null;
}
public UserSettings setInterests(string interests)
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setInterests(interests);
#endif
return this;
}
public UserSettings setOccupation(Occupation occupation)
{
switch(occupation) {
case Occupation.OTHER:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setOccupation(1);
#endif
return this;
}
case Occupation.WORK:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setOccupation(2);
#endif
return this;
}
case Occupation.SCHOOL:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setOccupation(3);
#endif
return this;
}
case Occupation.UNIVERSITY:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setOccupation(4);
#endif
return this;;
}
}
return null;
}
public UserSettings setRelation(Relation relation)
{
switch(relation) {
case Relation.OTHER:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setRelation(1);
#endif
return this;
}
case Relation.SINGLE:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setRelation(2);
#endif
return this;
}
case Relation.DATING:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setRelation(3);
#endif
return this;
}
case Relation.ENGAGED:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setRelation(4);
#endif
return this;
}
case Relation.MARRIED:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setRelation(5);
#endif
return this;
}
case Relation.SEARCHING:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setRelation(6);
#endif
return this;
}
}
return null;
}
public UserSettings setAlcohol(Alcohol alcohol)
{
switch(alcohol) {
case Alcohol.NEGATIVE:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setAlcohol(1);
#endif
return this;
}
case Alcohol.NEUTRAL:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setAlcohol(2);
#endif
return this;
}
case Alcohol.POSITIVE:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setAlcohol(3);
#endif
return this;
}
}
return null;
}
public UserSettings setSmoking(Smoking smoking)
{
switch(smoking) {
case Smoking.NEGATIVE:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setSmoking(1);
#endif
return this;
}
case Smoking.NEUTRAL:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setSmoking(2);
#endif
return this;
}
case Smoking.POSITIVE:
{
#if UNITY_ANDROID && !UNITY_EDITOR || UNITY_IPHONE && !UNITY_EDITOR
getInstance().setSmoking(3);
#endif
return this;
}
}
return null;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// 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
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Filters;
using NLog.Internal;
using NLog.Targets;
/// <summary>
/// Implementation of logging engine.
/// </summary>
internal static class LoggerImpl
{
private const int StackTraceSkipMethods = 0;
private static readonly Assembly nlogAssembly = typeof(LoggerImpl).Assembly;
private static readonly Assembly mscorlibAssembly = typeof(string).Assembly;
private static readonly Assembly systemAssembly = typeof(Debug).Assembly;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "Using 'NLog' in message.")]
internal static void Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
{
if (targets == null)
{
return;
}
StackTraceUsage stu = targets.GetStackTraceUsage();
if (stu != StackTraceUsage.None && !logEvent.HasStackTrace)
{
StackTrace stackTrace;
#if !SILVERLIGHT
stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource);
#else
stackTrace = new StackTrace();
#endif
int firstUserFrame = FindCallingMethodOnStackTrace(stackTrace, loggerType);
logEvent.SetStackTrace(stackTrace, firstUserFrame);
}
int originalThreadId = Thread.CurrentThread.ManagedThreadId;
AsyncContinuation exceptionHandler = ex =>
{
if (ex != null)
{
if (factory.ThrowExceptions && Thread.CurrentThread.ManagedThreadId == originalThreadId)
{
throw new NLogRuntimeException("Exception occurred in NLog", ex);
}
}
};
for (var t = targets; t != null; t = t.NextInChain)
{
if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler))
{
break;
}
}
}
private static int FindCallingMethodOnStackTrace(StackTrace stackTrace, Type loggerType)
{
int? firstUserFrame = null;
if (loggerType != null)
{
for (int i = 0; i < stackTrace.FrameCount; ++i)
{
StackFrame frame = stackTrace.GetFrame(i);
MethodBase mb = frame.GetMethod();
if (mb.DeclaringType == loggerType || (mb.DeclaringType != null && SkipAssembly(mb.DeclaringType.Assembly)))
firstUserFrame = i + 1;
else if (firstUserFrame != null)
break;
}
}
if (firstUserFrame == stackTrace.FrameCount)
firstUserFrame = null;
if (firstUserFrame == null)
{
for (int i = 0; i < stackTrace.FrameCount; ++i)
{
StackFrame frame = stackTrace.GetFrame(i);
MethodBase mb = frame.GetMethod();
Assembly methodAssembly = null;
if (mb.DeclaringType != null)
{
methodAssembly = mb.DeclaringType.Assembly;
}
if (SkipAssembly(methodAssembly))
{
firstUserFrame = i + 1;
}
else
{
if (firstUserFrame != 0)
{
break;
}
}
}
}
return firstUserFrame ?? 0;
}
private static bool SkipAssembly(Assembly assembly)
{
if (assembly == nlogAssembly)
{
return true;
}
if (assembly == mscorlibAssembly)
{
return true;
}
if (assembly == systemAssembly)
{
return true;
}
if (LogManager.HiddenAssemblies.Contains(assembly))
{
return true;
}
return false;
}
private static bool WriteToTargetWithFilterChain(TargetWithFilterChain targetListHead, LogEventInfo logEvent, AsyncContinuation onException)
{
Target target = targetListHead.Target;
FilterResult result = GetFilterResult(targetListHead.FilterChain, logEvent);
if ((result == FilterResult.Ignore) || (result == FilterResult.IgnoreFinal))
{
if (InternalLogger.IsDebugEnabled)
{
InternalLogger.Debug("{0}.{1} Rejecting message because of a filter.", logEvent.LoggerName, logEvent.Level);
}
if (result == FilterResult.IgnoreFinal)
{
return false;
}
return true;
}
target.WriteAsyncLogEvent(logEvent.WithContinuation(onException));
if (result == FilterResult.LogFinal)
{
return false;
}
return true;
}
/// <summary>
/// Gets the filter result.
/// </summary>
/// <param name="filterChain">The filter chain.</param>
/// <param name="logEvent">The log event.</param>
/// <returns>The result of the filter.</returns>
private static FilterResult GetFilterResult(IEnumerable<Filter> filterChain, LogEventInfo logEvent)
{
FilterResult result = FilterResult.Neutral;
try
{
foreach (Filter f in filterChain)
{
result = f.GetFilterResult(logEvent);
if (result != FilterResult.Neutral)
{
break;
}
}
return result;
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Exception during filter evaluation: {0}", exception);
return FilterResult.Ignore;
}
}
}
}
| |
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using System.Runtime.InteropServices;
/// @cond
namespace Gvr.Internal {
public abstract class GvrDevice :
#if UNITY_ANDROID
BaseAndroidDevice
#else
BaseVRDevice
#endif
{
// A relatively unique id to use when calling our C++ native render plugin.
private const int kRenderEvent = 0x47554342;
// Event IDs sent up from native layer. Bit flags.
// Keep in sync with the corresponding declaration in unity.h.
private const int kTriggered = 1 << 0;
private const int kTilted = 1 << 1;
private const int kProfileChanged = 1 << 2;
private const int kVRBackButtonPressed = 1 << 3;
private float[] headData = new float[16];
private float[] viewData = new float[16 * 6 + 12];
private float[] profileData = new float[13];
private Matrix4x4 headView = new Matrix4x4();
private Matrix4x4 leftEyeView = new Matrix4x4();
private Matrix4x4 rightEyeView = new Matrix4x4();
protected bool debugDisableNativeProjections = false;
protected bool debugDisableNativeUILayer = false;
public override void SetDistortionCorrectionEnabled(bool enabled) {
EnableDistortionCorrection(enabled);
}
public override void SetNeckModelScale(float scale) {
SetNeckModelFactor(scale);
}
public override void SetElectronicDisplayStabilizationEnabled(bool enabled) {
EnableElectronicDisplayStabilization(enabled);
}
public override bool SetDefaultDeviceProfile(System.Uri uri) {
byte[] profile = System.Text.Encoding.UTF8.GetBytes(uri.ToString());
return SetDefaultProfile(profile, profile.Length);
}
public override void Init() {
// Start will send a log event, so SetUnityVersion first.
byte[] version = System.Text.Encoding.UTF8.GetBytes(Application.unityVersion);
SetUnityVersion(version, version.Length);
Start();
}
public override void UpdateState() {
ProcessEvents();
GetHeadPose(headData);
ExtractMatrix(ref headView, headData);
headPose.SetRightHanded(headView.inverse);
}
public override void UpdateScreenData() {
UpdateProfile();
if (debugDisableNativeProjections) {
ComputeEyesFromProfile();
} else {
UpdateView();
}
profileChanged = true;
}
public override void Recenter() {
ResetHeadTracker();
}
public override void PostRender(RenderTexture stereoScreen) {
SetTextureId((int)stereoScreen.GetNativeTexturePtr());
GL.IssuePluginEvent(kRenderEvent);
}
public override void OnPause(bool pause) {
if (pause) {
Pause();
} else {
Resume();
}
}
public override void OnApplicationQuit() {
Stop();
base.OnApplicationQuit();
}
private void UpdateView() {
GetViewParameters(viewData);
int j = 0;
j = ExtractMatrix(ref leftEyeView, viewData, j);
j = ExtractMatrix(ref rightEyeView, viewData, j);
leftEyePose.SetRightHanded(leftEyeView.inverse);
rightEyePose.SetRightHanded(rightEyeView.inverse);
j = ExtractMatrix(ref leftEyeDistortedProjection, viewData, j);
j = ExtractMatrix(ref rightEyeDistortedProjection, viewData, j);
j = ExtractMatrix(ref leftEyeUndistortedProjection, viewData, j);
j = ExtractMatrix(ref rightEyeUndistortedProjection, viewData, j);
leftEyeUndistortedViewport.Set(viewData[j], viewData[j+1], viewData[j+2], viewData[j+3]);
leftEyeDistortedViewport = leftEyeUndistortedViewport;
j += 4;
rightEyeUndistortedViewport.Set(viewData[j], viewData[j+1], viewData[j+2], viewData[j+3]);
rightEyeDistortedViewport = rightEyeUndistortedViewport;
j += 4;
leftEyeOrientation = (int)viewData[j];
rightEyeOrientation = (int)viewData[j+1];
j += 2;
recommendedTextureSize = new Vector2(viewData[j], viewData[j+1]);
j += 2;
}
private void UpdateProfile() {
GetProfile(profileData);
GvrProfile.Viewer device = new GvrProfile.Viewer();
GvrProfile.Screen screen = new GvrProfile.Screen();
device.maxFOV.outer = profileData[0];
device.maxFOV.upper = profileData[1];
device.maxFOV.inner = profileData[2];
device.maxFOV.lower = profileData[3];
screen.width = profileData[4];
screen.height = profileData[5];
screen.border = profileData[6];
device.lenses.separation = profileData[7];
device.lenses.offset = profileData[8];
device.lenses.screenDistance = profileData[9];
device.lenses.alignment = (int)profileData[10];
device.distortion.Coef = new [] { profileData[11], profileData[12] };
Profile.screen = screen;
Profile.viewer = device;
float[] rect = new float[4];
Profile.GetLeftEyeNoLensTanAngles(rect);
float maxRadius = GvrProfile.GetMaxRadius(rect);
Profile.viewer.inverse = GvrProfile.ApproximateInverse(
Profile.viewer.distortion, maxRadius);
}
private static int ExtractMatrix(ref Matrix4x4 mat, float[] data, int i = 0) {
// Matrices returned from our native layer are in row-major order.
for (int r = 0; r < 4; r++) {
for (int c = 0; c < 4; c++, i++) {
mat[r, c] = data[i];
}
}
return i;
}
protected virtual void ProcessEvents() {
int flags = GetEventFlags();
triggered = ((flags & kTriggered) != 0);
tilted = ((flags & kTilted) != 0);
backButtonPressed = ((flags & kVRBackButtonPressed) != 0);
if ((flags & kProfileChanged) != 0) {
UpdateScreenData();
}
}
#if UNITY_IOS
private const string dllName = "__Internal";
#else
private const string dllName = "gvrunity";
#endif
[DllImport(dllName)]
private static extern void Start();
[DllImport(dllName)]
private static extern void SetTextureId(int id);
[DllImport(dllName)]
private static extern bool SetDefaultProfile(byte[] uri, int size);
[DllImport(dllName)]
private static extern void SetUnityVersion(byte[] version_str, int version_length);
[DllImport(dllName)]
private static extern void EnableDistortionCorrection(bool enable);
[DllImport(dllName)]
private static extern void EnableElectronicDisplayStabilization(bool enable);
[DllImport(dllName)]
private static extern void SetNeckModelFactor(float factor);
[DllImport(dllName)]
private static extern void ResetHeadTracker();
[DllImport(dllName)]
private static extern int GetEventFlags();
[DllImport(dllName)]
private static extern void GetProfile(float[] profile);
[DllImport(dllName)]
private static extern void GetHeadPose(float[] pose);
[DllImport(dllName)]
private static extern void GetViewParameters(float[] viewParams);
[DllImport(dllName)]
private static extern void Pause();
[DllImport(dllName)]
private static extern void Resume();
[DllImport(dllName)]
private static extern void Stop();
}
}
/// @endcond
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices.ComTypes;
using Marshal = System.Runtime.InteropServices.Marshal;
using VarEnum = System.Runtime.InteropServices.VarEnum;
using IFixedTypeInfo = Microsoft.Build.Tasks.IFixedTypeInfo;
using Xunit;
namespace Microsoft.Build.UnitTests
{
/// <summary>
/// A generic interface for creating composite type infos - e.g. a safe array of pointers to something
/// </summary>
public interface ICompositeTypeInfo
{
TYPEDESC CreateTypeDesc(IntPtr finalTypeHRef, MockUnmanagedMemoryHelper memoryHelper);
MockTypeInfo GetFinalTypeInfo();
}
/// <summary>
/// Safe array composite type info
/// </summary>
public class ArrayCompositeTypeInfo : ICompositeTypeInfo
{
private ICompositeTypeInfo _baseElementType;
public ArrayCompositeTypeInfo(ICompositeTypeInfo baseElement)
{
_baseElementType = baseElement;
}
#region ICreateTypeDesc Members
public TYPEDESC CreateTypeDesc(IntPtr finalTypeHRef, MockUnmanagedMemoryHelper memoryHelper)
{
TYPEDESC typeDesc;
typeDesc.vt = (short)VarEnum.VT_SAFEARRAY;
typeDesc.lpValue = memoryHelper.AllocateHandle(Marshal.SizeOf<TYPEDESC>());
Marshal.StructureToPtr(_baseElementType.CreateTypeDesc(finalTypeHRef, memoryHelper), typeDesc.lpValue, false);
return typeDesc;
}
/// <summary>
/// Defer to the base element to get the final type info - this will eventually terminate at a MockTypeInfo node
/// which returns itself
/// </summary>
/// <returns></returns>
public MockTypeInfo GetFinalTypeInfo()
{
return _baseElementType.GetFinalTypeInfo();
}
#endregion
}
/// <summary>
/// Pointer composite type info
/// </summary>
public class PtrCompositeTypeInfo : ICompositeTypeInfo
{
private ICompositeTypeInfo _baseElementType;
public PtrCompositeTypeInfo(ICompositeTypeInfo baseElement)
{
_baseElementType = baseElement;
}
#region ICompositeTypeInfo Members
public TYPEDESC CreateTypeDesc(IntPtr finalTypeHRef, MockUnmanagedMemoryHelper memoryHelper)
{
TYPEDESC typeDesc;
typeDesc.vt = (short)VarEnum.VT_PTR;
typeDesc.lpValue = memoryHelper.AllocateHandle(Marshal.SizeOf<TYPEDESC>());
Marshal.StructureToPtr(_baseElementType.CreateTypeDesc(finalTypeHRef, memoryHelper), typeDesc.lpValue, false);
return typeDesc;
}
public MockTypeInfo GetFinalTypeInfo()
{
return _baseElementType.GetFinalTypeInfo();
}
#endregion
}
/// <summary>
/// All the information necessary to describe a single function signature
/// </summary>
public struct FuncInfo
{
public FuncInfo(ICompositeTypeInfo[] parameters, ICompositeTypeInfo returnType)
{
this.parameters = parameters;
this.returnType = returnType;
}
public ICompositeTypeInfo[] parameters;
public ICompositeTypeInfo returnType;
}
/// <summary>
/// Mock class for the ITypeInfo interface
/// </summary>
public class MockTypeInfo : ITypeInfo, ICompositeTypeInfo, IFixedTypeInfo
{
static private int s_HREF_IMPLTYPES_OFFSET = 1000;
static private int s_HREF_VARS_OFFSET = 2000;
static private int s_HREF_FUNCSRET_OFFSET = 3000;
static private int s_HREF_FUNCSPARAM_OFFSET = 4000;
static private int s_HREF_FUNCSPARAM_OFFSET_PERFUNC = 100;
static private int s_HREF_RANGE = 999;
private MockTypeLib _containingTypeLib;
public MockTypeLib ContainingTypeLib
{
set
{
_containingTypeLib = value;
}
}
private int _indexInContainingTypeLib;
public int IndexInContainingTypeLib
{
set
{
_indexInContainingTypeLib = value;
}
}
private string _typeName;
public string TypeName
{
set
{
_typeName = value;
}
}
private TYPEATTR _typeAttributes;
private List<MockTypeInfo> _implementedTypes;
private List<ICompositeTypeInfo> _definedVariables;
private List<FuncInfo> _definedFunctions;
private MockUnmanagedMemoryHelper _memoryHelper;
private MockFaultInjectionHelper<MockTypeLibrariesFailurePoints> _faultInjector;
/// <summary>
/// Default constructor
/// </summary>
public MockTypeInfo()
{
_implementedTypes = new List<MockTypeInfo>();
_definedVariables = new List<ICompositeTypeInfo>();
_definedFunctions = new List<FuncInfo>();
_memoryHelper = new MockUnmanagedMemoryHelper();
// each type has a unique guid
_typeAttributes.guid = Guid.NewGuid();
// default typekind value is TKIND_ENUM so just pick something else that doesn't have a special meaning in the code
// (we skip enum type infos)
_typeAttributes.typekind = TYPEKIND.TKIND_INTERFACE;
}
/// <summary>
/// Use a known guid for creating this type info
/// </summary>
/// <param name="guid"></param>
public MockTypeInfo(Guid guid)
: this()
{
_typeAttributes.guid = guid;
}
/// <summary>
/// Use a custom type kind
/// </summary>
/// <param name="typeKind"></param>
public MockTypeInfo(TYPEKIND typeKind)
: this()
{
_typeAttributes.typekind = typeKind;
}
/// <summary>
/// Adds implementedType to the list of this type's implemented interfaces
/// </summary>
/// <param name="implementedType"></param>
public void ImplementsInterface(MockTypeInfo implementedType)
{
_typeAttributes.cImplTypes++;
_implementedTypes.Add(implementedType);
}
/// <summary>
/// Adds implementedType to the list of this type's defined variables
/// </summary>
/// <param name="implementedType"></param>
public void DefinesVariable(ICompositeTypeInfo variableType)
{
_typeAttributes.cVars++;
_definedVariables.Add(variableType);
}
/// <summary>
/// Adds a new function signature to the list of this type's implemented functions
/// </summary>
/// <param name="implementedType"></param>
public void DefinesFunction(MockTypeInfo[] parameters, MockTypeInfo returnType)
{
_typeAttributes.cFuncs++;
_definedFunctions.Add(new FuncInfo(parameters, returnType));
}
/// <summary>
/// Sets the fault injection object for this type
/// </summary>
/// <param name="faultInjector"></param>
public void SetFaultInjector(MockFaultInjectionHelper<MockTypeLibrariesFailurePoints> faultInjector)
{
_faultInjector = faultInjector;
}
/// <summary>
/// Helper method for verifying there are no memory leaks
/// </summary>
public void AssertAllHandlesReleased()
{
_memoryHelper.AssertAllHandlesReleased();
}
#region IFixedTypeInfo members
void IFixedTypeInfo.GetRefTypeOfImplType(int index, out System.IntPtr href)
{
Assert.True(index >= 0 && index < _typeAttributes.cImplTypes);
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_GetRefTypeOfImplType);
href = ((System.IntPtr)index + s_HREF_IMPLTYPES_OFFSET);
}
void IFixedTypeInfo.GetRefTypeInfo(System.IntPtr hRef, out IFixedTypeInfo ppTI)
{
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_GetRefTypeInfo);
int hRefInt = (int)hRef;
if (hRefInt >= s_HREF_IMPLTYPES_OFFSET && hRefInt <= s_HREF_IMPLTYPES_OFFSET + s_HREF_RANGE)
{
ppTI = _implementedTypes[hRefInt - s_HREF_IMPLTYPES_OFFSET];
}
else if (hRefInt >= s_HREF_VARS_OFFSET && hRefInt <= s_HREF_VARS_OFFSET + s_HREF_RANGE)
{
ppTI = _definedVariables[hRefInt - s_HREF_VARS_OFFSET].GetFinalTypeInfo();
}
else if (hRefInt >= s_HREF_FUNCSRET_OFFSET && hRefInt <= s_HREF_FUNCSRET_OFFSET + s_HREF_RANGE)
{
ppTI = _definedFunctions[hRefInt - s_HREF_FUNCSRET_OFFSET].returnType.GetFinalTypeInfo();
}
else if (hRefInt >= s_HREF_FUNCSPARAM_OFFSET && hRefInt <= s_HREF_FUNCSPARAM_OFFSET + s_HREF_RANGE)
{
ppTI = _definedFunctions[(hRefInt - s_HREF_FUNCSPARAM_OFFSET) / s_HREF_FUNCSPARAM_OFFSET_PERFUNC].parameters[(hRefInt - s_HREF_FUNCSPARAM_OFFSET) % s_HREF_FUNCSPARAM_OFFSET_PERFUNC].GetFinalTypeInfo();
}
else
{
ppTI = null;
Assert.True(false, "unexpected hRef value");
}
}
#endregion
#region Implemented ITypeInfo members
public void GetContainingTypeLib(out ITypeLib ppTLB, out int pIndex)
{
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_GetContainingTypeLib);
ppTLB = _containingTypeLib;
pIndex = _indexInContainingTypeLib;
}
public void GetTypeAttr(out IntPtr ppTypeAttr)
{
// Fail BEFORE allocating the handle to avoid leaks. If the real COM object fails in this method
// and doesn't return the handle or clean it up itself there's not much we can do to avoid the leak.
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_GetTypeAttr);
ppTypeAttr = _memoryHelper.AllocateHandle(Marshal.SizeOf<TYPEATTR>());
Marshal.StructureToPtr(_typeAttributes, ppTypeAttr, false);
}
public void ReleaseTypeAttr(IntPtr pTypeAttr)
{
_memoryHelper.FreeHandle(pTypeAttr);
// Fail AFTER releasing the handle to avoid leaks. If the real COM object fails in this method
// there's really nothing we can do to avoid leaking stuff
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_ReleaseTypeAttr);
}
public void GetRefTypeOfImplType(int index, out int href)
{
Assert.True(index >= 0 && index < _typeAttributes.cImplTypes);
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_GetRefTypeOfImplType);
href = index + s_HREF_IMPLTYPES_OFFSET;
}
public void GetRefTypeInfo(int hRef, out ITypeInfo ppTI)
{
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_GetRefTypeInfo);
if (hRef >= s_HREF_IMPLTYPES_OFFSET && hRef <= s_HREF_IMPLTYPES_OFFSET + s_HREF_RANGE)
{
ppTI = _implementedTypes[hRef - s_HREF_IMPLTYPES_OFFSET];
}
else if (hRef >= s_HREF_VARS_OFFSET && hRef <= s_HREF_VARS_OFFSET + s_HREF_RANGE)
{
ppTI = _definedVariables[hRef - s_HREF_VARS_OFFSET].GetFinalTypeInfo();
}
else if (hRef >= s_HREF_FUNCSRET_OFFSET && hRef <= s_HREF_FUNCSRET_OFFSET + s_HREF_RANGE)
{
ppTI = _definedFunctions[hRef - s_HREF_FUNCSRET_OFFSET].returnType.GetFinalTypeInfo();
}
else if (hRef >= s_HREF_FUNCSPARAM_OFFSET && hRef <= s_HREF_FUNCSPARAM_OFFSET + s_HREF_RANGE)
{
ppTI = _definedFunctions[(hRef - s_HREF_FUNCSPARAM_OFFSET) / s_HREF_FUNCSPARAM_OFFSET_PERFUNC].parameters[(hRef - s_HREF_FUNCSPARAM_OFFSET) % s_HREF_FUNCSPARAM_OFFSET_PERFUNC].GetFinalTypeInfo();
}
else
{
ppTI = null;
Assert.True(false, "unexpected hRef value");
}
}
public void GetVarDesc(int index, out IntPtr ppVarDesc)
{
// Fail BEFORE allocating the handle to avoid leaks. If the real COM object fails in this method
// and doesn't return the handle or clean it up itself there's not much we can do to avoid the leak.
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_GetVarDesc);
ppVarDesc = _memoryHelper.AllocateHandle(Marshal.SizeOf<VARDESC>());
_memoryHelper.EnterSubAllocationScope(ppVarDesc);
VARDESC varDesc = new VARDESC();
varDesc.elemdescVar.tdesc = _definedVariables[index].CreateTypeDesc(new IntPtr(index + s_HREF_VARS_OFFSET), _memoryHelper);
_memoryHelper.ExitSubAllocationScope();
Marshal.StructureToPtr(varDesc, ppVarDesc, false);
}
public void ReleaseVarDesc(IntPtr pVarDesc)
{
_memoryHelper.FreeHandle(pVarDesc);
// Fail AFTER releasing the handle to avoid leaks. If the real COM object fails in this method
// there's really nothing we can do to avoid leaking stuff
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_ReleaseVarDesc);
}
public void GetFuncDesc(int index, out IntPtr ppFuncDesc)
{
// Fail BEFORE allocating the handle to avoid leaks. If the real COM object fails in this method
// and doesn't return the handle or clean it up itself there's not much we can do to avoid the leak.
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_GetFuncDesc);
ppFuncDesc = _memoryHelper.AllocateHandle(Marshal.SizeOf<FUNCDESC>());
_memoryHelper.EnterSubAllocationScope(ppFuncDesc);
FUNCDESC funcDesc = new FUNCDESC();
funcDesc.lprgelemdescParam = _memoryHelper.AllocateHandle(_definedFunctions[index].parameters.Length * Marshal.SizeOf<ELEMDESC>());
funcDesc.cParams = (short)_definedFunctions[index].parameters.Length;
for (int i = 0; i < _definedFunctions[index].parameters.Length; i++)
{
ELEMDESC elemDesc = new ELEMDESC();
elemDesc.tdesc = _definedFunctions[index].parameters[i].CreateTypeDesc(
new IntPtr(index * s_HREF_FUNCSPARAM_OFFSET_PERFUNC + i + s_HREF_FUNCSPARAM_OFFSET), _memoryHelper);
Marshal.StructureToPtr(
elemDesc,
new IntPtr(funcDesc.lprgelemdescParam.ToInt64() + i * Marshal.SizeOf<ELEMDESC>()),
false);
}
funcDesc.elemdescFunc.tdesc = _definedFunctions[index].returnType.CreateTypeDesc(
new IntPtr(index + s_HREF_FUNCSRET_OFFSET), _memoryHelper);
_memoryHelper.ExitSubAllocationScope();
Marshal.StructureToPtr(funcDesc, ppFuncDesc, false);
}
public void ReleaseFuncDesc(IntPtr pFuncDesc)
{
_memoryHelper.FreeHandle(pFuncDesc);
// Fail AFTER releasing the handle to avoid leaks. If the real COM object fails in this method
// there's really nothing we can do to avoid leaking stuff
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_ReleaseFuncDesc);
}
public void GetDocumentation(int index, out string strName, out string strDocString, out int dwHelpContext, out string strHelpFile)
{
Assert.Equal(-1, index);
_faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_GetDocumentation);
strName = _typeName;
strDocString = "garbage";
dwHelpContext = -1;
strHelpFile = "garbage^2";
}
#endregion
#region ICreateTypeDesc Members
public TYPEDESC CreateTypeDesc(IntPtr finalTypeHRef, MockUnmanagedMemoryHelper memoryHelper)
{
TYPEDESC typeDesc;
typeDesc.vt = (short)VarEnum.VT_USERDEFINED;
typeDesc.lpValue = finalTypeHRef;
return typeDesc;
}
public MockTypeInfo GetFinalTypeInfo()
{
return this;
}
#endregion
#region Stubbed ITypeInfo members
public void AddressOfMember(int memid, INVOKEKIND invKind, out IntPtr ppv)
{
throw new Exception("The method or operation is not implemented.");
}
public void CreateInstance(object pUnkOuter, ref Guid riid, out object ppvObj)
{
throw new Exception("The method or operation is not implemented.");
}
public void GetDllEntry(int memid, INVOKEKIND invKind, IntPtr pBstrDllName, IntPtr pBstrName, IntPtr pwOrdinal)
{
throw new Exception("The method or operation is not implemented.");
}
public void GetIDsOfNames(string[] rgszNames, int cNames, int[] pMemId)
{
throw new Exception("The method or operation is not implemented.");
}
public void GetImplTypeFlags(int index, out IMPLTYPEFLAGS pImplTypeFlags)
{
throw new Exception("The method or operation is not implemented.");
}
public void GetMops(int memid, out string pBstrMops)
{
throw new Exception("The method or operation is not implemented.");
}
public void GetNames(int memid, string[] rgBstrNames, int cMaxNames, out int pcNames)
{
throw new Exception("The method or operation is not implemented.");
}
public void GetTypeComp(out ITypeComp ppTComp)
{
throw new Exception("The method or operation is not implemented.");
}
public void Invoke(object pvInstance, int memid, short wFlags, ref DISPPARAMS pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, out int puArgErr)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Kisa;
using Org.BouncyCastle.Asn1.Misc;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.Ntt;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Security
{
public sealed class ParameterUtilities
{
private ParameterUtilities()
{
}
private static readonly IDictionary algorithms = Platform.CreateHashtable();
private static readonly IDictionary basicIVSizes = Platform.CreateHashtable();
static ParameterUtilities()
{
AddAlgorithm("AES",
"AESWRAP");
AddAlgorithm("AES128",
"2.16.840.1.101.3.4.2",
NistObjectIdentifiers.IdAes128Cbc,
NistObjectIdentifiers.IdAes128Cfb,
NistObjectIdentifiers.IdAes128Ecb,
NistObjectIdentifiers.IdAes128Ofb,
NistObjectIdentifiers.IdAes128Wrap);
AddAlgorithm("AES192",
"2.16.840.1.101.3.4.22",
NistObjectIdentifiers.IdAes192Cbc,
NistObjectIdentifiers.IdAes192Cfb,
NistObjectIdentifiers.IdAes192Ecb,
NistObjectIdentifiers.IdAes192Ofb,
NistObjectIdentifiers.IdAes192Wrap);
AddAlgorithm("AES256",
"2.16.840.1.101.3.4.42",
NistObjectIdentifiers.IdAes256Cbc,
NistObjectIdentifiers.IdAes256Cfb,
NistObjectIdentifiers.IdAes256Ecb,
NistObjectIdentifiers.IdAes256Ofb,
NistObjectIdentifiers.IdAes256Wrap);
AddAlgorithm("BLOWFISH",
"1.3.6.1.4.1.3029.1.2");
AddAlgorithm("CAMELLIA",
"CAMELLIAWRAP");
AddAlgorithm("CAMELLIA128",
NttObjectIdentifiers.IdCamellia128Cbc,
NttObjectIdentifiers.IdCamellia128Wrap);
AddAlgorithm("CAMELLIA192",
NttObjectIdentifiers.IdCamellia192Cbc,
NttObjectIdentifiers.IdCamellia192Wrap);
AddAlgorithm("CAMELLIA256",
NttObjectIdentifiers.IdCamellia256Cbc,
NttObjectIdentifiers.IdCamellia256Wrap);
AddAlgorithm("CAST5",
"1.2.840.113533.7.66.10");
AddAlgorithm("CAST6");
AddAlgorithm("DES",
OiwObjectIdentifiers.DesCbc,
OiwObjectIdentifiers.DesCfb,
OiwObjectIdentifiers.DesEcb,
OiwObjectIdentifiers.DesOfb);
AddAlgorithm("DESEDE",
"DESEDEWRAP",
OiwObjectIdentifiers.DesEde,
PkcsObjectIdentifiers.IdAlgCms3DesWrap);
AddAlgorithm("DESEDE3",
PkcsObjectIdentifiers.DesEde3Cbc);
AddAlgorithm("GOST28147",
"GOST",
"GOST-28147",
CryptoProObjectIdentifiers.GostR28147Cbc);
AddAlgorithm("HC128");
AddAlgorithm("HC256");
#if INCLUDE_IDEA
AddAlgorithm("IDEA",
"1.3.6.1.4.1.188.7.1.1.2");
#endif
AddAlgorithm("NOEKEON");
AddAlgorithm("RC2",
PkcsObjectIdentifiers.RC2Cbc,
PkcsObjectIdentifiers.IdAlgCmsRC2Wrap);
AddAlgorithm("RC4",
"ARC4",
"1.2.840.113549.3.4");
AddAlgorithm("RC5",
"RC5-32");
AddAlgorithm("RC5-64");
AddAlgorithm("RC6");
AddAlgorithm("RIJNDAEL");
AddAlgorithm("SALSA20");
AddAlgorithm("SEED",
KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap,
KisaObjectIdentifiers.IdSeedCbc);
AddAlgorithm("SERPENT");
AddAlgorithm("SKIPJACK");
AddAlgorithm("TEA");
AddAlgorithm("TWOFISH");
AddAlgorithm("VMPC");
AddAlgorithm("VMPC-KSA3");
AddAlgorithm("XTEA");
AddBasicIVSizeEntries(8, "BLOWFISH", "DES", "DESEDE", "DESEDE3");
AddBasicIVSizeEntries(16, "AES", "AES128", "AES192", "AES256",
"CAMELLIA", "CAMELLIA128", "CAMELLIA192", "CAMELLIA256", "NOEKEON", "SEED");
// TODO These algorithms support an IV
// but JCE doesn't seem to provide an AlgorithmParametersGenerator for them
// "RIJNDAEL", "SKIPJACK", "TWOFISH"
}
private static void AddAlgorithm(
string canonicalName,
params object[] aliases)
{
algorithms[canonicalName] = canonicalName;
foreach (object alias in aliases)
{
algorithms[alias.ToString()] = canonicalName;
}
}
private static void AddBasicIVSizeEntries(int size, params string[] algorithms)
{
foreach (string algorithm in algorithms)
{
basicIVSizes.Add(algorithm, size);
}
}
public static string GetCanonicalAlgorithmName(
string algorithm)
{
return (string)algorithms[Platform.StringToUpper(algorithm)];
}
public static KeyParameter CreateKeyParameter(
DerObjectIdentifier algOid,
byte[] keyBytes)
{
return CreateKeyParameter(algOid.Id, keyBytes, 0, keyBytes.Length);
}
public static KeyParameter CreateKeyParameter(
string algorithm,
byte[] keyBytes)
{
return CreateKeyParameter(algorithm, keyBytes, 0, keyBytes.Length);
}
public static KeyParameter CreateKeyParameter(
DerObjectIdentifier algOid,
byte[] keyBytes,
int offset,
int length)
{
return CreateKeyParameter(algOid.Id, keyBytes, offset, length);
}
public static KeyParameter CreateKeyParameter(
string algorithm,
byte[] keyBytes,
int offset,
int length)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
string canonical = GetCanonicalAlgorithmName(algorithm);
if (canonical == null)
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
if (canonical == "DES")
return new DesParameters(keyBytes, offset, length);
if (canonical == "DESEDE" || canonical =="DESEDE3")
return new DesEdeParameters(keyBytes, offset, length);
if (canonical == "RC2")
return new RC2Parameters(keyBytes, offset, length);
return new KeyParameter(keyBytes, offset, length);
}
public static ICipherParameters GetCipherParameters(
DerObjectIdentifier algOid,
ICipherParameters key,
Asn1Object asn1Params)
{
return GetCipherParameters(algOid.Id, key, asn1Params);
}
public static ICipherParameters GetCipherParameters(
string algorithm,
ICipherParameters key,
Asn1Object asn1Params)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
string canonical = GetCanonicalAlgorithmName(algorithm);
if (canonical == null)
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
byte[] iv = null;
try
{
// TODO These algorithms support an IV
// but JCE doesn't seem to provide an AlgorithmParametersGenerator for them
// "RIJNDAEL", "SKIPJACK", "TWOFISH"
int basicIVKeySize = FindBasicIVSize(canonical);
if (basicIVKeySize != -1
|| canonical == "RIJNDAEL" || canonical == "SKIPJACK" || canonical == "TWOFISH")
{
iv = ((Asn1OctetString) asn1Params).GetOctets();
}
else if (canonical == "CAST5")
{
iv = Cast5CbcParameters.GetInstance(asn1Params).GetIV();
}
#if INCLUDE_IDEA
else if (canonical == "IDEA")
{
iv = IdeaCbcPar.GetInstance(asn1Params).GetIV();
}
#endif
else if (canonical == "RC2")
{
iv = RC2CbcParameter.GetInstance(asn1Params).GetIV();
}
}
catch (Exception e)
{
throw new ArgumentException("Could not process ASN.1 parameters", e);
}
if (iv != null)
{
return new ParametersWithIV(key, iv);
}
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
}
public static Asn1Encodable GenerateParameters(
DerObjectIdentifier algID,
SecureRandom random)
{
return GenerateParameters(algID.Id, random);
}
public static Asn1Encodable GenerateParameters(
string algorithm,
SecureRandom random)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
string canonical = GetCanonicalAlgorithmName(algorithm);
if (canonical == null)
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
// TODO These algorithms support an IV
// but JCE doesn't seem to provide an AlgorithmParametersGenerator for them
// "RIJNDAEL", "SKIPJACK", "TWOFISH"
int basicIVKeySize = FindBasicIVSize(canonical);
if (basicIVKeySize != -1)
return CreateIVOctetString(random, basicIVKeySize);
if (canonical == "CAST5")
return new Cast5CbcParameters(CreateIV(random, 8), 128);
#if INCLUDE_IDEA
if (canonical == "IDEA")
return new IdeaCbcPar(CreateIV(random, 8));
#endif
if (canonical == "RC2")
return new RC2CbcParameter(CreateIV(random, 8));
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
}
private static Asn1OctetString CreateIVOctetString(
SecureRandom random,
int ivLength)
{
return new DerOctetString(CreateIV(random, ivLength));
}
private static byte[] CreateIV(
SecureRandom random,
int ivLength)
{
byte[] iv = new byte[ivLength];
random.NextBytes(iv);
return iv;
}
private static int FindBasicIVSize(
string canonicalName)
{
if (!basicIVSizes.Contains(canonicalName))
return -1;
return (int)basicIVSizes[canonicalName];
}
}
}
| |
/*
* 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.
*/
#pragma warning disable 618
namespace Apache.Ignite.Core.Tests.Cache.Query.Continuous
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Event;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Cache.Event;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Tests for continuous query.
/// </summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
[SuppressMessage("ReSharper", "StaticMemberInGenericType")]
public abstract class ContinuousQueryAbstractTest
{
/** Cache name: ATOMIC, backup. */
protected const string CACHE_ATOMIC_BACKUP = "atomic_backup";
/** Cache name: ATOMIC, no backup. */
protected const string CACHE_ATOMIC_NO_BACKUP = "atomic_no_backup";
/** Cache name: TRANSACTIONAL, backup. */
protected const string CACHE_TX_BACKUP = "transactional_backup";
/** Cache name: TRANSACTIONAL, no backup. */
protected const string CACHE_TX_NO_BACKUP = "transactional_no_backup";
/** Listener events. */
public static BlockingCollection<CallbackEvent> CB_EVTS = new BlockingCollection<CallbackEvent>();
/** Listener events. */
public static BlockingCollection<FilterEvent> FILTER_EVTS = new BlockingCollection<FilterEvent>();
/** First node. */
private IIgnite grid1;
/** Second node. */
private IIgnite grid2;
/** Cache on the first node. */
private ICache<int, BinarizableEntry> cache1;
/** Cache on the second node. */
private ICache<int, BinarizableEntry> cache2;
/** Cache name. */
private readonly string cacheName;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cacheName">Cache name.</param>
protected ContinuousQueryAbstractTest(string cacheName)
{
this.cacheName = cacheName;
}
/// <summary>
/// Set-up routine.
/// </summary>
[TestFixtureSetUp]
public void SetUp()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof(BinarizableEntry)),
new BinaryTypeConfiguration(typeof(BinarizableFilter)),
new BinaryTypeConfiguration(typeof(KeepBinaryFilter))
}
},
SpringConfigUrl = "config\\cache-query-continuous.xml",
IgniteInstanceName = "grid-1"
};
grid1 = Ignition.Start(cfg);
cache1 = grid1.GetCache<int, BinarizableEntry>(cacheName);
cfg.IgniteInstanceName = "grid-2";
grid2 = Ignition.Start(cfg);
cache2 = grid2.GetCache<int, BinarizableEntry>(cacheName);
}
/// <summary>
/// Tear-down routine.
/// </summary>
[TestFixtureTearDown]
public void TearDown()
{
Ignition.StopAll(true);
}
/// <summary>
/// Before-test routine.
/// </summary>
[SetUp]
public void BeforeTest()
{
CB_EVTS = new BlockingCollection<CallbackEvent>();
FILTER_EVTS = new BlockingCollection<FilterEvent>();
AbstractFilter<BinarizableEntry>.res = true;
AbstractFilter<BinarizableEntry>.err = false;
AbstractFilter<BinarizableEntry>.marshErr = false;
AbstractFilter<BinarizableEntry>.unmarshErr = false;
cache1.Remove(PrimaryKey(cache1));
cache1.Remove(PrimaryKey(cache2));
Assert.AreEqual(0, cache1.GetSize());
Assert.AreEqual(0, cache2.GetSize());
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
/// Test arguments validation.
/// </summary>
[Test]
public void TestValidation()
{
Assert.Throws<ArgumentException>(() => { cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(null)); });
}
/// <summary>
/// Test multiple closes.
/// </summary>
[Test]
public void TestMultipleClose()
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
Assert.AreNotEqual(key1, key2);
ContinuousQuery<int, BinarizableEntry> qry =
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
IDisposable qryHnd;
using (qryHnd = cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
// Put from remote node.
cache2.GetAndPut(key2, Entry(key2));
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
}
qryHnd.Dispose();
}
/// <summary>
/// Test regular callback operations.
/// </summary>
[Test]
public void TestCallback()
{
CheckCallback(false);
}
/// <summary>
/// Check regular callback execution.
/// </summary>
/// <param name="loc"></param>
protected void CheckCallback(bool loc)
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
ContinuousQuery<int, BinarizableEntry> qry = loc ?
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>(), true) :
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
using (cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
cache1.GetAndPut(key1, Entry(key1 + 1));
CheckCallbackSingle(key1, Entry(key1), Entry(key1 + 1), CacheEntryEventType.Updated);
cache1.Remove(key1);
CheckCallbackSingle(key1, Entry(key1 + 1), null, CacheEntryEventType.Removed);
// Put from remote node.
cache2.GetAndPut(key2, Entry(key2));
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
cache1.GetAndPut(key2, Entry(key2 + 1));
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, Entry(key2), Entry(key2 + 1), CacheEntryEventType.Updated);
cache1.Remove(key2);
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, Entry(key2 + 1), null, CacheEntryEventType.Removed);
}
cache1.Put(key1, Entry(key1));
CheckNoCallback(100);
cache1.Put(key2, Entry(key2));
CheckNoCallback(100);
}
/// <summary>
/// Test Ignite injection into callback.
/// </summary>
[Test]
public void TestCallbackInjection()
{
Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>();
Assert.IsNull(cb.ignite);
using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb)))
{
Assert.IsNotNull(cb.ignite);
}
}
/// <summary>
/// Test binarizable filter logic.
/// </summary>
[Test]
public void TestFilterBinarizable()
{
CheckFilter(true, false);
}
/// <summary>
/// Test serializable filter logic.
/// </summary>
[Test]
public void TestFilterSerializable()
{
CheckFilter(false, false);
}
/// <summary>
/// Tests the defaults.
/// </summary>
[Test]
public void TestDefaults()
{
var qry = new ContinuousQuery<int, int>(null);
Assert.AreEqual(ContinuousQuery.DefaultAutoUnsubscribe, qry.AutoUnsubscribe);
Assert.AreEqual(ContinuousQuery.DefaultBufferSize, qry.BufferSize);
Assert.AreEqual(ContinuousQuery.DefaultTimeInterval, qry.TimeInterval);
Assert.IsFalse(qry.Local);
}
/// <summary>
/// Check filter.
/// </summary>
/// <param name="binarizable">Binarizable.</param>
/// <param name="loc">Local cache flag.</param>
protected void CheckFilter(bool binarizable, bool loc)
{
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = loc ?
new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true) :
new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
// Put from remote node.
int key2 = PrimaryKey(cache2);
cache1.GetAndPut(key2, Entry(key2));
if (loc)
{
CheckNoFilter(key2);
CheckNoCallback(key2);
}
else
{
CheckFilterSingle(key2, null, Entry(key2));
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
}
AbstractFilter<BinarizableEntry>.res = false;
// Ignored put from local node.
cache1.GetAndPut(key1, Entry(key1 + 1));
CheckFilterSingle(key1, Entry(key1), Entry(key1 + 1));
CheckNoCallback(100);
// Ignored put from remote node.
cache1.GetAndPut(key2, Entry(key2 + 1));
if (loc)
CheckNoFilter(100);
else
CheckFilterSingle(key2, Entry(key2), Entry(key2 + 1));
CheckNoCallback(100);
}
}
/// <summary>
/// Test binarizable filter error during invoke.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterInvokeErrorBinarizable()
{
CheckFilterInvokeError(true);
}
/// <summary>
/// Test serializable filter error during invoke.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterInvokeErrorSerializable()
{
CheckFilterInvokeError(false);
}
/// <summary>
/// Check filter error handling logic during invoke.
/// </summary>
private void CheckFilterInvokeError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.err = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
try
{
cache1.GetAndPut(PrimaryKey(cache1), Entry(1));
Assert.Fail("Should not reach this place.");
}
catch (IgniteException)
{
// No-op.
}
catch (Exception)
{
Assert.Fail("Unexpected error.");
}
// Put from remote node.
try
{
cache1.GetAndPut(PrimaryKey(cache2), Entry(1));
Assert.Fail("Should not reach this place.");
}
catch (IgniteException)
{
// No-op.
}
catch (Exception)
{
Assert.Fail("Unexpected error.");
}
}
}
/// <summary>
/// Test binarizable filter marshalling error.
/// </summary>
[Test]
public void TestFilterMarshalErrorBinarizable()
{
CheckFilterMarshalError(true);
}
/// <summary>
/// Test serializable filter marshalling error.
/// </summary>
[Test]
public void TestFilterMarshalErrorSerializable()
{
CheckFilterMarshalError(false);
}
/// <summary>
/// Check filter marshal error handling.
/// </summary>
/// <param name="binarizable">Binarizable flag.</param>
private void CheckFilterMarshalError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.marshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>)new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
Assert.Throws<Exception>(() =>
{
using (cache1.QueryContinuous(qry))
{
// No-op.
}
});
}
/// <summary>
/// Test non-serializable filter error.
/// </summary>
[Test]
public void TestFilterNonSerializable()
{
CheckFilterNonSerializable(false);
}
/// <summary>
/// Test non-serializable filter behavior.
/// </summary>
/// <param name="loc"></param>
protected void CheckFilterNonSerializable(bool loc)
{
AbstractFilter<BinarizableEntry>.unmarshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter = new LocalFilter();
ContinuousQuery<int, BinarizableEntry> qry = loc
? new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true)
: new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
if (loc)
{
using (cache1.QueryContinuous(qry))
{
// Local put must be fine.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
}
}
else
{
Assert.Throws<BinaryObjectException>(() =>
{
using (cache1.QueryContinuous(qry))
{
// No-op.
}
});
}
}
/// <summary>
/// Test binarizable filter unmarshalling error.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterUnmarshalErrorBinarizable()
{
CheckFilterUnmarshalError(true);
}
/// <summary>
/// Test serializable filter unmarshalling error.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterUnmarshalErrorSerializable()
{
CheckFilterUnmarshalError(false);
}
/// <summary>
/// Check filter unmarshal error handling.
/// </summary>
/// <param name="binarizable">Binarizable flag.</param>
private void CheckFilterUnmarshalError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.unmarshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Local put must be fine.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
// Remote put must fail.
try
{
cache1.GetAndPut(PrimaryKey(cache2), Entry(1));
Assert.Fail("Should not reach this place.");
}
catch (IgniteException)
{
// No-op.
}
catch (Exception)
{
Assert.Fail("Unexpected error.");
}
}
}
/// <summary>
/// Test Ignite injection into filters.
/// </summary>
[Test]
public void TestFilterInjection()
{
Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>();
BinarizableFilter filter = new BinarizableFilter();
Assert.IsNull(filter.ignite);
using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb, filter)))
{
// Local injection.
Assert.IsNotNull(filter.ignite);
// Remote injection.
cache1.GetAndPut(PrimaryKey(cache2), Entry(1));
FilterEvent evt;
Assert.IsTrue(FILTER_EVTS.TryTake(out evt, 500));
Assert.IsNotNull(evt.ignite);
}
}
/// <summary>
/// Test "keep-binary" scenario.
/// </summary>
[Test]
public void TestKeepBinary()
{
var cache = cache1.WithKeepBinary<int, IBinaryObject>();
ContinuousQuery<int, IBinaryObject> qry = new ContinuousQuery<int, IBinaryObject>(
new Listener<IBinaryObject>(), new KeepBinaryFilter());
using (cache.QueryContinuous(qry))
{
// 1. Local put.
cache1.GetAndPut(PrimaryKey(cache1), Entry(1));
CallbackEvent cbEvt;
FilterEvent filterEvt;
Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500));
Assert.AreEqual(PrimaryKey(cache1), filterEvt.entry.Key);
Assert.AreEqual(null, filterEvt.entry.OldValue);
Assert.AreEqual(Entry(1), (filterEvt.entry.Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
Assert.AreEqual(1, cbEvt.entries.Count);
Assert.AreEqual(PrimaryKey(cache1), cbEvt.entries.First().Key);
Assert.AreEqual(null, cbEvt.entries.First().OldValue);
Assert.AreEqual(Entry(1), (cbEvt.entries.First().Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
// 2. Remote put.
ClearEvents();
cache1.GetAndPut(PrimaryKey(cache2), Entry(2));
Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500));
Assert.AreEqual(PrimaryKey(cache2), filterEvt.entry.Key);
Assert.AreEqual(null, filterEvt.entry.OldValue);
Assert.AreEqual(Entry(2), (filterEvt.entry.Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
Assert.AreEqual(1, cbEvt.entries.Count);
Assert.AreEqual(PrimaryKey(cache2), cbEvt.entries.First().Key);
Assert.AreEqual(null, cbEvt.entries.First().OldValue);
Assert.AreEqual(Entry(2),
(cbEvt.entries.First().Value as IBinaryObject).Deserialize<BinarizableEntry>());
}
}
/// <summary>
/// Test value types (special handling is required for nulls).
/// </summary>
[Test]
public void TestValueTypes()
{
var cache = grid1.GetCache<int, int>(cacheName);
var qry = new ContinuousQuery<int, int>(new Listener<int>());
var key = PrimaryKey(cache);
using (cache.QueryContinuous(qry))
{
// First update
cache.Put(key, 1);
CallbackEvent cbEvt;
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
var cbEntry = cbEvt.entries.Single();
Assert.IsFalse(cbEntry.HasOldValue);
Assert.IsTrue(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(null, cbEntry.OldValue);
Assert.AreEqual(1, cbEntry.Value);
// Second update
cache.Put(key, 2);
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
cbEntry = cbEvt.entries.Single();
Assert.IsTrue(cbEntry.HasOldValue);
Assert.IsTrue(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(1, cbEntry.OldValue);
Assert.AreEqual(2, cbEntry.Value);
// Remove
cache.Remove(key);
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
cbEntry = cbEvt.entries.Single();
Assert.IsTrue(cbEntry.HasOldValue);
Assert.IsFalse(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(2, cbEntry.OldValue);
Assert.AreEqual(null, cbEntry.Value);
}
}
/// <summary>
/// Test whether buffer size works fine.
/// </summary>
[Test]
public void TestBufferSize()
{
// Put two remote keys in advance.
var rmtKeys = TestUtils.GetPrimaryKeys(cache2.Ignite, cache2.Name).Take(2).ToList();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
qry.BufferSize = 2;
qry.TimeInterval = TimeSpan.FromMilliseconds(1000000);
using (cache1.QueryContinuous(qry))
{
qry.BufferSize = 2;
cache1.GetAndPut(rmtKeys[0], Entry(rmtKeys[0]));
CheckNoCallback(100);
cache1.GetAndPut(rmtKeys[1], Entry(rmtKeys[1]));
CallbackEvent evt;
Assert.IsTrue(CB_EVTS.TryTake(out evt, 1000));
Assert.AreEqual(2, evt.entries.Count);
var entryRmt0 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[0]); });
var entryRmt1 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[1]); });
Assert.AreEqual(rmtKeys[0], entryRmt0.Key);
Assert.IsNull(entryRmt0.OldValue);
Assert.AreEqual(Entry(rmtKeys[0]), entryRmt0.Value);
Assert.AreEqual(rmtKeys[1], entryRmt1.Key);
Assert.IsNull(entryRmt1.OldValue);
Assert.AreEqual(Entry(rmtKeys[1]), entryRmt1.Value);
}
cache1.Remove(rmtKeys[0]);
cache1.Remove(rmtKeys[1]);
}
/// <summary>
/// Test whether timeout works fine.
/// </summary>
[Test]
public void TestTimeout()
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
ContinuousQuery<int, BinarizableEntry> qry =
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
qry.BufferSize = 2;
qry.TimeInterval = TimeSpan.FromMilliseconds(500);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
// Put from remote node.
cache1.GetAndPut(key2, Entry(key2));
CheckNoCallback(100);
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
}
}
/// <summary>
/// Test whether nested Ignite API call from callback works fine.
/// </summary>
[Test]
public void TestNestedCallFromCallback()
{
var cache = cache1.WithKeepBinary<int, IBinaryObject>();
int key = PrimaryKey(cache1);
NestedCallListener cb = new NestedCallListener();
using (cache.QueryContinuous(new ContinuousQuery<int, IBinaryObject>(cb)))
{
cache1.GetAndPut(key, Entry(key));
cb.countDown.Wait();
}
cache.Remove(key);
}
/// <summary>
/// Tests the initial query.
/// </summary>
[Test]
public void TestInitialQuery()
{
// Scan query, GetAll
TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.GetAll());
// Scan query, iterator
TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.ToList());
// Sql query, GetAll
TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.GetAll());
// Sql query, iterator
TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.ToList());
// Text query, GetAll
TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.GetAll());
// Text query, iterator
TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.ToList());
// Test exception: invalid initial query
var ex = Assert.Throws<IgniteException>(
() => TestInitialQuery(new TextQuery(typeof (BinarizableEntry), "*"), cur => cur.GetAll()));
Assert.AreEqual("Cannot parse '*': '*' or '?' not allowed as first character in WildcardQuery", ex.Message);
}
/// <summary>
/// Tests the initial query.
/// </summary>
private void TestInitialQuery(QueryBase initialQry, Func<IQueryCursor<ICacheEntry<int, BinarizableEntry>>,
IEnumerable<ICacheEntry<int, BinarizableEntry>>> getAllFunc)
{
var qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
cache1.Put(11, Entry(11));
cache1.Put(12, Entry(12));
cache1.Put(33, Entry(33));
try
{
IContinuousQueryHandle<ICacheEntry<int, BinarizableEntry>> contQry;
using (contQry = cache1.QueryContinuous(qry, initialQry))
{
// Check initial query
var initialEntries =
getAllFunc(contQry.GetInitialQueryCursor()).Distinct().OrderBy(x => x.Key).ToList();
Assert.Throws<InvalidOperationException>(() => contQry.GetInitialQueryCursor());
Assert.AreEqual(2, initialEntries.Count);
for (int i = 0; i < initialEntries.Count; i++)
{
Assert.AreEqual(i + 11, initialEntries[i].Key);
Assert.AreEqual(i + 11, initialEntries[i].Value.val);
}
// Check continuous query
cache1.Put(44, Entry(44));
CheckCallbackSingle(44, null, Entry(44), CacheEntryEventType.Created);
}
Assert.Throws<ObjectDisposedException>(() => contQry.GetInitialQueryCursor());
contQry.Dispose(); // multiple dispose calls are ok
}
finally
{
cache1.Clear();
}
}
/// <summary>
/// Check single filter event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected value.</param>
private void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal)
{
CheckFilterSingle(expKey, expOldVal, expVal, 1000);
ClearEvents();
}
/// <summary>
/// Check single filter event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected value.</param>
/// <param name="timeout">Timeout.</param>
private static void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal, int timeout)
{
FilterEvent evt;
Assert.IsTrue(FILTER_EVTS.TryTake(out evt, timeout));
Assert.AreEqual(expKey, evt.entry.Key);
Assert.AreEqual(expOldVal, evt.entry.OldValue);
Assert.AreEqual(expVal, evt.entry.Value);
ClearEvents();
}
/// <summary>
/// Clears the events collection.
/// </summary>
private static void ClearEvents()
{
while (FILTER_EVTS.Count > 0)
FILTER_EVTS.Take();
}
/// <summary>
/// Ensure that no filter events are logged.
/// </summary>
/// <param name="timeout">Timeout.</param>
private static void CheckNoFilter(int timeout)
{
FilterEvent evt;
Assert.IsFalse(FILTER_EVTS.TryTake(out evt, timeout));
}
/// <summary>
/// Check single callback event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected new value.</param>
/// <param name="expType">Expected type.</param>
/// <param name="timeout">Timeout.</param>
private static void CheckCallbackSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal,
CacheEntryEventType expType, int timeout = 1000)
{
CallbackEvent evt;
Assert.IsTrue(CB_EVTS.TryTake(out evt, timeout));
Assert.AreEqual(0, CB_EVTS.Count);
var e = evt.entries.Single();
Assert.AreEqual(expKey, e.Key);
Assert.AreEqual(expOldVal, e.OldValue);
Assert.AreEqual(expVal, e.Value);
Assert.AreEqual(expType, e.EventType);
}
/// <summary>
/// Ensure that no callback events are logged.
/// </summary>
/// <param name="timeout">Timeout.</param>
private void CheckNoCallback(int timeout)
{
CallbackEvent evt;
Assert.IsFalse(CB_EVTS.TryTake(out evt, timeout));
}
/// <summary>
/// Craate entry.
/// </summary>
/// <param name="val">Value.</param>
/// <returns>Entry.</returns>
private static BinarizableEntry Entry(int val)
{
return new BinarizableEntry(val);
}
/// <summary>
/// Get primary key for cache.
/// </summary>
/// <param name="cache">Cache.</param>
/// <returns>Primary key.</returns>
private static int PrimaryKey<T>(ICache<int, T> cache)
{
return TestUtils.GetPrimaryKey(cache.Ignite, cache.Name);
}
/// <summary>
/// Creates object-typed event.
/// </summary>
private static ICacheEntryEvent<object, object> CreateEvent<T, V>(ICacheEntryEvent<T,V> e)
{
if (!e.HasOldValue)
return new CacheEntryCreateEvent<object, object>(e.Key, e.Value);
if (!e.HasValue)
return new CacheEntryRemoveEvent<object, object>(e.Key, e.OldValue);
return new CacheEntryUpdateEvent<object, object>(e.Key, e.OldValue, e.Value);
}
/// <summary>
/// Binarizable entry.
/// </summary>
public class BinarizableEntry
{
/** Value. */
public readonly int val;
/** <inheritDot /> */
public override int GetHashCode()
{
return val;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="val">Value.</param>
public BinarizableEntry(int val)
{
this.val = val;
}
/** <inheritDoc /> */
public override bool Equals(object obj)
{
return obj != null && obj is BinarizableEntry && ((BinarizableEntry)obj).val == val;
}
/** <inheritDoc /> */
public override string ToString()
{
return string.Format("BinarizableEntry [Val: {0}]", val);
}
}
/// <summary>
/// Abstract filter.
/// </summary>
[Serializable]
public abstract class AbstractFilter<V> : ICacheEntryEventFilter<int, V>
{
/** Result. */
public static volatile bool res = true;
/** Throw error on invocation. */
public static volatile bool err;
/** Throw error during marshalling. */
public static volatile bool marshErr;
/** Throw error during unmarshalling. */
public static volatile bool unmarshErr;
/** Grid. */
[InstanceResource]
public IIgnite ignite;
/** <inheritDoc /> */
public bool Evaluate(ICacheEntryEvent<int, V> evt)
{
if (err)
throw new Exception("Filter error.");
FILTER_EVTS.Add(new FilterEvent(ignite, CreateEvent(evt)));
return res;
}
}
/// <summary>
/// Filter which cannot be serialized.
/// </summary>
public class LocalFilter : AbstractFilter<BinarizableEntry>, IBinarizable
{
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
/// <summary>
/// Binarizable filter.
/// </summary>
public class BinarizableFilter : AbstractFilter<BinarizableEntry>, IBinarizable
{
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
if (marshErr)
throw new Exception("Filter marshalling error.");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
if (unmarshErr)
throw new Exception("Filter unmarshalling error.");
}
}
/// <summary>
/// Serializable filter.
/// </summary>
[Serializable]
public class SerializableFilter : AbstractFilter<BinarizableEntry>, ISerializable
{
/// <summary>
/// Constructor.
/// </summary>
public SerializableFilter()
{
// No-op.
}
/// <summary>
/// Serialization constructor.
/// </summary>
/// <param name="info">Info.</param>
/// <param name="context">Context.</param>
protected SerializableFilter(SerializationInfo info, StreamingContext context)
{
if (unmarshErr)
throw new Exception("Filter unmarshalling error.");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (marshErr)
throw new Exception("Filter marshalling error.");
}
}
/// <summary>
/// Filter for "keep-binary" scenario.
/// </summary>
public class KeepBinaryFilter : AbstractFilter<IBinaryObject>
{
// No-op.
}
/// <summary>
/// Listener.
/// </summary>
public class Listener<V> : ICacheEntryEventListener<int, V>
{
[InstanceResource]
public IIgnite ignite;
/** <inheritDoc /> */
public void OnEvent(IEnumerable<ICacheEntryEvent<int, V>> evts)
{
CB_EVTS.Add(new CallbackEvent(evts.Select(CreateEvent).ToList()));
}
}
/// <summary>
/// Listener with nested Ignite API call.
/// </summary>
public class NestedCallListener : ICacheEntryEventListener<int, IBinaryObject>
{
/** Event. */
public readonly CountdownEvent countDown = new CountdownEvent(1);
public void OnEvent(IEnumerable<ICacheEntryEvent<int, IBinaryObject>> evts)
{
foreach (ICacheEntryEvent<int, IBinaryObject> evt in evts)
{
IBinaryObject val = evt.Value;
IBinaryType meta = val.GetBinaryType();
Assert.AreEqual(typeof(BinarizableEntry).FullName, meta.TypeName);
}
countDown.Signal();
}
}
/// <summary>
/// Filter event.
/// </summary>
public class FilterEvent
{
/** Grid. */
public IIgnite ignite;
/** Entry. */
public ICacheEntryEvent<object, object> entry;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="ignite">Grid.</param>
/// <param name="entry">Entry.</param>
public FilterEvent(IIgnite ignite, ICacheEntryEvent<object, object> entry)
{
this.ignite = ignite;
this.entry = entry;
}
}
/// <summary>
/// Callbakc event.
/// </summary>
public class CallbackEvent
{
/** Entries. */
public ICollection<ICacheEntryEvent<object, object>> entries;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="entries">Entries.</param>
public CallbackEvent(ICollection<ICacheEntryEvent<object, object>> entries)
{
this.entries = entries;
}
}
/// <summary>
/// ScanQuery filter for InitialQuery test.
/// </summary>
[Serializable]
private class InitialQueryScanFilter : ICacheEntryFilter<int, BinarizableEntry>
{
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, BinarizableEntry> entry)
{
return entry.Key < 33;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AndInt32()
{
var test = new SimpleBinaryOpTest__AndInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndInt32
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int32);
private const int Op2ElementCount = VectorSize / sizeof(Int32);
private const int RetElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable;
static SimpleBinaryOpTest__AndInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AndInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.And(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.And(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.And(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.And(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndInt32();
var result = Sse2.And(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.And(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
if ((int)(left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.And)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Lens;
namespace ConsoleHost
{
internal class Program
{
private static void Main()
{
PrintPreamble();
WarmUp();
var timer = false;
while (RequestInput(out var source, ref timer))
{
Console.WriteLine();
try
{
var lc = new LensCompiler(new LensCompilerOptions {AllowSave = true, MeasureTime = timer});
var res = lc.Run(source);
PrintObject(res);
if (timer)
PrintMeasurements(lc.Measurements);
}
catch (LensCompilerException ex)
{
PrintError(source, ex);
}
catch (Exception ex)
{
PrintException("An unexpected error has occured!", ex.Message + Environment.NewLine + ex.StackTrace);
}
}
}
private static bool RequestInput(out string input, ref bool timer)
{
var lines = new List<string>();
var prefix = 0;
while (true)
{
Console.Write("> ");
for (var idx = 0; idx < prefix; idx++)
SendKeys.SendWait(" ");
var line = Console.ReadLine();
if (line == null)
continue;
if (line.Length > 0)
{
if (line.Length > 1 && line[line.Length - 1] == '#')
{
lines.Add(line.Substring(0, line.Length - 1));
input = BuildString(lines);
return true;
}
#region Commands
if (line[0] == '#')
{
if (line == "#exit")
{
input = null;
return false;
}
if (line == "#run")
{
input = BuildString(lines);
return true;
}
if (line == "#clr")
{
lines = new List<string>();
Console.Clear();
PrintPreamble();
continue;
}
if (line.StartsWith("#timer"))
{
var param = line.Substring("#timer".Length).Trim().ToLowerInvariant();
if (param == "on")
{
timer = true;
PrintHint("Timer enabled.");
continue;
}
if (param == "off")
{
timer = false;
PrintHint("Timer disabled.");
continue;
}
}
if (line.StartsWith("#load"))
{
var param = line.Substring("#load".Length).Trim().ToLowerInvariant();
try
{
using (var fs = new FileStream(param, FileMode.Open, FileAccess.Read))
using (var sr = new StreamReader(fs))
{
input = sr.ReadToEnd();
return true;
}
}
catch
{
PrintHint(string.Format("File '{0}' could not be loaded!", param));
continue;
}
}
if (line == "#oops")
{
if (lines.Count > 0)
lines.RemoveAt(lines.Count - 1);
continue;
}
PrintHelp();
continue;
}
#endregion
}
prefix = GetIdent(line);
lines.Add(line.TrimEnd());
}
}
private static string BuildString(ICollection<string> lines)
{
var sb = new StringBuilder(lines.Count);
foreach (var curr in lines)
sb.AppendLine(curr);
return sb.ToString();
}
private static void PrintPreamble()
{
using (new OutputColor(ConsoleColor.DarkGray))
{
Console.WriteLine("=====================");
Console.WriteLine(" LENS Console Host");
Console.WriteLine("=====================");
Console.WriteLine("(type #help for help)");
Console.WriteLine();
}
}
private static void PrintException(string msg, string details)
{
using (new OutputColor(ConsoleColor.Yellow))
{
Console.WriteLine(msg);
Console.WriteLine();
Console.WriteLine(details);
Console.WriteLine();
}
}
private static void PrintError(string src, LensCompilerException ex)
{
using (new OutputColor(ConsoleColor.Red))
{
Console.WriteLine("Error {0}", ex.Message);
Console.WriteLine();
}
if (ex.StartLocation == null)
return;
var loc = ex.StartLocation.Value;
var line = src.Split(new[] {Environment.NewLine}, StringSplitOptions.None)[loc.Line - 1].TrimEnd();
var len = ex.EndLocation != null && ex.EndLocation.Value.Line == loc.Line
? ex.EndLocation.Value.Offset - loc.Offset
: line.Length - loc.Offset + 1;
using (new OutputColor(ConsoleColor.DarkGray))
Console.Write("> {0}", line.Substring(0, loc.Offset - 1));
using (new OutputColor(ConsoleColor.White, ConsoleColor.Red))
Console.Write("{0}", line.Substring(loc.Offset - 1, len));
if (len < line.Length - 1)
using (new OutputColor(ConsoleColor.DarkGray))
Console.Write("{0}", line.Substring(loc.Offset + len - 1));
Console.WriteLine();
Console.WriteLine();
}
private static void PrintHint(string hint)
{
using (new OutputColor(ConsoleColor.DarkGray))
{
Console.WriteLine();
Console.WriteLine(hint);
Console.WriteLine();
}
}
private static void PrintHelp()
{
using (new OutputColor(ConsoleColor.DarkGray))
{
Console.WriteLine();
Console.WriteLine("====================================");
Console.WriteLine("= LENS Compiler v4.2 =");
Console.WriteLine("= https://github.com/impworks/lens =");
Console.WriteLine("====================================");
Console.WriteLine();
Console.WriteLine("To enter a script, just type it line by line.");
Console.WriteLine("Finish the line with # to execute the script.");
Console.WriteLine();
Console.WriteLine("Available interpreter commands:");
Console.WriteLine();
Console.WriteLine(" #exit - close the interpreter");
Console.WriteLine(" #run - execute the script and print the output");
Console.WriteLine(" #oops - cancel last line");
Console.WriteLine(" #clr - clear the console");
Console.WriteLine();
Console.WriteLine(" #timer (on|off) - enable/disable time measurement");
Console.WriteLine(" #load <filename> - load file and execute its contents");
Console.WriteLine();
}
}
private static void PrintObject(dynamic obj)
{
Console.WriteLine();
Console.WriteLine(GetStringRepresentation(obj));
if ((object) obj != null)
using (new OutputColor(ConsoleColor.DarkGray))
Console.WriteLine("({0})", obj.GetType());
Console.WriteLine();
}
private static void PrintMeasurements(Dictionary<string, TimeSpan> measures)
{
using (new OutputColor(ConsoleColor.DarkGray))
{
foreach (var curr in measures)
Console.WriteLine("{0}: {1:0,00} ms.", curr.Key, curr.Value.TotalMilliseconds);
Console.WriteLine();
}
}
private static string GetStringRepresentation(dynamic obj)
{
if ((object) obj == null)
return "(null)";
if (obj is bool)
return obj ? "true" : "false";
if (obj is string)
return string.Format(@"""{0}""", obj);
if (obj is IDictionary)
{
var list = new List<string>();
var count = 0;
foreach (var currKey in obj.Keys)
{
if (count < 50)
{
list.Add(
string.Format(
"{0} => {1}",
GetStringRepresentation(currKey),
GetStringRepresentation(obj[currKey])
)
);
}
else
{
list.Add("...");
break;
}
count++;
}
return string.Format("{{ {0} }}", string.Join("; ", list));
}
if (obj is IEnumerable)
{
var list = new List<string>();
var count = 0;
foreach (var curr in obj)
{
if (count < 50)
{
list.Add(GetStringRepresentation(curr));
}
else
{
list.Add("...");
break;
}
count++;
}
return string.Format("[ {0} ]", string.Join("; ", list));
}
return obj is double || obj is float
? obj.ToString(CultureInfo.InvariantCulture)
: obj.ToString();
}
private static int GetIdent(string line)
{
var idx = 0;
while (idx < line.Length && line[idx] == ' ')
idx++;
if (ShouldIdent(line))
idx += 4;
return idx;
}
private static readonly Regex[] LineFeeds =
{
new Regex(@"^(type|record)\s+[_a-z][_a-z0-9]*$", RegexOptions.IgnoreCase | RegexOptions.Compiled),
new Regex(@"\bif\b.+\bthen$", RegexOptions.IgnoreCase | RegexOptions.Compiled),
new Regex(@"\b(while|for|using)\b.+\bdo$", RegexOptions.IgnoreCase | RegexOptions.Compiled),
new Regex(@"^(try|finally|else)$", RegexOptions.IgnoreCase | RegexOptions.Compiled),
new Regex(@"new\s*(\(|\[\[?|\{)$", RegexOptions.IgnoreCase | RegexOptions.Compiled),
new Regex(@"^catch\s+(\([_a-][_a-z0-9]*(\s+[_a-][_a-z0-9]*)?\))?$", RegexOptions.IgnoreCase | RegexOptions.Compiled)
};
private static bool ShouldIdent(string line)
{
var trim = line.Trim();
return trim.EndsWith("->") || LineFeeds.Any(curr => curr.IsMatch(trim));
}
private static void WarmUp()
{
var compiler = new LensCompiler(new LensCompilerOptions());
compiler.Run("1 + 2");
}
}
}
| |
using UnityEngine;
using System;
using System.Collections.Generic;
using PixelCrushers.DialogueSystem.UnityGUI;
namespace PixelCrushers.DialogueSystem.Examples {
/// <summary>
/// This component implements a proximity-based selector that allows the player to move into
/// range and use a usable object.
///
/// To mark an object usable, add the Usable component and a collider to it. The object's
/// layer should be in the layer mask specified on the Selector component.
///
/// The proximity selector tracks the most recent usable object whose trigger the player has
/// entered. It displays a targeting reticle and information about the object. If the target
/// is in range, the inRange reticle texture is displayed; otherwise the outOfRange texture is
/// displayed.
///
/// If the player presses the use button (which defaults to spacebar and Fire2), the targeted
/// object will receive an "OnUse" message.
///
/// You can hook into SelectedUsableObject and DeselectedUsableObject to get notifications
/// when the current target has changed.
/// </summary>
public class ProximitySelector : MonoBehaviour {
/// <summary>
/// This class defines the textures and size of the targeting reticle.
/// </summary>
[System.Serializable]
public class Reticle {
public Texture2D inRange;
public Texture2D outOfRange;
public float width = 64f;
public float height = 64f;
}
/// <summary>
/// If <c>true</c>, uses a default OnGUI to display a selection message and
/// targeting reticle.
/// </summary>
public bool useDefaultGUI = true;
/// <summary>
/// The GUI skin to use for the target's information (name and use message).
/// </summary>
public GUISkin guiSkin;
/// <summary>
/// The color of the information labels when the target is in range.
/// </summary>
public Color color = Color.yellow;
/// <summary>
/// The default use message. This can be overridden in the target's Usable component.
/// </summary>
public string defaultUseMessage = "(spacebar to interact)";
/// <summary>
/// The key that sends an OnUse message.
/// </summary>
public KeyCode useKey = KeyCode.Space;
/// <summary>
/// The button that sends an OnUse message.
/// </summary>
public string useButton = "Fire2";
/// <summary>
/// If ticked, the OnUse message is broadcast to the usable object's children.
/// </summary>
public bool broadcastToChildren = true;
/// <summary>
/// Occurs when the selector has targeted a usable object.
/// </summary>
public event SelectedUsableObjectDelegate SelectedUsableObject = null;
/// <summary>
/// Occurs when the selector has untargeted a usable object.
/// </summary>
public event DeselectedUsableObjectDelegate DeselectedUsableObject = null;
/// <summary>
/// Keeps track of which usable objects' triggers the selector is currently inside.
/// </summary>
private List<Usable> usablesInRange = new List<Usable>();
/// <summary>
/// The current usable that will receive an OnUse message if the player hits the use button.
/// </summary>
private Usable currentUsable = null;
/// <summary>
/// Caches the GUI style to use when displaying the selection message in OnGUI.
/// </summary>
private GUIStyle guiStyle = null;
/// <summary>
/// Sends an OnUse message to the current selection if the player presses the use button.
/// </summary>
void Update() {
// Exit if disabled or paused:
if (!enabled || (Time.timeScale <= 0)) return;
// If the player presses the use key/button, send the OnUse message:
if (IsUseButtonDown() && (currentUsable != null)) {
if (broadcastToChildren) {
currentUsable.gameObject.BroadcastMessage("OnUse", this.transform, SendMessageOptions.DontRequireReceiver);
} else {
currentUsable.gameObject.SendMessage("OnUse", this.transform, SendMessageOptions.DontRequireReceiver);
}
}
}
/// <summary>
/// Checks whether the player has just pressed the use button.
/// </summary>
/// <returns>
/// <c>true</c> if the use button/key is down; otherwise, <c>false</c>.
/// </returns>
private bool IsUseButtonDown() {
return ((useKey != KeyCode.None) && Input.GetKeyDown(useKey))
|| (!string.IsNullOrEmpty(useButton) && Input.GetButtonUp(useButton));
}
/// <summary>
/// If we entered a trigger, check if it's a usable object. If so, update the selection
/// and raise the SelectedUsableObject event.
/// </summary>
/// <param name='other'>
/// The trigger collider.
/// </param>
void OnTriggerEnter(Collider other) {
CheckTriggerEnter(other.gameObject);
}
/// <summary>
/// If we entered a 2D trigger, check if it's a usable object. If so, update the selection
/// and raise the SelectedUsableObject event.
/// </summary>
/// <param name='other'>
/// The 2D trigger collider.
/// </param>
void OnTriggerEnter2D(Collider2D other) {
CheckTriggerEnter(other.gameObject);
}
/// <summary>
/// If we just left a trigger, check if it's the current selection. If so, clear the
/// selection and raise the DeselectedUsableObject event. If we're still in range of
/// any other usables, select one of them.
/// </summary>
/// <param name='other'>
/// The trigger collider.
/// </param>
void OnTriggerExit(Collider other) {
CheckTriggerExit(other.gameObject);
}
/// <summary>
/// If we just left a 2D trigger, check if it's the current selection. If so, clear the
/// selection and raise the DeselectedUsableObject event. If we're still in range of
/// any other usables, select one of them.
/// </summary>
/// <param name='other'>
/// The 2D trigger collider.
/// </param>
void OnTriggerExit2D(Collider2D other) {
CheckTriggerExit(other.gameObject);
}
private void CheckTriggerEnter(GameObject other) {
Usable usable = other.GetComponent<Usable>();
if (usable != null) {
currentUsable = usable;
if (!usablesInRange.Contains(usable)) usablesInRange.Add(usable);
if (SelectedUsableObject != null) SelectedUsableObject(usable);
}
}
private void CheckTriggerExit(GameObject other) {
Usable usable = other.GetComponent<Usable>();
if (usable != null) {
if (usablesInRange.Contains(usable)) usablesInRange.Remove(usable);
if (currentUsable == usable) {
if (DeselectedUsableObject != null) DeselectedUsableObject(usable);
currentUsable = null;
if (usablesInRange.Count > 0) {
currentUsable = usablesInRange[0];
if (SelectedUsableObject != null) SelectedUsableObject(currentUsable);
}
}
}
}
/// <summary>
/// If useDefaultGUI is <c>true</c> and a usable object has been targeted, this method
/// draws a selection message and targeting reticle.
/// </summary>
void OnGUI() {
if (useDefaultGUI) {
GUI.skin = UnityGUITools.GetValidGUISkin(guiSkin);
if (guiStyle == null) {
guiStyle = new GUIStyle(GUI.skin.label);
guiStyle.alignment = TextAnchor.UpperCenter;
guiStyle.normal.textColor = color;
}
Rect screenRect = new Rect(0, 0, Screen.width, Screen.height);
if (currentUsable != null) {
string heading = string.IsNullOrEmpty(currentUsable.overrideName) ? currentUsable.name : currentUsable.overrideName;
string useMessage = string.IsNullOrEmpty(currentUsable.overrideUseMessage) ? defaultUseMessage : currentUsable.overrideUseMessage;
UnityGUITools.DrawText(screenRect, heading, guiStyle, TextStyle.Shadow);
UnityGUITools.DrawText(new Rect(0, guiStyle.CalcSize(new GUIContent("Ay")).y, Screen.width, Screen.height), useMessage, guiStyle, TextStyle.Shadow);
}
}
}
}
}
| |
namespace LuaInterface
{
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Threading;
using System.Text;
using UnityEngine;
public delegate byte[] ReadLuaFile(string name);
public static class LuaStatic
{
public static ReadLuaFile Load = null;
//private static int trace = 0;
static LuaStatic()
{
Load = DefaultLoader;
}
//public static void InitTraceback(IntPtr L)
//{
// int oldTop = LuaDLL.lua_gettop(L);
// LuaDLL.lua_getglobal(L, "debug");
// LuaDLL.lua_getfield(L, -1, "traceback");
// trace = LuaDLL.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
// LuaDLL.lua_settop(L, oldTop);
//}
static byte[] DefaultLoader(string path)
{
byte[] str = null;
if (File.Exists(path))
{
str = File.ReadAllBytes(path);
}
return str;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
public static int panic(IntPtr L)
{
string reason = String.Format("unprotected error in call to Lua API ({0})", LuaDLL.lua_tostring(L, -1));
LuaDLL.lua_pop(L, 1);
throw new LuaException(reason);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
public static int traceback(IntPtr L)
{
LuaDLL.lua_getglobal(L, "debug");
LuaDLL.lua_getfield(L, -1, "traceback");
LuaDLL.lua_pushvalue(L, 1);
LuaDLL.lua_pushnumber(L, 2);
LuaDLL.lua_call(L, 2, 1);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
public static int print(IntPtr L)
{
// For each argument we'll 'tostring' it
int n = LuaDLL.lua_gettop(L);
string s = String.Empty;
//LuaDLL.lua_getglobal(L, "debug");
//LuaDLL.lua_getfield(L, -1, "traceback");
//LuaDLL.lua_pushvalue(L, 1);
//LuaDLL.lua_pushnumber(L, 2);
//LuaDLL.lua_call(L, 2, 1);
//n = LuaDLL.lua_gettop(L);
LuaDLL.lua_getglobal(L, "tostring");
for( int i = 1; i <= n; i++ )
{
LuaDLL.lua_pushvalue(L, -1); /* function to be called */
LuaDLL.lua_pushvalue(L, i); /* value to print */
LuaDLL.lua_call(L, 1, 1);
if( i > 1 )
{
s += "\t";
}
s += LuaDLL.lua_tostring(L, -1);
LuaDLL.lua_pop(L, 1); /* pop result */
//LuaDLL.PrintCmd(s);
}
Debug.Log("LUA: " + s);
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
public static int loader(IntPtr L)
{
// Get script to load
string fileName = string.Empty;
fileName = LuaDLL.lua_tostring(L, 1);
//fileName = fileName.Replace('.', '/');
//fileName += ".lua";
string lowerName = fileName.ToLower();
if (lowerName.EndsWith(".lua")) {
int index = fileName.LastIndexOf('.');
fileName = fileName.Substring(0, index);
}
fileName = fileName.Replace('.', '/') + ".lua";
/*
// Load with Unity3D resources
byte[] text = Load(fileName);
if( text == null )
{
return 0;
}
LuaDLL.luaL_loadbuffer(L, text, text.Length, fileName);
*/
LuaScriptMgr mgr = LuaScriptMgr.GetMgrFromLuaState(L);
if (mgr == null) return 0;
LuaDLL.lua_pushstdcallcfunction(L, mgr.lua.tracebackFunction);
int oldTop = LuaDLL.lua_gettop(L);
byte[] text = LuaStatic.Load(fileName);
if (text == null) {
if (!fileName.Contains("mobdebug")) {
Debugger.LogError("Loader lua file failed: {0}", fileName);
}
LuaDLL.lua_pop(L, 1);
return 0;
}
if (LuaDLL.luaL_loadbuffer(L, text, text.Length, fileName) != 0) {
mgr.lua.ThrowExceptionFromError(oldTop);
LuaDLL.lua_pop(L, 1);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
public static int dofile(IntPtr L)
{
// Get script to load
string fileName = String.Empty;
fileName = LuaDLL.lua_tostring(L, 1);
//fileName.Replace('.', '/');
//fileName += ".lua";
string lowerName = fileName.ToLower();
if (lowerName.EndsWith(".lua")) {
int index = fileName.LastIndexOf('.');
fileName = fileName.Substring(0, index);
}
fileName = fileName.Replace('.', '/') + ".lua";
int n = LuaDLL.lua_gettop(L);
// Load with Unity3D resources
byte[] text = Load(fileName);
if( text == null )
{
return LuaDLL.lua_gettop(L) - n;
}
if (LuaDLL.luaL_loadbuffer(L, text, text.Length, fileName) == 0)
{
LuaDLL.lua_call(L, 0, LuaDLL.LUA_MULTRET);
}
return LuaDLL.lua_gettop(L) - n;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
public static int loadfile(IntPtr L)
{
return loader(L);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
public static int importWrap(IntPtr L) {
string fileName = String.Empty;
fileName = LuaDLL.lua_tostring(L, 1);
fileName = fileName.Replace('.', '_');
if (!string.IsNullOrEmpty(fileName)) {
LuaBinder.Bind(L, fileName);
}
return 0;
}
public static string init_luanet =
@"local metatable = {}
local rawget = rawget
local debug = debug
local import_type = luanet.import_type
local load_assembly = luanet.load_assembly
luanet.error, luanet.type = error, type
-- Lookup a .NET identifier component.
function metatable:__index(key) -- key is e.g. 'Form'
-- Get the fully-qualified name, e.g. 'System.Windows.Forms.Form'
local fqn = rawget(self,'.fqn')
fqn = ((fqn and fqn .. '.') or '') .. key
-- Try to find either a luanet function or a CLR type
local obj = rawget(luanet,key) or import_type(fqn)
-- If key is neither a luanet function or a CLR type, then it is simply
-- an identifier component.
if obj == nil then
-- It might be an assembly, so we load it too.
pcall(load_assembly,fqn)
obj = { ['.fqn'] = fqn }
setmetatable(obj, metatable)
end
-- Cache this lookup
rawset(self, key, obj)
return obj
end
-- A non-type has been called; e.g. foo = System.Foo()
function metatable:__call(...)
error('No such type: ' .. rawget(self,'.fqn'), 2)
end
-- This is the root of the .NET namespace
luanet['.fqn'] = false
setmetatable(luanet, metatable)
-- Preload the mscorlib assembly
luanet.load_assembly('mscorlib')
function traceback(msg)
return debug.traceback(msg, 1)
end";
}
}
| |
using System;
using System.Data;
using System.Collections.Generic;
namespace Epi.Data
{
/// <summary>
/// Abstract data type for databases
/// </summary>
public interface IDbDriver
{
#region Properties
/// <summary>
/// Gets the default schema prefix if applicable (ex. dbo for SQL Server)
/// </summary>
string SchemaPrefix
{
get;
}
/// <summary>
/// Property to specify if the same operation will be called multiple times. Data driver should use this to optimize code.
/// </summary>
bool IsBulkOperation
{
get;
set;
}
/// <summary>
/// Returns the full name of the data source. Typically used for display purposes
/// </summary>
string FullName
{
get;
}
/// <summary>
/// Gets/sets the Database name
/// </summary>
string DbName
{
get;
set;
}
/// <summary>
/// Gets the database connection string
/// </summary>
string ConnectionString
{
get;
set;
}
/// <summary>
/// Gets an OLE-compatible connection string.
/// This is needed by Epi Map, as ESRI does not understand .NET connection strings.
/// See http://www.ConnectionStrings.com for an OLE-compatible connection string for
/// your database.
/// </summary>
string OleConnectionString
{
get;
}
/// <summary>
/// What is this?
/// </summary>
string DataSource
{
get;
}
/// <summary>
/// Gets a user-friendly description of the otherwise bewildering connection string
/// </summary>
string ConnectionDescription
{
get;
}
/// <summary>
/// Returns the maximum number of columns a table can have.
/// </summary>
int TableColumnMax
{
get;
}
string SyntaxTrue
{
get;
}
string SyntaxFalse
{
get;
}
#endregion Properties
#region Methods
/// <summary>
/// Gets whether or not the database format is valid. Used for error checking on file-based database types.
/// </summary>
/// <param name="validationMessage">Any associated validation error messages</param>
/// <returns>bool</returns>
bool IsDatabaseFormatValid(ref string validationMessage);
/// <summary>
/// Gets permissions on this database
/// </summary>
/// <returns>ProjectPermissions</returns>
ProjectPermissions GetPermissions();
/// <summary>
/// Test database connectivity
/// </summary>
/// <returns>Returns true if connection can be made successfully</returns>
bool TestConnection();
/// <summary>
/// Creates a table with the given columns
/// </summary>
/// <param name="tableName">The name of the table to create</param>
/// <param name="columns">List of columns</param>
void CreateTable(string tableName, List<TableColumn> columns);
/// <summary>
/// Gets the names of all tables in the database
/// </summary>
/// <returns>Names of all tables in the database</returns>
List<string> GetTableNames();
/// <summary>
/// GetTableSchema
/// </summary>
/// <returns>Table Schema</returns>
DataSets.TableSchema.TablesDataTable GetTableSchema();
/// <summary>
/// Gets the number of tables in the database
/// </summary>
/// <returns>The number of tables in the database</returns>
int GetTableCount();
/// <summary>
/// Return the number of colums in the specified table
/// </summary>
/// <remarks>
/// Originaly intended to be used to keep view tables from getting to wide.
/// </remarks>
/// <param name="tableName"></param>
/// <returns>the number of columns in the </returns>
int GetTableColumnCount(string tableName);
/// <summary>
/// Change the data type of the column in current database
/// </summary>
/// <param name="tableName">name of the table</param>
/// <param name="columnName">name of the column</param>
/// <param name="columnType">new data type of the column</param>
/// <returns>Boolean</returns>
bool AlterColumnType(string tableName, string columnName, string columnType);
/// <summary>
/// Adds a column to the table
/// </summary>
/// <param name="tableName">name of the table</param>
/// <param name="column">The column</param>
/// <returns>Boolean</returns>
bool AddColumn(string tableName, TableColumn column);
/// <summary>
/// Executes a sql query to select records into a data table
/// </summary>
/// <param name="selectQuery"></param>
/// <returns></returns>
DataTable Select(Query selectQuery);
/// <summary>
/// Executes a SELECT statement against the database and returns a disconnected data table. NOTE: Use this overload to work with Typed DataSets.
/// </summary>
/// <param name="selectQuery">The query to be executed against the database</param>
/// <param name="table">Table that will contain the result</param>
/// <returns>A data table object</returns>
DataTable Select(Query selectQuery, DataTable table);
/// <summary>
/// Gets a value indicating whether or not a specific column exists for a table in the database
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <param name="columnName">Name of the column</param>
/// <returns>Boolean</returns>
bool ColumnExists(string tableName, string columnName);
/// <summary>
/// Compact the database
/// Note: May only apply to Access databases
/// </summary>
/// <returns>returns false on error</returns>
bool CompactDatabase();
/// <summary>
/// Executes a SQL statement that does not return any records.
/// Returns the number of records affected
/// </summary>
/// <param name="nonQueryStatement">The query to be executed against the database</param>
int ExecuteNonQuery(Query nonQueryStatement);
/// <summary>
/// Executes a SQL non-query within a transaction.
/// </summary>
/// <param name="nonQueryStatement">The query to be executed against the database</param>
/// <param name="transaction">The transaction through which to execute the non query</param>
int ExecuteNonQuery(Query nonQueryStatement, IDbTransaction transaction);
/// <summary>
/// Executes a scalar query against the database
/// </summary>
/// <param name="scalarStatement">The query to be executed against the database</param>
/// <returns></returns>
object ExecuteScalar(Query scalarStatement);
/// <summary>
/// Executes a scalar query against the database using an existing transaction
/// </summary>
/// <param name="scalarStatement">The query to be executed against the database</param>
/// <param name="transaction">The transaction through which to execute the scalar query</param>
/// <returns></returns>
object ExecuteScalar(Query scalarStatement, IDbTransaction transaction);
/// <summary>
/// Delete a specific table in current database
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>Boolean</returns>
bool DeleteTable(string tableName);
/// <summary>
/// Delete a specific column in current database
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <param name="columnName">Name of the column</param>
/// <returns>Boolean</returns>
bool DeleteColumn(string tableName, string columnName);
/// <summary>
/// Gets a value indicating whether or not a specific table exists in the database
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>Boolean</returns>
bool TableExists(string tableName);
/// <summary>
/// Gets primary_key schema information about an OLE table
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>DataTable with schema information</returns>
DataSets.TableColumnSchema.ColumnsDataTable GetTableColumnSchema(string tableName);
/// <summary>
/// Gets primary_key schema information about an OLE table
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>DataTable with schema information</returns>
DataSets.ANSI.TableColumnSchema.ColumnsDataTable GetTableColumnSchemaANSI(string tableName);
/// <summary>
/// Gets Primary_Keys schema information about an OLE table
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>DataTable with schema information</returns>
DataSets.TableKeysSchema.Primary_KeysDataTable GetTableKeysSchema(string tableName);
/// <summary>
/// Gets the contents of a table
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns>Datatable containing the table data</returns>
DataTable GetTableData(string tableName);
/// <summary>
/// Returns contents of a table.
/// </summary>
/// <param name="tableName"></param>
/// <param name="columnNames">Comma delimited string of column names and ASC/DESC order</param>
/// <returns></returns>
DataTable GetTableData(string tableName, string columnNames);
/// <summary>
/// Returns contents of a table.
/// </summary>
/// <param name="tableName">The name of the table to query</param>
/// <param name="columnNames">Comma delimited string of column names and ASC/DESC order</param>
/// <param name="sortCriteria">The criteria to sort by</param>
/// <returns></returns>
DataTable GetTableData(string tableName, string columnNames, string sortCriteria);
/// <summary>
/// Returns contents of a table.
/// </summary>
/// <param name="tableName"></param>
/// <param name="columnNames">List of column names to select. Column names should not be bracketed; this method will add brackets.</param>
/// <returns>DataTable</returns>
DataTable GetTableData(string tableName, List<string> columnNames);
/// <summary>
/// Returns contents of a table with only the top two rows.
/// </summary>
/// <param name="tableName">The name of the table to query</param>
/// <returns>DataTable</returns>
DataTable GetTopTwoTable(string tableName);
/// <summary>
/// TODO: Add method description here.
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
IDataReader GetTableDataReader(string tableName);
/// <summary>
/// TODO: Add method description here
/// </summary>
/// <param name="selectQuery"></param>
/// <returns></returns>
IDataReader ExecuteReader(Query selectQuery, CommandBehavior commandBehavior);
/// <summary>
/// TODO: Add method description here
/// </summary>
/// <param name="selectQuery"></param>
/// <returns></returns>
IDataReader ExecuteReader(Query selectQuery);
/// <summary>
/// TODO: Add method description here
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
List<string> GetTableColumnNames(string tableName);
/// <summary>
/// TODO: Add method description here
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
Dictionary<string, int> GetTableColumnNameTypePairs(string tableName);
/// <summary>
/// TODO: Add method description here
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
DataView GetTextColumnNames(string tableName);
/// <summary>
/// Begins a database transaction
/// </summary>
/// <returns>A specialized transaction object based on the current database engine type</returns>
IDbTransaction OpenTransaction();
/// <summary>
/// Begins a database transaction
/// </summary>
/// <param name="isolationLevel">The transaction locking behavior for the connection</param>
/// <returns>A specialized transaction object based on the current database engine type</returns>
IDbTransaction OpenTransaction(IsolationLevel isolationLevel);
/// <summary>
/// Closes a database transaction connection. Developer should commit or rollback transaction prior to calling this method.
/// </summary>
/// <returns>A specialized transaction object based on the current database engine type</returns>
void CloseTransaction(IDbTransaction transaction);
/// <summary>
/// TODO: Add method description here
/// </summary>
/// <param name="dataTable"></param>
/// <param name="tableName"></param>
/// <param name="insertQuery"></param>
/// <param name="updateQuery"></param>
void Update(DataTable dataTable, string tableName, Query insertQuery, Query updateQuery);
/// <summary>
/// Updates the GUIDs of a child table with those of the parent via a uniquekey/fkey relationship
/// </summary>
void UpdateGUIDs(string childTableName, string parentTableName);
/// <summary>
/// Updates the foreign and unique keys of a child table with those of the parent via the original keys that existed prior to an import from an Epi Info 3.5.x project.
/// </summary>
void UpdateKeys(string childTableName, string parentTableName);
/// <summary>
/// Disposes the object
/// </summary>
void Dispose();
/// <summary>
/// Creates an ANSI SQL-92 statement container
/// </summary>
/// <param name="ansiSqlStatement">A SQL Query following ANSI SQL-92 standards</param>
/// <returns>A Query object</returns>
Query CreateQuery(string ansiSqlStatement);
/// <summary>
/// Get a list of code table names for a given project
/// </summary>
/// <param name="project">Project</param>
/// <returns>DataTable</returns>
DataTable GetCodeTableNamesForProject(Project project);
/// <summary>
/// Get a list of code tables for a project
/// </summary>
/// <param name="db">IDbDriver db</param>
/// <returns>DataTable</returns>
DataSets.TableSchema.TablesDataTable GetCodeTableList(IDbDriver db);
/// <summary>
/// Identify the database in use. Used for code table management.
/// </summary>
/// <returns></returns>
string IdentifyDatabase();
/// <summary>
/// Returns Db specific column type
/// </summary>
/// <param name="dataType"></param>
/// <returns></returns>
string GetDbSpecificColumnType(GenericDbColumnType dataType);
/// <summary>
/// Inserts the string in escape characters. [] for SQL server and `` for MySQL etc.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
string InsertInEscape(string str);
/// <summary>
/// Inserts all strings in the list in escape characters.
/// </summary>
/// <param name="strings"></param>
/// <returns></returns>
List<string> InsertInEscape(List<string> strings);
/// <summary>
/// Provides a database frieldly string representation of date.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
string FormatDate(DateTime dt);
/// <summary>
/// Provides a database friendly string representation of date and time
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
string FormatDateTime(DateTime dt);
/// <summary>
/// Provides a database friendly string representation of time
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
string FormatTime(DateTime time);
System.Data.Common.DbDataAdapter GetDbAdapter(string p);
System.Data.IDbConnection GetConnection();
System.Data.Common.DbCommand GetCommand(string pKeyString, DataTable pDataTable);
System.Data.Common.DbCommandBuilder GetDbCommandBuilder(System.Data.Common.DbDataAdapter Adapter);
bool InsertBulkRows(string pSelectSQL, System.Data.Common.DbDataReader pDataReader, SetGadgetStatusHandler pStatusDelegate = null, CheckForCancellationHandler pCancellationDelegate = null);
bool Insert_1_Row(string pSelectSQL, System.Data.Common.DbDataReader pDataReader);
bool Update_1_Row(string pSelectSQL, string pKeyString, System.Data.Common.DbDataReader pDataReader);
bool CheckDatabaseTableExistance(string pFileString, string pTableName, bool pIsConnectionString = false);
bool CreateDataBase(string pFileString);
bool CheckDatabaseExistance(string pFileString, string pTableName, bool pIsConnectionString = false);
#endregion Methods
}
}
| |
// 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 gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using gciv = Google.Cloud.Iam.V1;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.ResourceManager.V3.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedOrganizationsClientTest
{
[xunit::FactAttribute]
public void GetOrganizationRequestObject()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
GetOrganizationRequest request = new GetOrganizationRequest
{
OrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
};
Organization expectedResponse = new Organization
{
OrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
DisplayName = "display_name137f65c2",
DirectoryCustomerId = "directory_customer_idde7714fb",
State = Organization.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetOrganization(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
Organization response = client.GetOrganization(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOrganizationRequestObjectAsync()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
GetOrganizationRequest request = new GetOrganizationRequest
{
OrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
};
Organization expectedResponse = new Organization
{
OrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
DisplayName = "display_name137f65c2",
DirectoryCustomerId = "directory_customer_idde7714fb",
State = Organization.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetOrganizationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Organization>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
Organization responseCallSettings = await client.GetOrganizationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Organization responseCancellationToken = await client.GetOrganizationAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetOrganization()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
GetOrganizationRequest request = new GetOrganizationRequest
{
OrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
};
Organization expectedResponse = new Organization
{
OrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
DisplayName = "display_name137f65c2",
DirectoryCustomerId = "directory_customer_idde7714fb",
State = Organization.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetOrganization(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
Organization response = client.GetOrganization(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOrganizationAsync()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
GetOrganizationRequest request = new GetOrganizationRequest
{
OrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
};
Organization expectedResponse = new Organization
{
OrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
DisplayName = "display_name137f65c2",
DirectoryCustomerId = "directory_customer_idde7714fb",
State = Organization.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetOrganizationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Organization>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
Organization responseCallSettings = await client.GetOrganizationAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Organization responseCancellationToken = await client.GetOrganizationAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetOrganizationResourceNames()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
GetOrganizationRequest request = new GetOrganizationRequest
{
OrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
};
Organization expectedResponse = new Organization
{
OrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
DisplayName = "display_name137f65c2",
DirectoryCustomerId = "directory_customer_idde7714fb",
State = Organization.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetOrganization(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
Organization response = client.GetOrganization(request.OrganizationName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetOrganizationResourceNamesAsync()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
GetOrganizationRequest request = new GetOrganizationRequest
{
OrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
};
Organization expectedResponse = new Organization
{
OrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
DisplayName = "display_name137f65c2",
DirectoryCustomerId = "directory_customer_idde7714fb",
State = Organization.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetOrganizationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Organization>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
Organization responseCallSettings = await client.GetOrganizationAsync(request.OrganizationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Organization responseCancellationToken = await client.GetOrganizationAsync(request.OrganizationName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicy()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request.Resource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyAsync()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Resource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyResourceNames()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request.ResourceAsResourceName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyResourceNamesAsync()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.ResourceAsResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.ResourceAsResourceName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicy()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request.Resource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyAsync()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Resource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyResourceNames()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request.ResourceAsResourceName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyResourceNamesAsync()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.ResourceAsResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.ResourceAsResourceName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissions()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.Resource, request.Permissions);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsAsync()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsResourceNames()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.ResourceAsResourceName, request.Permissions);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsResourceNamesAsync()
{
moq::Mock<Organizations.OrganizationsClient> mockGrpcClient = new moq::Mock<Organizations.OrganizationsClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OrganizationsClient client = new OrganizationsClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// ImplementationBuilder.cs
// Script#/Core/Compiler
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using ScriptSharp;
using ScriptSharp.CodeModel;
using ScriptSharp.ScriptModel;
namespace ScriptSharp.Compiler {
internal sealed class ImplementationBuilder : ILocalSymbolTable {
private CompilerOptions _options;
private IErrorHandler _errorHandler;
private SymbolScope _rootScope;
private SymbolScope _currentScope;
private int _generatedSymbolCount;
public ImplementationBuilder(CompilerOptions options, IErrorHandler errorHandler) {
_options = options;
_errorHandler = errorHandler;
}
private SymbolImplementation BuildImplementation(ISymbolTable symbolTable, CodeMemberSymbol symbolContext, BlockStatementNode implementationNode, bool addAllParameters) {
_rootScope = new SymbolScope(symbolTable);
_currentScope = _rootScope;
List<Statement> statements = new List<Statement>();
StatementBuilder statementBuilder = new StatementBuilder(this, symbolContext, _errorHandler, _options);
if (symbolContext.Parameters != null) {
int parameterCount = symbolContext.Parameters.Count;
if (addAllParameters == false) {
// For property getters (including indexers), we don't add the last parameter,
// which happens to be the "value" parameter, which only makes sense
// for the setter.
parameterCount--;
}
for (int paramIndex = 0; paramIndex < parameterCount; paramIndex++) {
_currentScope.AddSymbol(symbolContext.Parameters[paramIndex]);
}
}
if ((symbolContext.Type == SymbolType.Constructor) &&
((((ConstructorSymbol)symbolContext).Visibility & MemberVisibility.Static) == 0)) {
Debug.Assert(symbolContext.Parent is ClassSymbol);
if (((ClassSymbol)symbolContext.Parent).BaseClass != null) {
BaseInitializerExpression baseExpr = new BaseInitializerExpression();
ConstructorDeclarationNode ctorNode = (ConstructorDeclarationNode)symbolContext.ParseContext;
if (ctorNode.BaseArguments != null) {
ExpressionBuilder expressionBuilder =
new ExpressionBuilder(this, symbolContext, _errorHandler, _options);
Debug.Assert(ctorNode.BaseArguments is ExpressionListNode);
ICollection<Expression> args =
expressionBuilder.BuildExpressionList((ExpressionListNode)ctorNode.BaseArguments);
foreach (Expression paramExpr in args) {
baseExpr.AddParameterValue(paramExpr);
}
}
statements.Add(new ExpressionStatement(baseExpr));
}
}
foreach (StatementNode statementNode in implementationNode.Statements) {
Statement statement = statementBuilder.BuildStatement(statementNode);
if (statement != null) {
statements.Add(statement);
}
}
string thisIdentifier = "this";
if (symbolContext.Type == SymbolType.AnonymousMethod) {
thisIdentifier = "$this";
}
return new SymbolImplementation(statements, _rootScope, thisIdentifier);
}
public SymbolImplementation BuildEventAdd(EventSymbol eventSymbol) {
AccessorNode addNode = ((EventDeclarationNode)eventSymbol.ParseContext).Property.SetAccessor;
BlockStatementNode accessorBody = addNode.Implementation;
return BuildImplementation((ISymbolTable)eventSymbol.Parent,
eventSymbol, accessorBody, /* addParameters */ true);
}
public SymbolImplementation BuildEventRemove(EventSymbol eventSymbol) {
AccessorNode removeNode = ((EventDeclarationNode)eventSymbol.ParseContext).Property.GetAccessor;
BlockStatementNode accessorBody = removeNode.Implementation;
return BuildImplementation((ISymbolTable)eventSymbol.Parent,
eventSymbol, accessorBody, /* addParameters */ true);
}
public SymbolImplementation BuildField(FieldSymbol fieldSymbol) {
_rootScope = new SymbolScope((ISymbolTable)fieldSymbol.Parent);
_currentScope = _rootScope;
Expression initializerExpression = null;
FieldDeclarationNode fieldDeclarationNode = (FieldDeclarationNode)fieldSymbol.ParseContext;
Debug.Assert(fieldDeclarationNode != null);
VariableInitializerNode initializerNode = (VariableInitializerNode)fieldDeclarationNode.Initializers[0];
if (initializerNode.Value != null) {
ExpressionBuilder expressionBuilder = new ExpressionBuilder(this, fieldSymbol, _errorHandler, _options);
initializerExpression = expressionBuilder.BuildExpression(initializerNode.Value);
if (initializerExpression is MemberExpression) {
initializerExpression =
expressionBuilder.TransformMemberExpression((MemberExpression)initializerExpression);
}
}
else {
object defaultValue = null;
TypeSymbol fieldType = fieldSymbol.AssociatedType;
SymbolSet symbolSet = fieldSymbol.SymbolSet;
if (fieldType.Type == SymbolType.Enumeration) {
// The default for named values is null, so this only applies to
// regular enum types
EnumerationSymbol enumType = (EnumerationSymbol)fieldType;
if (enumType.UseNamedValues == false) {
defaultValue = 0;
}
}
else if ((fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Integer)) ||
(fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.UnsignedInteger)) ||
(fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Long)) ||
(fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.UnsignedLong)) ||
(fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Short)) ||
(fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.UnsignedShort)) ||
(fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Byte)) ||
(fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.SignedByte)) ||
(fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Double)) ||
(fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Single)) ||
(fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Decimal))) {
defaultValue = 0;
}
else if (fieldType == symbolSet.ResolveIntrinsicType(IntrinsicType.Boolean)) {
defaultValue = false;
}
if (defaultValue != null) {
initializerExpression =
new LiteralExpression(symbolSet.ResolveIntrinsicType(IntrinsicType.Object),
defaultValue);
fieldSymbol.SetImplementationState(/* hasInitializer */ true);
}
}
if (initializerExpression != null) {
List<Statement> statements = new List<Statement>();
statements.Add(new ExpressionStatement(initializerExpression, /* isFragment */ true));
return new SymbolImplementation(statements, null, "this");
}
return null;
}
public SymbolImplementation BuildMethod(MethodSymbol methodSymbol) {
BlockStatementNode methodBody = ((MethodDeclarationNode)methodSymbol.ParseContext).Implementation;
return BuildImplementation((ISymbolTable)methodSymbol.Parent,
methodSymbol, methodBody, /* addAllParameters */ true);
}
public SymbolImplementation BuildMethod(AnonymousMethodSymbol methodSymbol) {
BlockStatementNode methodBody = ((AnonymousMethodNode)methodSymbol.ParseContext).Implementation;
return BuildImplementation(methodSymbol.StackContext,
methodSymbol, methodBody, /* addAllParameters */ true);
}
public SymbolImplementation BuildIndexerGetter(IndexerSymbol indexerSymbol) {
AccessorNode getterNode = ((IndexerDeclarationNode)indexerSymbol.ParseContext).GetAccessor;
BlockStatementNode accessorBody = getterNode.Implementation;
return BuildImplementation((ISymbolTable)indexerSymbol.Parent,
indexerSymbol, accessorBody, /* addAllParameters */ false);
}
public SymbolImplementation BuildIndexerSetter(IndexerSymbol indexerSymbol) {
AccessorNode setterNode = ((IndexerDeclarationNode)indexerSymbol.ParseContext).SetAccessor;
BlockStatementNode accessorBody = setterNode.Implementation;
return BuildImplementation((ISymbolTable)indexerSymbol.Parent,
indexerSymbol, accessorBody, /* addAllParameters */ true);
}
public SymbolImplementation BuildPropertyGetter(PropertySymbol propertySymbol) {
AccessorNode getterNode = ((PropertyDeclarationNode)propertySymbol.ParseContext).GetAccessor;
BlockStatementNode accessorBody = getterNode.Implementation;
return BuildImplementation((ISymbolTable)propertySymbol.Parent,
propertySymbol, accessorBody, /* addAllParameters */ false);
}
public SymbolImplementation BuildPropertySetter(PropertySymbol propertySymbol) {
AccessorNode setterNode = ((PropertyDeclarationNode)propertySymbol.ParseContext).SetAccessor;
BlockStatementNode accessorBody = setterNode.Implementation;
return BuildImplementation((ISymbolTable)propertySymbol.Parent,
propertySymbol, accessorBody, /* addAllParameters */ true);
}
#region ISymbolTable Members
ICollection ISymbolTable.Symbols {
get {
Debug.Assert(_currentScope != null);
return ((ISymbolTable)_currentScope).Symbols;
}
}
Symbol ISymbolTable.FindSymbol(string name, Symbol context, SymbolFilter filter) {
Debug.Assert(_currentScope != null);
return ((ISymbolTable)_currentScope).FindSymbol(name, context, filter);
}
#endregion
#region ILocalSymbolTable Members
void ILocalSymbolTable.AddSymbol(LocalSymbol symbol) {
Debug.Assert(_currentScope != null);
_currentScope.AddSymbol(symbol);
}
string ILocalSymbolTable.CreateSymbolName(string nameHint) {
_generatedSymbolCount++;
return "$" + nameHint + _generatedSymbolCount;
}
void ILocalSymbolTable.PopScope() {
Debug.Assert(_currentScope != null);
_currentScope = _currentScope.Parent;
}
void ILocalSymbolTable.PushScope() {
Debug.Assert(_currentScope != null);
SymbolScope parentScope = _currentScope;
_currentScope = new SymbolScope(parentScope);
parentScope.AddChildScope(_currentScope);
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Specialized;
using Humanizer;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Localisation;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.Rooms;
using osu.Game.Overlays;
using osu.Game.Screens.OnlinePlay.Match.Components;
using osuTK;
namespace osu.Game.Screens.OnlinePlay.Playlists
{
public class PlaylistsMatchSettingsOverlay : MatchSettingsOverlay
{
public Action EditPlaylist;
private MatchSettings settings;
protected override OsuButton SubmitButton => settings.ApplyButton;
protected override bool IsLoading => settings.IsLoading; // should probably be replaced with an OngoingOperationTracker.
protected override void SelectBeatmap() => settings.SelectBeatmap();
protected override OnlinePlayComposite CreateSettings()
=> settings = new MatchSettings
{
RelativeSizeAxes = Axes.Both,
RelativePositionAxes = Axes.Y,
EditPlaylist = () => EditPlaylist?.Invoke()
};
protected class MatchSettings : OnlinePlayComposite
{
private const float disabled_alpha = 0.2f;
public Action EditPlaylist;
public OsuTextBox NameField, MaxParticipantsField, MaxAttemptsField;
public OsuDropdown<TimeSpan> DurationField;
public RoomAvailabilityPicker AvailabilityPicker;
public TriangleButton ApplyButton;
public bool IsLoading => loadingLayer.State.Value == Visibility.Visible;
public OsuSpriteText ErrorText;
private LoadingLayer loadingLayer;
private DrawableRoomPlaylist playlist;
private OsuSpriteText playlistLength;
private PurpleTriangleButton editPlaylistButton;
[Resolved(CanBeNull = true)]
private IRoomManager manager { get; set; }
[Resolved]
private Bindable<Room> currentRoom { get; set; }
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4Extensions.FromHex(@"28242d"),
},
new GridContainer
{
RelativeSizeAxes = Axes.Both,
RowDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
},
Content = new[]
{
new Drawable[]
{
new OsuScrollContainer
{
Padding = new MarginPadding
{
Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING,
Vertical = 10
},
RelativeSizeAxes = Axes.Both,
Children = new[]
{
new Container
{
Padding = new MarginPadding { Horizontal = WaveOverlayContainer.WIDTH_PADDING },
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new SectionContainer
{
Padding = new MarginPadding { Right = FIELD_PADDING / 2 },
Children = new[]
{
new Section("Room name")
{
Child = NameField = new SettingsTextBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
LengthLimit = 100
},
},
new Section("Duration")
{
Child = DurationField = new DurationDropdown
{
RelativeSizeAxes = Axes.X,
Items = new[]
{
TimeSpan.FromMinutes(30),
TimeSpan.FromHours(1),
TimeSpan.FromHours(2),
TimeSpan.FromHours(4),
TimeSpan.FromHours(8),
TimeSpan.FromHours(12),
//TimeSpan.FromHours(16),
TimeSpan.FromHours(24),
TimeSpan.FromDays(3),
TimeSpan.FromDays(7)
}
}
},
new Section("Allowed attempts (across all playlist items)")
{
Child = MaxAttemptsField = new SettingsNumberTextBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
PlaceholderText = "Unlimited",
},
},
new Section("Room visibility")
{
Alpha = disabled_alpha,
Child = AvailabilityPicker = new RoomAvailabilityPicker
{
Enabled = { Value = false }
},
},
new Section("Max participants")
{
Alpha = disabled_alpha,
Child = MaxParticipantsField = new SettingsNumberTextBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
ReadOnly = true,
},
},
new Section("Password (optional)")
{
Alpha = disabled_alpha,
Child = new SettingsPasswordTextBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
ReadOnly = true,
},
},
},
},
new SectionContainer
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Padding = new MarginPadding { Left = FIELD_PADDING / 2 },
Children = new[]
{
new Section("Playlist")
{
Child = new GridContainer
{
RelativeSizeAxes = Axes.X,
Height = 500,
Content = new[]
{
new Drawable[]
{
playlist = new DrawableRoomPlaylist(true, true) { RelativeSizeAxes = Axes.Both }
},
new Drawable[]
{
playlistLength = new OsuSpriteText
{
Margin = new MarginPadding { Vertical = 5 },
Colour = colours.Yellow,
Font = OsuFont.GetFont(size: 12),
}
},
new Drawable[]
{
editPlaylistButton = new PurpleTriangleButton
{
RelativeSizeAxes = Axes.X,
Height = 40,
Text = "Edit playlist",
Action = () => EditPlaylist?.Invoke()
}
}
},
RowDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.AutoSize),
}
}
},
},
},
},
}
},
},
},
new Drawable[]
{
new Container
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Y = 2,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4Extensions.FromHex(@"28242d").Darken(0.5f).Opacity(1f),
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 20),
Margin = new MarginPadding { Vertical = 20 },
Padding = new MarginPadding { Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING },
Children = new Drawable[]
{
ApplyButton = new CreateRoomButton
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Size = new Vector2(230, 55),
Enabled = { Value = false },
Action = apply,
},
ErrorText = new OsuSpriteText
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Alpha = 0,
Depth = 1,
Colour = colours.RedDark
}
}
}
}
}
}
}
},
loadingLayer = new LoadingLayer(true)
};
RoomName.BindValueChanged(name => NameField.Text = name.NewValue, true);
Availability.BindValueChanged(availability => AvailabilityPicker.Current.Value = availability.NewValue, true);
MaxParticipants.BindValueChanged(count => MaxParticipantsField.Text = count.NewValue?.ToString(), true);
MaxAttempts.BindValueChanged(count => MaxAttemptsField.Text = count.NewValue?.ToString(), true);
Duration.BindValueChanged(duration => DurationField.Current.Value = duration.NewValue ?? TimeSpan.FromMinutes(30), true);
playlist.Items.BindTo(Playlist);
Playlist.BindCollectionChanged(onPlaylistChanged, true);
}
protected override void Update()
{
base.Update();
ApplyButton.Enabled.Value = hasValidSettings;
}
public void SelectBeatmap() => editPlaylistButton.TriggerClick();
private void onPlaylistChanged(object sender, NotifyCollectionChangedEventArgs e) =>
playlistLength.Text = $"Length: {Playlist.GetTotalDuration()}";
private bool hasValidSettings => RoomID.Value == null && NameField.Text.Length > 0 && Playlist.Count > 0;
private void apply()
{
if (!ApplyButton.Enabled.Value)
return;
hideError();
RoomName.Value = NameField.Text;
Availability.Value = AvailabilityPicker.Current.Value;
if (int.TryParse(MaxParticipantsField.Text, out int max))
MaxParticipants.Value = max;
else
MaxParticipants.Value = null;
if (int.TryParse(MaxAttemptsField.Text, out max))
MaxAttempts.Value = max;
else
MaxAttempts.Value = null;
Duration.Value = DurationField.Current.Value;
manager?.CreateRoom(currentRoom.Value, onSuccess, onError);
loadingLayer.Show();
}
private void hideError() => ErrorText.FadeOut(50);
private void onSuccess(Room room) => loadingLayer.Hide();
private void onError(string text)
{
ErrorText.Text = text;
ErrorText.FadeIn(50);
loadingLayer.Hide();
}
}
public class CreateRoomButton : TriangleButton
{
public CreateRoomButton()
{
Text = "Create";
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
BackgroundColour = colours.Yellow;
Triangles.ColourLight = colours.YellowLight;
Triangles.ColourDark = colours.YellowDark;
}
}
private class DurationDropdown : OsuDropdown<TimeSpan>
{
public DurationDropdown()
{
Menu.MaxHeight = 100;
}
protected override LocalisableString GenerateItemText(TimeSpan item) => item.Humanize();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using sep02v2.Areas.HelpPage.Models;
namespace sep02v2.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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!
namespace Google.Analytics.Data.V1Beta.Snippets
{
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedBetaAnalyticsDataClientSnippets
{
/// <summary>Snippet for RunReport</summary>
public void RunReportRequestObject()
{
// Snippet: RunReport(RunReportRequest, CallSettings)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create();
// Initialize request argument(s)
RunReportRequest request = new RunReportRequest
{
Property = "",
Dimensions = { new Dimension(), },
Metrics = { new Metric(), },
DateRanges = { new DateRange(), },
DimensionFilter = new FilterExpression(),
MetricFilter = new FilterExpression(),
Offset = 0L,
Limit = 0L,
MetricAggregations =
{
MetricAggregation.Unspecified,
},
OrderBys = { new OrderBy(), },
CurrencyCode = "",
CohortSpec = new CohortSpec(),
KeepEmptyRows = false,
ReturnPropertyQuota = false,
};
// Make the request
RunReportResponse response = betaAnalyticsDataClient.RunReport(request);
// End snippet
}
/// <summary>Snippet for RunReportAsync</summary>
public async Task RunReportRequestObjectAsync()
{
// Snippet: RunReportAsync(RunReportRequest, CallSettings)
// Additional: RunReportAsync(RunReportRequest, CancellationToken)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync();
// Initialize request argument(s)
RunReportRequest request = new RunReportRequest
{
Property = "",
Dimensions = { new Dimension(), },
Metrics = { new Metric(), },
DateRanges = { new DateRange(), },
DimensionFilter = new FilterExpression(),
MetricFilter = new FilterExpression(),
Offset = 0L,
Limit = 0L,
MetricAggregations =
{
MetricAggregation.Unspecified,
},
OrderBys = { new OrderBy(), },
CurrencyCode = "",
CohortSpec = new CohortSpec(),
KeepEmptyRows = false,
ReturnPropertyQuota = false,
};
// Make the request
RunReportResponse response = await betaAnalyticsDataClient.RunReportAsync(request);
// End snippet
}
/// <summary>Snippet for RunPivotReport</summary>
public void RunPivotReportRequestObject()
{
// Snippet: RunPivotReport(RunPivotReportRequest, CallSettings)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create();
// Initialize request argument(s)
RunPivotReportRequest request = new RunPivotReportRequest
{
Property = "",
Dimensions = { new Dimension(), },
Metrics = { new Metric(), },
DateRanges = { new DateRange(), },
Pivots = { new Pivot(), },
DimensionFilter = new FilterExpression(),
MetricFilter = new FilterExpression(),
CurrencyCode = "",
CohortSpec = new CohortSpec(),
KeepEmptyRows = false,
ReturnPropertyQuota = false,
};
// Make the request
RunPivotReportResponse response = betaAnalyticsDataClient.RunPivotReport(request);
// End snippet
}
/// <summary>Snippet for RunPivotReportAsync</summary>
public async Task RunPivotReportRequestObjectAsync()
{
// Snippet: RunPivotReportAsync(RunPivotReportRequest, CallSettings)
// Additional: RunPivotReportAsync(RunPivotReportRequest, CancellationToken)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync();
// Initialize request argument(s)
RunPivotReportRequest request = new RunPivotReportRequest
{
Property = "",
Dimensions = { new Dimension(), },
Metrics = { new Metric(), },
DateRanges = { new DateRange(), },
Pivots = { new Pivot(), },
DimensionFilter = new FilterExpression(),
MetricFilter = new FilterExpression(),
CurrencyCode = "",
CohortSpec = new CohortSpec(),
KeepEmptyRows = false,
ReturnPropertyQuota = false,
};
// Make the request
RunPivotReportResponse response = await betaAnalyticsDataClient.RunPivotReportAsync(request);
// End snippet
}
/// <summary>Snippet for BatchRunReports</summary>
public void BatchRunReportsRequestObject()
{
// Snippet: BatchRunReports(BatchRunReportsRequest, CallSettings)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create();
// Initialize request argument(s)
BatchRunReportsRequest request = new BatchRunReportsRequest
{
Property = "",
Requests =
{
new RunReportRequest(),
},
};
// Make the request
BatchRunReportsResponse response = betaAnalyticsDataClient.BatchRunReports(request);
// End snippet
}
/// <summary>Snippet for BatchRunReportsAsync</summary>
public async Task BatchRunReportsRequestObjectAsync()
{
// Snippet: BatchRunReportsAsync(BatchRunReportsRequest, CallSettings)
// Additional: BatchRunReportsAsync(BatchRunReportsRequest, CancellationToken)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync();
// Initialize request argument(s)
BatchRunReportsRequest request = new BatchRunReportsRequest
{
Property = "",
Requests =
{
new RunReportRequest(),
},
};
// Make the request
BatchRunReportsResponse response = await betaAnalyticsDataClient.BatchRunReportsAsync(request);
// End snippet
}
/// <summary>Snippet for BatchRunPivotReports</summary>
public void BatchRunPivotReportsRequestObject()
{
// Snippet: BatchRunPivotReports(BatchRunPivotReportsRequest, CallSettings)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create();
// Initialize request argument(s)
BatchRunPivotReportsRequest request = new BatchRunPivotReportsRequest
{
Property = "",
Requests =
{
new RunPivotReportRequest(),
},
};
// Make the request
BatchRunPivotReportsResponse response = betaAnalyticsDataClient.BatchRunPivotReports(request);
// End snippet
}
/// <summary>Snippet for BatchRunPivotReportsAsync</summary>
public async Task BatchRunPivotReportsRequestObjectAsync()
{
// Snippet: BatchRunPivotReportsAsync(BatchRunPivotReportsRequest, CallSettings)
// Additional: BatchRunPivotReportsAsync(BatchRunPivotReportsRequest, CancellationToken)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync();
// Initialize request argument(s)
BatchRunPivotReportsRequest request = new BatchRunPivotReportsRequest
{
Property = "",
Requests =
{
new RunPivotReportRequest(),
},
};
// Make the request
BatchRunPivotReportsResponse response = await betaAnalyticsDataClient.BatchRunPivotReportsAsync(request);
// End snippet
}
/// <summary>Snippet for GetMetadata</summary>
public void GetMetadataRequestObject()
{
// Snippet: GetMetadata(GetMetadataRequest, CallSettings)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create();
// Initialize request argument(s)
GetMetadataRequest request = new GetMetadataRequest
{
MetadataName = MetadataName.FromProperty("[PROPERTY]"),
};
// Make the request
Metadata response = betaAnalyticsDataClient.GetMetadata(request);
// End snippet
}
/// <summary>Snippet for GetMetadataAsync</summary>
public async Task GetMetadataRequestObjectAsync()
{
// Snippet: GetMetadataAsync(GetMetadataRequest, CallSettings)
// Additional: GetMetadataAsync(GetMetadataRequest, CancellationToken)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync();
// Initialize request argument(s)
GetMetadataRequest request = new GetMetadataRequest
{
MetadataName = MetadataName.FromProperty("[PROPERTY]"),
};
// Make the request
Metadata response = await betaAnalyticsDataClient.GetMetadataAsync(request);
// End snippet
}
/// <summary>Snippet for GetMetadata</summary>
public void GetMetadata()
{
// Snippet: GetMetadata(string, CallSettings)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create();
// Initialize request argument(s)
string name = "properties/[PROPERTY]/metadata";
// Make the request
Metadata response = betaAnalyticsDataClient.GetMetadata(name);
// End snippet
}
/// <summary>Snippet for GetMetadataAsync</summary>
public async Task GetMetadataAsync()
{
// Snippet: GetMetadataAsync(string, CallSettings)
// Additional: GetMetadataAsync(string, CancellationToken)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync();
// Initialize request argument(s)
string name = "properties/[PROPERTY]/metadata";
// Make the request
Metadata response = await betaAnalyticsDataClient.GetMetadataAsync(name);
// End snippet
}
/// <summary>Snippet for GetMetadata</summary>
public void GetMetadataResourceNames()
{
// Snippet: GetMetadata(MetadataName, CallSettings)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create();
// Initialize request argument(s)
MetadataName name = MetadataName.FromProperty("[PROPERTY]");
// Make the request
Metadata response = betaAnalyticsDataClient.GetMetadata(name);
// End snippet
}
/// <summary>Snippet for GetMetadataAsync</summary>
public async Task GetMetadataResourceNamesAsync()
{
// Snippet: GetMetadataAsync(MetadataName, CallSettings)
// Additional: GetMetadataAsync(MetadataName, CancellationToken)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync();
// Initialize request argument(s)
MetadataName name = MetadataName.FromProperty("[PROPERTY]");
// Make the request
Metadata response = await betaAnalyticsDataClient.GetMetadataAsync(name);
// End snippet
}
/// <summary>Snippet for RunRealtimeReport</summary>
public void RunRealtimeReportRequestObject()
{
// Snippet: RunRealtimeReport(RunRealtimeReportRequest, CallSettings)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create();
// Initialize request argument(s)
RunRealtimeReportRequest request = new RunRealtimeReportRequest
{
Property = "",
Dimensions = { new Dimension(), },
Metrics = { new Metric(), },
DimensionFilter = new FilterExpression(),
MetricFilter = new FilterExpression(),
Limit = 0L,
MetricAggregations =
{
MetricAggregation.Unspecified,
},
OrderBys = { new OrderBy(), },
ReturnPropertyQuota = false,
MinuteRanges = { new MinuteRange(), },
};
// Make the request
RunRealtimeReportResponse response = betaAnalyticsDataClient.RunRealtimeReport(request);
// End snippet
}
/// <summary>Snippet for RunRealtimeReportAsync</summary>
public async Task RunRealtimeReportRequestObjectAsync()
{
// Snippet: RunRealtimeReportAsync(RunRealtimeReportRequest, CallSettings)
// Additional: RunRealtimeReportAsync(RunRealtimeReportRequest, CancellationToken)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync();
// Initialize request argument(s)
RunRealtimeReportRequest request = new RunRealtimeReportRequest
{
Property = "",
Dimensions = { new Dimension(), },
Metrics = { new Metric(), },
DimensionFilter = new FilterExpression(),
MetricFilter = new FilterExpression(),
Limit = 0L,
MetricAggregations =
{
MetricAggregation.Unspecified,
},
OrderBys = { new OrderBy(), },
ReturnPropertyQuota = false,
MinuteRanges = { new MinuteRange(), },
};
// Make the request
RunRealtimeReportResponse response = await betaAnalyticsDataClient.RunRealtimeReportAsync(request);
// End snippet
}
/// <summary>Snippet for CheckCompatibility</summary>
public void CheckCompatibilityRequestObject()
{
// Snippet: CheckCompatibility(CheckCompatibilityRequest, CallSettings)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.Create();
// Initialize request argument(s)
CheckCompatibilityRequest request = new CheckCompatibilityRequest
{
Property = "",
Dimensions = { new Dimension(), },
Metrics = { new Metric(), },
DimensionFilter = new FilterExpression(),
MetricFilter = new FilterExpression(),
CompatibilityFilter = Compatibility.Unspecified,
};
// Make the request
CheckCompatibilityResponse response = betaAnalyticsDataClient.CheckCompatibility(request);
// End snippet
}
/// <summary>Snippet for CheckCompatibilityAsync</summary>
public async Task CheckCompatibilityRequestObjectAsync()
{
// Snippet: CheckCompatibilityAsync(CheckCompatibilityRequest, CallSettings)
// Additional: CheckCompatibilityAsync(CheckCompatibilityRequest, CancellationToken)
// Create client
BetaAnalyticsDataClient betaAnalyticsDataClient = await BetaAnalyticsDataClient.CreateAsync();
// Initialize request argument(s)
CheckCompatibilityRequest request = new CheckCompatibilityRequest
{
Property = "",
Dimensions = { new Dimension(), },
Metrics = { new Metric(), },
DimensionFilter = new FilterExpression(),
MetricFilter = new FilterExpression(),
CompatibilityFilter = Compatibility.Unspecified,
};
// Make the request
CheckCompatibilityResponse response = await betaAnalyticsDataClient.CheckCompatibilityAsync(request);
// End snippet
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.CoreModules.Scripting.LSLHttp;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
/// <summary>
/// Tests for HTTP related functions in LSL
/// </summary>
[TestFixture]
public class LSL_ApiHttpTests : OpenSimTestCase
{
private Scene m_scene;
private MockScriptEngine m_engine;
private UrlModule m_urlModule;
private TaskInventoryItem m_scriptItem;
private LSL_Api m_lslApi;
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
// Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread.
Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest;
}
[TestFixtureTearDown]
public void TestFixureTearDown()
{
// We must set this back afterwards, otherwise later tests will fail since they're expecting multiple
// threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression
// tests really shouldn't).
Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod;
}
[SetUp]
public override void SetUp()
{
base.SetUp();
// This is an unfortunate bit of clean up we have to do because MainServer manages things through static
// variables and the VM is not restarted between tests.
uint port = 9999;
MainServer.RemoveHttpServer(port);
BaseHttpServer server = new BaseHttpServer(port, false, 0, "");
MainServer.AddHttpServer(server);
MainServer.Instance = server;
server.Start();
m_engine = new MockScriptEngine();
m_urlModule = new UrlModule();
m_scene = new SceneHelpers().SetupScene();
SceneHelpers.SetupSceneModules(m_scene, new IniConfigSource(), m_engine, m_urlModule);
SceneObjectGroup so = SceneHelpers.AddSceneObject(m_scene);
m_scriptItem = TaskInventoryHelpers.AddScript(m_scene.AssetService, so.RootPart);
// This is disconnected from the actual script - the mock engine does not set up any LSL_Api atm.
// Possibly this could be done and we could obtain it directly from the MockScriptEngine.
m_lslApi = new LSL_Api();
m_lslApi.Initialize(m_engine, so.RootPart, m_scriptItem);
}
[TearDown]
public void TearDown()
{
MainServer.Instance.Stop();
}
[Test]
public void TestLlReleaseUrl()
{
TestHelpers.InMethod();
m_lslApi.llRequestURL();
string returnedUri = m_engine.PostedEvents[m_scriptItem.ItemID][0].Params[2].ToString();
{
// Check that the initial number of URLs is correct
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls - 1));
}
{
// Check releasing a non-url
m_lslApi.llReleaseURL("GARBAGE");
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls - 1));
}
{
// Check releasing a non-existing url
m_lslApi.llReleaseURL("http://example.com");
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls - 1));
}
{
// Check URL release
m_lslApi.llReleaseURL(returnedUri);
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(returnedUri);
bool gotExpectedException = false;
try
{
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{}
}
catch (WebException e)
{
// using (HttpWebResponse response = (HttpWebResponse)e.Response)
// gotExpectedException = response.StatusCode == HttpStatusCode.NotFound;
gotExpectedException = true;
}
Assert.That(gotExpectedException, Is.True);
}
{
// Check releasing the same URL again
m_lslApi.llReleaseURL(returnedUri);
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls));
}
}
[Test]
public void TestLlRequestUrl()
{
TestHelpers.InMethod();
string requestId = m_lslApi.llRequestURL();
Assert.That(requestId, Is.Not.EqualTo(UUID.Zero.ToString()));
string returnedUri;
{
// Check that URL is correctly set up
Assert.That(m_lslApi.llGetFreeURLs().value, Is.EqualTo(m_urlModule.TotalUrls - 1));
Assert.That(m_engine.PostedEvents.ContainsKey(m_scriptItem.ItemID));
List<EventParams> events = m_engine.PostedEvents[m_scriptItem.ItemID];
Assert.That(events.Count, Is.EqualTo(1));
EventParams eventParams = events[0];
Assert.That(eventParams.EventName, Is.EqualTo("http_request"));
UUID returnKey;
string rawReturnKey = eventParams.Params[0].ToString();
string method = eventParams.Params[1].ToString();
returnedUri = eventParams.Params[2].ToString();
Assert.That(UUID.TryParse(rawReturnKey, out returnKey), Is.True);
Assert.That(method, Is.EqualTo(ScriptBaseClass.URL_REQUEST_GRANTED));
Assert.That(Uri.IsWellFormedUriString(returnedUri, UriKind.Absolute), Is.True);
}
{
// Check that request to URL works.
string testResponse = "Hello World";
m_engine.ClearPostedEvents();
m_engine.PostEventHook
+= (itemId, evp) => m_lslApi.llHTTPResponse(evp.Params[0].ToString(), 200, testResponse);
// Console.WriteLine("Trying {0}", returnedUri);
AssertHttpResponse(returnedUri, testResponse);
Assert.That(m_engine.PostedEvents.ContainsKey(m_scriptItem.ItemID));
List<EventParams> events = m_engine.PostedEvents[m_scriptItem.ItemID];
Assert.That(events.Count, Is.EqualTo(1));
EventParams eventParams = events[0];
Assert.That(eventParams.EventName, Is.EqualTo("http_request"));
UUID returnKey;
string rawReturnKey = eventParams.Params[0].ToString();
string method = eventParams.Params[1].ToString();
string body = eventParams.Params[2].ToString();
Assert.That(UUID.TryParse(rawReturnKey, out returnKey), Is.True);
Assert.That(method, Is.EqualTo("GET"));
Assert.That(body, Is.EqualTo(""));
}
}
private void AssertHttpResponse(string uri, string expectedResponse)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (Stream stream = webResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
Assert.That(reader.ReadToEnd(), Is.EqualTo(expectedResponse));
}
}
}
}
}
}
| |
using System;
using NUnit.Framework;
namespace FileHelpers.Tests.CommonTests
{
[TestFixture]
public class IgnoreEmpties
{
[Test]
public void IgnoreEmpty1()
{
var engine = new FileHelperEngine<IgnoreEmptyType1>();
var res = TestCommon.ReadTest<IgnoreEmptyType1>(engine, "Good", "IgnoreEmpty1.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(8, engine.LineNumber);
}
[Test]
public void IgnoreEmpty2()
{
var engine = new FileHelperEngine<IgnoreEmptyType1>();
object[] res = TestCommon.ReadTest(engine, "Good", "IgnoreEmpty2.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(8, engine.LineNumber);
}
[Test]
public void IgnoreEmpty3()
{
var engine = new FileHelperEngine<IgnoreEmptyType1>();
var res = TestCommon.ReadTest<IgnoreEmptyType1>(engine, "Good", "IgnoreEmpty3.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(8, engine.LineNumber);
}
[Test]
public void IgnoreEmpty1Async()
{
var asyncEngine = new FileHelperAsyncEngine<IgnoreEmptyType1>();
var res = TestCommon.ReadAllAsync<IgnoreEmptyType1>(asyncEngine, "Good", "IgnoreEmpty1.txt");
Assert.AreEqual(4, res.Count);
Assert.AreEqual(8, asyncEngine.LineNumber);
}
[Test]
public void IgnoreEmpty3Async()
{
var asyncEngine = new FileHelperAsyncEngine<IgnoreEmptyType1>();
var res = TestCommon.ReadAllAsync<IgnoreEmptyType1>(asyncEngine, "Good", "IgnoreEmpty3.txt");
Assert.AreEqual(4, res.Count);
Assert.AreEqual(7, asyncEngine.LineNumber);
}
[Test]
public void IgnoreEmpty4Bad()
{
var engine = new FileHelperEngine<IgnoreEmptyType1>();
Assert.Throws<BadUsageException>(
() => TestCommon.ReadTest<IgnoreEmptyType1>(engine, "Good", "IgnoreEmpty4.txt"));
}
[Test]
public void IgnoreEmpty4BadAsync()
{
var asyncEngine = new FileHelperAsyncEngine<IgnoreEmptyType1>();
Assert.Throws<BadUsageException>(
() => TestCommon.ReadAllAsync<IgnoreEmptyType1>(asyncEngine, "Good", "IgnoreEmpty4.txt"));
}
[Test]
public void IgnoreEmpty4()
{
var engine = new FileHelperEngine<IgnoreEmptyType1Spaces>();
object[] res = TestCommon.ReadTest<IgnoreEmptyType1Spaces>(engine, "Good", "IgnoreEmpty4.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(7, engine.LineNumber);
}
[Test]
public void IgnoreEmpty5()
{
var engine = new FileHelperEngine<IgnoreEmptyType1Spaces>();
var res = TestCommon.ReadTest<IgnoreEmptyType1Spaces>(engine, "Good", "IgnoreEmpty5.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(7, engine.LineNumber);
}
[Test]
public void IgnoreComment1()
{
var engine = new FileHelperEngine<IgnoreCommentsType>();
object[] res = TestCommon.ReadTest<IgnoreCommentsType>(engine, "Good", "IgnoreComments1.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(7, engine.LineNumber);
}
[Test]
public void IgnoreComment1Async()
{
var asyncEngine = new FileHelperAsyncEngine<IgnoreCommentsType>();
var res = TestCommon.ReadAllAsync<IgnoreCommentsType>(asyncEngine, "Good", "IgnoreComments1.txt");
Assert.AreEqual(4, res.Count);
Assert.AreEqual(7, asyncEngine.LineNumber);
}
[Test]
public void IgnoreComment2()
{
var engine = new FileHelperEngine<IgnoreCommentsType>();
var res = TestCommon.ReadTest<IgnoreCommentsType>(engine, "Good", "IgnoreComments2.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(7, engine.LineNumber);
}
[Test]
public void IgnoreComment3()
{
var engine = new FileHelperEngine<IgnoreCommentsType2>();
var res = TestCommon.ReadTest<IgnoreCommentsType2>(engine, "Good", "IgnoreComments1.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(7, engine.LineNumber);
}
[Test]
public void IgnoreComment4()
{
var engine = new FileHelperEngine<IgnoreCommentsType2>();
Assert.Throws<ConvertException>(
() => TestCommon.ReadTest<IgnoreCommentsType2>(engine, "Good", "IgnoreComments2.txt"));
Assert.AreEqual(3, engine.LineNumber);
}
[FixedLengthRecord]
#pragma warning disable CS0618 // Type or member is obsolete
[IgnoreCommentedLines("//")]
#pragma warning restore CS0618 // Type or member is obsolete
public class IgnoreCommentsType
{
[FieldFixedLength(8)]
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Field1;
[FieldFixedLength(3)]
public string Field2;
[FieldFixedLength(3)]
[FieldConverter(ConverterKind.Int32)]
public int Field3;
}
[FixedLengthRecord]
#pragma warning disable CS0618 // Type or member is obsolete
[IgnoreCommentedLines("//", false)]
#pragma warning restore CS0618 // Type or member is obsolete
public class IgnoreCommentsType2
{
[FieldFixedLength(8)]
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Field1;
[FieldFixedLength(3)]
public string Field2;
[FieldFixedLength(3)]
[FieldConverter(ConverterKind.Int32)]
public int Field3;
}
[FixedLengthRecord]
[IgnoreEmptyLines]
public class IgnoreEmptyType1
{
[FieldFixedLength(8)]
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Field1;
[FieldFixedLength(3)]
public string Field2;
[FieldFixedLength(3)]
[FieldConverter(ConverterKind.Int32)]
public int Field3;
}
[FixedLengthRecord]
[IgnoreEmptyLines(true)]
public class IgnoreEmptyType1Spaces
{
[FieldFixedLength(8)]
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Field1;
[FieldFixedLength(3)]
public string Field2;
[FieldFixedLength(3)]
[FieldConverter(ConverterKind.Int32)]
public int Field3;
}
[DelimitedRecord("|")]
[IgnoreEmptyLines]
public class IgnoreEmptyType2
{
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Field1;
[FieldFixedLength(3)]
public string Field2;
public int Field3;
}
}
}
| |
using System;
using System.Xml;
namespace nexposesharp
{
public class NexposeManager12 : NexposeManager11, IDisposable
{
NexposeSession _session;
public NexposeManager12 (NexposeSession session) : base (session)
{
if (!session.IsAuthenticated)
throw new Exception("Trying to create manager from unauthenticated session. Please authenticate.");
_session = session;
}
public XmlDocument GetEngineConfig(string engineID)
{
string cmd = "<EngineConfigRequest session-id=\"" + _session.SessionID + "\" engine-id=\"" + engineID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument DeleteEngine(string engineID)
{
string cmd = "<EngineDeleteRequest session-id=\"" + _session.SessionID + "\" engine-id=\"" + engineID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument SaveOrUpdateEngine(XmlNode engine)
{
string cmd = "<EngineSaveRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + engine.OuterXml;
cmd = cmd + "</EngineSaveRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument CreateTicket(XmlNode ticket)
{
string cmd = "<TicketCreateRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + ticket.OuterXml;
cmd = cmd + "</TicketCreateRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetTicketListing()
{
string cmd = "<TicketListingRequest session-id=\"" + _session.SessionID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetTicketDetails(string ticketID)
{
string cmd = "<TicketDetailsRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + "<Ticket id=\"" + ticketID + "\" /></TicketDetailsRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument DeleteTicket(string ticketID)
{
string cmd = "<TicketDeleteRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + "<Ticket id=\"" + ticketID + "\" /></TicketDeleteRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetPendingVulnExceptionCount()
{
string cmd = "<PendingVulnExceptionCountRequest session-id=\"" + _session.SessionID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetVulnerabilityExceptionListing()
{
string cmd = "<VulnerabilityExceptionListingRequest session-id=\"" + _session.SessionID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument CreateVulnerabilityException()
{
string cmd = "<VulnerabilityExceptionCreateRequest session-id=\"" + _session.SessionID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument ResubmitVulnerabilityException(string vulnExceptionID, string comment)
{
string cmd = "<VulnerabilityExceptionReSubmitRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + "<comment>" + comment + "</comment></VulnerabilityExceptionReSubmitRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument RecallVulnerabilityException(string vulnExceptionID)
{
string cmd = "<VulnerabilityExceptionRecallRequest session-id=\"" + _session.SessionID + "\" exception-id=\"" + vulnExceptionID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument ApproveVulnerabilityException(string vulnExceptionID)
{
string cmd = "<VulnerabilityExceptionApproveRequest session-id=\"" + _session.SessionID + "\" exception-id=\"" + vulnExceptionID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument RejectVulnerabilityException(string vulnExceptionID)
{
string cmd = "<VulnerabilityExceptionRejectRequest session-id=\"" + _session.SessionID + "\" exception-id=\"" + vulnExceptionID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument DeleteVulnerabilityException(string vulnExceptionID)
{
string cmd = "<VulnerabilityExceptionDeleteRequest session-id=\"" + _session.SessionID + "\" exception-id=\"" + vulnExceptionID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument UpdateCommentForVulnerabilityException(string vulnExceptionID, string reviewerComment, string submitterComment)
{
string cmd = "<VulnerabilityExceptionUpdateCommentRequest session-id=\"" + _session.SessionID + "\" exception-id=\"" + vulnExceptionID + "\" >";
cmd = cmd + "<reviewer-comment>" + CleanString(reviewerComment) + "</reviewer-comment>";
cmd = cmd + "<submitter-comment>" + CleanString(submitterComment) + "</submitter-comment>";
cmd = cmd + "</VulnerabilityExceptionUpdateCommentRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument UpdateExpiryDateForVulnerabilityException(string vulnExceptionID, string date)
{
string cmd = "<VulnerabilityExceptionUpdateExpiryDateRequest session-id=\"" + _session.SessionID + "\" exception-id=\"" + vulnExceptionID + "\" expiration-date=\"" + date + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument CreateMultiTenantUser(XmlNode userConfig)
{
string cmd = "<CreateMultiTenantUserRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + userConfig.OuterXml;
cmd = cmd + "<CreateMultiTenantUserRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetMultiTenantUserListing()
{
string cmd = "<MultiTenantUserListingRequest session-id=\"" + _session.SessionID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument UpdateMultiTenantUser(XmlNode user)
{
string cmd = "<MultiTenantUserUpdateRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + user.OuterXml;
cmd = cmd + "</MultiTenantUserUpdateRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetMultiTenantUserConfig(string userID)
{
string cmd = "<MultiTenantUserConfigRequest session-id=\"" + _session.SessionID + "\" user-id=\"" + userID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument DeleteMultiTenantUser(string userID)
{
string cmd = "<MultiTenantUserDeleteRequest session-id=\"" + _session.SessionID + "\" user-id=\"" + userID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument CreateSiloProfile(XmlNode siloConfig)
{
string cmd = "<SiloProfileCreateRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + siloConfig.OuterXml + "</SiloProfileCreateRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetSiloProfileListing()
{
string cmd ="<SiloProfileListingRequest session-id=\"" + _session.SessionID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument UpdateSiloProfile(XmlNode siloProfile)
{
string cmd = "<SiloProfileUpdateRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + siloProfile.OuterXml;
cmd = cmd + "</SiloProfileUpdateRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetSiloProfileConfig(string siloProfileID)
{
string cmd = "<SiloProfileConfigRequest session-id=\"" + _session.SessionID + "\" silo-profile-id=\"" + siloProfileID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument DeleteSiloProfile(string siloProfileID)
{
string cmd = "<SiloProfileDeletRequest session-id=\"" + _session.SessionID + "\" silo-profile-id=\"" + siloProfileID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument CreateSilo(XmlNode siloConfig)
{
string cmd = "<SiloCreateRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + siloConfig.OuterXml + "</SiloCreateRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetSiloListing()
{
string cmd = "<SiloListingRequest session-id=\"" + _session.SessionID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetSiloConfig(string siloID, string siloName)
{
string cmd = "<SiloConfigRequest session-id=\"" + _session.SessionID + "\" id=\"" + siloID + "\" name=\"" + CleanString(siloName) + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument UpdateSilo(XmlNode silo)
{
string cmd = "<SiloUpdateRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + silo.OuterXml;
cmd = cmd + "</SiloUpdateRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument DeleteSilo(string siloID, string siloName)
{
string cmd = "<SiloDeleteRequest session-id=\"" + _session.SessionID + "\" silo-id=\"" + siloID + "\" silo-name=\"" + CleanString(siloName) + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument CreateRole(XmlNode role)
{
string cmd = "<RoleCreateRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + role.OuterXml;
cmd = cmd + "</RoleCreateRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetRoleListing()
{
string cmd = "<RoleListingRequest session-id=\"" + _session.SessionID + "\" />";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetRoleDetails(string roleName)
{
string cmd = "<RoleDetailsRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + "<Role name=\"" + roleName + "\" />";
cmd = cmd + "</RoleDetailsRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument UpdateRole(XmlNode role)
{
string cmd = "<RoleUpdateRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + role.OuterXml;
cmd = cmd + "</RoleUpdateRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument DeleteRole(string roleName)
{
string cmd = "<RoleDeleteRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + "<Role name=\"" + roleName + "\" />";
cmd = cmd + "</RoleDeleteRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument CreateEnginePool(XmlNode pool)
{
string cmd = "<EnginePoolCreateRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + pool.OuterXml + "</EnginePoolCreateRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetEnginePoolListing()
{
string cmd = "<EnginePoolListingRequest session-id=\"" + _session.SessionID + "\" >";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument GetEnginePoolDetails(string enginePoolName)
{
string cmd = "<EnginePoolDetailsRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + "<EnginePool name=\"" + CleanString(enginePoolName) + "\" /></EnginePoolDetailsRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument UpdateEnginePool(XmlNode pool)
{
string cmd = "<EnginePoolUpdateRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + pool.OuterXml;
cmd = cmd + "</EnginePoolUpdateRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
public XmlDocument DeleteEnginePool(string enginePoolname)
{
string cmd = "<EnginePoolDeleteRequest session-id=\"" + _session.SessionID + "\" >";
cmd = cmd + "<EnginePool name=\"" + CleanString(enginePoolname) + "\" /></EnginePoolDeleteRequest>";
return _session.ExecuteCommand(cmd) as XmlDocument;
}
private string CleanString(string text)
{
return text.Replace(" & ", " & ")
.Replace("<", "<")
.Replace(">", ">");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: A random number generator.
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System
{
[Serializable]
public class Random
{
//
// Private Constants
//
private const int MBIG = Int32.MaxValue;
private const int MSEED = 161803398;
private const int MZ = 0;
//
// Member Variables
//
private int inext;
private int inextp;
private int[] SeedArray = new int[56];
//
// Public Constants
//
//
// Native Declarations
//
//
// Constructors
//
/*=========================================================================================
**Action: Initializes a new instance of the Random class, using a default seed value
===========================================================================================*/
public Random()
: this(GenerateSeed())
{
}
/*=========================================================================================
**Action: Initializes a new instance of the Random class, using a specified seed value
===========================================================================================*/
public Random(int Seed)
{
int ii = 0;
int mj, mk;
//Initialize our Seed array.
int subtraction = (Seed == Int32.MinValue) ? Int32.MaxValue : Math.Abs(Seed);
mj = MSEED - subtraction;
SeedArray[55] = mj;
mk = 1;
for (int i = 1; i < 55; i++)
{ //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position.
if ((ii += 21) >= 55) ii -= 55;
SeedArray[ii] = mk;
mk = mj - mk;
if (mk < 0) mk += MBIG;
mj = SeedArray[ii];
}
for (int k = 1; k < 5; k++)
{
for (int i = 1; i < 56; i++)
{
int n = i + 30;
if (n >= 55) n -= 55;
SeedArray[i] -= SeedArray[1 + n];
if (SeedArray[i] < 0) SeedArray[i] += MBIG;
}
}
inext = 0;
inextp = 21;
Seed = 1;
}
//
// Package Private Methods
//
/*====================================Sample====================================
**Action: Return a new random number [0..1) and reSeed the Seed array.
**Returns: A double [0..1)
**Arguments: None
**Exceptions: None
==============================================================================*/
protected virtual double Sample()
{
//Including this division at the end gives us significantly improved
//random number distribution.
return (InternalSample() * (1.0 / MBIG));
}
private int InternalSample()
{
int retVal;
int locINext = inext;
int locINextp = inextp;
if (++locINext >= 56) locINext = 1;
if (++locINextp >= 56) locINextp = 1;
retVal = SeedArray[locINext] - SeedArray[locINextp];
if (retVal == MBIG) retVal--;
if (retVal < 0) retVal += MBIG;
SeedArray[locINext] = retVal;
inext = locINext;
inextp = locINextp;
return retVal;
}
[ThreadStatic]
private static Random t_threadRandom;
private static readonly Random s_globalRandom = new Random(GenerateGlobalSeed());
/*=====================================GenerateSeed=====================================
**Returns: An integer that can be used as seed values for consecutively
creating lots of instances on the same thread within a short period of time.
========================================================================================*/
private static int GenerateSeed()
{
Random rnd = t_threadRandom;
if (rnd == null)
{
int seed;
lock (s_globalRandom)
{
seed = s_globalRandom.Next();
}
rnd = new Random(seed);
t_threadRandom = rnd;
}
return rnd.Next();
}
/*==================================GenerateGlobalSeed====================================
**Action: Creates a number to use as global seed.
**Returns: An integer that is safe to use as seed values for thread-local seed generators.
==========================================================================================*/
private static int GenerateGlobalSeed()
{
return Guid.NewGuid().GetHashCode();
}
//
// Public Instance Methods
//
/*=====================================Next=====================================
**Returns: An int [0..Int32.MaxValue)
**Arguments: None
**Exceptions: None.
==============================================================================*/
public virtual int Next()
{
return InternalSample();
}
private double GetSampleForLargeRange()
{
// The distribution of double value returned by Sample
// is not distributed well enough for a large range.
// If we use Sample for a range [Int32.MinValue..Int32.MaxValue)
// We will end up getting even numbers only.
int result = InternalSample();
// Note we can't use addition here. The distribution will be bad if we do that.
bool negative = (InternalSample() % 2 == 0) ? true : false; // decide the sign based on second sample
if (negative)
{
result = -result;
}
double d = result;
d += (Int32.MaxValue - 1); // get a number in range [0 .. 2 * Int32MaxValue - 1)
d /= 2 * (uint)Int32.MaxValue - 1;
return d;
}
/*=====================================Next=====================================
**Returns: An int [minvalue..maxvalue)
**Arguments: minValue -- the least legal value for the Random number.
** maxValue -- One greater than the greatest legal return value.
**Exceptions: None.
==============================================================================*/
public virtual int Next(int minValue, int maxValue)
{
if (minValue > maxValue)
{
throw new ArgumentOutOfRangeException(nameof(minValue), Environment.GetResourceString("Argument_MinMaxValue", nameof(minValue), nameof(maxValue)));
}
Contract.EndContractBlock();
long range = (long)maxValue - minValue;
if (range <= (long)Int32.MaxValue)
{
return ((int)(Sample() * range) + minValue);
}
else
{
return (int)((long)(GetSampleForLargeRange() * range) + minValue);
}
}
/*=====================================Next=====================================
**Returns: An int [0..maxValue)
**Arguments: maxValue -- One more than the greatest legal return value.
**Exceptions: None.
==============================================================================*/
public virtual int Next(int maxValue)
{
if (maxValue < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxValue), Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", nameof(maxValue)));
}
Contract.EndContractBlock();
return (int)(Sample() * maxValue);
}
/*=====================================Next=====================================
**Returns: A double [0..1)
**Arguments: None
**Exceptions: None
==============================================================================*/
public virtual double NextDouble()
{
return Sample();
}
/*==================================NextBytes===================================
**Action: Fills the byte array with random bytes [0..0x7f]. The entire array is filled.
**Returns:Void
**Arugments: buffer -- the array to be filled.
**Exceptions: None
==============================================================================*/
public virtual void NextBytes(byte[] buffer)
{
if (buffer == null) throw new ArgumentNullException(nameof(buffer));
Contract.EndContractBlock();
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)(InternalSample() % (Byte.MaxValue + 1));
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.