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. using System; using System.Globalization; using System.IO.Pipelines; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http { internal abstract class MessageBody { private static readonly MessageBody _zeroContentLengthClose = new ZeroContentLengthMessageBody(keepAlive: false); private static readonly MessageBody _zeroContentLengthKeepAlive = new ZeroContentLengthMessageBody(keepAlive: true); private readonly HttpProtocol _context; private bool _send100Continue = true; private long _observedBytes; private bool _stopped; protected bool _timingEnabled; protected bool _backpressure; protected long _alreadyTimedBytes; protected long _examinedUnconsumedBytes; protected MessageBody(HttpProtocol context) { _context = context; } public static MessageBody ZeroContentLengthClose => _zeroContentLengthClose; public static MessageBody ZeroContentLengthKeepAlive => _zeroContentLengthKeepAlive; public bool RequestKeepAlive { get; protected set; } public bool RequestUpgrade { get; protected set; } public virtual bool IsEmpty => false; protected KestrelTrace Log => _context.ServiceContext.Log; public abstract ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default); public abstract bool TryRead(out ReadResult readResult); public void AdvanceTo(SequencePosition consumed) { AdvanceTo(consumed, consumed); } public abstract void AdvanceTo(SequencePosition consumed, SequencePosition examined); public abstract void CancelPendingRead(); public abstract void Complete(Exception? exception); public virtual ValueTask CompleteAsync(Exception? exception) { Complete(exception); return default; } public virtual Task ConsumeAsync() { Task startTask = TryStartAsync(); if (!startTask.IsCompletedSuccessfully) { return ConsumeAwaited(startTask); } return OnConsumeAsync(); } private async Task ConsumeAwaited(Task startTask) { await startTask; await OnConsumeAsync(); } public virtual ValueTask StopAsync() { TryStop(); return OnStopAsync(); } protected virtual Task OnConsumeAsync() => Task.CompletedTask; protected virtual ValueTask OnStopAsync() => default; public virtual void Reset() { _send100Continue = true; _observedBytes = 0; _stopped = false; _timingEnabled = false; _backpressure = false; _alreadyTimedBytes = 0; _examinedUnconsumedBytes = 0; } protected ValueTask<FlushResult> TryProduceContinueAsync() { if (_send100Continue) { _send100Continue = false; return _context.HttpResponseControl.ProduceContinueAsync(); } return default; } protected Task TryStartAsync() { if (_context.HasStartedConsumingRequestBody) { return Task.CompletedTask; } OnReadStarting(); _context.HasStartedConsumingRequestBody = true; if (!RequestUpgrade) { // Accessing TraceIdentifier will lazy-allocate a string ID. // Don't access TraceIdentifer unless logging is enabled. if (Log.IsEnabled(LogLevel.Debug)) { Log.RequestBodyStart(_context.ConnectionIdFeature, _context.TraceIdentifier); } if (_context.MinRequestBodyDataRate != null) { _timingEnabled = true; _context.TimeoutControl.StartRequestBody(_context.MinRequestBodyDataRate); } } return OnReadStartedAsync(); } protected void TryStop() { if (_stopped) { return; } _stopped = true; if (!RequestUpgrade) { // Accessing TraceIdentifier will lazy-allocate a string ID // Don't access TraceIdentifer unless logging is enabled. if (Log.IsEnabled(LogLevel.Debug)) { Log.RequestBodyDone(_context.ConnectionIdFeature, _context.TraceIdentifier); } if (_timingEnabled) { if (_backpressure) { _context.TimeoutControl.StopTimingRead(); } _context.TimeoutControl.StopRequestBody(); } } } protected virtual void OnReadStarting() { } protected virtual Task OnReadStartedAsync() { return Task.CompletedTask; } protected void AddAndCheckObservedBytes(long observedBytes) { _observedBytes += observedBytes; var maxRequestBodySize = _context.MaxRequestBodySize; if (_observedBytes > maxRequestBodySize) { KestrelBadHttpRequestException.Throw(RequestRejectionReason.RequestBodyTooLarge, maxRequestBodySize.GetValueOrDefault().ToString(CultureInfo.InvariantCulture)); } } protected ValueTask<ReadResult> StartTimingReadAsync(ValueTask<ReadResult> readAwaitable, CancellationToken cancellationToken) { if (!readAwaitable.IsCompleted) { ValueTask<FlushResult> continueTask = TryProduceContinueAsync(); if (!continueTask.IsCompletedSuccessfully) { return StartTimingReadAwaited(continueTask, readAwaitable, cancellationToken); } else { continueTask.GetAwaiter().GetResult(); } if (_timingEnabled) { _backpressure = true; _context.TimeoutControl.StartTimingRead(); } } return readAwaitable; } protected async ValueTask<ReadResult> StartTimingReadAwaited(ValueTask<FlushResult> continueTask, ValueTask<ReadResult> readAwaitable, CancellationToken cancellationToken) { await continueTask; if (_timingEnabled) { _backpressure = true; _context.TimeoutControl.StartTimingRead(); } return await readAwaitable; } protected void CountBytesRead(long bytesInReadResult) { var numFirstSeenBytes = bytesInReadResult - _alreadyTimedBytes; if (numFirstSeenBytes > 0) { _context.TimeoutControl.BytesRead(numFirstSeenBytes); } } protected void StopTimingRead(long bytesInReadResult) { CountBytesRead(bytesInReadResult); if (_backpressure) { _backpressure = false; _context.TimeoutControl.StopTimingRead(); } } protected long TrackConsumedAndExaminedBytes(ReadResult readResult, SequencePosition consumed, SequencePosition examined) { // This code path is fairly hard to understand so let's break it down with an example // ReadAsync returns a ReadResult of length 50. // Advance(25, 40). The examined length would be 40 and consumed length would be 25. // _totalExaminedInPreviousReadResult starts at 0. newlyExamined is 40. // OnDataRead is called with length 40. // _totalExaminedInPreviousReadResult is now 40 - 25 = 15. // The next call to ReadAsync returns 50 again // Advance(5, 5) is called // newlyExamined is 5 - 15, or -10. // Update _totalExaminedInPreviousReadResult to 10 as we consumed 5. // The next call to ReadAsync returns 50 again // _totalExaminedInPreviousReadResult is 10 // Advance(50, 50) is called // newlyExamined = 50 - 10 = 40 // _totalExaminedInPreviousReadResult is now 50 // _totalExaminedInPreviousReadResult is finally 0 after subtracting consumedLength. long examinedLength, consumedLength, totalLength; if (consumed.Equals(examined)) { examinedLength = readResult.Buffer.Slice(readResult.Buffer.Start, examined).Length; consumedLength = examinedLength; } else { consumedLength = readResult.Buffer.Slice(readResult.Buffer.Start, consumed).Length; examinedLength = consumedLength + readResult.Buffer.Slice(consumed, examined).Length; } if (examined.Equals(readResult.Buffer.End)) { totalLength = examinedLength; } else { totalLength = readResult.Buffer.Length; } var newlyExaminedBytes = examinedLength - _examinedUnconsumedBytes; _examinedUnconsumedBytes += newlyExaminedBytes - consumedLength; _alreadyTimedBytes = totalLength - consumedLength; return newlyExaminedBytes; } } }
using System; using System.Collections.Generic; using System.Text; using Qwack.Dates; using Qwack.Core.Basic; using Qwack.Options.VolSurfaces; using static System.Math; using System.Linq; using Qwack.Transport.BasicTypes; namespace Qwack.Options.Asians { public static class TurnbullWakeman { public static double PV(double forward, double knownAverage, double sigma, double K, double tAvgStart, double tExpiry, double riskFree, OptionType callPut) { if (tExpiry <= 0) //work out intrinsic { return callPut == OptionType.Call ? Max(0, knownAverage - K) : Max(0, K - knownAverage); } var tau = Max(0, tAvgStart); var M = 2 * (Exp(sigma * sigma * tExpiry) - Exp(sigma * sigma * tau) * (1 + sigma * sigma * (tExpiry - tau))); M /= Pow(sigma, 4.0) * (tExpiry - tau) * (tExpiry - tau); //hack to fix deep ITM options have imaginary vol var sigma_a = tExpiry == 0 ? 0.0 : Sqrt(Log(M) / tExpiry); K = AsianUtils.AdjustedStrike(K, knownAverage, tExpiry, tAvgStart); if (K <= 0 && tAvgStart < 0) { if (callPut == OptionType.P) return 0; var t2 = tExpiry - tAvgStart; var expAvg = knownAverage * (t2 - tExpiry) / t2 + forward * tExpiry / t2; var df = Exp(-riskFree * tExpiry); return df * expAvg; } var pv = BlackFunctions.BlackPV(forward, K, riskFree, tExpiry, sigma_a, callPut); if (tAvgStart < 0) { pv *= tExpiry / (tExpiry - tAvgStart); } return pv; } public static double PV(double forward, double knownAverage, double sigma, double K, DateTime evalDate, DateTime avgStartDate, DateTime avgEndDate, double riskFree, OptionType callPut) { var tAvgStart = (avgStartDate - evalDate).Days / 365.0; var tExpiry = (avgEndDate - evalDate).Days / 365.0; return PV(forward, knownAverage, sigma, K, tAvgStart, tExpiry, riskFree, callPut); } public static double PV(double[] forwards, DateTime[] fixingDates, DateTime evalDate, DateTime payDate, double[] sigmas, double K, double riskFree, OptionType callPut, bool todayFixed=false) { if (payDate < evalDate) return 0.0; if (forwards.Length != fixingDates.Length || fixingDates.Length != sigmas.Length) throw new DataMisalignedException(); var nFixed = evalDate < fixingDates.First() ? 0 : fixingDates.Where(x => (todayFixed ? x <= evalDate : x < evalDate)).Count(); var nFloat = fixingDates.Length - nFixed; var m1 = forwards.Skip(nFixed).Average(); var wholeAverage = forwards.Average(); var tExpiry = evalDate.CalculateYearFraction(fixingDates.Last(), DayCountBasis.Act365F, false); var tPay = evalDate.CalculateYearFraction(payDate, DayCountBasis.Act365F, false); var df = Exp(-riskFree * tPay); if (tExpiry <= 0) //work out intrinsic { return df * (callPut == OptionType.Call ? Max(0, wholeAverage - K) : Max(0, K - wholeAverage)); } var m2 = 0.0; var ts = fixingDates.Select(x => Max(0, evalDate.CalculateYearFraction(x, DayCountBasis.Act365F, false))).ToArray(); for (var i = nFixed; i < fixingDates.Length; i++) for (var j = nFixed; j < fixingDates.Length; j++) m2 += forwards[i] * forwards[j] * Exp(sigmas[i] * sigmas[j] * ts[Min(i, j)]); m2 /= nFloat * nFloat; var sigma_a = Sqrt(1 / tExpiry * Log(m2 / (m1 * m1))); var tAvgStart = evalDate.CalculateYearFraction(fixingDates.First(), DayCountBasis.Act365F, false); var knownAverage = nFixed == 0 ? 0.0 : forwards.Take(nFixed).Average(); var k0 = K; K = AsianUtils.AdjustedStrike(K, knownAverage, tExpiry, tAvgStart); if (K <= 0) { return (callPut == OptionType.P) ? 0.0 : df * Max(wholeAverage - k0, 0); } var pv = BlackFunctions.BlackPV(m1, K, 0.0, tExpiry, sigma_a, callPut); if (tAvgStart < 0) { pv *= tExpiry / (tExpiry - tAvgStart); } return df * pv; } public static double Theta(double[] forwards, DateTime[] fixingDates, DateTime evalDate, DateTime payDate, double[] sigmas, double K, double riskFree, OptionType callPut) { if (payDate < evalDate) return 0.0; if (forwards.Length != fixingDates.Length || fixingDates.Length != sigmas.Length) throw new DataMisalignedException(); var m1 = forwards.Average(); var tExpiry = evalDate.CalculateYearFraction(fixingDates.Last(), DayCountBasis.Act365F); var tPay = evalDate.CalculateYearFraction(payDate, DayCountBasis.Act365F); var df = Exp(-riskFree * tPay); if (tExpiry <= 0) //work out intrinsic { return -riskFree * df * (callPut == OptionType.Call ? Max(0, m1 - K) : Max(0, K - m1)); } var pv1 = PV(forwards, fixingDates, evalDate, payDate, sigmas, K, riskFree, callPut); var pv2 = PV(forwards, fixingDates, evalDate.AddDays(1), payDate, sigmas, K, riskFree, callPut); return (pv2 - pv1) * 365; } public static double Delta(double forward, double knownAverage, double sigma, double K, double tAvgStart, double tExpiry, double riskFree, OptionType callPut) { var tau = Max(0, tAvgStart); var M = 2 * (Exp(sigma * sigma * tExpiry) - Exp(sigma * sigma * tau) * (1 + sigma * sigma * (tExpiry - tau))); M /= Pow(sigma, 4.0) * (tExpiry - tau) * (tExpiry - tau); var sigma_a = Sqrt(Log(M) / tExpiry); K = AsianUtils.AdjustedStrike(K, knownAverage, tExpiry, tAvgStart); if (K <= 0) { if (callPut == OptionType.P) return 0; var t2 = tExpiry - tAvgStart; var expAvg = knownAverage * (t2 - tExpiry) / t2 + forward * tExpiry / t2; var df = Exp(-riskFree * tExpiry); return df * (expAvg - K); } var delta = BlackFunctions.BlackDelta(forward, K, riskFree, tExpiry, sigma_a, callPut); if (tAvgStart < 0) { delta *= tExpiry / (tExpiry - tAvgStart); } return delta; } public static double Delta(double forward, double knownAverage, double sigma, double K, DateTime evalDate, DateTime avgStartDate, DateTime avgEndDate, double riskFree, OptionType callPut) { var tAvgStart = (avgStartDate - evalDate).Days / 365.0; var tExpiry = (avgEndDate - evalDate).Days / 365.0; return Delta(forward, knownAverage, sigma, K, tAvgStart, tExpiry, riskFree, callPut); } public static double StrikeForPV(double targetPV, double forward, double knownAverage, IVolSurface volSurface, DateTime evalDate, DateTime avgStartDate, DateTime avgEndDate, double riskFree, OptionType callPut) { var minStrike = forward / 100.0; var maxStrike = forward * 100.0; var volDate = avgStartDate.Average(avgEndDate); Func<double, double> testFunc = (absK => { var vol = volSurface.GetVolForAbsoluteStrike(absK, volDate, forward); var pv = PV(forward, knownAverage, vol, absK, evalDate, avgStartDate, avgEndDate, riskFree, callPut); return targetPV - pv; }); var solvedStrike = Math.Solvers.Brent.BrentsMethodSolve(testFunc, minStrike, maxStrike, 1e-8); return solvedStrike; } public static double StrikeForPV(double targetPV, double[] forwards, DateTime[] fixingDates, IVolSurface volSurface, DateTime evalDate, DateTime payDate, double riskFree, OptionType callPut) { var minStrike = forwards.Min() / 100.0; var maxStrike = forwards.Max() * 100.0; var ixMin = Array.BinarySearch(fixingDates, evalDate); if (ixMin < 0) ixMin = ~ixMin; Func<double, double> testFunc = (absK => { var vols = fixingDates.Select((d, ix) => ix >= ixMin ? volSurface.GetVolForAbsoluteStrike(absK, d, forwards[ix]) : 0.0).ToArray(); var pv = PV(forwards, fixingDates, evalDate, payDate, vols, absK, riskFree, callPut); return targetPV - pv; }); var solvedStrike = Math.Solvers.Brent.BrentsMethodSolve(testFunc, minStrike, maxStrike, 1e-8); return solvedStrike; } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Avalonia.FreeDesktop; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.Input.TextInput; using Avalonia.Platform.Interop; using static Avalonia.X11.XLib; namespace Avalonia.X11 { partial class X11Window { private ITextInputMethodImpl _ime; private IX11InputMethodControl _imeControl; private bool _processingIme; private Queue<(RawKeyEventArgs args, XEvent xev, int keyval, int keycode)> _imeQueue = new Queue<(RawKeyEventArgs args, XEvent xev, int keyVal, int keyCode)>(); unsafe void CreateIC() { if (_x11.HasXim) { XGetIMValues(_x11.Xim, XNames.XNQueryInputStyle, out var supported_styles, IntPtr.Zero); for (var c = 0; c < supported_styles->count_styles; c++) { var style = (XIMProperties)supported_styles->supported_styles[c]; if ((int)(style & XIMProperties.XIMPreeditPosition) != 0 && ((int)(style & XIMProperties.XIMStatusNothing) != 0)) { XPoint spot = default; XRectangle area = default; //using var areaS = new Utf8Buffer("area"); using var spotS = new Utf8Buffer("spotLocation"); using var fontS = new Utf8Buffer("fontSet"); var list = XVaCreateNestedList(0, //areaS, &area, spotS, &spot, fontS, _x11.DefaultFontSet, IntPtr.Zero); _xic = XCreateIC(_x11.Xim, XNames.XNClientWindow, _handle, XNames.XNFocusWindow, _handle, XNames.XNInputStyle, new IntPtr((int)style), XNames.XNResourceName, _platform.Options.WmClass, XNames.XNResourceClass, _platform.Options.WmClass, XNames.XNPreeditAttributes, list, IntPtr.Zero); XFree(list); break; } } XFree(new IntPtr(supported_styles)); } if (_xic == IntPtr.Zero) _xic = XCreateIC(_x11.Xim, XNames.XNInputStyle, new IntPtr((int)(XIMProperties.XIMPreeditNothing | XIMProperties.XIMStatusNothing)), XNames.XNClientWindow, _handle, XNames.XNFocusWindow, _handle, IntPtr.Zero); } void InitializeIme() { var ime = AvaloniaLocator.Current.GetService<IX11InputMethodFactory>()?.CreateClient(_handle); if (ime == null && _x11.HasXim) { var xim = new XimInputMethod(this); ime = (xim, xim); } if (ime != null) { (_ime, _imeControl) = ime.Value; _imeControl.Commit += s => ScheduleInput(new RawTextInputEventArgs(_keyboard, (ulong)_x11.LastActivityTimestamp.ToInt64(), _inputRoot, s)); _imeControl.ForwardKey += ev => { ScheduleInput(new RawKeyEventArgs(_keyboard, (ulong)_x11.LastActivityTimestamp.ToInt64(), _inputRoot, ev.Type, X11KeyTransform.ConvertKey((X11Key)ev.KeyVal), (RawInputModifiers)ev.Modifiers)); }; } } void UpdateImePosition() => _imeControl?.UpdateWindowInfo(Position, RenderScaling); void HandleKeyEvent(ref XEvent ev) { var index = ev.KeyEvent.state.HasAllFlags(XModifierMask.ShiftMask); // We need the latin key, since it's mainly used for hotkeys, we use a different API for text anyway var key = (X11Key)XKeycodeToKeysym(_x11.Display, ev.KeyEvent.keycode, index ? 1 : 0).ToInt32(); // Manually switch the Shift index for the keypad, // there should be a proper way to do this if (ev.KeyEvent.state.HasAllFlags(XModifierMask.Mod2Mask) && key > X11Key.Num_Lock && key <= X11Key.KP_9) key = (X11Key)XKeycodeToKeysym(_x11.Display, ev.KeyEvent.keycode, index ? 0 : 1).ToInt32(); var filtered = ScheduleKeyInput(new RawKeyEventArgs(_keyboard, (ulong)ev.KeyEvent.time.ToInt64(), _inputRoot, ev.type == XEventName.KeyPress ? RawKeyEventType.KeyDown : RawKeyEventType.KeyUp, X11KeyTransform.ConvertKey(key), TranslateModifiers(ev.KeyEvent.state)), ref ev, (int)key, ev.KeyEvent.keycode); if (ev.type == XEventName.KeyPress && !filtered) TriggerClassicTextInputEvent(ref ev); } void TriggerClassicTextInputEvent(ref XEvent ev) { var text = TranslateEventToString(ref ev); if (text != null) ScheduleInput( new RawTextInputEventArgs(_keyboard, (ulong)ev.KeyEvent.time.ToInt64(), _inputRoot, text), ref ev); } private const int ImeBufferSize = 64 * 1024; [ThreadStatic] private static IntPtr ImeBuffer; unsafe string TranslateEventToString(ref XEvent ev) { if (ImeBuffer == IntPtr.Zero) ImeBuffer = Marshal.AllocHGlobal(ImeBufferSize); var len = Xutf8LookupString(_xic, ref ev, ImeBuffer.ToPointer(), ImeBufferSize, out _, out var istatus); var status = (XLookupStatus)istatus; if (len == 0) return null; string text; if (status == XLookupStatus.XBufferOverflow) return null; else text = Encoding.UTF8.GetString((byte*)ImeBuffer.ToPointer(), len); if (text == null) return null; if (text.Length == 1) { if (text[0] < ' ' || text[0] == 0x7f) //Control codes or DEL return null; } return text; } bool ScheduleKeyInput(RawKeyEventArgs args, ref XEvent xev, int keyval, int keycode) { _x11.LastActivityTimestamp = xev.ButtonEvent.time; if (_imeControl != null && _imeControl.IsEnabled) { if (FilterIme(args, xev, keyval, keycode)) return true; } ScheduleInput(args); return false; } bool FilterIme(RawKeyEventArgs args, XEvent xev, int keyval, int keycode) { if (_ime == null) return false; _imeQueue.Enqueue((args, xev, keyval, keycode)); if (!_processingIme) ProcessNextImeEvent(); return true; } async void ProcessNextImeEvent() { if(_processingIme) return; _processingIme = true; try { while (_imeQueue.Count != 0) { var ev = _imeQueue.Dequeue(); if (_imeControl == null || !await _imeControl.HandleEventAsync(ev.args, ev.keyval, ev.keycode)) { ScheduleInput(ev.args); if (ev.args.Type == RawKeyEventType.KeyDown) TriggerClassicTextInputEvent(ref ev.xev); } } } finally { _processingIme = false; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Timers; using libsecondlife; using libsecondlife.Packets; namespace SLNetworkComm { /// <summary> /// SLNetCom is a class built on top of libsecondlife that provides a way to /// raise events on the proper thread (for GUI apps especially). /// </summary> public partial class SLNetCom { private SecondLife client; private LoginOptions loginOptions; private bool loggingIn = false; private bool loggedIn = false; private bool teleporting = false; private const string MainGridLogin = @"https://login.agni.lindenlab.com/cgi-bin/login.cgi"; private const string BetaGridLogin = @"https://login.aditi.lindenlab.com/cgi-bin/login.cgi"; // NetcomSync is used for raising certain events on the // GUI/main thread. Useful if you're modifying GUI controls // in the client app when responding to those events. private ISynchronizeInvoke netcomSync; public SLNetCom(SecondLife client) { this.client = client; loginOptions = new LoginOptions(); AddClientEvents(); AddPacketCallbacks(); } private void AddClientEvents() { client.Self.OnChat += new AgentManager.ChatCallback(Self_OnChat); client.Self.OnInstantMessage += new AgentManager.InstantMessageCallback(Self_OnInstantMessage); client.Self.OnBalanceUpdated += new AgentManager.BalanceCallback(Avatar_OnBalanceUpdated); client.Self.OnTeleport += new AgentManager.TeleportCallback(Self_OnTeleport); client.Network.OnConnected += new NetworkManager.ConnectedCallback(Network_OnConnected); client.Network.OnDisconnected += new NetworkManager.DisconnectedCallback(Network_OnDisconnected); client.Network.OnLogin += new NetworkManager.LoginCallback(Network_OnLogin); client.Network.OnLogoutReply += new NetworkManager.LogoutCallback(Network_OnLogoutReply); } private void Self_OnInstantMessage(InstantMessage im, Simulator simulator) { InstantMessageEventArgs ea = new InstantMessageEventArgs(im, simulator); if (netcomSync != null) netcomSync.BeginInvoke(new OnInstantMessageRaise(OnInstantMessageReceived), new object[] { ea }); else OnInstantMessageReceived(ea); } private void Network_OnLogin(LoginStatus login, string message) { if (login == LoginStatus.Success) loggedIn = true; ClientLoginEventArgs ea = new ClientLoginEventArgs(login, message); if (netcomSync != null) netcomSync.BeginInvoke(new OnClientLoginRaise(OnClientLoginStatus), new object[] { ea }); else OnClientLoginStatus(ea); } private void Network_OnLogoutReply(List<LLUUID> inventoryItems) { loggedIn = false; if (netcomSync != null) netcomSync.BeginInvoke(new OnClientLogoutRaise(OnClientLoggedOut), new object[] { EventArgs.Empty }); else OnClientLoggedOut(EventArgs.Empty); } private void Self_OnTeleport(string message, AgentManager.TeleportStatus status, AgentManager.TeleportFlags flags) { if (status == AgentManager.TeleportStatus.Finished || status == AgentManager.TeleportStatus.Failed) teleporting = false; TeleportStatusEventArgs ea = new TeleportStatusEventArgs(message, status, flags); if (netcomSync != null) netcomSync.BeginInvoke(new OnTeleportStatusRaise(OnTeleportStatusChanged), new object[] { ea }); else OnTeleportStatusChanged(ea); } private void Network_OnConnected(object sender) { client.Self.RequestBalance(); client.Appearance.SetPreviousAppearance(false); } private void Self_OnChat(string message, ChatAudibleLevel audible, ChatType type, ChatSourceType sourceType, string fromName, LLUUID id, LLUUID ownerid, LLVector3 position) { ChatEventArgs ea = new ChatEventArgs(message, audible, type, sourceType, fromName, id, ownerid, position); if (netcomSync != null) netcomSync.BeginInvoke(new OnChatRaise(OnChatReceived), new object[] { ea }); else OnChatReceived(ea); } private void AddPacketCallbacks() { client.Network.RegisterCallback(PacketType.AlertMessage, new NetworkManager.PacketCallback(AlertMessageHandler)); } private void Network_OnDisconnected(NetworkManager.DisconnectType type, string message) { if (!loggedIn) return; loggedIn = false; ClientDisconnectEventArgs ea = new ClientDisconnectEventArgs(type, message); if (netcomSync != null) netcomSync.BeginInvoke(new OnClientDisconnectRaise(OnClientDisconnected), new object[] { ea }); else OnClientDisconnected(ea); } private void Avatar_OnBalanceUpdated(int balance) { MoneyBalanceEventArgs ea = new MoneyBalanceEventArgs(balance); if (netcomSync != null) netcomSync.BeginInvoke(new OnMoneyBalanceRaise(OnMoneyBalanceUpdated), new object[] { ea }); else OnMoneyBalanceUpdated(ea); } private void AlertMessageHandler(Packet packet, Simulator simulator) { if (packet.Type != PacketType.AlertMessage) return; AlertMessagePacket alertPacket = (AlertMessagePacket)packet; AlertMessageEventArgs ea = new AlertMessageEventArgs( Helpers.FieldToUTF8String(alertPacket.AlertData.Message)); if (netcomSync != null) netcomSync.BeginInvoke(new OnAlertMessageRaise(OnAlertMessageReceived), new object[] { ea }); else OnAlertMessageReceived(ea); } public void Login() { loggingIn = true; OverrideEventArgs ea = new OverrideEventArgs(); OnClientLoggingIn(ea); if (ea.Cancel) { loggingIn = false; return; } if (string.IsNullOrEmpty(loginOptions.FirstName) || string.IsNullOrEmpty(loginOptions.LastName) || string.IsNullOrEmpty(loginOptions.Password)) { OnClientLoginStatus( new ClientLoginEventArgs(LoginStatus.Failed, "One or more fields are blank.")); } string startLocation = string.Empty; switch (loginOptions.StartLocation) { case StartLocationType.Home: startLocation = "home"; break; case StartLocationType.Last: startLocation = "last"; break; case StartLocationType.Custom: startLocation = loginOptions.StartLocationCustom.Trim(); StartLocationParser parser = new StartLocationParser(startLocation); startLocation = NetworkManager.StartLocation(parser.Sim, parser.X, parser.Y, parser.Z); break; } string password; if (loginOptions.IsPasswordMD5) password = loginOptions.Password; else password = Helpers.MD5(loginOptions.Password); LoginParams loginParams = client.Network.DefaultLoginParams( loginOptions.FirstName, loginOptions.LastName, password, loginOptions.UserAgent, loginOptions.Author); loginParams.Start = startLocation; switch (loginOptions.Grid) { case LoginGrid.MainGrid: client.Settings.LOGIN_SERVER = MainGridLogin; break; case LoginGrid.BetaGrid: client.Settings.LOGIN_SERVER = BetaGridLogin; break; case LoginGrid.Custom: client.Settings.LOGIN_SERVER = loginOptions.GridCustomLoginUri; break; } client.Network.BeginLogin(loginParams); } public void Logout() { if (!loggedIn) { OnClientLoggedOut(EventArgs.Empty); return; } OverrideEventArgs ea = new OverrideEventArgs(); OnClientLoggingOut(ea); if (ea.Cancel) return; client.Network.Logout(); } public void ChatOut(string chat, ChatType type, int channel) { if (!loggedIn) return; client.Self.Chat(chat, channel, type); OnChatSent(new ChatSentEventArgs(chat, type, channel)); } public void SendInstantMessage(string message, LLUUID target, LLUUID session) { if (!loggedIn) return; //client.Self.InstantMessage(target, message, session); client.Self.InstantMessage( loginOptions.FullName, target, message, session, InstantMessageDialog.MessageFromAgent, InstantMessageOnline.Online, client.Self.SimPosition, client.Network.CurrentSim.ID, null); OnInstantMessageSent(new InstantMessageSentEventArgs(message, target, session, DateTime.Now)); } public void SendIMStartTyping(LLUUID target, LLUUID session) { if (!loggedIn) return; client.Self.InstantMessage( loginOptions.FullName, target, "typing", session, InstantMessageDialog.StartTyping, InstantMessageOnline.Online, client.Self.SimPosition, client.Network.CurrentSim.ID, null); } public void SendIMStopTyping(LLUUID target, LLUUID session) { if (!loggedIn) return; client.Self.InstantMessage( loginOptions.FullName, target, "typing", session, InstantMessageDialog.StopTyping, InstantMessageOnline.Online, client.Self.SimPosition, client.Network.CurrentSim.ID, null); } public void Teleport(string sim, LLVector3 coordinates) { if (!loggedIn) return; if (teleporting) return; TeleportingEventArgs ea = new TeleportingEventArgs(sim, coordinates); OnTeleporting(ea); if (ea.Cancel) return; teleporting = true; client.Self.Teleport(sim, coordinates); } public bool IsLoggingIn { get { return loggingIn; } } public bool IsLoggedIn { get { return loggedIn; } } public bool IsTeleporting { get { return teleporting; } } public LoginOptions LoginOptions { get { return loginOptions; } set { loginOptions = value; } } public ISynchronizeInvoke NetcomSync { get { return netcomSync; } set { netcomSync = value; } } } }
using System; using System.Runtime.InteropServices; using System.Security; using BulletSharp.Math; namespace BulletSharp { public delegate void ContactDestroyedEventHandler(Object userPersistantData); public delegate void ContactProcessedEventHandler(ManifoldPoint cp, CollisionObject body0, CollisionObject body1); public class PersistentManifold : IDisposable //: TypedObject { internal IntPtr _native; private bool _preventDelete; static ContactDestroyedEventHandler _contactDestroyed; static ContactProcessedEventHandler _contactProcessed; static ContactDestroyedUnmanagedDelegate _contactDestroyedUnmanaged; static ContactProcessedUnmanagedDelegate _contactProcessedUnmanaged; static IntPtr _contactDestroyedUnmanagedPtr; static IntPtr _contactProcessedUnmanagedPtr; [UnmanagedFunctionPointer(Native.Conv), SuppressUnmanagedCodeSecurity] private delegate bool ContactDestroyedUnmanagedDelegate(IntPtr userPersistantData); [UnmanagedFunctionPointer(Native.Conv), SuppressUnmanagedCodeSecurity] private delegate bool ContactProcessedUnmanagedDelegate(IntPtr cp, IntPtr body0, IntPtr body1); static bool ContactDestroyedUnmanaged(IntPtr userPersistentData) { _contactDestroyed.Invoke(GCHandle.FromIntPtr(userPersistentData).Target); return false; } static bool ContactProcessedUnmanaged(IntPtr cp, IntPtr body0, IntPtr body1) { _contactProcessed.Invoke(new ManifoldPoint(cp, true), CollisionObject.GetManaged(body0), CollisionObject.GetManaged(body1)); return false; } public static event ContactDestroyedEventHandler ContactDestroyed { add { if (_contactDestroyedUnmanaged == null) { _contactDestroyedUnmanaged = new ContactDestroyedUnmanagedDelegate(ContactDestroyedUnmanaged); _contactDestroyedUnmanagedPtr = Marshal.GetFunctionPointerForDelegate(_contactDestroyedUnmanaged); } setGContactDestroyedCallback(_contactDestroyedUnmanagedPtr); _contactDestroyed += value; } remove { _contactDestroyed -= value; if (_contactDestroyed == null) { setGContactDestroyedCallback(IntPtr.Zero); } } } public static event ContactProcessedEventHandler ContactProcessed { add { if (_contactProcessedUnmanaged == null) { _contactProcessedUnmanaged = new ContactProcessedUnmanagedDelegate(ContactProcessedUnmanaged); _contactProcessedUnmanagedPtr = Marshal.GetFunctionPointerForDelegate(_contactProcessedUnmanaged); } setGContactProcessedCallback(_contactProcessedUnmanagedPtr); _contactProcessed += value; } remove { _contactProcessed -= value; if (_contactProcessed == null) { setGContactProcessedCallback(IntPtr.Zero); } } } internal PersistentManifold(IntPtr native, bool preventDelete) { _native = native; _preventDelete = preventDelete; } public PersistentManifold() { _native = btPersistentManifold_new(); } public PersistentManifold(CollisionObject body0, CollisionObject body1, int __unnamed2, float contactBreakingThreshold, float contactProcessingThreshold) { _native = btPersistentManifold_new2(body0._native, body1._native, __unnamed2, contactBreakingThreshold, contactProcessingThreshold); } public int AddManifoldPoint(ManifoldPoint newPoint) { return btPersistentManifold_addManifoldPoint(_native, newPoint._native); } public int AddManifoldPoint(ManifoldPoint newPoint, bool isPredictive) { return btPersistentManifold_addManifoldPoint2(_native, newPoint._native, isPredictive); } public void ClearManifold() { btPersistentManifold_clearManifold(_native); } public void ClearUserCache(ManifoldPoint pt) { btPersistentManifold_clearUserCache(_native, pt._native); } public int GetCacheEntry(ManifoldPoint newPoint) { return btPersistentManifold_getCacheEntry(_native, newPoint._native); } public ManifoldPoint GetContactPoint(int index) { return new ManifoldPoint(btPersistentManifold_getContactPoint(_native, index), true); } public void RefreshContactPointsRef(ref Matrix trA, ref Matrix trB) { btPersistentManifold_refreshContactPoints(_native, ref trA, ref trB); } public void RefreshContactPoints(Matrix trA, Matrix trB) { btPersistentManifold_refreshContactPoints(_native, ref trA, ref trB); } public void RemoveContactPoint(int index) { btPersistentManifold_removeContactPoint(_native, index); } public void ReplaceContactPoint(ManifoldPoint newPoint, int insertIndex) { btPersistentManifold_replaceContactPoint(_native, newPoint._native, insertIndex); } public void SetBodies(CollisionObject body0, CollisionObject body1) { btPersistentManifold_setBodies(_native, body0._native, body1._native); } public bool ValidContactDistance(ManifoldPoint pt) { return btPersistentManifold_validContactDistance(_native, pt._native); } public CollisionObject Body0 { get { return CollisionObject.GetManaged(btPersistentManifold_getBody0(_native)); } } public CollisionObject Body1 { get { return CollisionObject.GetManaged(btPersistentManifold_getBody1(_native)); } } public int CompanionIdA { get { return btPersistentManifold_getCompanionIdA(_native); } set { btPersistentManifold_setCompanionIdA(_native, value); } } public int CompanionIdB { get { return btPersistentManifold_getCompanionIdB(_native); } set { btPersistentManifold_setCompanionIdB(_native, value); } } public float ContactBreakingThreshold { get { return btPersistentManifold_getContactBreakingThreshold(_native); } set { btPersistentManifold_setContactBreakingThreshold(_native, value); } } public float ContactProcessingThreshold { get { return btPersistentManifold_getContactProcessingThreshold(_native); } set { btPersistentManifold_setContactProcessingThreshold(_native, value); } } public int Index1A { get { return btPersistentManifold_getIndex1a(_native); } set { btPersistentManifold_setIndex1a(_native, value); } } public int NumContacts { get { return btPersistentManifold_getNumContacts(_native); } set { btPersistentManifold_setNumContacts(_native, value); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { if (!_preventDelete) { btPersistentManifold_delete(_native); } _native = IntPtr.Zero; } } ~PersistentManifold() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btPersistentManifold_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btPersistentManifold_new2(IntPtr body0, IntPtr body1, int __unnamed2, float contactBreakingThreshold, float contactProcessingThreshold); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btPersistentManifold_addManifoldPoint(IntPtr obj, IntPtr newPoint); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btPersistentManifold_addManifoldPoint2(IntPtr obj, IntPtr newPoint, bool isPredictive); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btPersistentManifold_clearManifold(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btPersistentManifold_clearUserCache(IntPtr obj, IntPtr pt); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btPersistentManifold_getBody0(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btPersistentManifold_getBody1(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btPersistentManifold_getCacheEntry(IntPtr obj, IntPtr newPoint); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btPersistentManifold_getCompanionIdA(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btPersistentManifold_getCompanionIdB(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btPersistentManifold_getContactBreakingThreshold(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btPersistentManifold_getContactPoint(IntPtr obj, int index); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btPersistentManifold_getContactProcessingThreshold(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btPersistentManifold_getIndex1a(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btPersistentManifold_getNumContacts(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btPersistentManifold_refreshContactPoints(IntPtr obj, [In] ref Matrix trA, [In] ref Matrix trB); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btPersistentManifold_removeContactPoint(IntPtr obj, int index); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btPersistentManifold_replaceContactPoint(IntPtr obj, IntPtr newPoint, int insertIndex); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btPersistentManifold_setBodies(IntPtr obj, IntPtr body0, IntPtr body1); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btPersistentManifold_setCompanionIdA(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btPersistentManifold_setCompanionIdB(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btPersistentManifold_setContactBreakingThreshold(IntPtr obj, float contactBreakingThreshold); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btPersistentManifold_setContactProcessingThreshold(IntPtr obj, float contactProcessingThreshold); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btPersistentManifold_setIndex1a(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btPersistentManifold_setNumContacts(IntPtr obj, int cachedPoints); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btPersistentManifold_validContactDistance(IntPtr obj, IntPtr pt); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btPersistentManifold_delete(IntPtr obj); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern IntPtr getGContactDestroyedCallback(); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern IntPtr getGContactProcessedCallback(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void setGContactDestroyedCallback(IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void setGContactProcessedCallback(IntPtr value); } }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // 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. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define BEHAVIAC_ENABLE_PUSH_OPT using System; using System.Collections.Generic; namespace behaviac { public class Variables { public Variables(Dictionary<uint, IInstantiatedVariable> vars) { this.m_variables = vars; } public Variables() { this.m_variables = new Dictionary<uint, IInstantiatedVariable>(); } public bool IsExisting(uint varId) { return this.m_variables.ContainsKey(varId); } public virtual IInstantiatedVariable GetVariable(uint varId) { if (this.m_variables != null && this.m_variables.ContainsKey(varId)) { return this.m_variables[varId]; } return null; } public virtual void AddVariable(uint varId, IInstantiatedVariable pVar, int stackIndex) { Debug.Check(!this.m_variables.ContainsKey(varId)); this.m_variables[varId] = pVar; } public void Log(Agent agent) { #if !BEHAVIAC_RELEASE var e = this.m_variables.Keys.GetEnumerator(); while (e.MoveNext()) { uint id = e.Current; IInstantiatedVariable pVar = this.m_variables[id]; pVar.Log(agent); } #endif } public void UnLoad(string variableName) { Debug.Check(!string.IsNullOrEmpty(variableName)); uint varId = Utils.MakeVariableId(variableName); if (this.m_variables.ContainsKey(varId)) { this.m_variables.Remove(varId); } } public void Unload() { } public void CopyTo(Agent pAgent, Variables target) { target.m_variables.Clear(); var e = this.m_variables.Keys.GetEnumerator(); while (e.MoveNext()) { uint id = e.Current; IInstantiatedVariable pVar = this.m_variables[id]; IInstantiatedVariable pNew = pVar.clone(); target.m_variables[id] = pNew; } if (!Object.ReferenceEquals(pAgent, null)) { e = target.m_variables.Keys.GetEnumerator(); while (e.MoveNext()) { uint id = e.Current; IInstantiatedVariable pVar = this.m_variables[id]; pVar.CopyTo(pAgent); } } } private void Save(ISerializableNode node) { CSerializationID variablesId = new CSerializationID("vars"); ISerializableNode varsNode = node.newChild(variablesId); var e = this.m_variables.Values.GetEnumerator(); while (e.MoveNext()) { e.Current.Save(varsNode); } } protected Dictionary<uint, IInstantiatedVariable> m_variables = new Dictionary<uint, IInstantiatedVariable>(); public Dictionary<uint, IInstantiatedVariable> Vars { get { return this.m_variables; } } } #if BEHAVIAC_USE_HTN public class AgentState : Variables, IDisposable { private List<AgentState> state_stack = null; public AgentState(Dictionary<uint, IInstantiatedVariable> vars) : base(vars) { } public AgentState() { } public AgentState(AgentState parent) { this.parent = parent; } public void Dispose() { this.Pop(); } private static Stack<AgentState> pool = new Stack<AgentState>(); private AgentState parent = null; #if BEHAVIAC_ENABLE_PUSH_OPT private bool m_forced; private int m_pushed; #endif public int Depth { get { int d = 1; if (this.state_stack != null && this.state_stack.Count > 0) { for (int i = this.state_stack.Count - 1; i >= 0; --i) { AgentState t = this.state_stack[i]; d += 1 + t.m_pushed; } } return d; } } public int Top { get { if (this.state_stack != null && this.state_stack.Count > 0) { return this.state_stack.Count - 1; } return -1; } } public override void AddVariable(uint varId, IInstantiatedVariable pVar, int stackIndex) { if (this.state_stack != null && this.state_stack.Count > 0 && stackIndex > 0 && stackIndex < this.state_stack.Count) { AgentState t = this.state_stack[stackIndex]; t.AddVariable(varId, pVar, -1); } else { base.AddVariable(varId, pVar, -1); } } public override IInstantiatedVariable GetVariable(uint varId) { if (this.state_stack != null && this.state_stack.Count > 0) { for (int i = this.state_stack.Count - 1; i >= 0; --i) { AgentState t = this.state_stack[i]; IInstantiatedVariable pVar = t.GetVariable(varId); if (pVar != null) { return pVar; } } } return base.GetVariable(varId); } public AgentState Push(bool bForcePush) { #if BEHAVIAC_ENABLE_PUSH_OPT if (!bForcePush) { //if the top has nothing new added, to use it again if (this.state_stack != null && this.state_stack.Count > 0) { AgentState t = this.state_stack[this.state_stack.Count - 1]; if (!t.m_forced && t.m_variables.Count == 0) { t.m_pushed++; return t; } } } #endif AgentState newly = null; lock (pool) { if (pool.Count > 0) { newly = pool.Pop(); //set the parent newly.parent = this; } else { newly = new AgentState(this); } newly.m_forced = bForcePush; if (bForcePush) { //base.CopyTo(null, newly); this.CopyTopValueTo(newly); } } if (this.state_stack == null) { this.state_stack = new List<AgentState>(); } //add the newly one at the end of the list as the top this.state_stack.Add(newly); return newly; } private void CopyTopValueTo(AgentState newly) { var e = this.m_variables.Keys.GetEnumerator(); while (e.MoveNext()) { uint id = e.Current; IInstantiatedVariable pVar = this.GetVariable(id); IInstantiatedVariable pNew = pVar.clone(); newly.m_variables[id] = pNew; } } public void Pop() { #if BEHAVIAC_ENABLE_PUSH_OPT if (this.m_pushed > 0) { this.m_pushed--; if (this.m_variables.Count > 0) { this.m_variables.Clear(); return; } return; } #endif if (this.state_stack != null && this.state_stack.Count > 0) { AgentState top = this.state_stack[this.state_stack.Count - 1]; top.Pop(); return; } #if BEHAVIAC_ENABLE_PUSH_OPT this.m_pushed = 0; this.m_forced = false; #endif if (this.state_stack != null) { this.state_stack.Clear(); } this.m_variables.Clear(); Debug.Check(this.state_stack == null); Debug.Check(this.parent != null); this.parent.PopTop(); this.parent = null; lock (pool) { Debug.Check(!pool.Contains(this)); pool.Push(this); } } private void PopTop() { Debug.Check(this.state_stack != null); Debug.Check(this.state_stack.Count > 0); //remove the last one this.state_stack.RemoveAt(this.state_stack.Count - 1); } } #endif//BEHAVIAC_USE_HTN }
using System.Threading.Tasks; using Amplified.CSharp.Extensions; using Xunit; using static Amplified.CSharp.Maybe; namespace Amplified.CSharp { // ReSharper disable once InconsistentNaming public class AsyncMaybe_FlatMap { [Fact] public async Task Sync_ReturningSome_WhenSome_ReturnsResultOfInner() { const int expected = 5; var result = await Some(2).ToAsync().FlatMap(some => Some(some + 3)).OrFail(); Assert.Equal(expected, result); } [Fact] public async Task Async_ReturningSome_WhenSome_ReturnsResultOfInner() { const int expected = 5; var result = await Some(2).ToAsync().FlatMapAsync(some => Task.FromResult(Some(some + 3))).OrFail(); Assert.Equal(expected, result); } [Fact] public async Task Sync_ReturningAsyncSome_WhenSome_ReturnsResultOfInner() { const int expected = 5; var result = await Some(2).ToAsync().FlatMap(some => Some(some + 3).ToAsync()).OrFail(); Assert.Equal(expected, result); } [Fact] public async Task Async_ReturningAsyncSome_WhenSome_ReturnsResultOfInner() { const int expected = 5; var result = await Some(2).ToAsync().FlatMapAsync(some => Task.FromResult(Some(some + 3).ToAsync())).OrFail(); Assert.Equal(expected, result); } [Fact] public async Task Sync_ReturningSome_WhenNone_ReturnsNone() { var isNone = await AsyncMaybe<int>.None().FlatMap(some => Some(some + 3)).IsNone; Assert.True(isNone); } [Fact] public async Task Async_ReturningSome_WhenNone_ReturnsNone() { var isNone = await AsyncMaybe<int>.None().FlatMapAsync(some => Task.FromResult(Some(some + 3))).IsNone; Assert.True(isNone); } [Fact] public async Task Sync_ReturningAsyncSome_WhenNone_ReturnsNone() { var isNone = await AsyncMaybe<int>.None().FlatMap(some => Some(some + 3).ToAsync()).IsNone; Assert.True(isNone); } [Fact] public async Task Async_ReturningAsyncSome_WhenNone_ReturnsNone() { var isNone = await AsyncMaybe<int>.None().FlatMapAsync(some => Task.FromResult(Some(some + 3).ToAsync())).IsNone; Assert.True(isNone); } #region AsyncMaybe<Unit>.FlatMap(Func<Maybe<T>>) [Fact] public async Task Sync_ReturningSome_UsingNoArgs_WhenNone_ReturnsNone() { var source = await AsyncMaybe<Unit>.None().FlatMapUnit(() => Maybe<int>.Some(3)); source.MustBeNone(); } [Fact] public async Task Sync_ReturningSome_UsingNoArgs_WhenSome_ReturnsSome() { const int expected = 3; var source = await AsyncMaybe<Unit>.Some(new Unit()).FlatMapUnit(() => Maybe<int>.Some(expected)); var result = source.MustBeSome(); Assert.Equal(expected, result); } [Fact] public async Task Sync_ReturningNone_UsingNoArgs_WhenNone_ReturnsNone() { var source = await AsyncMaybe<Unit>.None().FlatMapUnit(() => Maybe<int>.Some(3)); source.MustBeNone(); } [Fact] public async Task Sync_ReturningNoneUsingLambda_UsingNoArgs_WhenSome_ReturnsNone() { // ReSharper disable once ConvertClosureToMethodGroup var source = await AsyncMaybe<Unit>.Some(new Unit()).FlatMapUnit(() => Maybe<int>.None()); source.MustBeNone(); } [Fact] public async Task Sync_ReturningNoneUsingMethodRefernece_UsingNoArgs_WhenSome_ReturnsNone() { var source = await AsyncMaybe<Unit>.Some(new Unit()).FlatMapUnit(Maybe<int>.None); source.MustBeNone(); } #endregion #region AsyncMaybe<Unit>.FlatMap(Func<AsyncMaybe<T>>) [Fact] public async Task Sync_ReturningAsyncSome_UsingNoArgs_WhenNone_ReturnsNone() { var source = await AsyncMaybe<Unit>.None().FlatMapUnit(() => AsyncMaybe<int>.Some(3)); source.MustBeNone(); } [Fact] public async Task Sync_ReturningAsyncSome_UsingNoArgs_WhenSome_ReturnsSome() { const int expected = 3; var source = await AsyncMaybe<Unit>.Some(new Unit()).FlatMapUnit(() => AsyncMaybe<int>.Some(expected)); var result = source.MustBeSome(); Assert.Equal(expected, result); } [Fact] public async Task Sync_ReturningAsyncNone_UsingNoArgs_WhenNone_ReturnsNone() { var source = await AsyncMaybe<Unit>.None().FlatMapUnit(() => AsyncMaybe<int>.Some(3)); source.MustBeNone(); } [Fact] public async Task Sync_ReturningAsyncNoneUsingLambda_UsingNoArgs_WhenSome_ReturnsNone() { // ReSharper disable once ConvertClosureToMethodGroup var source = await AsyncMaybe<Unit>.Some(new Unit()).FlatMapUnit(() => AsyncMaybe<int>.None()); source.MustBeNone(); } [Fact] public async Task Sync_ReturningAsyncNoneUsingMethodRefernece_UsingNoArgs_WhenSome_ReturnsNone() { var source = await AsyncMaybe<Unit>.Some(new Unit()).FlatMapUnit(AsyncMaybe<int>.None); source.MustBeNone(); } #endregion #region AsyncMaybe<Unit>.FlatMapAsync(Func<Task<Maybe<T>>>)) [Fact] public async Task Async_ReturningSome_UsingNoArgs_WhenNone_ReturnsNone() { var source = await AsyncMaybe<Unit>.None().FlatMapUnitAsync(() => Task.FromResult(Maybe<int>.Some(3))); source.MustBeNone(); } [Fact] public async Task Async_ReturningSome_UsingNoArgs_WhenSome_ReturnsSome() { const int expected = 3; var source = await AsyncMaybe<Unit>.Some(new Unit()).FlatMapUnitAsync(() => Task.FromResult(Maybe<int>.Some(expected))); var result = source.MustBeSome(); Assert.Equal(expected, result); } [Fact] public async Task Async_ReturningNone_UsingNoArgs_WhenNone_ReturnsNone() { var source = await AsyncMaybe<Unit>.None().FlatMapUnitAsync(() => Task.FromResult(Maybe<int>.None())); source.MustBeNone(); } [Fact] public async Task Async_ReturningNone_UsingNoArgs_WhenSome_ReturnsNone() { var source = await AsyncMaybe<Unit>.Some(new Unit()).FlatMapUnitAsync(() => Task.FromResult(Maybe<int>.None())); source.MustBeNone(); } #endregion #region AsyncMaybe<Unit>.FlatMapAsync(Func<Task<AsyncMaybe<T>>>)) [Fact] public async Task Async_ReturningAsyncSome_UsingNoArgs_WhenNone_ReturnsNone() { var source = await AsyncMaybe<Unit>.None().FlatMapUnitAsync(() => Task.FromResult(AsyncMaybe<int>.Some(3))); source.MustBeNone(); } [Fact] public async Task Async_ReturningAsyncSome_UsingNoArgs_WhenSome_ReturnsSome() { const int expected = 3; var source = await AsyncMaybe<Unit>.Some(new Unit()).FlatMapUnitAsync(() => Task.FromResult(AsyncMaybe<int>.Some(expected))); var result = source.MustBeSome(); Assert.Equal(expected, result); } [Fact] public async Task Async_ReturningAsyncNone_UsingNoArgs_WhenNone_ReturnsNone() { var source = await AsyncMaybe<Unit>.None().FlatMapUnitAsync(() => Task.FromResult(AsyncMaybe<int>.None())); source.MustBeNone(); } [Fact] public async Task Async_ReturningAsyncNone_UsingNoArgs_WhenSome_ReturnsNone() { var source = await AsyncMaybe<Unit>.Some(new Unit()).FlatMapUnitAsync(() => Task.FromResult(AsyncMaybe<int>.None())); source.MustBeNone(); } #endregion } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Kodestruct.Common.CalculationLogger; using Kodestruct.Common.CalculationLogger.Interfaces; using Kodestruct.Common.Section.Interfaces; using Kodestruct.Common.Section.SectionTypes; using Kodestruct.Steel.AISC.AISC360v10.Flexure; using Kodestruct.Steel.AISC.Interfaces; using Kodestruct.Steel.AISC.SteelEntities; using Kodestruct.Steel.AISC.SteelEntities.Materials; using Kodestruct.Steel.AISC.SteelEntities.Sections; using Kodestruct.Steel.AISC360v10.Connections.AffectedElements; using Kodestruct.Common.Entities; namespace Kodestruct.Steel.AISC.AISC360v10.Connections.AffectedMembers { public partial class AffectedElementInFlexure: AffectedElement { bool IsCompactDoublySymmetricForFlexure; bool IsRolled; ISection GrossSectionShape {get; set;} ISection NetSectionShape { get; set; } public AffectedElementInFlexure(ISection GrossSection, ISection NetSection, double F_y, double F_u, bool IsCompactDoublySymmetricForFlexure=true, bool IsRolled = false) : base(F_y, F_u) { SteelMaterial material = new SteelMaterial(F_y, F_u, SteelConstants.ModulusOfElasticity, SteelConstants.ShearModulus); this.Section = new SteelGeneralSection(GrossSection, material); this.SectionNet = new SteelGeneralSection(NetSection, material); this.GrossSectionShape =GrossSection ; this.NetSectionShape = NetSection; this.IsCompactDoublySymmetricForFlexure = IsCompactDoublySymmetricForFlexure; this.IsRolled = IsRolled; Log = new CalcLog(); } public double GetFlexuralStrength(double L_b) { double phiM_n =0.0; double F_y = this.Section.Material.YieldStress; double F_u = this.Section.Material.UltimateStress; ISection section = Section.Shape; bool IsValidGrossSection = ValidateGrossSection(); bool IsValidNetSection = true; if (this.NetSectionShape!=null) { IsValidNetSection = ValidateNetSection(); } double phiM_nLTB, phiM_nNet, phiM_nGross; //Gross Section Yielding if (IsCompactDoublySymmetricForFlexure == true) { double Z = GrossSectionShape.Z_x; phiM_nGross = 0.9 * F_y * Z; } else { double S = Math.Min(GrossSectionShape.S_xBot, GrossSectionShape.S_xTop); phiM_nGross = 0.9*F_y*S; } //Net Section Fracture if ( NetSectionShape == null) { phiM_nNet = double.PositiveInfinity; } else { if (GrossSectionShape is ISectionI) { if (NetSectionShape is ISectionI) { SectionIWithFlangeHoles netSec = NetSectionShape as SectionIWithFlangeHoles; phiM_nNet = GetTensionFlangeRuptureStrength(GrossSectionShape as ISectionI, NetSectionShape as ISectionI); } else { throw new Exception("If I-Shape is used for Gross section,specify I-Shape with holes object type for net sections."); } } else { phiM_nNet = 0.75 * NetSectionShape.Z_x * F_u; } } //Lateral Stability if (L_b != 0) { double S = Math.Min(GrossSectionShape.S_xBot, GrossSectionShape.S_xTop); double lambda = this.GetLambda(L_b); double Q = this.GetBucklingReductionCoefficientQ(lambda); double F_cr = F_y * Q; if (Q<1.0) { phiM_nLTB = 0.9 * S * F_cr; } else { phiM_nLTB = double.PositiveInfinity; } } else { phiM_nLTB = double.PositiveInfinity; } List<double> LimitStates = new List<double>() { phiM_nLTB, phiM_nNet, phiM_nGross }; phiM_n = LimitStates.Min(); return phiM_n; } private bool ValidateNetSection() { //if (this.NetSectionShape is SectionOfPlateWithHoles || this.NetSectionShape is SectionIWithFlangeHoles) if (this.NetSectionShape is SectionOfPlateWithHoles || this.NetSectionShape is SectionIWithFlangeHoles) { return true; } else { throw new Exception("Wrong section type. Use SectionOfPlateWithHoles or SectionIWithFlangeHoles."); } } private bool ValidateGrossSection() { if (this.GrossSectionShape is SectionRectangular || this.GrossSectionShape is SectionI) { return true; } else { throw new Exception("Wrong section type. Only SectionRectangular and SectionI are supported."); } } public double GetTensionFlangeRuptureStrength(ISectionI ShapeIGross, ISectionI ShapeINet) { double phiM_n = -1; double F_y = Section.Material.YieldStress; double F_u = Section.Material.UltimateStress; double S_g = Math.Min(ShapeIGross.S_xBot, ShapeIGross.S_xTop); SectionIWithFlangeHoles netSec = ShapeINet as SectionIWithFlangeHoles; if (netSec == null) { throw new Exception("Net section shape not recognized"); } double A_fgB = ShapeIGross.b_fBot * ShapeIGross.t_fBot; double A_fgT = ShapeIGross.b_fTop * ShapeIGross.t_fTop; double A_fnB = netSec.b_fBot * netSec.t_fBot- netSec.b_hole * netSec.N_holes* netSec.t_fBot; double A_fnT = netSec.b_fTop * netSec.t_fTop- netSec.b_hole * netSec.N_holes*netSec.t_fTop; double Y_t = GetY_t(); double BotFlangeRuptureMoment = GetNetSectionRuptureStrength(A_fnB, A_fgB, Y_t ); double TopFlangeRuptureMoment = GetNetSectionRuptureStrength(A_fnT, A_fgT, Y_t); phiM_n = Math.Min(BotFlangeRuptureMoment, TopFlangeRuptureMoment); return phiM_n; } private double GetNetSectionRuptureStrength(double A_fn, double A_fg, double Y_t) { double phiM_n = 0.0; double F_y = Section.Material.YieldStress; double F_u = Section.Material.UltimateStress; if (F_u * A_fn >= Y_t * F_y * A_fg) { //LimitStateDoes not apply return double.PositiveInfinity; } else { double S_g = Math.Min(GrossSectionShape.S_xBot, GrossSectionShape.S_xTop); double M_n = F_u * A_fn / A_fg * S_g; //F13-1 phiM_n = 0.9 * M_n; } return phiM_n; } private double GetY_t() { double F_y = Section.Material.YieldStress; double F_u = Section.Material.UltimateStress; if (F_y/F_u<=0.8) { return 1.0; } else { return 1.1; } } } }
// 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.Immutable; using System.Reflection.Metadata.Tests; using Xunit; namespace System.Reflection.Metadata.Ecma335.Tests { public class MetadataRootBuilderTests { private string ReadVersion(BlobBuilder metadata) { using (var provider = MetadataReaderProvider.FromMetadataImage(metadata.ToImmutableArray())) { return provider.GetMetadataReader().MetadataVersion; } } [Fact] public void Ctor_Errors() { var mdBuilder = new MetadataBuilder(); Assert.Throws<ArgumentNullException>(() => new MetadataRootBuilder(null)); AssertExtensions.Throws<ArgumentException>("metadataVersion", () => new MetadataRootBuilder(mdBuilder, new string('x', 255))); } [Fact] public void Serialize_Errors() { var mdBuilder = new MetadataBuilder(); var rootBuilder = new MetadataRootBuilder(mdBuilder); var builder = new BlobBuilder(); Assert.Throws<ArgumentNullException>(() => rootBuilder.Serialize(null, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => rootBuilder.Serialize(builder, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => rootBuilder.Serialize(builder, 0, -1)); } [Fact] public void Headers() { var mdBuilder = new MetadataBuilder(); var rootBuilder = new MetadataRootBuilder(mdBuilder); var builder = new BlobBuilder(); rootBuilder.Serialize(builder, 0, 0); AssertEx.Equal(new byte[] { // signature: 0x42, 0x53, 0x4A, 0x42, // major version (1) 0x01, 0x00, // minor version (1) 0x01, 0x00, // reserved (0) 0x00, 0x00, 0x00, 0x00, // padded version length: 0x0C, 0x00, 0x00, 0x00, // padded version: (byte)'v', (byte)'4', (byte)'.', (byte)'0', (byte)'.', (byte)'3', (byte)'0', (byte)'3', (byte)'1', (byte)'9', 0x00, 0x00, // flags (0): 0x00, 0x00, // stream count: 0x05, 0x00, // stream headers: 0x6C, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x00, (byte)'#', (byte)'~', 0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, (byte)'#', (byte)'S', (byte)'t', (byte)'r', (byte)'i', (byte)'n', (byte)'g', (byte)'s', 0x00, 0x00, 0x00, 0x00, 0x8C, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, (byte)'#', (byte)'U', (byte)'S', 0x00, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)'#', (byte)'G', (byte)'U', (byte)'I', (byte)'D', 0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, (byte)'#', (byte)'B', (byte)'l', (byte)'o', (byte)'b', 0x00, 0x00, 0x00, // -------- // #~ // -------- // Reserved (0) 0x00, 0x00, 0x00, 0x00, // Major Version (2) 0x02, // Minor Version (0) 0x00, // Heap Sizes 0x00, // Reserved (1) 0x01, // Present tables 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Sorted tables 0x00, 0xFA, 0x01, 0x33, 0x00, 0x16, 0x00, 0x00, // Rows (empty) // Tables (empty) // Padding and alignment 0x00, 0x00, 0x00, 0x00, // -------- // #Strings // -------- 0x00, 0x00, 0x00, 0x00, // -------- // #US // -------- 0x00, 0x00, 0x00, 0x00, // -------- // #GUID // -------- // -------- // #Blob // -------- 0x00, 0x00, 0x00, 0x00, }, builder.ToArray()); } [Fact] public void EncHeaders() { var mdBuilder = new MetadataBuilder(); mdBuilder.AddEncLogEntry(MetadataTokens.MethodDefinitionHandle(1), EditAndContinueOperation.AddMethod); var rootBuilder = new MetadataRootBuilder(mdBuilder); var builder = new BlobBuilder(); rootBuilder.Serialize(builder, 0, 0); AssertEx.Equal(new byte[] { // signature: 0x42, 0x53, 0x4A, 0x42, // major version (1) 0x01, 0x00, // minor version (1) 0x01, 0x00, // reserved (0) 0x00, 0x00, 0x00, 0x00, // padded version length: 0x0C, 0x00, 0x00, 0x00, // padded version: (byte)'v', (byte)'4', (byte)'.', (byte)'0', (byte)'.', (byte)'3', (byte)'0', (byte)'3', (byte)'1', (byte)'9', 0x00, 0x00, // flags (0): 0x00, 0x00, // stream count: 0x06, 0x00, // stream headers: 0x7C, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, (byte)'#', (byte)'-', 0x00, 0x00, 0xA4, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, (byte)'#', (byte)'S', (byte)'t', (byte)'r', (byte)'i', (byte)'n', (byte)'g', (byte)'s', 0x00, 0x00, 0x00, 0x00, 0xA8, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, (byte)'#', (byte)'U', (byte)'S', 0x00, 0xAC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)'#', (byte)'G', (byte)'U', (byte)'I', (byte)'D', 0x00, 0x00, 0x00, 0xAC, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, (byte)'#', (byte)'B', (byte)'l', (byte)'o', (byte)'b', 0x00, 0x00, 0x00, 0xB0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)'#', (byte)'J', (byte)'T', (byte)'D', 0x00, 0x00, 0x00, 0x00, // -------- // #- // -------- // Reserved (0) 0x00, 0x00, 0x00, 0x00, // Major Version (2) 0x02, // Minor Version (0) 0x00, // Heap Sizes 0xA7, // Reserved (1) 0x01, // Present tables 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, // Sorted tables 0x00, 0xFA, 0x01, 0x33, 0x00, 0x16, 0x00, 0x00, // Rows 0x01, 0x00, 0x00, 0x00, // // EncLog Table (token, operation) // 0x01, 0x00, 0x00, 0x06, 0x01, 0x00, 0x00, 0x00, // Padding and alignment 0x00, 0x00, 0x00, 0x00, // -------- // #Strings // -------- 0x00, 0x00, 0x00, 0x00, // -------- // #US // -------- 0x00, 0x00, 0x00, 0x00, // -------- // #GUID // -------- // -------- // #Blob // -------- 0x00, 0x00, 0x00, 0x00, // -------- // #JTD // -------- }, builder.ToArray()); } [Fact] public void MetadataVersion_Default() { var mdBuilder = new MetadataBuilder(); mdBuilder.AddModule(0, default(StringHandle), default(GuidHandle), default(GuidHandle), default(GuidHandle)); var rootBuilder = new MetadataRootBuilder(mdBuilder); var builder = new BlobBuilder(); rootBuilder.Serialize(builder, 0, 0); AssertEx.Equal(new byte[] { // padded version length: 0x0C, 0x00, 0x00, 0x00, // padded version: (byte)'v', (byte)'4', (byte)'.', (byte)'0', (byte)'.', (byte)'3', (byte)'0', (byte)'3', (byte)'1', (byte)'9', 0x00, 0x00, }, builder.Slice(12, -132)); Assert.Equal(rootBuilder.MetadataVersion, ReadVersion(builder)); } [Fact] public void MetadataVersion_Empty() { var version = ""; var mdBuilder = new MetadataBuilder(); mdBuilder.AddModule(0, default(StringHandle), default(GuidHandle), default(GuidHandle), default(GuidHandle)); var rootBuilder = new MetadataRootBuilder(mdBuilder, version); var builder = new BlobBuilder(); rootBuilder.Serialize(builder, 0, 0); AssertEx.Equal(new byte[] { // padded version length: 0x04, 0x00, 0x00, 0x00, // padded version: 0x00, 0x00, 0x00, 0x00, }, builder.Slice(12, -132)); Assert.Equal(version, ReadVersion(builder)); } [Fact] public void MetadataVersion_MaxLength() { var version = new string('x', 254); var mdBuilder = new MetadataBuilder(); mdBuilder.AddModule(0, default(StringHandle), default(GuidHandle), default(GuidHandle), default(GuidHandle)); var rootBuilder = new MetadataRootBuilder(mdBuilder, version); var builder = new BlobBuilder(); rootBuilder.Serialize(builder, 0, 0); AssertEx.Equal(new byte[] { // padded version length: 0x00, 0x01, 0x00, 0x00, // padded version: 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x00, 0x00 }, builder.Slice(12, -132)); Assert.Equal(version, ReadVersion(builder)); } [Fact] public void MetadataVersion() { var version = "\u1234\ud800"; var mdBuilder = new MetadataBuilder(); mdBuilder.AddModule(0, default(StringHandle), default(GuidHandle), default(GuidHandle), default(GuidHandle)); var rootBuilder = new MetadataRootBuilder(mdBuilder, version); var builder = new BlobBuilder(); rootBuilder.Serialize(builder, 0, 0); AssertEx.Equal(new byte[] { // padded version length: 0x08, 0x00, 0x00, 0x00, // padded version: // [ E1 88 B4 ] -> U+1234 // [ ED ] -> invalid (ED cannot be followed by A0) -> U+FFFD // [ A0 ] -> invalid (not ASCII, not valid leading byte) -> U+FFFD // [ 80 ] -> invalid (not ASCII, not valid leading byte) -> U+FFFD 0xE1, 0x88, 0xB4, 0xED, 0xA0, 0x80, 0x00, 0x00, }, builder.Slice(12, -132)); // the default decoder replaces bad byte sequences by U+FFFD if (PlatformDetection.IsNetCore) { Assert.Equal("\u1234\ufffd\ufffd\ufffd", ReadVersion(builder)); } else { // Versions of .NET prior to Core 3.0 didn't follow Unicode recommendations for U+FFFD substitution, // so they sometimes emitted too few replacement chars. Assert.Equal("\u1234\ufffd\ufffd", ReadVersion(builder)); } } } }
// // System.Web.UI.WebControls.TreeNode.cs // // Authors: // Lluis Sanchez Gual (lluis@novell.com) // // (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // #if NET_2_0 using System; using System.Collections; using System.Text; using System.ComponentModel; using System.Web.UI; namespace System.Web.UI.WebControls { [ParseChildrenAttribute (true, "ChildNodes")] public class TreeNode: IStateManager, ICloneable { StateBag ViewState = new StateBag (); TreeNodeCollection nodes; bool marked; TreeView tree; TreeNode parent; int index; string path; int depth = -1; bool dataBound; string dataPath; object dataItem; IHierarchyData hierarchyData; bool gotBinding; TreeNodeBinding binding; PropertyDescriptorCollection boundProperties; internal TreeNode (TreeView tree) { Tree = tree; } public TreeNode () { } public TreeNode (string text) { Text = text; } public TreeNode (string text, string value) { Text = text; Value = value; } public TreeNode (string text, string value, string imageUrl) { Text = text; Value = value; ImageUrl = imageUrl; } public TreeNode (string text, string value, string imageUrl, string navigateUrl, string target) { Text = text; Value = value; ImageUrl = imageUrl; NavigateUrl = navigateUrl; Target = target; } [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] [Browsable (false)] public int Depth { get { if (depth != -1) return depth; depth = 0; TreeNode nod = parent; while (nod != null) { depth++; nod = nod.parent; } return depth; } } void ResetPathData () { path = null; depth = -1; gotBinding = false; } internal TreeView Tree { get { return tree; } set { if (SelectedFlag) { if (value != null) value.SetSelectedNode (this, false); else if (tree != null) tree.SetSelectedNode (null, false); } tree = value; if (nodes != null) nodes.SetTree (tree); ResetPathData (); } } [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] [DefaultValue (false)] [Browsable (false)] public bool DataBound { get { return dataBound; } } [DefaultValue (null)] [Browsable (false)] public object DataItem { get { if (!dataBound) throw new InvalidOperationException ("TreeNode is not data bound."); return dataItem; } } [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] [DefaultValue ("")] [Browsable (false)] public string DataPath { get { if (!dataBound) throw new InvalidOperationException ("TreeNode is not data bound."); return dataPath; } } [DefaultValue (false)] public virtual bool Checked { get { object o = ViewState ["Checked"]; if (o != null) return (bool)o; return false; } set { ViewState ["Checked"] = value; if (tree != null) tree.NotifyCheckChanged (this); } } [DefaultValue (null)] [MergableProperty (false)] [Browsable (false)] [PersistenceMode (PersistenceMode.InnerDefaultProperty)] public virtual TreeNodeCollection ChildNodes { get { if (nodes == null) { if (PopulateOnDemand && tree == null) return null; if (DataBound) FillBoundChildren (); else nodes = new TreeNodeCollection (this); if (IsTrackingViewState) ((IStateManager)nodes).TrackViewState(); if (PopulateOnDemand && !Populated) { Populated = true; Populate (); } } return nodes; } } [DefaultValue (false)] public virtual bool Expanded { get { object o = ViewState ["Expanded"]; if (o != null) return (bool)o; return false; } set { ViewState ["Expanded"] = value; if (tree != null) tree.NotifyExpandedChanged (this); } } [Localizable (true)] [DefaultValue ("")] public virtual string ImageToolTip { get { object o = ViewState ["ImageToolTip"]; if (o != null) return (string)o; if (DataBound) { TreeNodeBinding bin = GetBinding (); if (bin != null) { if (bin.ImageToolTipField != "") return (string) GetBoundPropertyValue (bin.ImageToolTipField); return bin.ImageToolTip; } } return ""; } set { ViewState ["ImageToolTip"] = value; } } [DefaultValue ("")] [UrlProperty] [Editor ("System.Web.UI.Design.ImageUrlEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))] public virtual string ImageUrl { get { object o = ViewState ["ImageUrl"]; if (o != null) return (string)o; if (DataBound) { TreeNodeBinding bin = GetBinding (); if (bin != null) { if (bin.ImageUrlField != "") return (string) GetBoundPropertyValue (bin.ImageUrlField); return bin.ImageUrl; } } return ""; } set { ViewState ["ImageUrl"] = value; } } [DefaultValue ("")] [UrlProperty] [Editor ("System.Web.UI.Design.UrlEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))] public virtual string NavigateUrl { get { object o = ViewState ["NavigateUrl"]; if (o != null) return (string)o; if (DataBound) { TreeNodeBinding bin = GetBinding (); if (bin != null) { if (bin.NavigateUrlField != "") return (string) GetBoundPropertyValue (bin.NavigateUrlField); return bin.NavigateUrl; } } return ""; } set { ViewState ["NavigateUrl"] = value; } } [DefaultValue (false)] public bool PopulateOnDemand { get { object o = ViewState ["PopulateOnDemand"]; if (o != null) return (bool)o; if (DataBound) { TreeNodeBinding bin = GetBinding (); if (bin != null) return bin.PopulateOnDemand; } return false; } set { ViewState ["PopulateOnDemand"] = value; } } [DefaultValue (TreeNodeSelectAction.Select)] public TreeNodeSelectAction SelectAction { get { object o = ViewState ["SelectAction"]; if (o != null) return (TreeNodeSelectAction)o; if (DataBound) { TreeNodeBinding bin = GetBinding (); if (bin != null) return bin.SelectAction; } return TreeNodeSelectAction.Select; } set { ViewState ["SelectAction"] = value; } } [DefaultValue (false)] public bool ShowCheckBox { get { object o = ViewState ["ShowCheckBox"]; if (o != null) return (bool)o; if (DataBound) { TreeNodeBinding bin = GetBinding (); if (bin != null) return bin.ShowCheckBox; } return false; } set { ViewState ["ShowCheckBox"] = value; } } internal bool IsShowCheckBoxSet { get { return ViewState ["ShowCheckBox"] != null; } } [DefaultValue ("")] public virtual string Target { get { object o = ViewState ["Target"]; if(o != null) return (string)o; if (DataBound) { TreeNodeBinding bin = GetBinding (); if (bin != null) { if (bin.TargetField != "") return (string) GetBoundPropertyValue (bin.TargetField); return bin.Target; } } return ""; } set { ViewState ["Target"] = value; } } [Localizable (true)] [DefaultValue ("")] [WebSysDescription ("The display text of the tree node.")] public virtual string Text { get { object o = ViewState ["Text"]; if (o != null) return (string)o; if (DataBound) { TreeNodeBinding bin = GetBinding (); if (bin != null) { string text; if (bin.TextField != "") text = (string) GetBoundPropertyValue (bin.TextField); else if (bin.Text != "") text = bin.Text; else text = GetDefaultBoundText (); if (bin.FormatString.Length != 0) text = string.Format (bin.FormatString, text); return text; } return GetDefaultBoundText (); } return ""; } set { ViewState ["Text"] = value; } } [Localizable (true)] [DefaultValue ("")] public virtual string ToolTip { get { object o = ViewState ["ToolTip"]; if(o != null) return (string)o; if (DataBound) { TreeNodeBinding bin = GetBinding (); if (bin != null) { if (bin.ToolTipField != "") return (string) GetBoundPropertyValue (bin.ToolTipField); return bin.ToolTip; } } return ""; } set { ViewState ["ToolTip"] = value; } } [Localizable (true)] [DefaultValue ("")] public virtual string Value { get { object o = ViewState ["Value"]; if(o != null) return (string)o; if (DataBound) { TreeNodeBinding bin = GetBinding (); if (bin != null) { if (bin.ValueField != "") return (string) GetBoundPropertyValue (bin.ValueField); if (bin.Value != "") return bin.Value; } return GetDefaultBoundText (); } return ""; } set { ViewState ["Value"] = value; } } [DefaultValue (false)] public virtual bool Selected { get { return SelectedFlag; } set { if (tree != null) { if (!value && tree.SelectedNode == this) tree.SetSelectedNode (null, false); else if (value) tree.SetSelectedNode (this, false); } else SelectedFlag = value; } } internal virtual bool SelectedFlag { get { object o = ViewState ["Selected"]; if(o != null) return (bool)o; return false; } set { ViewState ["Selected"] = value; } } [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] [Browsable (false)] public TreeNode Parent { get { return parent; } } [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] [Browsable (false)] public string ValuePath { get { if (tree == null) return Value; StringBuilder sb = new StringBuilder (Value); TreeNode node = parent; while (node != null) { sb.Insert (0, tree.PathSeparator); sb.Insert (0, node.Value); node = node.Parent; } return sb.ToString (); } } internal int Index { get { return index; } set { index = value; ResetPathData (); } } internal void SetParent (TreeNode node) { parent = node; ResetPathData (); } internal string Path { get { if (path != null) return path; StringBuilder sb = new StringBuilder (index.ToString()); TreeNode node = parent; while (node != null) { sb.Insert (0, '_'); sb.Insert (0, node.Index.ToString ()); node = node.Parent; } path = sb.ToString (); return path; } } internal bool Populated { get { object o = ViewState ["Populated"]; if (o != null) return (bool) o; return false; } set { ViewState ["Populated"] = value; } } internal bool HasChildData { get { return nodes != null; } } protected virtual void Populate () { tree.NotifyPopulateRequired (this); } public void Collapse () { Expanded = false; } public void CollapseAll () { SetExpandedRec (false, -1); } public void Expand () { Expanded = true; } internal void Expand (int depth) { SetExpandedRec (true, depth); } public void ExpandAll () { SetExpandedRec (true, -1); } void SetExpandedRec (bool expanded, int depth) { Expanded = expanded; if (depth == 0) return; foreach (TreeNode nod in ChildNodes) nod.SetExpandedRec (expanded, depth - 1); } public void Select () { Selected = true; } public void ToggleExpandState () { Expanded = !Expanded; } public void LoadViewState (object savedState) { if (savedState == null) return; object[] states = (object[]) savedState; ViewState.LoadViewState (states [0]); if (tree != null && SelectedFlag) tree.SetSelectedNode (this, true); if (!PopulateOnDemand || Populated) ((IStateManager)ChildNodes).LoadViewState (states [1]); } public object SaveViewState () { object[] states = new object[2]; states[0] = ViewState.SaveViewState(); states[1] = (nodes == null ? null : ((IStateManager)nodes).SaveViewState()); for (int i = 0; i < states.Length; i++) { if (states [i] != null) return states; } return null; } public void TrackViewState () { if (marked) return; marked = true; ViewState.TrackViewState(); if (nodes != null) ((IStateManager)nodes).TrackViewState (); } public bool IsTrackingViewState { get { return marked; } } internal void SetDirty () { ViewState.SetDirty (); } public object Clone () { TreeNode nod = tree != null ? tree.CreateNode () : new TreeNode (); foreach (DictionaryEntry e in ViewState) nod.ViewState [(string)e.Key] = e.Value; foreach (TreeNode c in ChildNodes) nod.ChildNodes.Add ((TreeNode)c.Clone ()); return nod; } internal void Bind (IHierarchyData hierarchyData) { this.hierarchyData = hierarchyData; dataBound = true; dataPath = hierarchyData.Path; dataItem = hierarchyData.Item; } internal void SetDataItem (object item) { dataItem = item; } internal void SetDataPath (string path) { dataPath = path; } internal void SetDataBound (bool bound) { dataBound = bound; } string GetDefaultBoundText () { if (hierarchyData != null) return hierarchyData.ToString (); else if (dataItem != null) return dataItem.ToString (); else return string.Empty; } string GetDataItemType () { if (hierarchyData != null) return hierarchyData.Type; else if (dataItem != null) return dataItem.GetType().ToString (); else return string.Empty; } internal bool IsParentNode { get { return ChildNodes.Count > 0 && Parent != null; } } internal bool IsLeafNode { get { return ChildNodes.Count == 0; } } internal bool IsRootNode { get { return ChildNodes.Count > 0 && Parent == null; } } TreeNodeBinding GetBinding () { if (tree == null) return null; if (gotBinding) return binding; binding = tree.FindBindingForNode (GetDataItemType (), Depth); gotBinding = true; return binding; } object GetBoundPropertyValue (string name) { if (boundProperties == null) { if (hierarchyData != null) boundProperties = TypeDescriptor.GetProperties (hierarchyData); else boundProperties = TypeDescriptor.GetProperties (dataItem); } PropertyDescriptor prop = boundProperties.Find (name, true); if (prop == null) throw new InvalidOperationException ("Property '" + name + "' not found in data bound item"); if (hierarchyData != null) return prop.GetValue (hierarchyData); else return prop.GetValue (dataItem); } void FillBoundChildren () { nodes = new TreeNodeCollection (this); if (hierarchyData == null || !hierarchyData.HasChildren) return; if (tree.MaxDataBindDepth != -1 && Depth >= tree.MaxDataBindDepth) return; IHierarchicalEnumerable e = hierarchyData.GetChildren (); foreach (object obj in e) { IHierarchyData hdata = e.GetHierarchyData (obj); TreeNode node = tree != null ? tree.CreateNode () : new TreeNode (); node.Bind (hdata); nodes.Add (node); } } internal void BeginRenderText (HtmlTextWriter writer) { RenderPreText (writer); } internal void EndRenderText (HtmlTextWriter writer) { RenderPostText (writer); } protected virtual void RenderPreText (HtmlTextWriter writer) { } protected virtual void RenderPostText (HtmlTextWriter writer) { } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** Class: AppDomainSetup ** ** Purpose: Defines the settings that the loader uses to find assemblies in an ** AppDomain ** ** Date: Dec 22, 2000 ** =============================================================================*/ namespace System { using System; #if FEATURE_CLICKONCE using System.Deployment.Internal.Isolation; using System.Deployment.Internal.Isolation.Manifest; using System.Runtime.Hosting; #endif using System.Runtime.CompilerServices; using System.Runtime; using System.Text; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Reflection; using System.Security; using System.Security.Permissions; using System.Security.Policy; using System.Globalization; using Path = System.IO.Path; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Collections; using System.Collections.Generic; [Serializable] [ClassInterface(ClassInterfaceType.None)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AppDomainSetup : IAppDomainSetup { [Serializable] internal enum LoaderInformation { // If you add a new value, add the corresponding property // to AppDomain.GetData() and SetData()'s switch statements, // as well as fusionsetup.h. ApplicationBaseValue = 0, // LOADER_APPLICATION_BASE ConfigurationFileValue = 1, // LOADER_CONFIGURATION_BASE DynamicBaseValue = 2, // LOADER_DYNAMIC_BASE DevPathValue = 3, // LOADER_DEVPATH ApplicationNameValue = 4, // LOADER_APPLICATION_NAME PrivateBinPathValue = 5, // LOADER_PRIVATE_PATH PrivateBinPathProbeValue = 6, // LOADER_PRIVATE_BIN_PATH_PROBE ShadowCopyDirectoriesValue = 7, // LOADER_SHADOW_COPY_DIRECTORIES ShadowCopyFilesValue = 8, // LOADER_SHADOW_COPY_FILES CachePathValue = 9, // LOADER_CACHE_PATH LicenseFileValue = 10, // LOADER_LICENSE_FILE DisallowPublisherPolicyValue = 11, // LOADER_DISALLOW_PUBLISHER_POLICY DisallowCodeDownloadValue = 12, // LOADER_DISALLOW_CODE_DOWNLOAD DisallowBindingRedirectsValue = 13, // LOADER_DISALLOW_BINDING_REDIRECTS DisallowAppBaseProbingValue = 14, // LOADER_DISALLOW_APPBASE_PROBING ConfigurationBytesValue = 15, // LOADER_CONFIGURATION_BYTES LoaderMaximum = 18 // LOADER_MAXIMUM } // Constants from fusionsetup.h. private const string LOADER_OPTIMIZATION = "LOADER_OPTIMIZATION"; private const string CONFIGURATION_EXTENSION = ".config"; private const string APPENV_RELATIVEPATH = "RELPATH"; private const string MACHINE_CONFIGURATION_FILE = "config\\machine.config"; private const string ACTAG_HOST_CONFIG_FILE = "HOST_CONFIG"; #if FEATURE_FUSION private const string LICENSE_FILE = "LICENSE_FILE"; #endif // Constants from fusionpriv.h private const string ACTAG_APP_CONFIG_FILE = "APP_CONFIG_FILE"; private const string ACTAG_MACHINE_CONFIG = "MACHINE_CONFIG"; private const string ACTAG_APP_BASE_URL = "APPBASE"; private const string ACTAG_APP_NAME = "APP_NAME"; private const string ACTAG_BINPATH_PROBE_ONLY = "BINPATH_PROBE_ONLY"; private const string ACTAG_APP_CACHE_BASE = "CACHE_BASE"; private const string ACTAG_DEV_PATH = "DEV_PATH"; private const string ACTAG_APP_DYNAMIC_BASE = "DYNAMIC_BASE"; private const string ACTAG_FORCE_CACHE_INSTALL = "FORCE_CACHE_INSTALL"; private const string ACTAG_APP_PRIVATE_BINPATH = "PRIVATE_BINPATH"; private const string ACTAG_APP_SHADOW_COPY_DIRS = "SHADOW_COPY_DIRS"; private const string ACTAG_DISALLOW_APPLYPUBLISHERPOLICY = "DISALLOW_APP"; private const string ACTAG_CODE_DOWNLOAD_DISABLED = "CODE_DOWNLOAD_DISABLED"; private const string ACTAG_DISALLOW_APP_BINDING_REDIRECTS = "DISALLOW_APP_REDIRECTS"; private const string ACTAG_DISALLOW_APP_BASE_PROBING = "DISALLOW_APP_BASE_PROBING"; private const string ACTAG_APP_CONFIG_BLOB = "APP_CONFIG_BLOB"; // This class has an unmanaged representation so be aware you will need to make edits in vm\object.h if you change the order // of these fields or add new ones. private string[] _Entries; private LoaderOptimization _LoaderOptimization; #pragma warning disable 169 private String _AppBase; // for compat with v1.1 #pragma warning restore 169 [OptionalField(VersionAdded = 2)] private AppDomainInitializer _AppDomainInitializer; [OptionalField(VersionAdded = 2)] private string[] _AppDomainInitializerArguments; #if FEATURE_CLICKONCE [OptionalField(VersionAdded = 2)] private ActivationArguments _ActivationArguments; #endif #if FEATURE_CORECLR // On the CoreCLR, this contains just the name of the permission set that we install in the new appdomain. // Not the ToXml().ToString() of an ApplicationTrust object. #endif [OptionalField(VersionAdded = 2)] private string _ApplicationTrust; [OptionalField(VersionAdded = 2)] private byte[] _ConfigurationBytes; #if FEATURE_COMINTEROP [OptionalField(VersionAdded = 3)] private bool _DisableInterfaceCache = false; #endif // FEATURE_COMINTEROP [OptionalField(VersionAdded = 4)] private string _AppDomainManagerAssembly; [OptionalField(VersionAdded = 4)] private string _AppDomainManagerType; #if FEATURE_APTCA [OptionalField(VersionAdded = 4)] private string[] _AptcaVisibleAssemblies; #endif // A collection of strings used to indicate which breaking changes shouldn't be applied // to an AppDomain. We only use the keys, the values are ignored. [OptionalField(VersionAdded = 4)] private Dictionary<string, object> _CompatFlags; [OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5 private String _TargetFrameworkName; #if !FEATURE_CORECLR [NonSerialized] internal AppDomainSortingSetupInfo _AppDomainSortingSetupInfo; #endif [OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5 private bool _CheckedForTargetFrameworkName; #if FEATURE_RANDOMIZED_STRING_HASHING [OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5 private bool _UseRandomizedStringHashing; #endif [SecuritySafeCritical] internal AppDomainSetup(AppDomainSetup copy, bool copyDomainBoundData) { string[] mine = Value; if(copy != null) { string[] other = copy.Value; int mineSize = _Entries.Length; int otherSize = other.Length; int size = (otherSize < mineSize) ? otherSize : mineSize; for (int i = 0; i < size; i++) mine[i] = other[i]; if (size < mineSize) { // This case can happen when the copy is a deserialized version of // an AppDomainSetup object serialized by Everett. for (int i = size; i < mineSize; i++) mine[i] = null; } _LoaderOptimization = copy._LoaderOptimization; _AppDomainInitializerArguments = copy.AppDomainInitializerArguments; #if FEATURE_CLICKONCE _ActivationArguments = copy.ActivationArguments; #endif _ApplicationTrust = copy._ApplicationTrust; if (copyDomainBoundData) _AppDomainInitializer = copy.AppDomainInitializer; else _AppDomainInitializer = null; _ConfigurationBytes = copy.GetConfigurationBytes(); #if FEATURE_COMINTEROP _DisableInterfaceCache = copy._DisableInterfaceCache; #endif // FEATURE_COMINTEROP _AppDomainManagerAssembly = copy.AppDomainManagerAssembly; _AppDomainManagerType = copy.AppDomainManagerType; #if FEATURE_APTCA _AptcaVisibleAssemblies = copy.PartialTrustVisibleAssemblies; #endif if (copy._CompatFlags != null) { SetCompatibilitySwitches(copy._CompatFlags.Keys); } #if !FEATURE_CORECLR if(copy._AppDomainSortingSetupInfo != null) { _AppDomainSortingSetupInfo = new AppDomainSortingSetupInfo(copy._AppDomainSortingSetupInfo); } #endif _TargetFrameworkName = copy._TargetFrameworkName; #if FEATURE_RANDOMIZED_STRING_HASHING _UseRandomizedStringHashing = copy._UseRandomizedStringHashing; #endif } else _LoaderOptimization = LoaderOptimization.NotSpecified; } public AppDomainSetup() { _LoaderOptimization = LoaderOptimization.NotSpecified; } #if FEATURE_CLICKONCE // Creates an AppDomainSetup object from an application identity. public AppDomainSetup (ActivationContext activationContext) : this (new ActivationArguments(activationContext)) {} [System.Security.SecuritySafeCritical] // auto-generated public AppDomainSetup (ActivationArguments activationArguments) { if (activationArguments == null) throw new ArgumentNullException("activationArguments"); Contract.EndContractBlock(); _LoaderOptimization = LoaderOptimization.NotSpecified; ActivationArguments = activationArguments; Contract.Assert(activationArguments.ActivationContext != null, "Cannot set base directory without activation context"); string entryPointPath = CmsUtils.GetEntryPointFullPath(activationArguments); if (!String.IsNullOrEmpty(entryPointPath)) SetupDefaults(entryPointPath); else ApplicationBase = activationArguments.ActivationContext.ApplicationDirectory; } #endif // !FEATURE_CLICKONCE #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal void SetupDefaults(string imageLocation, bool imageLocationAlreadyNormalized = false) { char[] sep = {'\\', '/'}; int i = imageLocation.LastIndexOfAny(sep); if (i == -1) { ApplicationName = imageLocation; } else { ApplicationName = imageLocation.Substring(i+1); string appBase = imageLocation.Substring(0, i+1); if (imageLocationAlreadyNormalized) Value[(int) LoaderInformation.ApplicationBaseValue] = appBase; else ApplicationBase = appBase; } ConfigurationFile = ApplicationName + AppDomainSetup.ConfigurationExtension; } internal string[] Value { get { if( _Entries == null) _Entries = new String[(int)LoaderInformation.LoaderMaximum]; return _Entries; } } internal String GetUnsecureApplicationBase() { return Value[(int) LoaderInformation.ApplicationBaseValue]; } public string AppDomainManagerAssembly { get { return _AppDomainManagerAssembly; } set { _AppDomainManagerAssembly = value; } } public string AppDomainManagerType { get { return _AppDomainManagerType; } set { _AppDomainManagerType = value; } } #if FEATURE_APTCA public string[] PartialTrustVisibleAssemblies { get { return _AptcaVisibleAssemblies; } set { if (value != null) { _AptcaVisibleAssemblies = (string[])value.Clone(); Array.Sort<string>(_AptcaVisibleAssemblies, StringComparer.OrdinalIgnoreCase); } else { _AptcaVisibleAssemblies = null; } } } #endif public String ApplicationBase { #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif [Pure] get { return VerifyDir(GetUnsecureApplicationBase(), false); } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif set { Value[(int) LoaderInformation.ApplicationBaseValue] = NormalizePath(value, false); } } private String NormalizePath(String path, bool useAppBase) { if(path == null) return null; // If we add very long file name support ("\\?\") to the Path class then this is unnecesary, // but we do not plan on doing this for now. // Long path checks can be quirked, and as loading default quirks too early in the setup of an AppDomain is risky // we'll avoid checking path lengths- we'll still fail at MAX_PATH later if we're !useAppBase when we call Path's // NormalizePath. if (!useAppBase) path = Security.Util.URLString.PreProcessForExtendedPathRemoval( checkPathLength: false, url: path, isFileUrl: false); int len = path.Length; if (len == 0) return null; #if !PLATFORM_UNIX bool UNCpath = false; #endif // !PLATFORM_UNIX if ((len > 7) && (String.Compare( path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0)) { int trim; if (path[6] == '\\') { if ((path[7] == '\\') || (path[7] == '/')) { // Don't allow "file:\\\\", because we can't tell the difference // with it for "file:\\" + "\\server" and "file:\\\" + "\localpath" if ( (len > 8) && ((path[8] == '\\') || (path[8] == '/')) ) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars")); // file:\\\ means local path else #if !PLATFORM_UNIX trim = 8; #else // For Unix platform, trim the first 7 charcaters only. // Trimming the first 8 characters will cause // the root path separator to be trimmed away, // and the absolute local path becomes a relative local path. trim = 7; #endif // !PLATFORM_UNIX } // file:\\ means remote server else { trim = 5; #if !PLATFORM_UNIX UNCpath = true; #endif // !PLATFORM_UNIX } } // local path else if (path[7] == '/') #if !PLATFORM_UNIX trim = 8; #else // For Unix platform, trim the first 7 characters only. // Trimming the first 8 characters will cause // the root path separator to be trimmed away, // and the absolute local path becomes a relative local path. trim = 7; #endif // !PLATFORM_UNIX // remote else { // file://\\remote if ( (len > 8) && (path[7] == '\\') && (path[8] == '\\') ) trim = 7; else { // file://remote trim = 5; #if !PLATFORM_UNIX // Create valid UNC path by changing // all occurences of '/' to '\\' in path System.Text.StringBuilder winPathBuilder = new System.Text.StringBuilder(len); for (int i = 0; i < len; i++) { char c = path[i]; if (c == '/') winPathBuilder.Append('\\'); else winPathBuilder.Append(c); } path = winPathBuilder.ToString(); #endif // !PLATFORM_UNIX } #if !PLATFORM_UNIX UNCpath = true; #endif // !PLATFORM_UNIX } path = path.Substring(trim); len -= trim; } #if !PLATFORM_UNIX bool localPath; // UNC if (UNCpath || ( (len > 1) && ( (path[0] == '/') || (path[0] == '\\') ) && ( (path[1] == '/') || (path[1] == '\\') ) )) localPath = false; else { int colon = path.IndexOf(':') + 1; // protocol other than file: if ((colon != 0) && (len > colon+1) && ( (path[colon] == '/') || (path[colon] == '\\') ) && ( (path[colon+1] == '/') || (path[colon+1] == '\\') )) localPath = false; else localPath = true; } if (localPath) #else if ( (len == 1) || ( (path[0] != '/') && (path[0] != '\\') ) ) #endif // !PLATFORM_UNIX { if (useAppBase && ( (len == 1) || (path[1] != ':') )) { String appBase = Value[(int) LoaderInformation.ApplicationBaseValue]; if ((appBase == null) || (appBase.Length == 0)) throw new MemberAccessException(Environment.GetResourceString("AppDomain_AppBaseNotSet")); StringBuilder result = StringBuilderCache.Acquire(); bool slash = false; if ((path[0] == '/') || (path[0] == '\\')) { string pathRoot = AppDomain.NormalizePath(appBase, fullCheck: false); pathRoot = pathRoot.Substring(0, IO.PathInternal.GetRootLength(pathRoot)); if (pathRoot.Length == 0) { // URL int index = appBase.IndexOf(":/", StringComparison.Ordinal); if (index == -1) index = appBase.IndexOf(":\\", StringComparison.Ordinal); // Get past last slashes of "url:http://" int urlLen = appBase.Length; for (index += 1; (index < urlLen) && ((appBase[index] == '/') || (appBase[index] == '\\')); index++); // Now find the next slash to get domain name for(; (index < urlLen) && (appBase[index] != '/') && (appBase[index] != '\\'); index++); pathRoot = appBase.Substring(0, index); } result.Append(pathRoot); slash = true; } else result.Append(appBase); // Make sure there's a slash separator (and only one) int aLen = result.Length - 1; if ((result[aLen] != '/') && (result[aLen] != '\\')) { if (!slash) { #if !PLATFORM_UNIX if (appBase.IndexOf(":/", StringComparison.Ordinal) == -1) result.Append('\\'); else #endif // !PLATFORM_UNIX result.Append('/'); } } else if (slash) result.Remove(aLen, 1); result.Append(path); path = StringBuilderCache.GetStringAndRelease(result); } else path = AppDomain.NormalizePath(path, fullCheck: true); } return path; } private bool IsFilePath(String path) { #if !PLATFORM_UNIX return (path[1] == ':') || ( (path[0] == '\\') && (path[1] == '\\') ); #else return (path[0] == '/'); #endif // !PLATFORM_UNIX } internal static String ApplicationBaseKey { get { return ACTAG_APP_BASE_URL; } } public String ConfigurationFile { [System.Security.SecuritySafeCritical] // auto-generated get { return VerifyDir(Value[(int) LoaderInformation.ConfigurationFileValue], true); } set { Value[(int) LoaderInformation.ConfigurationFileValue] = value; } } // Used by the ResourceManager internally. This must not do any // security checks to avoid infinite loops. internal String ConfigurationFileInternal { get { return NormalizePath(Value[(int) LoaderInformation.ConfigurationFileValue], true); } } internal static String ConfigurationFileKey { get { return ACTAG_APP_CONFIG_FILE; } } public byte[] GetConfigurationBytes() { if (_ConfigurationBytes == null) return null; return (byte[]) _ConfigurationBytes.Clone(); } public void SetConfigurationBytes(byte[] value) { _ConfigurationBytes = value; } private static String ConfigurationBytesKey { get { return ACTAG_APP_CONFIG_BLOB; } } // only needed by AppDomain.Setup(). Not really needed by users. internal Dictionary<string, object> GetCompatibilityFlags() { return _CompatFlags; } public void SetCompatibilitySwitches(IEnumerable<String> switches) { #if !FEATURE_CORECLR if(_AppDomainSortingSetupInfo != null) { _AppDomainSortingSetupInfo._useV2LegacySorting = false; _AppDomainSortingSetupInfo._useV4LegacySorting = false; } #endif #if FEATURE_RANDOMIZED_STRING_HASHING _UseRandomizedStringHashing = false; #endif if (switches != null) { _CompatFlags = new Dictionary<string, object>(); foreach (String str in switches) { #if !FEATURE_CORECLR if(StringComparer.OrdinalIgnoreCase.Equals("NetFx40_Legacy20SortingBehavior", str)) { if(_AppDomainSortingSetupInfo == null) { _AppDomainSortingSetupInfo = new AppDomainSortingSetupInfo(); } _AppDomainSortingSetupInfo._useV2LegacySorting = true; } if(StringComparer.OrdinalIgnoreCase.Equals("NetFx45_Legacy40SortingBehavior", str)) { if(_AppDomainSortingSetupInfo == null) { _AppDomainSortingSetupInfo = new AppDomainSortingSetupInfo(); } _AppDomainSortingSetupInfo._useV4LegacySorting = true; } #endif #if FEATURE_RANDOMIZED_STRING_HASHING if(StringComparer.OrdinalIgnoreCase.Equals("UseRandomizedStringHashAlgorithm", str)) { _UseRandomizedStringHashing = true; } #endif _CompatFlags.Add(str, null); } } else { _CompatFlags = null; } } // A target Framework moniker, in a format parsible by the FrameworkName class. public String TargetFrameworkName { get { return _TargetFrameworkName; } set { _TargetFrameworkName = value; } } internal bool CheckedForTargetFrameworkName { get { return _CheckedForTargetFrameworkName; } set { _CheckedForTargetFrameworkName = value; } } #if !FEATURE_CORECLR [SecurityCritical] public void SetNativeFunction(string functionName, int functionVersion, IntPtr functionPointer) { if(functionName == null) { throw new ArgumentNullException("functionName"); } if(functionPointer == IntPtr.Zero) { throw new ArgumentNullException("functionPointer"); } if(String.IsNullOrWhiteSpace(functionName)) { throw new ArgumentException(Environment.GetResourceString("Argument_NPMSInvalidName"), "functionName"); } Contract.EndContractBlock(); if(functionVersion < 1) { throw new ArgumentException(Environment.GetResourceString("ArgumentException_MinSortingVersion", 1, functionName)); } if(_AppDomainSortingSetupInfo == null) { _AppDomainSortingSetupInfo = new AppDomainSortingSetupInfo(); } if(String.Equals(functionName, "IsNLSDefinedString", StringComparison.OrdinalIgnoreCase)) { _AppDomainSortingSetupInfo._pfnIsNLSDefinedString = functionPointer; } if (String.Equals(functionName, "CompareStringEx", StringComparison.OrdinalIgnoreCase)) { _AppDomainSortingSetupInfo._pfnCompareStringEx = functionPointer; } if (String.Equals(functionName, "LCMapStringEx", StringComparison.OrdinalIgnoreCase)) { _AppDomainSortingSetupInfo._pfnLCMapStringEx = functionPointer; } if (String.Equals(functionName, "FindNLSStringEx", StringComparison.OrdinalIgnoreCase)) { _AppDomainSortingSetupInfo._pfnFindNLSStringEx = functionPointer; } if (String.Equals(functionName, "CompareStringOrdinal", StringComparison.OrdinalIgnoreCase)) { _AppDomainSortingSetupInfo._pfnCompareStringOrdinal = functionPointer; } if (String.Equals(functionName, "GetNLSVersionEx", StringComparison.OrdinalIgnoreCase)) { _AppDomainSortingSetupInfo._pfnGetNLSVersionEx = functionPointer; } if (String.Equals(functionName, "FindStringOrdinal", StringComparison.OrdinalIgnoreCase)) { _AppDomainSortingSetupInfo._pfnFindStringOrdinal = functionPointer; } } #endif public String DynamicBase { [System.Security.SecuritySafeCritical] // auto-generated get { return VerifyDir(Value[(int) LoaderInformation.DynamicBaseValue], true); } [System.Security.SecuritySafeCritical] // auto-generated set { if (value == null) Value[(int) LoaderInformation.DynamicBaseValue] = null; else { if(ApplicationName == null) throw new MemberAccessException(Environment.GetResourceString("AppDomain_RequireApplicationName")); StringBuilder s = new StringBuilder( NormalizePath(value, false) ); s.Append('\\'); string h = ParseNumbers.IntToString(ApplicationName.GetLegacyNonRandomizedHashCode(), 16, 8, '0', ParseNumbers.PrintAsI4); s.Append(h); Value[(int) LoaderInformation.DynamicBaseValue] = s.ToString(); } } } internal static String DynamicBaseKey { get { return ACTAG_APP_DYNAMIC_BASE; } } public bool DisallowPublisherPolicy { get { return (Value[(int) LoaderInformation.DisallowPublisherPolicyValue] != null); } set { if (value) Value[(int) LoaderInformation.DisallowPublisherPolicyValue]="true"; else Value[(int) LoaderInformation.DisallowPublisherPolicyValue]=null; } } public bool DisallowBindingRedirects { get { return (Value[(int) LoaderInformation.DisallowBindingRedirectsValue] != null); } set { if (value) Value[(int) LoaderInformation.DisallowBindingRedirectsValue] = "true"; else Value[(int) LoaderInformation.DisallowBindingRedirectsValue] = null; } } public bool DisallowCodeDownload { get { return (Value[(int) LoaderInformation.DisallowCodeDownloadValue] != null); } set { if (value) Value[(int) LoaderInformation.DisallowCodeDownloadValue] = "true"; else Value[(int) LoaderInformation.DisallowCodeDownloadValue] = null; } } public bool DisallowApplicationBaseProbing { get { return (Value[(int) LoaderInformation.DisallowAppBaseProbingValue] != null); } set { if (value) Value[(int) LoaderInformation.DisallowAppBaseProbingValue] = "true"; else Value[(int) LoaderInformation.DisallowAppBaseProbingValue] = null; } } [System.Security.SecurityCritical] // auto-generated private String VerifyDir(String dir, bool normalize) { if (dir != null) { if (dir.Length == 0) dir = null; else { if (normalize) dir = NormalizePath(dir, true); // The only way AppDomainSetup is exposed in coreclr is through the AppDomainManager // and the AppDomainManager is a SecurityCritical type. Also, all callers of callstacks // leading from VerifyDir are SecurityCritical. So we can remove the Demand because // we have validated that all callers are SecurityCritical #if !FEATURE_CORECLR if (IsFilePath(dir)) new FileIOPermission( FileIOPermissionAccess.PathDiscovery, dir ).Demand(); #endif // !FEATURE_CORECLR } } return dir; } [System.Security.SecurityCritical] // auto-generated private void VerifyDirList(String dirs) { if (dirs != null) { String[] dirArray = dirs.Split(';'); int len = dirArray.Length; for (int i = 0; i < len; i++) VerifyDir(dirArray[i], true); } } internal String DeveloperPath { [System.Security.SecurityCritical] // auto-generated get { String dirs = Value[(int) LoaderInformation.DevPathValue]; VerifyDirList(dirs); return dirs; } set { if(value == null) Value[(int) LoaderInformation.DevPathValue] = null; else { String[] directories = value.Split(';'); int size = directories.Length; StringBuilder newPath = StringBuilderCache.Acquire(); bool fDelimiter = false; for(int i = 0; i < size; i++) { if(directories[i].Length != 0) { if(fDelimiter) newPath.Append(";"); else fDelimiter = true; newPath.Append(Path.GetFullPathInternal(directories[i])); } } String newString = StringBuilderCache.GetStringAndRelease(newPath); if (newString.Length == 0) Value[(int) LoaderInformation.DevPathValue] = null; else Value[(int) LoaderInformation.DevPathValue] = newString; } } } internal static String DisallowPublisherPolicyKey { get { return ACTAG_DISALLOW_APPLYPUBLISHERPOLICY; } } internal static String DisallowCodeDownloadKey { get { return ACTAG_CODE_DOWNLOAD_DISABLED; } } internal static String DisallowBindingRedirectsKey { get { return ACTAG_DISALLOW_APP_BINDING_REDIRECTS; } } internal static String DeveloperPathKey { get { return ACTAG_DEV_PATH; } } internal static String DisallowAppBaseProbingKey { get { return ACTAG_DISALLOW_APP_BASE_PROBING; } } public String ApplicationName { get { return Value[(int) LoaderInformation.ApplicationNameValue]; } set { Value[(int) LoaderInformation.ApplicationNameValue] = value; } } internal static String ApplicationNameKey { get { return ACTAG_APP_NAME; } } [XmlIgnoreMember] public AppDomainInitializer AppDomainInitializer { get { return _AppDomainInitializer; } set { _AppDomainInitializer = value; } } public string[] AppDomainInitializerArguments { get { return _AppDomainInitializerArguments; } set { _AppDomainInitializerArguments = value; } } #if FEATURE_CLICKONCE [XmlIgnoreMember] public ActivationArguments ActivationArguments { [Pure] get { return _ActivationArguments; } set { _ActivationArguments = value; } } #endif // !FEATURE_CLICKONCE internal ApplicationTrust InternalGetApplicationTrust() { if (_ApplicationTrust == null) return null; #if FEATURE_CORECLR ApplicationTrust grantSet = new ApplicationTrust(NamedPermissionSet.GetBuiltInSet(_ApplicationTrust)); #else SecurityElement securityElement = SecurityElement.FromString(_ApplicationTrust); ApplicationTrust grantSet = new ApplicationTrust(); grantSet.FromXml(securityElement); #endif return grantSet; } #if FEATURE_CORECLR internal void InternalSetApplicationTrust(String permissionSetName) { _ApplicationTrust = permissionSetName; } #else internal void InternalSetApplicationTrust(ApplicationTrust value) { if (value != null) { _ApplicationTrust = value.ToXml().ToString(); } else { _ApplicationTrust = null; } } #endif #if FEATURE_CLICKONCE [XmlIgnoreMember] public ApplicationTrust ApplicationTrust { get { return InternalGetApplicationTrust(); } set { InternalSetApplicationTrust(value); } } #else // FEATURE_CLICKONCE [XmlIgnoreMember] internal ApplicationTrust ApplicationTrust { get { return InternalGetApplicationTrust(); } #if !FEATURE_CORECLR set { InternalSetApplicationTrust(value); } #endif } #endif // FEATURE_CLICKONCE public String PrivateBinPath { [System.Security.SecuritySafeCritical] // auto-generated get { String dirs = Value[(int) LoaderInformation.PrivateBinPathValue]; VerifyDirList(dirs); return dirs; } set { Value[(int) LoaderInformation.PrivateBinPathValue] = value; } } internal static String PrivateBinPathKey { get { return ACTAG_APP_PRIVATE_BINPATH; } } public String PrivateBinPathProbe { get { return Value[(int) LoaderInformation.PrivateBinPathProbeValue]; } set { Value[(int) LoaderInformation.PrivateBinPathProbeValue] = value; } } internal static String PrivateBinPathProbeKey { get { return ACTAG_BINPATH_PROBE_ONLY; } } public String ShadowCopyDirectories { [System.Security.SecuritySafeCritical] // auto-generated get { String dirs = Value[(int) LoaderInformation.ShadowCopyDirectoriesValue]; VerifyDirList(dirs); return dirs; } set { Value[(int) LoaderInformation.ShadowCopyDirectoriesValue] = value; } } internal static String ShadowCopyDirectoriesKey { get { return ACTAG_APP_SHADOW_COPY_DIRS; } } public String ShadowCopyFiles { get { return Value[(int) LoaderInformation.ShadowCopyFilesValue]; } set { if((value != null) && (String.Compare(value, "true", StringComparison.OrdinalIgnoreCase) == 0)) Value[(int) LoaderInformation.ShadowCopyFilesValue] = value; else Value[(int) LoaderInformation.ShadowCopyFilesValue] = null; } } internal static String ShadowCopyFilesKey { get { return ACTAG_FORCE_CACHE_INSTALL; } } public String CachePath { [System.Security.SecuritySafeCritical] // auto-generated get { return VerifyDir(Value[(int) LoaderInformation.CachePathValue], false); } set { Value[(int) LoaderInformation.CachePathValue] = NormalizePath(value, false); } } internal static String CachePathKey { get { return ACTAG_APP_CACHE_BASE; } } public String LicenseFile { [System.Security.SecuritySafeCritical] // auto-generated get { return VerifyDir(Value[(int) LoaderInformation.LicenseFileValue], true); } set { Value[(int) LoaderInformation.LicenseFileValue] = value; } } public LoaderOptimization LoaderOptimization { get { return _LoaderOptimization; } set { _LoaderOptimization = value; } } internal static string LoaderOptimizationKey { get { return LOADER_OPTIMIZATION; } } internal static string ConfigurationExtension { get { return CONFIGURATION_EXTENSION; } } internal static String PrivateBinPathEnvironmentVariable { get { return APPENV_RELATIVEPATH; } } internal static string RuntimeConfigurationFile { get { return MACHINE_CONFIGURATION_FILE; } } internal static string MachineConfigKey { get { return ACTAG_MACHINE_CONFIG; } } internal static string HostBindingKey { get { return ACTAG_HOST_CONFIG_FILE; } } #if FEATURE_FUSION [SecurityCritical] internal bool UpdateContextPropertyIfNeeded(LoaderInformation FieldValue, String FieldKey, String UpdatedField, IntPtr fusionContext, AppDomainSetup oldADS) { String FieldString = Value[(int) FieldValue], OldFieldString = (oldADS == null ? null : oldADS.Value[(int) FieldValue]); if (FieldString != OldFieldString) { // Compare references since strings are immutable UpdateContextProperty(fusionContext, FieldKey, UpdatedField == null ? FieldString : UpdatedField); return true; } return false; } [SecurityCritical] internal void UpdateBooleanContextPropertyIfNeeded(LoaderInformation FieldValue, String FieldKey, IntPtr fusionContext, AppDomainSetup oldADS) { if (Value[(int) FieldValue] != null) UpdateContextProperty(fusionContext, FieldKey, "true"); else if (oldADS != null && oldADS.Value[(int) FieldValue] != null) UpdateContextProperty(fusionContext, FieldKey, "false"); } [SecurityCritical] internal static bool ByteArraysAreDifferent(Byte[] A, Byte[] B) { int length = A.Length; if (length != B.Length) return true; for(int i = 0; i < length; i++) { if (A[i] != B[i]) return true; } return false; } [System.Security.SecurityCritical] // auto-generated internal static void UpdateByteArrayContextPropertyIfNeeded(Byte[] NewArray, Byte[] OldArray, String FieldKey, IntPtr fusionContext) { if ((NewArray != null && OldArray == null) || (NewArray == null && OldArray != null) || (NewArray != null && OldArray != null && ByteArraysAreDifferent(NewArray, OldArray))) UpdateContextProperty(fusionContext, FieldKey, NewArray); } [System.Security.SecurityCritical] // auto-generated internal void SetupFusionContext(IntPtr fusionContext, AppDomainSetup oldADS) { UpdateContextPropertyIfNeeded(LoaderInformation.ApplicationBaseValue, ApplicationBaseKey, null, fusionContext, oldADS); UpdateContextPropertyIfNeeded(LoaderInformation.PrivateBinPathValue, PrivateBinPathKey, null, fusionContext, oldADS); UpdateContextPropertyIfNeeded(LoaderInformation.DevPathValue, DeveloperPathKey, null, fusionContext, oldADS); UpdateBooleanContextPropertyIfNeeded(LoaderInformation.DisallowPublisherPolicyValue, DisallowPublisherPolicyKey, fusionContext, oldADS); UpdateBooleanContextPropertyIfNeeded(LoaderInformation.DisallowCodeDownloadValue, DisallowCodeDownloadKey, fusionContext, oldADS); UpdateBooleanContextPropertyIfNeeded(LoaderInformation.DisallowBindingRedirectsValue, DisallowBindingRedirectsKey, fusionContext, oldADS); UpdateBooleanContextPropertyIfNeeded(LoaderInformation.DisallowAppBaseProbingValue, DisallowAppBaseProbingKey, fusionContext, oldADS); if(UpdateContextPropertyIfNeeded(LoaderInformation.ShadowCopyFilesValue, ShadowCopyFilesKey, ShadowCopyFiles, fusionContext, oldADS)) { // If we are asking for shadow copy directories then default to // only to the ones that are in the private bin path. if(Value[(int) LoaderInformation.ShadowCopyDirectoriesValue] == null) ShadowCopyDirectories = BuildShadowCopyDirectories(); UpdateContextPropertyIfNeeded(LoaderInformation.ShadowCopyDirectoriesValue, ShadowCopyDirectoriesKey, null, fusionContext, oldADS); } UpdateContextPropertyIfNeeded(LoaderInformation.CachePathValue, CachePathKey, null, fusionContext, oldADS); UpdateContextPropertyIfNeeded(LoaderInformation.PrivateBinPathProbeValue, PrivateBinPathProbeKey, PrivateBinPathProbe, fusionContext, oldADS); UpdateContextPropertyIfNeeded(LoaderInformation.ConfigurationFileValue, ConfigurationFileKey, null, fusionContext, oldADS); UpdateByteArrayContextPropertyIfNeeded(_ConfigurationBytes, oldADS == null ? null : oldADS.GetConfigurationBytes(), ConfigurationBytesKey, fusionContext); UpdateContextPropertyIfNeeded(LoaderInformation.ApplicationNameValue, ApplicationNameKey, ApplicationName, fusionContext, oldADS); UpdateContextPropertyIfNeeded(LoaderInformation.DynamicBaseValue, DynamicBaseKey, null, fusionContext, oldADS); // Always add the runtime configuration file to the appdomain UpdateContextProperty(fusionContext, MachineConfigKey, RuntimeEnvironment.GetRuntimeDirectoryImpl() + RuntimeConfigurationFile); String hostBindingFile = RuntimeEnvironment.GetHostBindingFile(); if(hostBindingFile != null || oldADS != null) // If oldADS != null, we don't know the old value of the hostBindingFile, so we force an update even when hostBindingFile == null. UpdateContextProperty(fusionContext, HostBindingKey, hostBindingFile); } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void UpdateContextProperty(IntPtr fusionContext, string key, Object value); #endif // FEATURE_FUSION static internal int Locate(String s) { if(String.IsNullOrEmpty(s)) return -1; #if FEATURE_FUSION // verify assumptions hardcoded into the switch below Contract.Assert('A' == ACTAG_APP_CONFIG_FILE[0] , "Assumption violated"); Contract.Assert('A' == ACTAG_APP_NAME[0] , "Assumption violated"); Contract.Assert('A' == ACTAG_APP_BASE_URL[0] , "Assumption violated"); Contract.Assert('B' == ACTAG_BINPATH_PROBE_ONLY[0] , "Assumption violated"); Contract.Assert('C' == ACTAG_APP_CACHE_BASE[0] , "Assumption violated"); Contract.Assert('D' == ACTAG_DEV_PATH[0] , "Assumption violated"); Contract.Assert('D' == ACTAG_APP_DYNAMIC_BASE[0] , "Assumption violated"); Contract.Assert('F' == ACTAG_FORCE_CACHE_INSTALL[0] , "Assumption violated"); Contract.Assert('L' == LICENSE_FILE[0] , "Assumption violated"); Contract.Assert('P' == ACTAG_APP_PRIVATE_BINPATH[0] , "Assumption violated"); Contract.Assert('S' == ACTAG_APP_SHADOW_COPY_DIRS[0], "Assumption violated"); Contract.Assert('D' == ACTAG_DISALLOW_APPLYPUBLISHERPOLICY[0], "Assumption violated"); Contract.Assert('C' == ACTAG_CODE_DOWNLOAD_DISABLED[0], "Assumption violated"); Contract.Assert('D' == ACTAG_DISALLOW_APP_BINDING_REDIRECTS[0], "Assumption violated"); Contract.Assert('D' == ACTAG_DISALLOW_APP_BASE_PROBING[0], "Assumption violated"); Contract.Assert('A' == ACTAG_APP_CONFIG_BLOB[0], "Assumption violated"); switch (s[0]) { case 'A': if (s == ACTAG_APP_CONFIG_FILE) return (int)LoaderInformation.ConfigurationFileValue; if (s == ACTAG_APP_NAME) return (int)LoaderInformation.ApplicationNameValue; if (s == ACTAG_APP_BASE_URL) return (int)LoaderInformation.ApplicationBaseValue; if (s == ACTAG_APP_CONFIG_BLOB) return (int)LoaderInformation.ConfigurationBytesValue; break; case 'B': if (s == ACTAG_BINPATH_PROBE_ONLY) return (int)LoaderInformation.PrivateBinPathProbeValue; break; case 'C': if (s == ACTAG_APP_CACHE_BASE) return (int)LoaderInformation.CachePathValue; if (s == ACTAG_CODE_DOWNLOAD_DISABLED) return (int)LoaderInformation.DisallowCodeDownloadValue; break; case 'D': if (s == ACTAG_DEV_PATH) return (int)LoaderInformation.DevPathValue; if (s == ACTAG_APP_DYNAMIC_BASE) return (int)LoaderInformation.DynamicBaseValue; if (s == ACTAG_DISALLOW_APPLYPUBLISHERPOLICY) return (int)LoaderInformation.DisallowPublisherPolicyValue; if (s == ACTAG_DISALLOW_APP_BINDING_REDIRECTS) return (int)LoaderInformation.DisallowBindingRedirectsValue; if (s == ACTAG_DISALLOW_APP_BASE_PROBING) return (int)LoaderInformation.DisallowAppBaseProbingValue; break; case 'F': if (s == ACTAG_FORCE_CACHE_INSTALL) return (int)LoaderInformation.ShadowCopyFilesValue; break; case 'L': if (s == LICENSE_FILE) return (int)LoaderInformation.LicenseFileValue; break; case 'P': if (s == ACTAG_APP_PRIVATE_BINPATH) return (int)LoaderInformation.PrivateBinPathValue; break; case 'S': if (s == ACTAG_APP_SHADOW_COPY_DIRS) return (int)LoaderInformation.ShadowCopyDirectoriesValue; break; } #else Contract.Assert('A' == ACTAG_APP_BASE_URL[0] , "Assumption violated"); if (s[0]=='A' && s == ACTAG_APP_BASE_URL) return (int)LoaderInformation.ApplicationBaseValue; #endif //FEATURE_FUSION return -1; } #if FEATURE_FUSION private string BuildShadowCopyDirectories() { // Default to only to the ones that are in the private bin path. String binPath = Value[(int) LoaderInformation.PrivateBinPathValue]; if(binPath == null) return null; StringBuilder result = StringBuilderCache.Acquire(); String appBase = Value[(int) LoaderInformation.ApplicationBaseValue]; if(appBase != null) { char[] sep = {';'}; string[] directories = binPath.Split(sep); int size = directories.Length; bool appendSlash = !( (appBase[appBase.Length-1] == '/') || (appBase[appBase.Length-1] == '\\') ); if (size == 0) { result.Append(appBase); if (appendSlash) result.Append('\\'); result.Append(binPath); } else { for(int i = 0; i < size; i++) { result.Append(appBase); if (appendSlash) result.Append('\\'); result.Append(directories[i]); if (i < size-1) result.Append(';'); } } } return StringBuilderCache.GetStringAndRelease(result); } #endif // FEATURE_FUSION #if FEATURE_COMINTEROP public bool SandboxInterop { get { return _DisableInterfaceCache; } set { _DisableInterfaceCache = value; } } #endif // FEATURE_COMINTEROP } }
// // FullScreenWindow.cs // // Authors: // Aaron Bockover <abockover@novell.com> // Larry Ewing <lewing@novell.com> // Gabriel Burt <gburt@novell.com> // // Copyright 2008-2010 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; using Banshee.Gui; using Banshee.MediaEngine; using Banshee.ServiceStack; namespace Banshee.NowPlaying { public class FullscreenWindow : Window { private Gtk.Window parent; private FullscreenControls controls; private InterfaceActionService action_service; public FullscreenWindow (Window parent) : base (WindowType.Toplevel) { Title = parent.Title; AppPaintable = true; this.parent = parent; this.action_service = ServiceManager.Get<InterfaceActionService> (); AddAccelGroup (action_service.UIManager.AccelGroup); SetupWidget (); } protected override bool OnKeyPressEvent (Gdk.EventKey evnt) { PlayerEngineService player = ServiceManager.PlayerEngine; bool control = (evnt.State & Gdk.ModifierType.ShiftMask) != 0; bool shift = (evnt.State & Gdk.ModifierType.ControlMask) != 0; bool mod = control || shift; uint fixed_seek = 15000; // 15 seconds uint fast_seek = player.Length > 0 ? (uint)(player.Length * 0.15) : fixed_seek; // 15% or fixed uint slow_seek = player.Length > 0 ? (uint)(player.Length * 0.05) : fixed_seek; // 5% or fixed switch (evnt.Key) { case Gdk.Key.F11: case Gdk.Key.Escape: Hide (); return true; case Gdk.Key.C: case Gdk.Key.c: case Gdk.Key.V: case Gdk.Key.v: case Gdk.Key.Tab: if (controls == null || !controls.Visible) { ShowControls (); } else { HideControls (); } return true; case Gdk.Key.Return: case Gdk.Key.KP_Enter: if (ServiceManager.PlayerEngine.InDvdMenu) { ServiceManager.PlayerEngine.ActivateCurrentMenu (); } else if (controls == null || !controls.Visible) { ShowControls (); } else { HideControls (); } return true; case Gdk.Key.Right: case Gdk.Key.rightarrow: case Gdk.Key.KP_Right: if (ServiceManager.PlayerEngine.InDvdMenu) { ServiceManager.PlayerEngine.NavigateToRightMenu (); } else { player.Position += mod ? fast_seek : slow_seek; ShowControls (); } break; case Gdk.Key.Left: case Gdk.Key.leftarrow: case Gdk.Key.KP_Left: if (ServiceManager.PlayerEngine.InDvdMenu) { ServiceManager.PlayerEngine.NavigateToLeftMenu (); } else { player.Position -= mod ? fast_seek : slow_seek; ShowControls (); } break; case Gdk.Key.uparrow: case Gdk.Key.Up: case Gdk.Key.KP_Up: if (ServiceManager.PlayerEngine.InDvdMenu) { ServiceManager.PlayerEngine.NavigateToUpMenu (); } break; case Gdk.Key.downarrow: case Gdk.Key.Down: case Gdk.Key.KP_Down: if (ServiceManager.PlayerEngine.InDvdMenu) { ServiceManager.PlayerEngine.NavigateToDownMenu (); } break; } return base.OnKeyPressEvent (evnt); } #region Widgetry and show/hide logic private void SetupWidget () { Deletable = false; TransientFor = null; Decorated = false; CanFocus = true; ConfigureWindow (); } private void ConfigureWindow () { Gdk.Screen screen = Screen; int monitor = screen.GetMonitorAtWindow (parent.Window); Gdk.Rectangle bounds = screen.GetMonitorGeometry (monitor); Move (bounds.X, bounds.Y); Resize (bounds.Width, bounds.Height); if (controls != null) { int width, height; controls.GetSize(out width, out height); if (width > bounds.Width) { controls.Resize(bounds.Width, height); } } } protected override void OnRealized () { Events |= Gdk.EventMask.PointerMotionMask; base.OnRealized (); Window.OverrideRedirect = true; Screen.SizeChanged += OnScreenSizeChanged; } protected override void OnUnrealized () { Screen.SizeChanged -= OnScreenSizeChanged; base.OnUnrealized (); } protected override bool OnDeleteEvent (Gdk.Event evnt) { Hide (); return true; } protected override void OnShown () { base.OnShown (); OnHideCursorTimeout (); ConfigureWindow (); HasFocus = true; parent.AddNotification ("is-active", ParentActiveNotification); } protected override void OnHidden () { DestroyControls (); base.OnHidden (); } private void OnScreenSizeChanged (object o, EventArgs args) { ConfigureWindow (); } private void ParentActiveNotification (object o, GLib.NotifyArgs args) { if (parent.IsActive) { Hide (); parent.RemoveNotification ("is-active", ParentActiveNotification); } } #endregion #region Control Window private void ShowControls () { if (controls == null) { controls = new FullscreenControls (this, action_service); } controls.Show (); } private void HideControls () { if (controls != null) { controls.Hide (); QueueDraw (); } } private void DestroyControls () { if (controls != null) { controls.Destroy (); controls = null; } } private bool ControlsActive { get { if (controls == null || !controls.Visible) { return false; } else if (controls.Active) { return true; } int cursor_x, cursor_y; int window_x, window_y; controls.Window.Screen.Display.GetPointer (out cursor_x, out cursor_y); controls.GetPosition (out window_x, out window_y); Gdk.Rectangle box = new Gdk.Rectangle (window_x, window_y, controls.Allocation.Width, controls.Allocation.Height); return box.Contains (cursor_x, cursor_y); } } #endregion #region Mouse Cursor Logic private const int CursorUpdatePositionDelay = 500; // How long (ms) before the cursor position is updated private const int CursorHideDelay = 5000; // How long (ms) to remain stationary before it hides private const int CursorShowMovementThreshold = 150; // How far (px) to move before it shows again private uint hide_cursor_timeout_id; private uint cursor_update_position_timeout_id; private int hide_cursor_x; private int hide_cursor_y; private bool cursor_is_hidden { get { switch (Window.Cursor?.CursorType) { case Gdk.CursorType.BlankCursor: return true; default: return false; } } } protected override bool OnMotionNotifyEvent (Gdk.EventMotion evnt) { if (cursor_is_hidden) { if (Math.Abs (hide_cursor_x - evnt.X) > CursorShowMovementThreshold || Math.Abs (hide_cursor_y - evnt.Y) > CursorShowMovementThreshold) { ShowCursor (); ShowControls (); } else { if (cursor_update_position_timeout_id > 0) { GLib.Source.Remove (cursor_update_position_timeout_id); } cursor_update_position_timeout_id = GLib.Timeout.Add (CursorUpdatePositionDelay, OnCursorUpdatePositionTimeout); } } else if (!ControlsActive) { if (hide_cursor_timeout_id > 0) { GLib.Source.Remove (hide_cursor_timeout_id); } hide_cursor_timeout_id = GLib.Timeout.Add (CursorHideDelay, OnHideCursorTimeout); } return base.OnMotionNotifyEvent (evnt); } private bool OnCursorUpdatePositionTimeout () { UpdateHiddenCursorPosition (); cursor_update_position_timeout_id = 0; return false; } private bool OnHideCursorTimeout () { if (!ControlsActive) { HideCursor (); HideControls (); } hide_cursor_timeout_id = 0; return false; } private void UpdateHiddenCursorPosition () { GetPointer (out hide_cursor_x, out hide_cursor_y); } private void ShowCursor () { Window.Cursor = null; } private void HideCursor () { if (Window == null) { return; } Gdk.Cursor cursor = new Gdk.Cursor (Gdk.CursorType.BlankCursor); Window.Cursor = cursor; cursor.Dispose (); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.ComponentModel.Design; using System.Globalization; using System.Runtime.InteropServices; namespace System.ComponentModel { /// <summary> /// Provides a type converter to convert object references to and from various /// other representations. /// </summary> public class ReferenceConverter : TypeConverter { private static readonly string s_none = SR.toStringNone; private Type _type; /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.ReferenceConverter'/> class. /// </summary> public ReferenceConverter(Type type) { _type = type; } /// <summary> /// Gets a value indicating whether this converter can convert an object in the /// given source type to a reference object using the specified context. /// </summary> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string) && context != null) { return true; } return base.CanConvertFrom(context, sourceType); } /// <summary> /// Converts the given object to the reference type. /// </summary> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { string text = ((string)value).Trim(); if (!string.Equals(text, s_none) && context != null) { // Try the reference service first. IReferenceService refSvc = (IReferenceService)context.GetService(typeof(IReferenceService)); if (refSvc != null) { object obj = refSvc.GetReference(text); if (obj != null) { return obj; } } // Now try IContainer IContainer cont = context.Container; if (cont != null) { object obj = cont.Components[text]; if (obj != null) { return obj; } } } return null; } return base.ConvertFrom(context, culture, value); } /// <summary> /// Converts the given value object to the reference type /// using the specified context and arguments. /// </summary> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw new ArgumentNullException(nameof(destinationType)); } if (destinationType == typeof(string)) { if (value != null) { // Try the reference service first. IReferenceService refSvc = (IReferenceService) context?.GetService(typeof(IReferenceService)); if (refSvc != null) { string name = refSvc.GetName(value); if (name != null) { return name; } } // Now see if this is an IComponent. if (!Marshal.IsComObject(value) && value is IComponent) { IComponent comp = (IComponent)value; ISite site = comp.Site; string name = site?.Name; if (name != null) { return name; } } // Couldn't find it. return string.Empty; } return s_none; } return base.ConvertTo(context, culture, value, destinationType); } /// <summary> /// Gets a collection of standard values for the reference data type. /// </summary> public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { object[] components = null; if (context != null) { var list = new List<object> { null }; // Try the reference service first. IReferenceService refSvc = (IReferenceService)context.GetService(typeof(IReferenceService)); if (refSvc != null) { object[] objs = refSvc.GetReferences(_type); int count = objs.Length; for (int i = 0; i < count; i++) { if (IsValueAllowed(context, objs[i])) list.Add(objs[i]); } } else { // Now try IContainer. IContainer cont = context.Container; if (cont != null) { ComponentCollection objs = cont.Components; foreach (IComponent obj in objs) { if (obj != null && _type.IsInstanceOfType(obj) && IsValueAllowed(context, obj)) { list.Add(obj); } } } } components = list.ToArray(); Array.Sort(components, 0, components.Length, new ReferenceComparer(this)); } return new StandardValuesCollection(components); } /// <summary> /// Gets a value indicating whether the list of standard values returned from /// <see cref='System.ComponentModel.ReferenceConverter.GetStandardValues'/> is an exclusive list. /// </summary> public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) => true; /// <summary> /// Gets a value indicating whether this object supports a standard set of values /// that can be picked from a list. /// </summary> public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true; /// <summary> /// Gets a value indicating whether a particular value can be added to /// the standard values collection. /// </summary> protected virtual bool IsValueAllowed(ITypeDescriptorContext context, object value) => true; /// <summary> /// IComparer object used for sorting references /// </summary> private class ReferenceComparer : IComparer { private ReferenceConverter _converter; public ReferenceComparer(ReferenceConverter converter) { _converter = converter; } public int Compare(object item1, object item2) { string itemName1 = _converter.ConvertToString(item1); string itemName2 = _converter.ConvertToString(item2); return string.Compare(itemName1, itemName2, false, CultureInfo.InvariantCulture); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.HSSF.Record.Common { using System; using System.IO; using System.Text; using NUnit.Framework; using NPOI.HSSF.Record; using NPOI.HSSF.Record.Cont; using NPOI.Util; /** * Tests that {@link UnicodeString} record size calculates correctly. The record size * is used when serializing {@link SSTRecord}s. * * @author Jason Height (jheight at apache.org) */ [TestFixture] public class TestUnicodeString { private static int MAX_DATA_SIZE = RecordInputStream.MAX_RECORD_DATA_SIZE; /** a 4 character string requiring 16 bit encoding */ private static String STR_16_BIT = "A\u591A\u8A00\u8A9E"; private static void ConfirmSize(int expectedSize, UnicodeString s) { ConfirmSize(expectedSize, s, 0); } /** * Note - a value of zero for <tt>amountUsedInCurrentRecord</tt> would only ever occur just * After a {@link ContinueRecord} had been started. In the Initial {@link SSTRecord} this * value starts at 8 (for the first {@link UnicodeString} written). In general, it can be * any value between 0 and {@link #MAX_DATA_SIZE} */ private static void ConfirmSize(int expectedSize, UnicodeString s, int amountUsedInCurrentRecord) { ContinuableRecordOutput out1 = ContinuableRecordOutput.CreateForCountingOnly(); out1.WriteContinue(); for(int i=amountUsedInCurrentRecord; i>0; i--) { out1.WriteByte(0); } int size0 = out1.TotalSize; s.Serialize(out1); int size1 = out1.TotalSize; int actualSize = size1-size0; Assert.AreEqual(expectedSize, actualSize); } [Test] public void TestSmallStringSize() { //Test a basic string UnicodeString s = MakeUnicodeString("Test"); ConfirmSize(7, s); //Test a small string that is uncompressed s = MakeUnicodeString(STR_16_BIT); s.OptionFlags = (/*setter*/(byte)0x01); ConfirmSize(11, s); //Test a compressed small string that has rich text formatting s.String = (/*setter*/"Test"); s.OptionFlags = (/*setter*/(byte)0x8); UnicodeString.FormatRun r = new UnicodeString.FormatRun((short)0, (short)1); s.AddFormatRun(r); UnicodeString.FormatRun r2 = new UnicodeString.FormatRun((short)2, (short)2); s.AddFormatRun(r2); ConfirmSize(17, s); //Test a uncompressed small string that has rich text formatting s.String = (/*setter*/STR_16_BIT); s.OptionFlags = (/*setter*/(byte)0x9); ConfirmSize(21, s); //Test a compressed small string that has rich text and extended text s.String = (/*setter*/"Test"); s.OptionFlags = (/*setter*/(byte)0xC); ConfirmSize(17, s); // Extended phonetics data // Minimum size is 14 // Also Adds 4 bytes to hold the length s.ExtendedRst=( new UnicodeString.ExtRst() ); ConfirmSize(35, s); //Test a uncompressed small string that has rich text and extended text s.String = (/*setter*/STR_16_BIT); s.OptionFlags = (/*setter*/(byte)0xD); ConfirmSize(39, s); s.ExtendedRst = (/*setter*/null); ConfirmSize(21, s); } [Test] public void TestPerfectStringSize() { //Test a basic string UnicodeString s = MakeUnicodeString(MAX_DATA_SIZE - 2 - 1); ConfirmSize(MAX_DATA_SIZE, s); //Test an uncompressed string //Note that we can only ever Get to a maximim size of 8227 since an uncompressed //string is writing double bytes. s = MakeUnicodeString((MAX_DATA_SIZE - 2 - 1) / 2, true); s.OptionFlags = (/*setter*/(byte)0x1); ConfirmSize(MAX_DATA_SIZE - 1, s); } [Test] public void TestPerfectRichStringSize() { //Test a rich text string UnicodeString s = MakeUnicodeString(MAX_DATA_SIZE - 2 - 1 - 8 - 2); s.AddFormatRun(new UnicodeString.FormatRun((short)1, (short)0)); s.AddFormatRun(new UnicodeString.FormatRun((short)2, (short)1)); s.OptionFlags = (/*setter*/(byte)0x8); ConfirmSize(MAX_DATA_SIZE, s); //Test an uncompressed rich text string //Note that we can only ever Get to a maximum size of 8227 since an uncompressed //string is writing double bytes. s = MakeUnicodeString((MAX_DATA_SIZE - 2 - 1 - 8 - 2) / 2, true); s.AddFormatRun(new UnicodeString.FormatRun((short)1, (short)0)); s.AddFormatRun(new UnicodeString.FormatRun((short)2, (short)1)); s.OptionFlags = (/*setter*/(byte)0x9); ConfirmSize(MAX_DATA_SIZE - 1, s); } [Test] public void TestContinuedStringSize() { //Test a basic string UnicodeString s = MakeUnicodeString(MAX_DATA_SIZE - 2 - 1 + 20); ConfirmSize(MAX_DATA_SIZE + 4 + 1 + 20, s); } /** Tests that a string size calculation that fits neatly in two records, the second being a continue*/ [Test] public void TestPerfectContinuedStringSize() { //Test a basic string int strSize = MAX_DATA_SIZE * 2; //String overhead strSize -= 3; //Continue Record overhead strSize -= 4; //Continue Record Additional byte overhead strSize -= 1; UnicodeString s = MakeUnicodeString(strSize); ConfirmSize(MAX_DATA_SIZE * 2, s); } [Test] public void TestFormatRun() { UnicodeString.FormatRun fr = new UnicodeString.FormatRun((short)4, (short)0x15c); Assert.AreEqual(4, fr.CharacterPos); Assert.AreEqual(0x15c, fr.FontIndex); MemoryStream baos = new MemoryStream(); LittleEndianOutputStream out1 = new LittleEndianOutputStream(baos); fr.Serialize(out1); byte[] b = baos.ToArray(); Assert.AreEqual(4, b.Length); Assert.AreEqual(4, b[0]); Assert.AreEqual(0, b[1]); Assert.AreEqual(0x5c, b[2]); Assert.AreEqual(0x01, b[3]); LittleEndianInputStream inp = new LittleEndianInputStream( new MemoryStream(b) ); fr = new UnicodeString.FormatRun(inp); Assert.AreEqual(4, fr.CharacterPos); Assert.AreEqual(0x15c, fr.FontIndex); } [Test] public void TestExtRstFromEmpty() { UnicodeString.ExtRst ext = new UnicodeString.ExtRst(); Assert.AreEqual(0, ext.NumberOfRuns); Assert.AreEqual(0, ext.FormattingFontIndex); Assert.AreEqual(0, ext.FormattingOptions); Assert.AreEqual("", ext.PhoneticText); Assert.AreEqual(0, ext.PhRuns.Length); Assert.AreEqual(10, ext.DataSize); // Excludes 4 byte header MemoryStream baos = new MemoryStream(); LittleEndianOutputStream out1 = new LittleEndianOutputStream(baos); ContinuableRecordOutput cout = new ContinuableRecordOutput(out1, 0xffff); ext.Serialize(cout); cout.WriteContinue(); byte[] b = baos.ToArray(); Assert.AreEqual(20, b.Length); // First 4 bytes from the outputstream Assert.AreEqual(-1, (sbyte)b[0]); Assert.AreEqual(-1, (sbyte)b[1]); Assert.AreEqual(14, b[2]); Assert.AreEqual(00, b[3]); // Reserved Assert.AreEqual(1, b[4]); Assert.AreEqual(0, b[5]); // Data size Assert.AreEqual(10, b[6]); Assert.AreEqual(00, b[7]); // Font*2 Assert.AreEqual(0, b[8]); Assert.AreEqual(0, b[9]); Assert.AreEqual(0, b[10]); Assert.AreEqual(0, b[11]); // 0 Runs Assert.AreEqual(0, b[12]); Assert.AreEqual(0, b[13]); // Size=0, *2 Assert.AreEqual(0, b[14]); Assert.AreEqual(0, b[15]); Assert.AreEqual(0, b[16]); Assert.AreEqual(0, b[17]); // Last 2 bytes from the outputstream Assert.AreEqual(ContinueRecord.sid, b[18]); Assert.AreEqual(0, b[19]); // Load in again and re-test byte[] data = new byte[14]; Array.Copy(b, 4, data, 0, data.Length); LittleEndianInputStream inp = new LittleEndianInputStream( new MemoryStream(data) ); ext = new UnicodeString.ExtRst(inp, data.Length); Assert.AreEqual(0, ext.NumberOfRuns); Assert.AreEqual(0, ext.FormattingFontIndex); Assert.AreEqual(0, ext.FormattingOptions); Assert.AreEqual("", ext.PhoneticText); Assert.AreEqual(0, ext.PhRuns.Length); } [Test] public void TestExtRstFromData() { byte[] data = new byte[] { 01, 00, 0x0C, 00, 00, 00, 0x37, 00, 00, 00, 00, 00, 00, 00, 00, 00 // Cruft at the end, as found from real files }; Assert.AreEqual(16, data.Length); LittleEndianInputStream inp = new LittleEndianInputStream( new MemoryStream(data) ); UnicodeString.ExtRst ext = new UnicodeString.ExtRst(inp, data.Length); Assert.AreEqual(0x0c, ext.DataSize); // Excludes 4 byte header Assert.AreEqual(0, ext.NumberOfRuns); Assert.AreEqual(0x37, ext.FormattingOptions); Assert.AreEqual(0, ext.FormattingFontIndex); Assert.AreEqual("", ext.PhoneticText); Assert.AreEqual(0, ext.PhRuns.Length); } [Test] public void TestCorruptExtRstDetection() { byte[] data = new byte[] { 0x79, 0x79, 0x11, 0x11, 0x22, 0x22, 0x33, 0x33, }; Assert.AreEqual(8, data.Length); LittleEndianInputStream inp = new LittleEndianInputStream( new MemoryStream(data) ); UnicodeString.ExtRst ext = new UnicodeString.ExtRst(inp, data.Length); // Will be empty Assert.AreEqual(ext, new UnicodeString.ExtRst()); // If written, will be the usual size Assert.AreEqual(10, ext.DataSize); // Excludes 4 byte header // Is empty Assert.AreEqual(0, ext.NumberOfRuns); Assert.AreEqual(0, ext.FormattingOptions); Assert.AreEqual(0, ext.FormattingFontIndex); Assert.AreEqual("", ext.PhoneticText); Assert.AreEqual(0, ext.PhRuns.Length); } private static UnicodeString MakeUnicodeString(String s) { UnicodeString st = new UnicodeString(s); st.OptionFlags = (/*setter*/(byte)0); return st; } private static UnicodeString MakeUnicodeString(int numChars) { return MakeUnicodeString(numChars, false); } /** * @param is16Bit if <code>true</code> the Created string will have characters > 0x00FF * @return a string of the specified number of characters */ private static UnicodeString MakeUnicodeString(int numChars, bool is16Bit) { StringBuilder b = new StringBuilder(numChars); int charBase = is16Bit ? 0x8A00 : 'A'; for (int i = 0; i < numChars; i++) { char ch = (char)((i % 16) + charBase); b.Append(ch); } return MakeUnicodeString(b.ToString()); } } }
/* WinUSBNet library * (C) 2010 Thomas Bleeker (www.madwizard.org) * * Licensed under the MIT license, see license.txt or: * http://www.opensource.org/licenses/mit-license.php */ /* NOTE: Parts of the code in this file are based on the work of Jan Axelson * See http://www.lvr.com/winusb.htm for more information */ using System; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Threading; using System.ComponentModel; namespace MadWizard.WinUSBNet.API { /// <summary> /// Wrapper for a WinUSB device dealing with the WinUSB and additional interface handles /// </summary> partial class WinUSBDevice : IDisposable { private bool _disposed = false; private SafeFileHandle _deviceHandle; private IntPtr _winUsbHandle = IntPtr.Zero; private IntPtr[] _addInterfaces = null; public WinUSBDevice() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~WinUSBDevice() { Dispose(false); } private void CheckNotDisposed() { if (_disposed) throw new ObjectDisposedException("USB device object has been disposed."); } // TODO: check if not disposed on methods (although this is already checked by USBDevice) protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { // Dispose managed resources if (_deviceHandle != null && !_deviceHandle.IsInvalid) _deviceHandle.Dispose(); _deviceHandle = null; } // Dispose unmanaged resources FreeWinUSB(); _disposed = true; } private void FreeWinUSB() { if (_addInterfaces != null) { for (int i = 0; i < _addInterfaces.Length; i++) { WinUsb_Free(_addInterfaces[i]); } _addInterfaces = null; } if (_winUsbHandle != IntPtr.Zero) WinUsb_Free(_winUsbHandle); _winUsbHandle = IntPtr.Zero; } public USB_DEVICE_DESCRIPTOR GetDeviceDescriptor() { USB_DEVICE_DESCRIPTOR deviceDesc; uint transfered; uint size = (uint)Marshal.SizeOf(typeof(USB_DEVICE_DESCRIPTOR)); bool success = WinUsb_GetDescriptor(_winUsbHandle, USB_DEVICE_DESCRIPTOR_TYPE, 0, 0, out deviceDesc, size, out transfered); if (!success) throw APIException.Win32("Failed to get USB device descriptor."); if (transfered != size) throw APIException.Win32("Incomplete USB device descriptor."); return deviceDesc; } public string GetStringDescriptor(byte index) { byte[] buffer = new byte[256]; uint transfered; bool success = WinUsb_GetDescriptor(_winUsbHandle, USB_STRING_DESCRIPTOR_TYPE, index, 0, buffer, (uint)buffer.Length, out transfered); if (!success) throw APIException.Win32("Failed to get USB string descriptor (" + index + ")."); int length = buffer[0] - 2; if (length <= 0) return null; char[] chars = System.Text.Encoding.Unicode.GetChars(buffer, 2, length); return new string(chars); } public void ControlTransfer(byte requestType, byte request, ushort value, ushort index, ushort length, byte[] data) { uint bytesReturned = 0; WINUSB_SETUP_PACKET setupPacket; setupPacket.RequestType = requestType; setupPacket.Request = request; setupPacket.Value = value; setupPacket.Index = index; setupPacket.Length = length; bool success = WinUsb_ControlTransfer(_winUsbHandle, setupPacket, data, length, ref bytesReturned, IntPtr.Zero); if (!success) // todo check bytes returned? throw APIException.Win32("Control transfer on WinUSB device failed."); } public void OpenDevice(string devicePathName) { try { _deviceHandle = FileIO.CreateFile(devicePathName, (FileIO.GENERIC_WRITE | FileIO.GENERIC_READ), FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, FileIO.FILE_ATTRIBUTE_NORMAL | FileIO.FILE_FLAG_OVERLAPPED, 0); if (_deviceHandle.IsInvalid) throw APIException.Win32("Failed to open WinUSB device handle."); InitializeDevice(); } catch(Exception) { if (_deviceHandle != null) { _deviceHandle.Dispose(); _deviceHandle = null; } FreeWinUSB(); throw; } } private IntPtr InterfaceHandle(int index) { if (index == 0) return _winUsbHandle; return _addInterfaces[index - 1]; } public int InterfaceCount { get { return 1 + (_addInterfaces == null ? 0 : _addInterfaces.Length); } } public void GetInterfaceInfo(int interfaceIndex, out USB_INTERFACE_DESCRIPTOR descriptor, out WINUSB_PIPE_INFORMATION[] pipes) { var pipeList = new List<WINUSB_PIPE_INFORMATION>(); bool success = WinUsb_QueryInterfaceSettings(InterfaceHandle(interfaceIndex), 0, out descriptor); if (!success) throw APIException.Win32("Failed to get WinUSB device interface descriptor."); IntPtr interfaceHandle = InterfaceHandle(interfaceIndex); for (byte pipeIdx = 0; pipeIdx < descriptor.bNumEndpoints; pipeIdx++) { WINUSB_PIPE_INFORMATION pipeInfo; success = WinUsb_QueryPipe(interfaceHandle, 0, pipeIdx, out pipeInfo); pipeList.Add(pipeInfo); if (!success) throw APIException.Win32("Failed to get WinUSB device pipe information."); } pipes = pipeList.ToArray(); } private void InitializeDevice() { bool success; success = WinUsb_Initialize(_deviceHandle, ref _winUsbHandle); if (!success) throw APIException.Win32("Failed to initialize WinUSB handle. Device might not be connected."); List<IntPtr> interfaces = new List<IntPtr>(); byte numAddInterfaces = 0; byte idx = 0; try { while (true) { IntPtr ifaceHandle = IntPtr.Zero; success = WinUsb_GetAssociatedInterface(_winUsbHandle, idx, out ifaceHandle); if (!success) { if (Marshal.GetLastWin32Error() == ERROR_NO_MORE_ITEMS) break; throw APIException.Win32("Failed to enumerate interfaces for WinUSB device."); } interfaces.Add(ifaceHandle); idx++; numAddInterfaces++; } } finally { // Save interface handles (will be cleaned by Dispose) // also in case of exception (which is why it is in finally block), // because some handles might have already been opened and need // to be disposed. _addInterfaces = interfaces.ToArray(); } // Bind handle (needed for overlapped I/O thread pool) ThreadPool.BindHandle(_deviceHandle); // TODO: bind interface handles as well? doesn't seem to be necessary } public void ReadPipe(int ifaceIndex, byte pipeID, byte[] buffer, int offset, int bytesToRead, out uint bytesRead) { bool success; unsafe { fixed (byte* pBuffer = buffer) { success = WinUsb_ReadPipe(InterfaceHandle(ifaceIndex), pipeID, pBuffer + offset, (uint)bytesToRead, out bytesRead, IntPtr.Zero); } } if (!success) throw APIException.Win32("Failed to read pipe on WinUSB device."); } private unsafe void HandleOverlappedAPI(bool success, string errorMessage, NativeOverlapped* pOverlapped, USBAsyncResult result, int bytesTransfered) { if (!success) { if (Marshal.GetLastWin32Error() != FileIO.ERROR_IO_PENDING) { Overlapped.Unpack(pOverlapped); Overlapped.Free(pOverlapped); throw APIException.Win32(errorMessage); } } else { // Immediate success! Overlapped.Unpack(pOverlapped); Overlapped.Free(pOverlapped); result.OnCompletion(true, null, bytesTransfered, false); // is the callback still called in this case?? todo } } public void ReadPipeOverlapped(int ifaceIndex, byte pipeID, byte[] buffer, int offset, int bytesToRead, USBAsyncResult result) { Overlapped overlapped = new Overlapped(); overlapped.AsyncResult = result; unsafe { NativeOverlapped* pOverlapped = null; uint bytesRead; pOverlapped = overlapped.Pack(PipeIOCallback, buffer); bool success; // Buffer is pinned already by overlapped.Pack fixed (byte* pBuffer = buffer) { success = WinUsb_ReadPipe(InterfaceHandle(ifaceIndex), pipeID, pBuffer + offset, (uint)bytesToRead, out bytesRead, pOverlapped); } HandleOverlappedAPI(success, "Failed to asynchronously read pipe on WinUSB device.", pOverlapped, result, (int)bytesRead); } } public void WriteOverlapped(int ifaceIndex, byte pipeID, byte[] buffer, int offset, int bytesToWrite, USBAsyncResult result) { Overlapped overlapped = new Overlapped(); overlapped.AsyncResult = result; unsafe { NativeOverlapped* pOverlapped = null; uint bytesWritten; pOverlapped = overlapped.Pack(PipeIOCallback, buffer); bool success; // Buffer is pinned already by overlapped.Pack fixed (byte* pBuffer = buffer) { success = WinUsb_WritePipe(InterfaceHandle(ifaceIndex), pipeID, pBuffer + offset, (uint)bytesToWrite, out bytesWritten, pOverlapped); } HandleOverlappedAPI(success, "Failed to asynchronously write pipe on WinUSB device.", pOverlapped, result, (int)bytesWritten); } } public void ControlTransferOverlapped(byte requestType, byte request, ushort value, ushort index, ushort length, byte[] data, USBAsyncResult result) { uint bytesReturned = 0; WINUSB_SETUP_PACKET setupPacket; setupPacket.RequestType = requestType; setupPacket.Request = request; setupPacket.Value = value; setupPacket.Index = index; setupPacket.Length = length; Overlapped overlapped = new Overlapped(); overlapped.AsyncResult = result; unsafe { NativeOverlapped* pOverlapped = null; pOverlapped = overlapped.Pack(PipeIOCallback, data); bool success = WinUsb_ControlTransfer(_winUsbHandle, setupPacket, data, length, ref bytesReturned, pOverlapped); HandleOverlappedAPI(success, "Asynchronous control transfer on WinUSB device failed.", pOverlapped, result, (int)bytesReturned); } } private unsafe void PipeIOCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped) { try { Exception error = null; if (errorCode != 0) { error = APIException.Win32("Asynchronous operation on WinUSB device failed.", (int)errorCode); } Overlapped overlapped = Overlapped.Unpack(pOverlapped); USBAsyncResult result = (USBAsyncResult)overlapped.AsyncResult; Overlapped.Free(pOverlapped); pOverlapped = null; result.OnCompletion(false, error, (int)numBytes, true); } finally { if (pOverlapped != null) { Overlapped.Unpack(pOverlapped); Overlapped.Free(pOverlapped); } } } public void AbortPipe(int ifaceIndex, byte pipeID) { bool success = WinUsb_AbortPipe(InterfaceHandle(ifaceIndex), pipeID); if (!success) throw APIException.Win32("Failed to abort pipe on WinUSB device."); } public void WritePipe(int ifaceIndex, byte pipeID, byte[] buffer, int offset, int length) { uint bytesWritten; bool success; unsafe { fixed (byte* pBuffer = buffer) { success = WinUsb_WritePipe(InterfaceHandle(ifaceIndex), pipeID, pBuffer + offset, (uint)length, out bytesWritten, IntPtr.Zero); } } if (!success || (bytesWritten != length)) throw APIException.Win32("Failed to write pipe on WinUSB device."); } public void FlushPipe(int ifaceIndex, byte pipeID) { bool success = WinUsb_FlushPipe(InterfaceHandle(ifaceIndex), pipeID); if (!success) throw APIException.Win32("Failed to flush pipe on WinUSB device."); } public void SetPipePolicy(int ifaceIndex, byte pipeID, POLICY_TYPE policyType, bool value) { byte byteVal = (byte)(value ? 1 : 0); bool success = WinUsb_SetPipePolicy(InterfaceHandle(ifaceIndex), pipeID, (uint)policyType, 1, ref byteVal); if (!success) throw APIException.Win32("Failed to set WinUSB pipe policy."); } public void SetPipePolicy(int ifaceIndex, byte pipeID, POLICY_TYPE policyType, uint value) { bool success = WinUsb_SetPipePolicy(InterfaceHandle(ifaceIndex), pipeID, (uint)policyType, 4, ref value); if (!success) throw APIException.Win32("Failed to set WinUSB pipe policy."); } public bool GetPipePolicyBool(int ifaceIndex, byte pipeID, POLICY_TYPE policyType) { byte result; uint length = 1; bool success = WinUsb_GetPipePolicy(InterfaceHandle(ifaceIndex), pipeID, (uint)policyType, ref length, out result); if (!success || length != 1) throw APIException.Win32("Failed to get WinUSB pipe policy."); return result != 0; } public uint GetPipePolicyUInt(int ifaceIndex, byte pipeID, POLICY_TYPE policyType) { uint result; uint length = 4; bool success = WinUsb_GetPipePolicy(InterfaceHandle(ifaceIndex), pipeID, (uint)policyType, ref length, out result); if (!success || length != 4) throw APIException.Win32("Failed to get WinUSB pipe policy."); return result; } } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * API Version: 2006-03-01 * */ using System; using System.Collections.Specialized; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.S3.Util; namespace Amazon.S3.Model { /// <summary> /// Base class for all S3 operation responses. /// Provides a header collection which is used to store the response headers. /// Also exposes the RequestId and AmazonId2 from S3 responses, as well as a /// Response Stream is the operation returned a stream. /// Lastly, if the response contained metadata, they are stored in the Metadata /// collection. /// </summary> public class S3Response : IDisposable { #region Private Members /// <summary> /// web headers for all requests. /// </summary> private WebHeaderCollection webHeaders; private NameValueCollection metadata; private Stream responseStream; internal HttpWebResponse httpResponse; private bool disposed; private string requestId; private string amazonId2; private string responseXml; #endregion #region Dispose Pattern /// <summary> /// Disposes of all managed and unmanaged resources. /// </summary> public void Dispose() { Dispose(true); if (!this.disposed) { GC.SuppressFinalize(this); } } private void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { //Remove Managed Resources if (webHeaders != null) { webHeaders.Clear(); } } // Remove Unmanaged Resources // I.O.W. remove resources that have to be explicitly // "Dispose"d or Closed. For an S3 Response, these are: // 1. The Response Stream for GET Object requests // 2. The HttpResponse object for GET Object requests if (responseStream != null) { responseStream.Close(); responseStream = null; } if (httpResponse != null) { httpResponse.Close(); httpResponse = null; } disposed = true; } } /// <summary> /// The destructor for the S3Response class. /// </summary> ~S3Response() { Dispose(false); } #endregion #region RequestId /// <summary> /// Gets and sets the RequestId property. /// </summary> [XmlElementAttribute(ElementName = "RequestId")] public string RequestId { get { return this.requestId; } set { this.requestId = value; } } #endregion #region AmazonId2 /// <summary> /// Gets and sets the AmazonId2 property. /// This property corresponds to the x-amz-id-2 header in the HTTP response from the Amazon S3 service. The value of this header is used for internal troubleshooting purposes. /// </summary> [XmlElementAttribute(ElementName = "AmazonId2")] public string AmazonId2 { get { return this.amazonId2; } set { this.amazonId2 = value; } } #endregion #region ResponseStream /// <summary> /// Gets and sets the ResponseStream property. This property /// only has a valid value for GetObjectResponses. In order to /// use this stream without leaking the underlying resource, please /// wrap access to the stream within a using block. /// <code></code> /// </summary> [XmlElementAttribute(ElementName = "ResponseStream")] public Stream ResponseStream { get { return this.responseStream; } set { this.responseStream = value; } } #endregion #region Headers /// <summary> /// Gets and sets the Headers property. /// Information like the request-id, the amz-id-2 are /// retrieved fro the Headers and presented to the user /// via properties of the response object. /// </summary> [XmlIgnore] public virtual WebHeaderCollection Headers { get { if (this.webHeaders == null) { this.webHeaders = new WebHeaderCollection(); } return this.webHeaders; } set { this.webHeaders = value; string hdr; if (!String.IsNullOrEmpty(hdr = value.Get(S3Constants.AmzRequestIdHeader))) { RequestId = hdr; } if (!String.IsNullOrEmpty(hdr = value.Get(S3Constants.AmzId2Header))) { AmazonId2 = hdr; } foreach (string key in value.Keys) { if (key.StartsWith("x-amz-meta-")) { Metadata.Add(key, value.Get(key)); } } } } #endregion #region Metadata /// <summary> /// Gets and sets the Metadata property. /// </summary> [XmlIgnore] public NameValueCollection Metadata { get { if (this.metadata == null) { this.metadata = new NameValueCollection(); } return this.metadata; } } #endregion #region ResponseXml /// <summary> /// Gets and sets the ResponseXml property. This is the /// original xml response received from S3 /// </summary> [XmlIgnore] public string ResponseXml { get { return this.responseXml; } set { this.responseXml = value; } } #endregion #region StatusCode /// <summary> /// Gets the HTTP Status code from the service response. /// </summary> [XmlIgnore] public HttpStatusCode StatusCode { get { return this.httpResponse.StatusCode; } } #endregion #region Public Methods /// <summary> /// String Representation of this object. Overrides Object.ToString() /// </summary> /// <returns>This object as a string</returns> public override string ToString() { StringBuilder xml = new StringBuilder(1024); XmlSerializer serializer = new XmlSerializer(this.GetType()); using (StringWriter sw = new StringWriter(xml)) { serializer.Serialize(sw, this); } return xml.ToString(); } #endregion #region ProcessResponseBody /// <summary> /// A blank virtual method to allow sub classes to provide /// custom response body parsing. /// </summary> /// <param name="responseBody">The response from a request to S3</param> internal virtual void ProcessResponseBody(string responseBody) { } #endregion } }
/**************************************************************************** Copyright (c) 2013-2015 scutgame.com http://www.scutgame.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using ZyGames.Framework.Collection.Generic; using ZyGames.Framework.Common; using ZyGames.Framework.Common.Reflect; using ZyGames.Framework.Model; using ZyGames.Framework.Event; using ZyGames.Framework.Common.Log; using ZyGames.Framework.RPC.IO; namespace ZyGames.Framework.Game.Contract { /// <summary> /// The entity sync data operation. /// </summary> public static class EntitySyncManger { private const int SyncActionId = 200; private static DictionaryExtend<string, bool> _syncPools; private static ConcurrentQueue<BaseEntity> _sendQueue; private static Thread _queueProcessThread; private static ManualResetEvent singal = new ManualResetEvent(false); private static int _runningQueue; internal static event Func<int, byte[], bool> SendHandle; static EntitySyncManger() { _syncPools = new DictionaryExtend<string, bool>(); _sendQueue = new ConcurrentQueue<BaseEntity>(); Interlocked.Exchange(ref _runningQueue, 1); _queueProcessThread = new Thread(ProcessQueue); _queueProcessThread.Start(); } /// <summary> /// Dispose /// </summary> public static void Dispose() { Interlocked.Exchange(ref _runningQueue, 0); try { singal.Set(); singal.Dispose(); _queueProcessThread.Abort(); } catch { } } /// <summary> /// entity data send to client /// </summary> /// <param name="sender"></param> /// <param name="eventargs"></param> public static void OnChange(AbstractEntity sender, CacheItemEventArgs eventargs) { try { if (sender == null || (sender as BaseEntity) == null || !sender.GetSchema().IsEntitySync) { return; } string key = sender.GetKeyCode(); if (!_syncPools.ContainsKey(key)) { _syncPools[key] = true; _sendQueue.Enqueue(sender as BaseEntity); singal.Set(); } } catch (Exception ex) { TraceLog.WriteError("EntitySync Notify error:{0}", ex); } } private static void ProcessQueue(object state) { while (_runningQueue == 1) { singal.WaitOne(); if (_runningQueue == 1) { Thread.Sleep(100);//Delay 100ms } while (_runningQueue == 1) { BaseEntity entity; if (_sendQueue.TryDequeue(out entity)) { string key = entity.GetKeyCode(); byte[] buffer = DoSerialize(entity); _syncPools.Remove(key); DoSend(entity.PersonalId, buffer); } else { break; } } singal.Reset(); } } private static void DoSend(string personalId, byte[] buffer) { if (buffer == null) return; if (SendHandle != null) { SendHandle(personalId.ToInt(), buffer); } } private static byte[] DoSerialize(params BaseEntity[] entityList) { var rootWriter = new MessageStructure(); rootWriter.PushIntoStack(entityList.Length); object fieldValue = null; foreach (var entity in entityList) { var schema = entity.GetSchema(); if (schema == null) { continue; } var recordWriter = new MessageStructure(); recordWriter.PushIntoStack(schema.Name); //write columns var columns = schema.GetColumns(); foreach (var column in columns) { fieldValue = entity.GetPropertyValue(column.Name); if (EntitySchemaSet.IsSupportType(column.ColumnType)) { recordWriter.PushIntoStack(column.ColumnType, fieldValue); } else if (column.HasChild) { PushChildStack(recordWriter, column, fieldValue); } } rootWriter.PushIntoStack(recordWriter); } var head = new MessageHead(SyncActionId); rootWriter.WriteBuffer(head); return rootWriter.PopBuffer(); } private static void PushChildStack(MessageStructure parent, SchemaColumn parentColumn, object value) { if (parentColumn.IsDictionary) { var column = parentColumn.Children[1]; dynamic dict = value; dynamic keys = dict.Keys; int count = dict.Count; parent.PushIntoStack(count); foreach (var key in keys) { object item = dict[key]; var itemWriter = new MessageStructure(); itemWriter.PushIntoStack(key); if (EntitySchemaSet.IsSupportType(column.ColumnType)) { itemWriter.PushIntoStack(column.ColumnType, item); } else if (column.HasChild) { PushChildStack(itemWriter, column, item); } parent.PushIntoStack(itemWriter); } } else if (parentColumn.IsList) { var column = parentColumn.Children[0]; dynamic list = value; int count = list.Count; parent.PushIntoStack(count); foreach (var item in list) { var itemWriter = new MessageStructure(); if (EntitySchemaSet.IsSupportType(column.ColumnType)) { itemWriter.PushIntoStack(column.ColumnType, item); } else if (column.HasChild) { PushChildStack(itemWriter, column, item); } parent.PushIntoStack(itemWriter); } } else { //child entity object parent.PushIntoStack(1); var typeAccessor = ObjectAccessor.Create(value, true); var itemWriter = new MessageStructure(); foreach (var column in parentColumn.Children) { try { var fieldValue = typeAccessor[column.Name]; if (EntitySchemaSet.IsSupportType(column.ColumnType)) { itemWriter.PushIntoStack(column.ColumnType, fieldValue); } else if (column.HasChild) { PushChildStack(itemWriter, column, fieldValue); } } catch { } } parent.PushIntoStack(itemWriter); } } } }
// // 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.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for automation dsc node configurations. (see /// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more /// information) /// </summary> internal partial class DscNodeConfigurationOperations : IServiceOperations<AutomationManagementClient>, IDscNodeConfigurationOperations { /// <summary> /// Initializes a new instance of the DscNodeConfigurationOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DscNodeConfigurationOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Retrieve the Dsc node configurations by node configuration. (see /// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='nodeConfigurationName'> /// Required. The Dsc node configuration name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get Dsc node configuration operation. /// </returns> public async Task<DscNodeConfigurationGetResponse> GetAsync(string resourceGroupName, string automationAccount, string nodeConfigurationName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (nodeConfigurationName == null) { throw new ArgumentNullException("nodeConfigurationName"); } // 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("automationAccount", automationAccount); tracingParameters.Add("nodeConfigurationName", nodeConfigurationName); 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/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/nodeConfigurations/"; url = url + Uri.EscapeDataString(nodeConfigurationName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // 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 DscNodeConfigurationGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeConfigurationGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DscNodeConfiguration nodeConfigurationInstance = new DscNodeConfiguration(); result.NodeConfiguration = nodeConfigurationInstance; JToken configurationNameValue = responseDoc["configurationName"]; if (configurationNameValue != null && configurationNameValue.Type != JTokenType.Null) { string configurationNameInstance = ((string)configurationNameValue); nodeConfigurationInstance.Name = configurationNameInstance; } JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); nodeConfigurationInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken creationTimeValue = responseDoc["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); nodeConfigurationInstance.CreationTime = creationTimeInstance; } JToken configurationValue = responseDoc["configuration"]; if (configurationValue != null && configurationValue.Type != JTokenType.Null) { DscConfigurationAssociationProperty configurationInstance = new DscConfigurationAssociationProperty(); nodeConfigurationInstance.Configuration = configurationInstance; JToken nameValue = configurationValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); configurationInstance.Name = nameInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); nodeConfigurationInstance.Id = idInstance; } JToken nameValue2 = responseDoc["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); nodeConfigurationInstance.Name = nameInstance2; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); nodeConfigurationInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); nodeConfigurationInstance.Tags.Add(tagsKey, tagsValue); } } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); nodeConfigurationInstance.Type = typeInstance; } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); nodeConfigurationInstance.Etag = etagInstance; } } } 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> /// Retrieve a list of dsc node configurations. (see /// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Optional. The parameters supplied to the list operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list job operation. /// </returns> public async Task<DscNodeConfigurationListResponse> ListAsync(string resourceGroupName, string automationAccount, DscNodeConfigurationListParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // 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("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/nodeConfigurations"; List<string> queryParameters = new List<string>(); List<string> odataFilter = new List<string>(); if (parameters != null && parameters.ConfigurationName != null) { odataFilter.Add("configuration/name eq '" + Uri.EscapeDataString(parameters.ConfigurationName) + "'"); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // 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 DscNodeConfigurationListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeConfigurationListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DscNodeConfiguration dscNodeConfigurationInstance = new DscNodeConfiguration(); result.DscNodeConfigurations.Add(dscNodeConfigurationInstance); JToken configurationNameValue = valueValue["configurationName"]; if (configurationNameValue != null && configurationNameValue.Type != JTokenType.Null) { string configurationNameInstance = ((string)configurationNameValue); dscNodeConfigurationInstance.Name = configurationNameInstance; } JToken lastModifiedTimeValue = valueValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); dscNodeConfigurationInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken creationTimeValue = valueValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); dscNodeConfigurationInstance.CreationTime = creationTimeInstance; } JToken configurationValue = valueValue["configuration"]; if (configurationValue != null && configurationValue.Type != JTokenType.Null) { DscConfigurationAssociationProperty configurationInstance = new DscConfigurationAssociationProperty(); dscNodeConfigurationInstance.Configuration = configurationInstance; JToken nameValue = configurationValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); configurationInstance.Name = nameInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dscNodeConfigurationInstance.Id = idInstance; } JToken nameValue2 = valueValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); dscNodeConfigurationInstance.Name = nameInstance2; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dscNodeConfigurationInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); dscNodeConfigurationInstance.Tags.Add(tagsKey, tagsValue); } } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); dscNodeConfigurationInstance.Type = typeInstance; } JToken etagValue = valueValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); dscNodeConfigurationInstance.Etag = etagInstance; } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve next list of dsc node configrations. (see /// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more /// information) /// </summary> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list job operation. /// </returns> public async Task<DscNodeConfigurationListResponse> 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 httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // 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 DscNodeConfigurationListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeConfigurationListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DscNodeConfiguration dscNodeConfigurationInstance = new DscNodeConfiguration(); result.DscNodeConfigurations.Add(dscNodeConfigurationInstance); JToken configurationNameValue = valueValue["configurationName"]; if (configurationNameValue != null && configurationNameValue.Type != JTokenType.Null) { string configurationNameInstance = ((string)configurationNameValue); dscNodeConfigurationInstance.Name = configurationNameInstance; } JToken lastModifiedTimeValue = valueValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); dscNodeConfigurationInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken creationTimeValue = valueValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); dscNodeConfigurationInstance.CreationTime = creationTimeInstance; } JToken configurationValue = valueValue["configuration"]; if (configurationValue != null && configurationValue.Type != JTokenType.Null) { DscConfigurationAssociationProperty configurationInstance = new DscConfigurationAssociationProperty(); dscNodeConfigurationInstance.Configuration = configurationInstance; JToken nameValue = configurationValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); configurationInstance.Name = nameInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dscNodeConfigurationInstance.Id = idInstance; } JToken nameValue2 = valueValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); dscNodeConfigurationInstance.Name = nameInstance2; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dscNodeConfigurationInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); dscNodeConfigurationInstance.Tags.Add(tagsKey, tagsValue); } } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); dscNodeConfigurationInstance.Type = typeInstance; } JToken etagValue = valueValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); dscNodeConfigurationInstance.Etag = etagInstance; } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Framework.WebServices.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// A storage manager plugin /// First published in XenServer 4.0. /// </summary> public partial class SM : XenObject<SM> { #region Constructors public SM() { } public SM(string uuid, string name_label, string name_description, string type, string vendor, string copyright, string version, string required_api_version, Dictionary<string, string> configuration, string[] capabilities, Dictionary<string, long> features, Dictionary<string, string> other_config, string driver_filename, string[] required_cluster_stack) { this.uuid = uuid; this.name_label = name_label; this.name_description = name_description; this.type = type; this.vendor = vendor; this.copyright = copyright; this.version = version; this.required_api_version = required_api_version; this.configuration = configuration; this.capabilities = capabilities; this.features = features; this.other_config = other_config; this.driver_filename = driver_filename; this.required_cluster_stack = required_cluster_stack; } /// <summary> /// Creates a new SM from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public SM(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new SM from a Proxy_SM. /// </summary> /// <param name="proxy"></param> public SM(Proxy_SM proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given SM. /// </summary> public override void UpdateFrom(SM record) { uuid = record.uuid; name_label = record.name_label; name_description = record.name_description; type = record.type; vendor = record.vendor; copyright = record.copyright; version = record.version; required_api_version = record.required_api_version; configuration = record.configuration; capabilities = record.capabilities; features = record.features; other_config = record.other_config; driver_filename = record.driver_filename; required_cluster_stack = record.required_cluster_stack; } internal void UpdateFrom(Proxy_SM proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; name_label = proxy.name_label == null ? null : proxy.name_label; name_description = proxy.name_description == null ? null : proxy.name_description; type = proxy.type == null ? null : proxy.type; vendor = proxy.vendor == null ? null : proxy.vendor; copyright = proxy.copyright == null ? null : proxy.copyright; version = proxy.version == null ? null : proxy.version; required_api_version = proxy.required_api_version == null ? null : proxy.required_api_version; configuration = proxy.configuration == null ? null : Maps.convert_from_proxy_string_string(proxy.configuration); capabilities = proxy.capabilities == null ? new string[] {} : (string [])proxy.capabilities; features = proxy.features == null ? null : Maps.convert_from_proxy_string_long(proxy.features); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); driver_filename = proxy.driver_filename == null ? null : proxy.driver_filename; required_cluster_stack = proxy.required_cluster_stack == null ? new string[] {} : (string [])proxy.required_cluster_stack; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this SM /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("name_label")) name_label = Marshalling.ParseString(table, "name_label"); if (table.ContainsKey("name_description")) name_description = Marshalling.ParseString(table, "name_description"); if (table.ContainsKey("type")) type = Marshalling.ParseString(table, "type"); if (table.ContainsKey("vendor")) vendor = Marshalling.ParseString(table, "vendor"); if (table.ContainsKey("copyright")) copyright = Marshalling.ParseString(table, "copyright"); if (table.ContainsKey("version")) version = Marshalling.ParseString(table, "version"); if (table.ContainsKey("required_api_version")) required_api_version = Marshalling.ParseString(table, "required_api_version"); if (table.ContainsKey("configuration")) configuration = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "configuration")); if (table.ContainsKey("capabilities")) capabilities = Marshalling.ParseStringArray(table, "capabilities"); if (table.ContainsKey("features")) features = Maps.convert_from_proxy_string_long(Marshalling.ParseHashTable(table, "features")); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("driver_filename")) driver_filename = Marshalling.ParseString(table, "driver_filename"); if (table.ContainsKey("required_cluster_stack")) required_cluster_stack = Marshalling.ParseStringArray(table, "required_cluster_stack"); } public Proxy_SM ToProxy() { Proxy_SM result_ = new Proxy_SM(); result_.uuid = uuid ?? ""; result_.name_label = name_label ?? ""; result_.name_description = name_description ?? ""; result_.type = type ?? ""; result_.vendor = vendor ?? ""; result_.copyright = copyright ?? ""; result_.version = version ?? ""; result_.required_api_version = required_api_version ?? ""; result_.configuration = Maps.convert_to_proxy_string_string(configuration); result_.capabilities = capabilities; result_.features = Maps.convert_to_proxy_string_long(features); result_.other_config = Maps.convert_to_proxy_string_string(other_config); result_.driver_filename = driver_filename ?? ""; result_.required_cluster_stack = required_cluster_stack; return result_; } public bool DeepEquals(SM other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._name_label, other._name_label) && Helper.AreEqual2(this._name_description, other._name_description) && Helper.AreEqual2(this._type, other._type) && Helper.AreEqual2(this._vendor, other._vendor) && Helper.AreEqual2(this._copyright, other._copyright) && Helper.AreEqual2(this._version, other._version) && Helper.AreEqual2(this._required_api_version, other._required_api_version) && Helper.AreEqual2(this._configuration, other._configuration) && Helper.AreEqual2(this._capabilities, other._capabilities) && Helper.AreEqual2(this._features, other._features) && Helper.AreEqual2(this._other_config, other._other_config) && Helper.AreEqual2(this._driver_filename, other._driver_filename) && Helper.AreEqual2(this._required_cluster_stack, other._required_cluster_stack); } public override string SaveChanges(Session session, string opaqueRef, SM server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { SM.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given SM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static SM get_record(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_record(session.opaque_ref, _sm); else return new SM(session.XmlRpcProxy.sm_get_record(session.opaque_ref, _sm ?? "").parse()); } /// <summary> /// Get a reference to the SM instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<SM> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<SM>.Create(session.XmlRpcProxy.sm_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get all the SM instances with the given label. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_label">label of object to return</param> public static List<XenRef<SM>> get_by_name_label(Session session, string _label) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_by_name_label(session.opaque_ref, _label); else return XenRef<SM>.Create(session.XmlRpcProxy.sm_get_by_name_label(session.opaque_ref, _label ?? "").parse()); } /// <summary> /// Get the uuid field of the given SM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static string get_uuid(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_uuid(session.opaque_ref, _sm); else return session.XmlRpcProxy.sm_get_uuid(session.opaque_ref, _sm ?? "").parse(); } /// <summary> /// Get the name/label field of the given SM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static string get_name_label(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_name_label(session.opaque_ref, _sm); else return session.XmlRpcProxy.sm_get_name_label(session.opaque_ref, _sm ?? "").parse(); } /// <summary> /// Get the name/description field of the given SM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static string get_name_description(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_name_description(session.opaque_ref, _sm); else return session.XmlRpcProxy.sm_get_name_description(session.opaque_ref, _sm ?? "").parse(); } /// <summary> /// Get the type field of the given SM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static string get_type(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_type(session.opaque_ref, _sm); else return session.XmlRpcProxy.sm_get_type(session.opaque_ref, _sm ?? "").parse(); } /// <summary> /// Get the vendor field of the given SM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static string get_vendor(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_vendor(session.opaque_ref, _sm); else return session.XmlRpcProxy.sm_get_vendor(session.opaque_ref, _sm ?? "").parse(); } /// <summary> /// Get the copyright field of the given SM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static string get_copyright(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_copyright(session.opaque_ref, _sm); else return session.XmlRpcProxy.sm_get_copyright(session.opaque_ref, _sm ?? "").parse(); } /// <summary> /// Get the version field of the given SM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static string get_version(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_version(session.opaque_ref, _sm); else return session.XmlRpcProxy.sm_get_version(session.opaque_ref, _sm ?? "").parse(); } /// <summary> /// Get the required_api_version field of the given SM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static string get_required_api_version(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_required_api_version(session.opaque_ref, _sm); else return session.XmlRpcProxy.sm_get_required_api_version(session.opaque_ref, _sm ?? "").parse(); } /// <summary> /// Get the configuration field of the given SM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static Dictionary<string, string> get_configuration(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_configuration(session.opaque_ref, _sm); else return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.sm_get_configuration(session.opaque_ref, _sm ?? "").parse()); } /// <summary> /// Get the capabilities field of the given SM. /// First published in XenServer 4.0. /// Deprecated since XenServer 6.2. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> [Deprecated("XenServer 6.2")] public static string[] get_capabilities(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_capabilities(session.opaque_ref, _sm); else return (string [])session.XmlRpcProxy.sm_get_capabilities(session.opaque_ref, _sm ?? "").parse(); } /// <summary> /// Get the features field of the given SM. /// First published in XenServer 6.2. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static Dictionary<string, long> get_features(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_features(session.opaque_ref, _sm); else return Maps.convert_from_proxy_string_long(session.XmlRpcProxy.sm_get_features(session.opaque_ref, _sm ?? "").parse()); } /// <summary> /// Get the other_config field of the given SM. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static Dictionary<string, string> get_other_config(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_other_config(session.opaque_ref, _sm); else return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.sm_get_other_config(session.opaque_ref, _sm ?? "").parse()); } /// <summary> /// Get the driver_filename field of the given SM. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static string get_driver_filename(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_driver_filename(session.opaque_ref, _sm); else return session.XmlRpcProxy.sm_get_driver_filename(session.opaque_ref, _sm ?? "").parse(); } /// <summary> /// Get the required_cluster_stack field of the given SM. /// First published in XenServer 7.0. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> public static string[] get_required_cluster_stack(Session session, string _sm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_required_cluster_stack(session.opaque_ref, _sm); else return (string [])session.XmlRpcProxy.sm_get_required_cluster_stack(session.opaque_ref, _sm ?? "").parse(); } /// <summary> /// Set the other_config field of the given SM. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _sm, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.sm_set_other_config(session.opaque_ref, _sm, _other_config); else session.XmlRpcProxy.sm_set_other_config(session.opaque_ref, _sm ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given SM. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _sm, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.sm_add_to_other_config(session.opaque_ref, _sm, _key, _value); else session.XmlRpcProxy.sm_add_to_other_config(session.opaque_ref, _sm ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given SM. If the key is not in that Map, then do nothing. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_sm">The opaque_ref of the given sm</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _sm, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.sm_remove_from_other_config(session.opaque_ref, _sm, _key); else session.XmlRpcProxy.sm_remove_from_other_config(session.opaque_ref, _sm ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the SMs known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<SM>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_all(session.opaque_ref); else return XenRef<SM>.Create(session.XmlRpcProxy.sm_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the SM Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<SM>, SM> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.sm_get_all_records(session.opaque_ref); else return XenRef<SM>.Create<Proxy_SM>(session.XmlRpcProxy.sm_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// a human-readable name /// </summary> public virtual string name_label { get { return _name_label; } set { if (!Helper.AreEqual(value, _name_label)) { _name_label = value; NotifyPropertyChanged("name_label"); } } } private string _name_label = ""; /// <summary> /// a notes field containing human-readable description /// </summary> public virtual string name_description { get { return _name_description; } set { if (!Helper.AreEqual(value, _name_description)) { _name_description = value; NotifyPropertyChanged("name_description"); } } } private string _name_description = ""; /// <summary> /// SR.type /// </summary> public virtual string type { get { return _type; } set { if (!Helper.AreEqual(value, _type)) { _type = value; NotifyPropertyChanged("type"); } } } private string _type = ""; /// <summary> /// Vendor who created this plugin /// </summary> public virtual string vendor { get { return _vendor; } set { if (!Helper.AreEqual(value, _vendor)) { _vendor = value; NotifyPropertyChanged("vendor"); } } } private string _vendor = ""; /// <summary> /// Entity which owns the copyright of this plugin /// </summary> public virtual string copyright { get { return _copyright; } set { if (!Helper.AreEqual(value, _copyright)) { _copyright = value; NotifyPropertyChanged("copyright"); } } } private string _copyright = ""; /// <summary> /// Version of the plugin /// </summary> public virtual string version { get { return _version; } set { if (!Helper.AreEqual(value, _version)) { _version = value; NotifyPropertyChanged("version"); } } } private string _version = ""; /// <summary> /// Minimum SM API version required on the server /// </summary> public virtual string required_api_version { get { return _required_api_version; } set { if (!Helper.AreEqual(value, _required_api_version)) { _required_api_version = value; NotifyPropertyChanged("required_api_version"); } } } private string _required_api_version = ""; /// <summary> /// names and descriptions of device config keys /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> configuration { get { return _configuration; } set { if (!Helper.AreEqual(value, _configuration)) { _configuration = value; NotifyPropertyChanged("configuration"); } } } private Dictionary<string, string> _configuration = new Dictionary<string, string>() {}; /// <summary> /// capabilities of the SM plugin /// </summary> public virtual string[] capabilities { get { return _capabilities; } set { if (!Helper.AreEqual(value, _capabilities)) { _capabilities = value; NotifyPropertyChanged("capabilities"); } } } private string[] _capabilities = {}; /// <summary> /// capabilities of the SM plugin, with capability version numbers /// First published in XenServer 6.2. /// </summary> public virtual Dictionary<string, long> features { get { return _features; } set { if (!Helper.AreEqual(value, _features)) { _features = value; NotifyPropertyChanged("features"); } } } private Dictionary<string, long> _features = new Dictionary<string, long>() {}; /// <summary> /// additional configuration /// First published in XenServer 4.1. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; /// <summary> /// filename of the storage driver /// First published in XenServer 5.0. /// </summary> public virtual string driver_filename { get { return _driver_filename; } set { if (!Helper.AreEqual(value, _driver_filename)) { _driver_filename = value; NotifyPropertyChanged("driver_filename"); } } } private string _driver_filename = ""; /// <summary> /// The storage plugin requires that one of these cluster stacks is configured and running. /// First published in XenServer 7.0. /// </summary> public virtual string[] required_cluster_stack { get { return _required_cluster_stack; } set { if (!Helper.AreEqual(value, _required_cluster_stack)) { _required_cluster_stack = value; NotifyPropertyChanged("required_cluster_stack"); } } } private string[] _required_cluster_stack = {}; } }
/* * Copyright 2013 ThirdMotion, 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. */ /** * @class strange.extensions.injector.impl.Injector * * Supplies injection for all mapped dependencies. * * Extension satisfies injection dependencies. Works in conjuntion with * (and therefore relies on) the Reflector. * * Dependencies may be Constructor injections (all parameters will be satisfied), * or setter injections. * * Classes utilizing this injector must be marked with the following metatags: * <ul> * <li>[Inject] - Use this metatag on any setter you wish to have supplied by injection.</li> * <li>[Construct] - Use this metatag on the specific Constructor you wish to inject into when using Constructor injection. If you omit this tag, the Constructor with the shortest list of dependencies will be selected automatically.</li> * <li>[PostConstruct] - Use this metatag on any method(s) you wish to fire directly after dependencies are supplied</li> * </ul> * * The Injection system is quite loud and specific where dependencies are unmapped, * throwing Exceptions to warn you. This is exceptionally useful in ensuring that * your app is well structured. */ using System; using System.Collections.Generic; using System.Reflection; using strange.extensions.injector.api; using strange.extensions.reflector.api; namespace strange.extensions.injector.impl { public class Injector : IInjector { private Dictionary<IInjectionBinding, int> infinityLock; private const int INFINITY_LIMIT = 10; public Injector () { factory = new InjectorFactory(); } public IInjectorFactory factory{ get; set;} public IInjectionBinder binder{ get; set;} public IReflectionBinder reflector{ get; set;} public object Instantiate(IInjectionBinding binding) { failIf(binder == null, "Attempt to instantiate from Injector without a Binder", InjectionExceptionType.NO_BINDER); failIf(factory == null, "Attempt to inject into Injector without a Factory", InjectionExceptionType.NO_FACTORY); armorAgainstInfiniteLoops (binding); object retv = null; Type reflectionType = null; if (binding.value is Type) { reflectionType = binding.value as Type; } else if (binding.value == null) { object[] tl = binding.key as object[]; reflectionType = tl [0] as Type; if (reflectionType.IsPrimitive || reflectionType == typeof(Decimal) || reflectionType == typeof(string)) { retv = binding.value; } } else { retv = binding.value; } if (retv == null) //If we don't have an existing value, go ahead and create one. { IReflectedClass reflection = reflector.Get (reflectionType); Type[] parameters = reflection.constructorParameters; int aa = parameters.Length; object[] args = new object [aa]; for (int a = 0; a < aa; a++) { args [a] = getValueInjection (parameters[a] as Type, null, null); } retv = factory.Get (binding, args); //If the InjectorFactory returns null, just return it. Otherwise inject the retv if it needs it //This could happen if Activator.CreateInstance returns null if (retv != null) { if (binding.toInject) { retv = Inject (retv, false); } if (binding.type == InjectionBindingType.SINGLETON || binding.type == InjectionBindingType.VALUE) { //prevent double-injection binding.ToInject(false); } } } infinityLock = null; //Clear our infinity lock so the next time we instantiate we don't consider this a circular dependency return retv; } public object Inject(object target) { return Inject (target, true); } public object Inject(object target, bool attemptConstructorInjection) { failIf(binder == null, "Attempt to inject into Injector without a Binder", InjectionExceptionType.NO_BINDER); failIf(reflector == null, "Attempt to inject without a reflector", InjectionExceptionType.NO_REFLECTOR); failIf(target == null, "Attempt to inject into null instance", InjectionExceptionType.NULL_TARGET); //Some things can't be injected into. Bail out. Type t = target.GetType (); if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(string)) { return target; } IReflectedClass reflection = reflector.Get (t); if (attemptConstructorInjection) { target = performConstructorInjection(target, reflection); } performSetterInjection(target, reflection); postInject(target, reflection); return target; } public void Uninject(object target) { failIf(binder == null, "Attempt to inject into Injector without a Binder", InjectionExceptionType.NO_BINDER); failIf(reflector == null, "Attempt to inject without a reflector", InjectionExceptionType.NO_REFLECTOR); failIf(target == null, "Attempt to inject into null instance", InjectionExceptionType.NULL_TARGET); Type t = target.GetType (); if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(string)) { return; } IReflectedClass reflection = reflector.Get (t); performUninjection (target, reflection); } private object performConstructorInjection(object target, IReflectedClass reflection) { failIf(target == null, "Attempt to perform constructor injection into a null object", InjectionExceptionType.NULL_TARGET); failIf(reflection == null, "Attempt to perform constructor injection without a reflection", InjectionExceptionType.NULL_REFLECTION); ConstructorInfo constructor = reflection.constructor; failIf(constructor == null, "Attempt to construction inject a null constructor", InjectionExceptionType.NULL_CONSTRUCTOR); Type[] constructorParameters = reflection.constructorParameters; object[] values = new object[constructorParameters.Length]; int i = 0; foreach (Type type in constructorParameters) { values[i] = getValueInjection(type, null, target); i++; } if (values.Length == 0) { return target; } object constructedObj = constructor.Invoke (values); return (constructedObj == null) ? target : constructedObj; } private void performSetterInjection(object target, IReflectedClass reflection) { failIf(target == null, "Attempt to inject into a null object", InjectionExceptionType.NULL_TARGET); failIf(reflection == null, "Attempt to inject without a reflection", InjectionExceptionType.NULL_REFLECTION); failIf(reflection.setters.Length != reflection.setterNames.Length, "Attempt to perform setter injection with mismatched names.\nThere must be exactly as many names as setters.", InjectionExceptionType.SETTER_NAME_MISMATCH); int aa = reflection.setters.Length; for(int a = 0; a < aa; a++) { KeyValuePair<Type, PropertyInfo> pair = reflection.setters [a]; object value = getValueInjection(pair.Key, reflection.setterNames[a], target); injectValueIntoPoint (value, target, pair.Value); } } private object getValueInjection(Type t, object name, object target) { IInjectionBinding binding = binder.GetBinding (t, name); failIf(binding == null, "Attempt to Instantiate a null binding.", InjectionExceptionType.NULL_BINDING, t, name, target); if (binding.type == InjectionBindingType.VALUE) { if (!binding.toInject) { return binding.value; } else { object retv = Inject (binding.value, false); binding.ToInject (false); return retv; } } else if (binding.type == InjectionBindingType.SINGLETON) { if (binding.value is Type || binding.value == null) Instantiate (binding); return binding.value; } else { return Instantiate (binding); } } //Inject the value into the target at the specified injection point private void injectValueIntoPoint(object value, object target, PropertyInfo point) { failIf(target == null, "Attempt to inject into a null target", InjectionExceptionType.NULL_TARGET); failIf(point == null, "Attempt to inject into a null point", InjectionExceptionType.NULL_INJECTION_POINT); failIf(value == null, "Attempt to inject null into a target object", InjectionExceptionType.NULL_VALUE_INJECTION); point.SetValue (target, value, null); } //After injection, call any methods labelled with the [PostConstruct] tag private void postInject(object target, IReflectedClass reflection) { failIf(target == null, "Attempt to PostConstruct a null target", InjectionExceptionType.NULL_TARGET); failIf(reflection == null, "Attempt to PostConstruct without a reflection", InjectionExceptionType.NULL_REFLECTION); MethodInfo[] postConstructors = reflection.postConstructors; if (postConstructors != null) { foreach(MethodInfo method in postConstructors) { method.Invoke (target, null); } } } //Note that uninjection can only clean publicly settable points private void performUninjection(object target, IReflectedClass reflection) { int aa = reflection.setters.Length; for(int a = 0; a < aa; a++) { KeyValuePair<Type, PropertyInfo> pair = reflection.setters [a]; pair.Value.SetValue (target, null, null); } } private void failIf(bool condition, string message, InjectionExceptionType type) { failIf (condition, message, type, null, null, null); } private void failIf(bool condition, string message, InjectionExceptionType type, Type t, object name) { failIf(condition, message, type, t, name, null); } private void failIf(bool condition, string message, InjectionExceptionType type, Type t, object name, object target) { if (condition) { message += "\n\t\ttarget: " + target; message += "\n\t\ttype: " + t; message += "\n\t\tname: " + name; throw new InjectionException(message, type); } } private void armorAgainstInfiniteLoops(IInjectionBinding binding) { if (binding == null) { return; } if (infinityLock == null) { infinityLock = new Dictionary<IInjectionBinding, int> (); } if(infinityLock.ContainsKey(binding) == false) { infinityLock.Add (binding, 0); } infinityLock [binding] = infinityLock [binding] + 1; if (infinityLock [binding] > INFINITY_LIMIT) { throw new InjectionException ("There appears to be a circular dependency. Terminating loop.", InjectionExceptionType.CIRCULAR_DEPENDENCY); } } } }
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using ICSharpCode.Decompiler.Ast.Transforms; using ICSharpCode.Decompiler.ILAst; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.PatternMatching; using ICSharpCode.NRefactory.Utils; using Mono.Cecil; using Mono.Cecil.Cil; namespace ICSharpCode.Decompiler.Ast { using Ast = ICSharpCode.NRefactory.CSharp; using Cecil = Mono.Cecil; public class AstMethodBodyBuilder { MethodDefinition methodDef; TypeSystem typeSystem; DecompilerContext context; HashSet<ILVariable> localVariablesToDefine = new HashSet<ILVariable>(); // local variables that are missing a definition /// <summary> /// Creates the body for the method definition. /// </summary> /// <param name="methodDef">Method definition to decompile.</param> /// <param name="context">Decompilation context.</param> /// <param name="parameters">Parameter declarations of the method being decompiled. /// These are used to update the parameter names when the decompiler generates names for the parameters.</param> /// <returns>Block for the method body</returns> public static BlockStatement CreateMethodBody(MethodDefinition methodDef, DecompilerContext context, IEnumerable<ParameterDeclaration> parameters = null) { MethodDefinition oldCurrentMethod = context.CurrentMethod; Debug.Assert(oldCurrentMethod == null || oldCurrentMethod == methodDef); context.CurrentMethod = methodDef; context.CurrentMethodIsAsync = false; try { AstMethodBodyBuilder builder = new AstMethodBodyBuilder(); builder.methodDef = methodDef; builder.context = context; builder.typeSystem = methodDef.Module.TypeSystem; if (Debugger.IsAttached) { return builder.CreateMethodBody(parameters); } else { try { return builder.CreateMethodBody(parameters); } catch (OperationCanceledException) { throw; } catch (Exception ex) { throw new ICSharpCode.Decompiler.DecompilerException(methodDef, ex); } } } finally { context.CurrentMethod = oldCurrentMethod; } } public BlockStatement CreateMethodBody(IEnumerable<ParameterDeclaration> parameters) { if (methodDef.Body == null) { return null; } context.CancellationToken.ThrowIfCancellationRequested(); ILBlock ilMethod = new ILBlock(); ILAstBuilder astBuilder = new ILAstBuilder(); ilMethod.Body = astBuilder.Build(methodDef, true, context); context.CancellationToken.ThrowIfCancellationRequested(); ILAstOptimizer bodyGraph = new ILAstOptimizer(); bodyGraph.Optimize(context, ilMethod); context.CancellationToken.ThrowIfCancellationRequested(); var localVariables = ilMethod.GetSelfAndChildrenRecursive<ILExpression>().Select(e => e.Operand as ILVariable) .Where(v => v != null && !v.IsParameter).Distinct(); Debug.Assert(context.CurrentMethod == methodDef); NameVariables.AssignNamesToVariables(context, astBuilder.Parameters, localVariables, ilMethod); if (parameters != null) { foreach (var pair in (from p in parameters join v in astBuilder.Parameters on p.Annotation<ParameterDefinition>() equals v.OriginalParameter select new { p, v.Name })) { pair.p.Name = pair.Name; } } context.CancellationToken.ThrowIfCancellationRequested(); Ast.BlockStatement astBlock = TransformBlock(ilMethod); CommentStatement.ReplaceAll(astBlock); // convert CommentStatements to Comments Statement insertionPoint = astBlock.Statements.FirstOrDefault(); foreach (ILVariable v in localVariablesToDefine) { AstType type; if (v.Type.ContainsAnonymousType()) type = new SimpleType("var"); else type = AstBuilder.ConvertType(v.Type); var newVarDecl = new VariableDeclarationStatement(type, v.Name); newVarDecl.Variables.Single().AddAnnotation(v); astBlock.Statements.InsertBefore(insertionPoint, newVarDecl); } astBlock.AddAnnotation(new MemberMapping(methodDef) { LocalVariables = localVariables }); return astBlock; } Ast.BlockStatement TransformBlock(ILBlock block) { Ast.BlockStatement astBlock = new BlockStatement(); if (block != null) { foreach(ILNode node in block.GetChildren()) { astBlock.Statements.AddRange(TransformNode(node)); } } return astBlock; } IEnumerable<Statement> TransformNode(ILNode node) { if (node is ILLabel) { yield return new Ast.LabelStatement { Label = ((ILLabel)node).Name }; } else if (node is ILExpression) { List<ILRange> ilRanges = ILRange.OrderAndJoint(node.GetSelfAndChildrenRecursive<ILExpression>().SelectMany(e => e.ILRanges)); AstNode codeExpr = TransformExpression((ILExpression)node); if (codeExpr != null) { codeExpr = codeExpr.WithAnnotation(ilRanges); if (codeExpr is Ast.Expression) { yield return new Ast.ExpressionStatement { Expression = (Ast.Expression)codeExpr }; } else if (codeExpr is Ast.Statement) { yield return (Ast.Statement)codeExpr; } else { throw new Exception(); } } } else if (node is ILWhileLoop) { ILWhileLoop ilLoop = (ILWhileLoop)node; WhileStatement whileStmt = new WhileStatement() { Condition = ilLoop.Condition != null ? (Expression)TransformExpression(ilLoop.Condition) : new PrimitiveExpression(true), EmbeddedStatement = TransformBlock(ilLoop.BodyBlock) }; yield return whileStmt; } else if (node is ILCondition) { ILCondition conditionalNode = (ILCondition)node; bool hasFalseBlock = conditionalNode.FalseBlock.EntryGoto != null || conditionalNode.FalseBlock.Body.Count > 0; yield return new Ast.IfElseStatement { Condition = (Expression)TransformExpression(conditionalNode.Condition), TrueStatement = TransformBlock(conditionalNode.TrueBlock), FalseStatement = hasFalseBlock ? TransformBlock(conditionalNode.FalseBlock) : null }; } else if (node is ILSwitch) { ILSwitch ilSwitch = (ILSwitch)node; if (TypeAnalysis.IsBoolean(ilSwitch.Condition.InferredType) && ( from cb in ilSwitch.CaseBlocks where cb.Values != null from val in cb.Values select val ).Any(val => val != 0 && val != 1)) { // If switch cases contain values other then 0 and 1, force the condition to be non-boolean ilSwitch.Condition.ExpectedType = typeSystem.Int32; } SwitchStatement switchStmt = new SwitchStatement() { Expression = (Expression)TransformExpression(ilSwitch.Condition) }; foreach (var caseBlock in ilSwitch.CaseBlocks) { SwitchSection section = new SwitchSection(); if (caseBlock.Values != null) { section.CaseLabels.AddRange(caseBlock.Values.Select(i => new CaseLabel() { Expression = AstBuilder.MakePrimitive(i, ilSwitch.Condition.ExpectedType ?? ilSwitch.Condition.InferredType) })); } else { section.CaseLabels.Add(new CaseLabel()); } section.Statements.Add(TransformBlock(caseBlock)); switchStmt.SwitchSections.Add(section); } yield return switchStmt; } else if (node is ILTryCatchBlock) { ILTryCatchBlock tryCatchNode = ((ILTryCatchBlock)node); var tryCatchStmt = new Ast.TryCatchStatement(); tryCatchStmt.TryBlock = TransformBlock(tryCatchNode.TryBlock); foreach (var catchClause in tryCatchNode.CatchBlocks) { if (catchClause.ExceptionVariable == null && (catchClause.ExceptionType == null || catchClause.ExceptionType.MetadataType == MetadataType.Object)) { tryCatchStmt.CatchClauses.Add(new Ast.CatchClause { Body = TransformBlock(catchClause) }); } else { tryCatchStmt.CatchClauses.Add( new Ast.CatchClause { Type = AstBuilder.ConvertType(catchClause.ExceptionType), VariableName = catchClause.ExceptionVariable == null ? null : catchClause.ExceptionVariable.Name, Body = TransformBlock(catchClause) }.WithAnnotation(catchClause.ExceptionVariable)); } } if (tryCatchNode.FinallyBlock != null) tryCatchStmt.FinallyBlock = TransformBlock(tryCatchNode.FinallyBlock); if (tryCatchNode.FaultBlock != null) { CatchClause cc = new CatchClause(); cc.Body = TransformBlock(tryCatchNode.FaultBlock); cc.Body.Add(new ThrowStatement()); // rethrow tryCatchStmt.CatchClauses.Add(cc); } yield return tryCatchStmt; } else if (node is ILFixedStatement) { ILFixedStatement fixedNode = (ILFixedStatement)node; FixedStatement fixedStatement = new FixedStatement(); foreach (ILExpression initializer in fixedNode.Initializers) { Debug.Assert(initializer.Code == ILCode.Stloc); ILVariable v = (ILVariable)initializer.Operand; fixedStatement.Variables.Add( new VariableInitializer { Name = v.Name, Initializer = (Expression)TransformExpression(initializer.Arguments[0]) }.WithAnnotation(v)); } fixedStatement.Type = AstBuilder.ConvertType(((ILVariable)fixedNode.Initializers[0].Operand).Type); fixedStatement.EmbeddedStatement = TransformBlock(fixedNode.BodyBlock); yield return fixedStatement; } else if (node is ILBlock) { yield return TransformBlock((ILBlock)node); } else { throw new Exception("Unknown node type"); } } AstNode TransformExpression(ILExpression expr) { AstNode node = TransformByteCode(expr); Expression astExpr = node as Expression; // get IL ranges - used in debugger List<ILRange> ilRanges = ILRange.OrderAndJoint(expr.GetSelfAndChildrenRecursive<ILExpression>().SelectMany(e => e.ILRanges)); AstNode result; if (astExpr != null) result = Convert(astExpr, expr.InferredType, expr.ExpectedType); else result = node; if (result != null) result = result.WithAnnotation(new TypeInformation(expr.InferredType)); if (result != null) return result.WithAnnotation(ilRanges); return result; } AstNode TransformByteCode(ILExpression byteCode) { object operand = byteCode.Operand; AstType operandAsTypeRef = AstBuilder.ConvertType(operand as Cecil.TypeReference); List<Ast.Expression> args = new List<Expression>(); foreach(ILExpression arg in byteCode.Arguments) { args.Add((Ast.Expression)TransformExpression(arg)); } Ast.Expression arg1 = args.Count >= 1 ? args[0] : null; Ast.Expression arg2 = args.Count >= 2 ? args[1] : null; Ast.Expression arg3 = args.Count >= 3 ? args[2] : null; switch (byteCode.Code) { #region Arithmetic case ILCode.Add: case ILCode.Add_Ovf: case ILCode.Add_Ovf_Un: { BinaryOperatorExpression boe; if (byteCode.InferredType is PointerType) { if (byteCode.Arguments[0].ExpectedType is PointerType) { arg2 = DivideBySize(arg2, ((PointerType)byteCode.InferredType).ElementType); boe = new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2); boe.AddAnnotation(IntroduceUnsafeModifier.PointerArithmeticAnnotation); } else if (byteCode.Arguments[1].ExpectedType is PointerType) { arg1 = DivideBySize(arg1, ((PointerType)byteCode.InferredType).ElementType); boe = new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2); boe.AddAnnotation(IntroduceUnsafeModifier.PointerArithmeticAnnotation); } else { boe = new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2); } } else { boe = new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2); } boe.AddAnnotation(byteCode.Code == ILCode.Add ? AddCheckedBlocks.UncheckedAnnotation : AddCheckedBlocks.CheckedAnnotation); return boe; } case ILCode.Sub: case ILCode.Sub_Ovf: case ILCode.Sub_Ovf_Un: { BinaryOperatorExpression boe; if (byteCode.InferredType is PointerType) { if (byteCode.Arguments[0].ExpectedType is PointerType) { arg2 = DivideBySize(arg2, ((PointerType)byteCode.InferredType).ElementType); boe = new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Subtract, arg2); boe.WithAnnotation(IntroduceUnsafeModifier.PointerArithmeticAnnotation); } else { boe = new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Subtract, arg2); } } else { boe = new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Subtract, arg2); } boe.AddAnnotation(byteCode.Code == ILCode.Sub ? AddCheckedBlocks.UncheckedAnnotation : AddCheckedBlocks.CheckedAnnotation); return boe; } case ILCode.Div: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Divide, arg2); case ILCode.Div_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Divide, arg2); case ILCode.Mul: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2).WithAnnotation(AddCheckedBlocks.UncheckedAnnotation); case ILCode.Mul_Ovf: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2).WithAnnotation(AddCheckedBlocks.CheckedAnnotation); case ILCode.Mul_Ovf_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2).WithAnnotation(AddCheckedBlocks.CheckedAnnotation); case ILCode.Rem: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Modulus, arg2); case ILCode.Rem_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Modulus, arg2); case ILCode.And: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.BitwiseAnd, arg2); case ILCode.Or: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.BitwiseOr, arg2); case ILCode.Xor: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ExclusiveOr, arg2); case ILCode.Shl: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftLeft, arg2); case ILCode.Shr: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2); case ILCode.Shr_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2); case ILCode.Neg: return new Ast.UnaryOperatorExpression(UnaryOperatorType.Minus, arg1).WithAnnotation(AddCheckedBlocks.UncheckedAnnotation); case ILCode.Not: return new Ast.UnaryOperatorExpression(UnaryOperatorType.BitNot, arg1); case ILCode.PostIncrement: case ILCode.PostIncrement_Ovf: case ILCode.PostIncrement_Ovf_Un: { if (arg1 is DirectionExpression) arg1 = ((DirectionExpression)arg1).Expression.Detach(); var uoe = new Ast.UnaryOperatorExpression( (int)byteCode.Operand > 0 ? UnaryOperatorType.PostIncrement : UnaryOperatorType.PostDecrement, arg1); uoe.AddAnnotation((byteCode.Code == ILCode.PostIncrement) ? AddCheckedBlocks.UncheckedAnnotation : AddCheckedBlocks.CheckedAnnotation); return uoe; } #endregion #region Arrays case ILCode.Newarr: { var ace = new Ast.ArrayCreateExpression(); ace.Type = operandAsTypeRef; ComposedType ct = operandAsTypeRef as ComposedType; if (ct != null) { // change "new (int[,])[10] to new int[10][,]" ct.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers); } if (byteCode.Code == ILCode.InitArray) { ace.Initializer = new ArrayInitializerExpression(); ace.Initializer.Elements.AddRange(args); } else { ace.Arguments.Add(arg1); } return ace; } case ILCode.InitArray: { var ace = new Ast.ArrayCreateExpression(); ace.Type = operandAsTypeRef; ComposedType ct = operandAsTypeRef as ComposedType; var arrayType = (ArrayType) operand; if (ct != null) { // change "new (int[,])[10] to new int[10][,]" ct.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers); ace.Initializer = new ArrayInitializerExpression(); } var newArgs = new List<Expression>(); foreach (var arrayDimension in arrayType.Dimensions.Skip(1).Reverse()) { int length = (int)arrayDimension.UpperBound - (int)arrayDimension.LowerBound; for (int j = 0; j < args.Count; j += length) { var child = new ArrayInitializerExpression(); child.Elements.AddRange(args.GetRange(j, length)); newArgs.Add(child); } var temp = args; args = newArgs; newArgs = temp; newArgs.Clear(); } ace.Initializer.Elements.AddRange(args); return ace; } case ILCode.Ldlen: return arg1.Member("Length"); case ILCode.Ldelem_I: case ILCode.Ldelem_I1: case ILCode.Ldelem_I2: case ILCode.Ldelem_I4: case ILCode.Ldelem_I8: case ILCode.Ldelem_U1: case ILCode.Ldelem_U2: case ILCode.Ldelem_U4: case ILCode.Ldelem_R4: case ILCode.Ldelem_R8: case ILCode.Ldelem_Ref: case ILCode.Ldelem_Any: return arg1.Indexer(arg2); case ILCode.Ldelema: return MakeRef(arg1.Indexer(arg2)); case ILCode.Stelem_I: case ILCode.Stelem_I1: case ILCode.Stelem_I2: case ILCode.Stelem_I4: case ILCode.Stelem_I8: case ILCode.Stelem_R4: case ILCode.Stelem_R8: case ILCode.Stelem_Ref: case ILCode.Stelem_Any: return new Ast.AssignmentExpression(arg1.Indexer(arg2), arg3); case ILCode.CompoundAssignment: { CastExpression cast = arg1 as CastExpression; var boe = cast != null ? (BinaryOperatorExpression)cast.Expression : arg1 as BinaryOperatorExpression; // AssignmentExpression doesn't support overloaded operators so they have to be processed to BinaryOperatorExpression if (boe == null) { var tmp = new ParenthesizedExpression(arg1); ReplaceMethodCallsWithOperators.ProcessInvocationExpression((InvocationExpression)arg1); boe = (BinaryOperatorExpression)tmp.Expression; } var assignment = new Ast.AssignmentExpression { Left = boe.Left.Detach(), Operator = ReplaceMethodCallsWithOperators.GetAssignmentOperatorForBinaryOperator(boe.Operator), Right = boe.Right.Detach() }.CopyAnnotationsFrom(boe); // We do not mark the resulting assignment as RestoreOriginalAssignOperatorAnnotation, because // the operator cannot be translated back to the expanded form (as the left-hand expression // would be evaluated twice, and might have side-effects) if (cast != null) { cast.Expression = assignment; return cast; } else { return assignment; } } #endregion #region Comparison case ILCode.Ceq: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Equality, arg2); case ILCode.Cne: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.InEquality, arg2); case ILCode.Cgt: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThan, arg2); case ILCode.Cgt_Un: { // can also mean Inequality, when used with object references TypeReference arg1Type = byteCode.Arguments[0].InferredType; if (arg1Type != null && !arg1Type.IsValueType) goto case ILCode.Cne; goto case ILCode.Cgt; } case ILCode.Cle_Un: { // can also mean Equality, when used with object references TypeReference arg1Type = byteCode.Arguments[0].InferredType; if (arg1Type != null && !arg1Type.IsValueType) goto case ILCode.Ceq; goto case ILCode.Cle; } case ILCode.Cle: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.LessThanOrEqual, arg2); case ILCode.Cge_Un: case ILCode.Cge: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThanOrEqual, arg2); case ILCode.Clt_Un: case ILCode.Clt: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.LessThan, arg2); #endregion #region Logical case ILCode.LogicNot: return new Ast.UnaryOperatorExpression(UnaryOperatorType.Not, arg1); case ILCode.LogicAnd: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ConditionalAnd, arg2); case ILCode.LogicOr: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ConditionalOr, arg2); case ILCode.TernaryOp: return new Ast.ConditionalExpression() { Condition = arg1, TrueExpression = arg2, FalseExpression = arg3 }; case ILCode.NullCoalescing: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.NullCoalescing, arg2); #endregion #region Branch case ILCode.Br: return new Ast.GotoStatement(((ILLabel)byteCode.Operand).Name); case ILCode.Brtrue: return new Ast.IfElseStatement() { Condition = arg1, TrueStatement = new BlockStatement() { new Ast.GotoStatement(((ILLabel)byteCode.Operand).Name) } }; case ILCode.LoopOrSwitchBreak: return new Ast.BreakStatement(); case ILCode.LoopContinue: return new Ast.ContinueStatement(); #endregion #region Conversions case ILCode.Conv_I1: case ILCode.Conv_I2: case ILCode.Conv_I4: case ILCode.Conv_I8: case ILCode.Conv_U1: case ILCode.Conv_U2: case ILCode.Conv_U4: case ILCode.Conv_U8: case ILCode.Conv_I: case ILCode.Conv_U: { // conversion was handled by Convert() function using the info from type analysis CastExpression cast = arg1 as CastExpression; if (cast != null) { cast.AddAnnotation(AddCheckedBlocks.UncheckedAnnotation); } return arg1; } case ILCode.Conv_R4: case ILCode.Conv_R8: case ILCode.Conv_R_Un: // TODO return arg1; case ILCode.Conv_Ovf_I1: case ILCode.Conv_Ovf_I2: case ILCode.Conv_Ovf_I4: case ILCode.Conv_Ovf_I8: case ILCode.Conv_Ovf_U1: case ILCode.Conv_Ovf_U2: case ILCode.Conv_Ovf_U4: case ILCode.Conv_Ovf_U8: case ILCode.Conv_Ovf_I1_Un: case ILCode.Conv_Ovf_I2_Un: case ILCode.Conv_Ovf_I4_Un: case ILCode.Conv_Ovf_I8_Un: case ILCode.Conv_Ovf_U1_Un: case ILCode.Conv_Ovf_U2_Un: case ILCode.Conv_Ovf_U4_Un: case ILCode.Conv_Ovf_U8_Un: case ILCode.Conv_Ovf_I: case ILCode.Conv_Ovf_U: case ILCode.Conv_Ovf_I_Un: case ILCode.Conv_Ovf_U_Un: { // conversion was handled by Convert() function using the info from type analysis CastExpression cast = arg1 as CastExpression; if (cast != null) { cast.AddAnnotation(AddCheckedBlocks.CheckedAnnotation); } return arg1; } case ILCode.Unbox_Any: // unboxing does not require a cast if the argument was an isinst instruction if (arg1 is AsExpression && byteCode.Arguments[0].Code == ILCode.Isinst && TypeAnalysis.IsSameType(operand as TypeReference, byteCode.Arguments[0].Operand as TypeReference)) return arg1; else goto case ILCode.Castclass; case ILCode.Castclass: if ((byteCode.Arguments[0].InferredType != null && byteCode.Arguments[0].InferredType.IsGenericParameter) || ((Cecil.TypeReference)operand).IsGenericParameter) return arg1.CastTo(new PrimitiveType("object")).CastTo(operandAsTypeRef); else return arg1.CastTo(operandAsTypeRef); case ILCode.Isinst: return arg1.CastAs(operandAsTypeRef); case ILCode.Box: return arg1; case ILCode.Unbox: return MakeRef(arg1.CastTo(operandAsTypeRef)); #endregion #region Indirect case ILCode.Ldind_Ref: case ILCode.Ldobj: if (arg1 is DirectionExpression) return ((DirectionExpression)arg1).Expression.Detach(); else return new UnaryOperatorExpression(UnaryOperatorType.Dereference, arg1); case ILCode.Stind_Ref: case ILCode.Stobj: if (arg1 is DirectionExpression) return new AssignmentExpression(((DirectionExpression)arg1).Expression.Detach(), arg2); else return new AssignmentExpression(new UnaryOperatorExpression(UnaryOperatorType.Dereference, arg1), arg2); #endregion case ILCode.Arglist: return new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.ArgListAccess }; case ILCode.Break: return InlineAssembly(byteCode, args); case ILCode.Call: case ILCode.CallGetter: case ILCode.CallSetter: return TransformCall(false, byteCode, args); case ILCode.Callvirt: case ILCode.CallvirtGetter: case ILCode.CallvirtSetter: return TransformCall(true, byteCode, args); case ILCode.Ldftn: { Cecil.MethodReference cecilMethod = ((MethodReference)operand); var expr = new Ast.IdentifierExpression(cecilMethod.Name); expr.TypeArguments.AddRange(ConvertTypeArguments(cecilMethod)); expr.AddAnnotation(cecilMethod); return new IdentifierExpression("ldftn").Invoke(expr) .WithAnnotation(new Transforms.DelegateConstruction.Annotation(false)); } case ILCode.Ldvirtftn: { Cecil.MethodReference cecilMethod = ((MethodReference)operand); var expr = new Ast.IdentifierExpression(cecilMethod.Name); expr.TypeArguments.AddRange(ConvertTypeArguments(cecilMethod)); expr.AddAnnotation(cecilMethod); return new IdentifierExpression("ldvirtftn").Invoke(expr) .WithAnnotation(new Transforms.DelegateConstruction.Annotation(true)); } case ILCode.Calli: return InlineAssembly(byteCode, args); case ILCode.Ckfinite: return InlineAssembly(byteCode, args); case ILCode.Constrained: return InlineAssembly(byteCode, args); case ILCode.Cpblk: return InlineAssembly(byteCode, args); case ILCode.Cpobj: return InlineAssembly(byteCode, args); case ILCode.Dup: return arg1; case ILCode.Endfilter: return InlineAssembly(byteCode, args); case ILCode.Endfinally: return null; case ILCode.Initblk: return InlineAssembly(byteCode, args); case ILCode.Initobj: return InlineAssembly(byteCode, args); case ILCode.DefaultValue: return MakeDefaultValue((TypeReference)operand); case ILCode.Jmp: return InlineAssembly(byteCode, args); case ILCode.Ldc_I4: return AstBuilder.MakePrimitive((int)operand, byteCode.InferredType); case ILCode.Ldc_I8: return AstBuilder.MakePrimitive((long)operand, byteCode.InferredType); case ILCode.Ldc_R4: case ILCode.Ldc_R8: case ILCode.Ldc_Decimal: return new Ast.PrimitiveExpression(operand); case ILCode.Ldfld: if (arg1 is DirectionExpression) arg1 = ((DirectionExpression)arg1).Expression.Detach(); return arg1.Member(((FieldReference) operand).Name).WithAnnotation(operand); case ILCode.Ldsfld: return AstBuilder.ConvertType(((FieldReference)operand).DeclaringType) .Member(((FieldReference)operand).Name).WithAnnotation(operand); case ILCode.Stfld: if (arg1 is DirectionExpression) arg1 = ((DirectionExpression)arg1).Expression.Detach(); return new AssignmentExpression(arg1.Member(((FieldReference) operand).Name).WithAnnotation(operand), arg2); case ILCode.Stsfld: return new AssignmentExpression( AstBuilder.ConvertType(((FieldReference)operand).DeclaringType) .Member(((FieldReference)operand).Name).WithAnnotation(operand), arg1); case ILCode.Ldflda: if (arg1 is DirectionExpression) arg1 = ((DirectionExpression)arg1).Expression.Detach(); return MakeRef(arg1.Member(((FieldReference) operand).Name).WithAnnotation(operand)); case ILCode.Ldsflda: return MakeRef( AstBuilder.ConvertType(((FieldReference)operand).DeclaringType) .Member(((FieldReference)operand).Name).WithAnnotation(operand)); case ILCode.Ldloc: { ILVariable v = (ILVariable)operand; if (!v.IsParameter) localVariablesToDefine.Add((ILVariable)operand); Expression expr; if (v.IsParameter && v.OriginalParameter.Index < 0) expr = new ThisReferenceExpression(); else expr = new Ast.IdentifierExpression(((ILVariable)operand).Name).WithAnnotation(operand); return v.IsParameter && v.Type is ByReferenceType ? MakeRef(expr) : expr; } case ILCode.Ldloca: { ILVariable v = (ILVariable)operand; if (v.IsParameter && v.OriginalParameter.Index < 0) return MakeRef(new ThisReferenceExpression()); if (!v.IsParameter) localVariablesToDefine.Add((ILVariable)operand); return MakeRef(new Ast.IdentifierExpression(((ILVariable)operand).Name).WithAnnotation(operand)); } case ILCode.Ldnull: return new Ast.NullReferenceExpression(); case ILCode.Ldstr: return new Ast.PrimitiveExpression(operand); case ILCode.Ldtoken: if (operand is Cecil.TypeReference) { return AstBuilder.CreateTypeOfExpression((TypeReference)operand).Member("TypeHandle"); } else { Expression referencedEntity; string loadName; string handleName; if (operand is Cecil.FieldReference) { loadName = "fieldof"; handleName = "FieldHandle"; FieldReference fr = (FieldReference)operand; referencedEntity = AstBuilder.ConvertType(fr.DeclaringType).Member(fr.Name).WithAnnotation(fr); } else if (operand is Cecil.MethodReference) { loadName = "methodof"; handleName = "MethodHandle"; MethodReference mr = (MethodReference)operand; var methodParameters = mr.Parameters.Select(p => new TypeReferenceExpression(AstBuilder.ConvertType(p.ParameterType))); referencedEntity = AstBuilder.ConvertType(mr.DeclaringType).Invoke(mr.Name, methodParameters).WithAnnotation(mr); } else { loadName = "ldtoken"; handleName = "Handle"; referencedEntity = new IdentifierExpression(FormatByteCodeOperand(byteCode.Operand)); } return new IdentifierExpression(loadName).Invoke(referencedEntity).WithAnnotation(new LdTokenAnnotation()).Member(handleName); } case ILCode.Leave: return new GotoStatement() { Label = ((ILLabel)operand).Name }; case ILCode.Localloc: { PointerType ptrType = byteCode.InferredType as PointerType; TypeReference type; if (ptrType != null) { type = ptrType.ElementType; } else { type = typeSystem.Byte; } return new StackAllocExpression { Type = AstBuilder.ConvertType(type), CountExpression = DivideBySize(arg1, type) }; } case ILCode.Mkrefany: { DirectionExpression dir = arg1 as DirectionExpression; if (dir != null) { return new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.MakeRef, Arguments = { dir.Expression.Detach() } }; } else { return InlineAssembly(byteCode, args); } } case ILCode.Refanytype: return new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.RefType, Arguments = { arg1 } }.Member("TypeHandle"); case ILCode.Refanyval: return MakeRef( new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.RefValue, Arguments = { arg1, new TypeReferenceExpression(operandAsTypeRef) } }); case ILCode.Newobj: { Cecil.TypeReference declaringType = ((MethodReference)operand).DeclaringType; if (declaringType is ArrayType) { ComposedType ct = AstBuilder.ConvertType((ArrayType)declaringType) as ComposedType; if (ct != null && ct.ArraySpecifiers.Count >= 1) { var ace = new Ast.ArrayCreateExpression(); ct.ArraySpecifiers.First().Remove(); ct.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers); ace.Type = ct; ace.Arguments.AddRange(args); return ace; } } if (declaringType.IsAnonymousType()) { MethodDefinition ctor = ((MethodReference)operand).Resolve(); if (methodDef != null) { AnonymousTypeCreateExpression atce = new AnonymousTypeCreateExpression(); if (CanInferAnonymousTypePropertyNamesFromArguments(args, ctor.Parameters)) { atce.Initializers.AddRange(args); } else { for (int i = 0; i < args.Count; i++) { atce.Initializers.Add( new NamedExpression { Name = ctor.Parameters[i].Name, Expression = args[i] }); } } return atce; } } var oce = new Ast.ObjectCreateExpression(); oce.Type = AstBuilder.ConvertType(declaringType); oce.Arguments.AddRange(args); return oce.WithAnnotation(operand); } case ILCode.No: return InlineAssembly(byteCode, args); case ILCode.Nop: return null; case ILCode.Pop: return arg1; case ILCode.Readonly: return InlineAssembly(byteCode, args); case ILCode.Ret: if (methodDef.ReturnType.FullName != "System.Void") { return new Ast.ReturnStatement { Expression = arg1 }; } else { return new Ast.ReturnStatement(); } case ILCode.Rethrow: return new Ast.ThrowStatement(); case ILCode.Sizeof: return new Ast.SizeOfExpression { Type = operandAsTypeRef }; case ILCode.Stloc: { ILVariable locVar = (ILVariable)operand; if (!locVar.IsParameter) localVariablesToDefine.Add(locVar); return new Ast.AssignmentExpression(new Ast.IdentifierExpression(locVar.Name).WithAnnotation(locVar), arg1); } case ILCode.Switch: return InlineAssembly(byteCode, args); case ILCode.Tail: return InlineAssembly(byteCode, args); case ILCode.Throw: return new Ast.ThrowStatement { Expression = arg1 }; case ILCode.Unaligned: return InlineAssembly(byteCode, args); case ILCode.Volatile: return InlineAssembly(byteCode, args); case ILCode.YieldBreak: return new Ast.YieldBreakStatement(); case ILCode.YieldReturn: return new Ast.YieldReturnStatement { Expression = arg1 }; case ILCode.InitObject: case ILCode.InitCollection: { ArrayInitializerExpression initializer = new ArrayInitializerExpression(); for (int i = 1; i < args.Count; i++) { Match m = objectInitializerPattern.Match(args[i]); if (m.Success) { MemberReferenceExpression mre = m.Get<MemberReferenceExpression>("left").Single(); initializer.Elements.Add( new NamedExpression { Name = mre.MemberName, Expression = m.Get<Expression>("right").Single().Detach() }.CopyAnnotationsFrom(mre)); } else { m = collectionInitializerPattern.Match(args[i]); if (m.Success) { if (m.Get("arg").Count() == 1) { initializer.Elements.Add(m.Get<Expression>("arg").Single().Detach()); } else { ArrayInitializerExpression argList = new ArrayInitializerExpression(); foreach (var expr in m.Get<Expression>("arg")) { argList.Elements.Add(expr.Detach()); } initializer.Elements.Add(argList); } } else { initializer.Elements.Add(args[i]); } } } ObjectCreateExpression oce = arg1 as ObjectCreateExpression; DefaultValueExpression dve = arg1 as DefaultValueExpression; if (oce != null) { oce.Initializer = initializer; return oce; } else if (dve != null) { oce = new ObjectCreateExpression(dve.Type.Detach()); oce.CopyAnnotationsFrom(dve); oce.Initializer = initializer; return oce; } else { return new AssignmentExpression(arg1, initializer); } } case ILCode.InitializedObject: return new InitializedObjectExpression(); case ILCode.Wrap: return arg1.WithAnnotation(PushNegation.LiftedOperatorAnnotation); case ILCode.AddressOf: return MakeRef(arg1); case ILCode.ExpressionTreeParameterDeclarations: args[args.Count - 1].AddAnnotation(new ParameterDeclarationAnnotation(byteCode)); return args[args.Count - 1]; case ILCode.Await: return new UnaryOperatorExpression(UnaryOperatorType.Await, UnpackDirectionExpression(arg1)); case ILCode.NullableOf: case ILCode.ValueOf: return arg1; default: throw new Exception("Unknown OpCode: " + byteCode.Code); } } internal static bool CanInferAnonymousTypePropertyNamesFromArguments(IList<Expression> args, IList<ParameterDefinition> parameters) { for (int i = 0; i < args.Count; i++) { string inferredName; if (args[i] is IdentifierExpression) inferredName = ((IdentifierExpression)args[i]).Identifier; else if (args[i] is MemberReferenceExpression) inferredName = ((MemberReferenceExpression)args[i]).MemberName; else inferredName = null; if (inferredName != parameters[i].Name) { return false; } } return true; } static readonly AstNode objectInitializerPattern = new AssignmentExpression( new MemberReferenceExpression { Target = new InitializedObjectExpression(), MemberName = Pattern.AnyString }.WithName("left"), new AnyNode("right") ); static readonly AstNode collectionInitializerPattern = new InvocationExpression { Target = new MemberReferenceExpression { Target = new InitializedObjectExpression(), MemberName = "Add" }, Arguments = { new Repeat(new AnyNode("arg")) } }; sealed class InitializedObjectExpression : IdentifierExpression { public InitializedObjectExpression() : base("__initialized_object__") {} protected internal override bool DoMatch(AstNode other, Match match) { return other is InitializedObjectExpression; } } /// <summary> /// Divides expr by the size of 'type'. /// </summary> Expression DivideBySize(Expression expr, TypeReference type) { CastExpression cast = expr as CastExpression; if (cast != null && cast.Type is PrimitiveType && ((PrimitiveType)cast.Type).Keyword == "int") expr = cast.Expression.Detach(); Expression sizeOfExpression; switch (TypeAnalysis.GetInformationAmount(type)) { case 1: case 8: sizeOfExpression = new PrimitiveExpression(1); break; case 16: sizeOfExpression = new PrimitiveExpression(2); break; case 32: sizeOfExpression = new PrimitiveExpression(4); break; case 64: sizeOfExpression = new PrimitiveExpression(8); break; default: sizeOfExpression = new SizeOfExpression { Type = AstBuilder.ConvertType(type) }; break; } BinaryOperatorExpression boe = expr as BinaryOperatorExpression; if (boe != null && boe.Operator == BinaryOperatorType.Multiply && sizeOfExpression.IsMatch(boe.Right)) return boe.Left.Detach(); if (sizeOfExpression.IsMatch(expr)) return new PrimitiveExpression(1); return new BinaryOperatorExpression(expr, BinaryOperatorType.Divide, sizeOfExpression); } Expression MakeDefaultValue(TypeReference type) { TypeDefinition typeDef = type.Resolve(); if (typeDef != null) { if (TypeAnalysis.IsIntegerOrEnum(typeDef)) return AstBuilder.MakePrimitive(0, typeDef); else if (!typeDef.IsValueType) return new NullReferenceExpression(); switch (typeDef.FullName) { case "System.Nullable`1": return new NullReferenceExpression(); case "System.Single": return new PrimitiveExpression(0f); case "System.Double": return new PrimitiveExpression(0.0); case "System.Decimal": return new PrimitiveExpression(0m); } } return new DefaultValueExpression { Type = AstBuilder.ConvertType(type) }; } AstNode TransformCall(bool isVirtual, ILExpression byteCode, List<Ast.Expression> args) { Cecil.MethodReference cecilMethod = (MethodReference)byteCode.Operand; Cecil.MethodDefinition cecilMethodDef = cecilMethod.Resolve(); Ast.Expression target; List<Ast.Expression> methodArgs = new List<Ast.Expression>(args); if (cecilMethod.HasThis) { target = methodArgs[0]; methodArgs.RemoveAt(0); // Unpack any DirectionExpression that is used as target for the call // (calling methods on value types implicitly passes the first argument by reference) target = UnpackDirectionExpression(target); if (cecilMethodDef != null) { // convert null.ToLower() to ((string)null).ToLower() if (target is NullReferenceExpression) target = target.CastTo(AstBuilder.ConvertType(cecilMethod.DeclaringType)); if (cecilMethodDef.DeclaringType.IsInterface) { TypeReference tr = byteCode.Arguments[0].InferredType; if (tr != null) { TypeDefinition td = tr.Resolve(); if (td != null && !td.IsInterface) { // Calling an interface method on a non-interface object: // we need to introduce an explicit cast target = target.CastTo(AstBuilder.ConvertType(cecilMethod.DeclaringType)); } } } } } else { target = new TypeReferenceExpression { Type = AstBuilder.ConvertType(cecilMethod.DeclaringType) }; } if (target is ThisReferenceExpression && !isVirtual) { // a non-virtual call on "this" might be a "base"-call. if (cecilMethod.DeclaringType.GetElementType() != methodDef.DeclaringType) { // If we're not calling a method in the current class; we must be calling one in the base class. target = new BaseReferenceExpression(); } } if (cecilMethod.Name == ".ctor" && cecilMethod.DeclaringType.IsValueType) { // On value types, the constructor can be called. // This is equivalent to 'target = new ValueType(args);'. ObjectCreateExpression oce = new ObjectCreateExpression(); oce.Type = AstBuilder.ConvertType(cecilMethod.DeclaringType); oce.AddAnnotation(cecilMethod); AdjustArgumentsForMethodCall(cecilMethod, methodArgs); oce.Arguments.AddRange(methodArgs); return new AssignmentExpression(target, oce); } if (cecilMethod.Name == "Get" && cecilMethod.DeclaringType is ArrayType && methodArgs.Count > 1) { return target.Indexer(methodArgs); } else if (cecilMethod.Name == "Set" && cecilMethod.DeclaringType is ArrayType && methodArgs.Count > 2) { return new AssignmentExpression(target.Indexer(methodArgs.GetRange(0, methodArgs.Count - 1)), methodArgs.Last()); } // Test whether the method is an accessor: if (cecilMethodDef != null) { if (cecilMethodDef.IsGetter && methodArgs.Count == 0) { foreach (var prop in cecilMethodDef.DeclaringType.Properties) { if (prop.GetMethod == cecilMethodDef) return target.Member(prop.Name).WithAnnotation(prop).WithAnnotation(cecilMethod); } } else if (cecilMethodDef.IsGetter) { // with parameters PropertyDefinition indexer = GetIndexer(cecilMethodDef); if (indexer != null) return target.Indexer(methodArgs).WithAnnotation(indexer).WithAnnotation(cecilMethod); } else if (cecilMethodDef.IsSetter && methodArgs.Count == 1) { foreach (var prop in cecilMethodDef.DeclaringType.Properties) { if (prop.SetMethod == cecilMethodDef) return new Ast.AssignmentExpression(target.Member(prop.Name).WithAnnotation(prop).WithAnnotation(cecilMethod), methodArgs[0]); } } else if (cecilMethodDef.IsSetter && methodArgs.Count > 1) { PropertyDefinition indexer = GetIndexer(cecilMethodDef); if (indexer != null) return new AssignmentExpression( target.Indexer(methodArgs.GetRange(0, methodArgs.Count - 1)).WithAnnotation(indexer).WithAnnotation(cecilMethod), methodArgs[methodArgs.Count - 1] ); } else if (cecilMethodDef.IsAddOn && methodArgs.Count == 1) { foreach (var ev in cecilMethodDef.DeclaringType.Events) { if (ev.AddMethod == cecilMethodDef) { return new Ast.AssignmentExpression { Left = target.Member(ev.Name).WithAnnotation(ev).WithAnnotation(cecilMethod), Operator = AssignmentOperatorType.Add, Right = methodArgs[0] }; } } } else if (cecilMethodDef.IsRemoveOn && methodArgs.Count == 1) { foreach (var ev in cecilMethodDef.DeclaringType.Events) { if (ev.RemoveMethod == cecilMethodDef) { return new Ast.AssignmentExpression { Left = target.Member(ev.Name).WithAnnotation(ev).WithAnnotation(cecilMethod), Operator = AssignmentOperatorType.Subtract, Right = methodArgs[0] }; } } } else if (cecilMethodDef.Name == "Invoke" && cecilMethodDef.DeclaringType.BaseType != null && cecilMethodDef.DeclaringType.BaseType.FullName == "System.MulticastDelegate") { AdjustArgumentsForMethodCall(cecilMethod, methodArgs); return target.Invoke(methodArgs).WithAnnotation(cecilMethod); } } // Default invocation AdjustArgumentsForMethodCall(cecilMethodDef ?? cecilMethod, methodArgs); return target.Invoke(cecilMethod.Name, ConvertTypeArguments(cecilMethod), methodArgs).WithAnnotation(cecilMethod); } static Expression UnpackDirectionExpression(Expression target) { if (target is DirectionExpression) { return ((DirectionExpression)target).Expression.Detach(); } else { return target; } } static void AdjustArgumentsForMethodCall(MethodReference cecilMethod, List<Expression> methodArgs) { // Convert 'ref' into 'out' where necessary for (int i = 0; i < methodArgs.Count && i < cecilMethod.Parameters.Count; i++) { DirectionExpression dir = methodArgs[i] as DirectionExpression; ParameterDefinition p = cecilMethod.Parameters[i]; if (dir != null && p.IsOut && !p.IsIn) dir.FieldDirection = FieldDirection.Out; } } internal static PropertyDefinition GetIndexer(MethodDefinition cecilMethodDef) { TypeDefinition typeDef = cecilMethodDef.DeclaringType; string indexerName = null; foreach (CustomAttribute ca in typeDef.CustomAttributes) { if (ca.Constructor.FullName == "System.Void System.Reflection.DefaultMemberAttribute::.ctor(System.String)") { indexerName = ca.ConstructorArguments.Single().Value as string; break; } } if (indexerName == null) return null; foreach (PropertyDefinition prop in typeDef.Properties) { if (prop.Name == indexerName) { if (prop.GetMethod == cecilMethodDef || prop.SetMethod == cecilMethodDef) return prop; } } return null; } #if DEBUG static readonly ConcurrentDictionary<ILCode, int> unhandledOpcodes = new ConcurrentDictionary<ILCode, int>(); #endif [Conditional("DEBUG")] public static void ClearUnhandledOpcodes() { #if DEBUG unhandledOpcodes.Clear(); #endif } [Conditional("DEBUG")] public static void PrintNumberOfUnhandledOpcodes() { #if DEBUG foreach (var pair in unhandledOpcodes) { Debug.WriteLine("AddMethodBodyBuilder unhandled opcode: {1}x {0}", pair.Key, pair.Value); } #endif } static Expression InlineAssembly(ILExpression byteCode, List<Ast.Expression> args) { #if DEBUG unhandledOpcodes.AddOrUpdate(byteCode.Code, c => 1, (c, n) => n+1); #endif // Output the operand of the unknown IL code as well if (byteCode.Operand != null) { args.Insert(0, new IdentifierExpression(FormatByteCodeOperand(byteCode.Operand))); } return new IdentifierExpression(byteCode.Code.GetName()).Invoke(args); } static string FormatByteCodeOperand(object operand) { if (operand == null) { return string.Empty; //} else if (operand is ILExpression) { // return string.Format("IL_{0:X2}", ((ILExpression)operand).Offset); } else if (operand is MethodReference) { return ((MethodReference)operand).Name + "()"; } else if (operand is Cecil.TypeReference) { return ((Cecil.TypeReference)operand).FullName; } else if (operand is VariableDefinition) { return "V_" + ((VariableDefinition)operand).Index; } else if (operand is ParameterDefinition) { return ((ParameterDefinition)operand).Name; } else if (operand is FieldReference) { return ((FieldReference)operand).Name; } else if (operand is string) { return "\"" + operand + "\""; } else if (operand is int) { return operand.ToString(); } else { return operand.ToString(); } } static IEnumerable<AstType> ConvertTypeArguments(MethodReference cecilMethod) { GenericInstanceMethod g = cecilMethod as GenericInstanceMethod; if (g == null) return null; if (g.GenericArguments.Any(ta => ta.ContainsAnonymousType())) return null; return g.GenericArguments.Select(t => AstBuilder.ConvertType(t)); } static Ast.DirectionExpression MakeRef(Ast.Expression expr) { return new DirectionExpression { Expression = expr, FieldDirection = FieldDirection.Ref }; } Ast.Expression Convert(Ast.Expression expr, Cecil.TypeReference actualType, Cecil.TypeReference reqType) { if (actualType == null || reqType == null || TypeAnalysis.IsSameType(actualType, reqType)) { return expr; } else if (actualType is ByReferenceType && reqType is PointerType && expr is DirectionExpression) { return Convert( new UnaryOperatorExpression(UnaryOperatorType.AddressOf, ((DirectionExpression)expr).Expression.Detach()), new PointerType(((ByReferenceType)actualType).ElementType), reqType); } else if (actualType is PointerType && reqType is ByReferenceType) { expr = Convert(expr, actualType, new PointerType(((ByReferenceType)reqType).ElementType)); return new DirectionExpression { FieldDirection = FieldDirection.Ref, Expression = new UnaryOperatorExpression(UnaryOperatorType.Dereference, expr) }; } else if (actualType is PointerType && reqType is PointerType) { if (actualType.FullName != reqType.FullName) return expr.CastTo(AstBuilder.ConvertType(reqType)); else return expr; } else { bool actualIsIntegerOrEnum = TypeAnalysis.IsIntegerOrEnum(actualType); bool requiredIsIntegerOrEnum = TypeAnalysis.IsIntegerOrEnum(reqType); if (TypeAnalysis.IsBoolean(reqType)) { if (TypeAnalysis.IsBoolean(actualType)) return expr; if (actualIsIntegerOrEnum) { return new BinaryOperatorExpression(expr, BinaryOperatorType.InEquality, AstBuilder.MakePrimitive(0, actualType)); } else { return new BinaryOperatorExpression(expr, BinaryOperatorType.InEquality, new NullReferenceExpression()); } } if (TypeAnalysis.IsBoolean(actualType) && requiredIsIntegerOrEnum) { return new ConditionalExpression { Condition = expr, TrueExpression = AstBuilder.MakePrimitive(1, reqType), FalseExpression = AstBuilder.MakePrimitive(0, reqType) }; } if (expr is PrimitiveExpression && !requiredIsIntegerOrEnum && TypeAnalysis.IsEnum(actualType)) { return expr.CastTo(AstBuilder.ConvertType(actualType)); } bool actualIsPrimitiveType = actualIsIntegerOrEnum || actualType.MetadataType == MetadataType.Single || actualType.MetadataType == MetadataType.Double; bool requiredIsPrimitiveType = requiredIsIntegerOrEnum || reqType.MetadataType == MetadataType.Single || reqType.MetadataType == MetadataType.Double; if (actualIsPrimitiveType && requiredIsPrimitiveType) { return expr.CastTo(AstBuilder.ConvertType(reqType)); } return expr; } } } }
using System; using System.Collections.Generic; using System.Net.Sockets; using ProtoBuf.Meta; using System.IO; using System.Net; namespace Camp.HogRider { public class Server { TcpClient _client; readonly string _host; readonly int _port; readonly int _bufferSize; int _nBytesAvailable; Dictionary<int, Type> _idTypeMap = new Dictionary<int, Type>(); Dictionary<Type, int> _typeIdMap = new Dictionary<Type, int>(); public event Action<object> MessageReceived; public event Action Connected; public event Action Disconnected; public event Action<Exception> ExceptionRaised; public const int DefaultBufferSize = 2 << 11; public Server(string host, int port, int bufferSize = DefaultBufferSize) { _host = host; _port = port; _bufferSize = bufferSize; StaticProtocolRegistration.RegisterAll(this); } public void Register(int typeId, Type type) { _idTypeMap[typeId] = type; _typeIdMap[type] = typeId; } void OnException(Exception ex) { Stop(); if (ExceptionRaised != null) ExceptionRaised(ex); } public static IPAddress GetIPAddress(string host) { // Dns may be blocked without internet connection even if the host is actually an IP string. IPAddress result; if (IPAddress.TryParse(host, out result)) return result; IPAddress[] candidates = Dns.GetHostAddresses(host); if (candidates.Length == 1) return candidates[0]; var random = new Random(); int index = random.Next(candidates.Length); return candidates[index]; } #region Connecting public void Start() { if (_client != null) return; IPAddress address = GetIPAddress(_host); _client = new TcpClient(); _client.BeginConnect(address, _port, OnConnected, state: null); } void OnConnected(IAsyncResult result) { try { _client.EndConnect(result); if (Connected != null) Connected(); ReceiveLoop(); } catch (Exception ex) { OnException(ex); } } public void Stop() { if (_client == null) return; _client.Close(); if (Disconnected != null) Disconnected(); _client = null; _nBytesAvailable = 0; } #endregion #region Receiving void ReceiveLoop(byte[] buffer = null) { buffer = buffer ?? new byte[_bufferSize]; _client.GetStream().BeginRead(buffer, 0, buffer.Length, OnReceived, state: buffer); } void OnReceived(IAsyncResult result) { var buffer = (byte[])result.AsyncState; try { int nByteReceived = _client.GetStream().EndRead(result); if (nByteReceived == 0) { Stop(); return; } _nBytesAvailable += nByteReceived; TryDeserialize(buffer); ReceiveLoop(buffer); } catch (Exception ex) { OnException(ex); } } const int HeaderLength = sizeof(int) * 2; void TryDeserialize(byte[] buffer) { // |-------------|-------------|------------------....| // totalLength type id message // |<--- totalLength --->| if (_nBytesAvailable < HeaderLength) return; int totalLength = BitConverter.ToInt32(buffer, 0); if (totalLength + sizeof(int) > _nBytesAvailable) return; int typeId = BitConverter.ToInt32(buffer, sizeof(int)); var messageLength = totalLength - sizeof(int); using (var ms = new MemoryStream(buffer, HeaderLength, messageLength, writable: false)) { var message = RuntimeTypeModel.Default.Deserialize(ms, null, _idTypeMap[typeId]); if (MessageReceived != null) MessageReceived(message); } _nBytesAvailable -= totalLength; // It is ok for _nBytesAvailable to be ZERO. Array.Copy(buffer, totalLength + sizeof(int), buffer, 0, _nBytesAvailable); } #endregion #region Sending public void Send(object message) { byte[] buffer = new byte[_bufferSize]; // Type id, write it down with first 4 bytes skipped (preserved for messageLength). int typeId = _typeIdMap[message.GetType()]; BitConverter.GetBytes(typeId).CopyTo(buffer, sizeof(int)); using (var ms = new MemoryStream(buffer, HeaderLength, buffer.Length - HeaderLength, writable: true)) { RuntimeTypeModel.Default.Serialize(ms, message); int messageLength = (int)ms.Position; BitConverter.GetBytes(messageLength + sizeof(int)).CopyTo(buffer, 0); _client.GetStream().BeginWrite(buffer, 0, messageLength + HeaderLength, OnSent, state: null); } } void OnSent(IAsyncResult result) { try { _client.GetStream().EndWrite(result); } catch (Exception ex) { OnException(ex); } } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PlotView.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // <summary> // Provides a view that can show a <see cref="PlotModel" />. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace OxyPlot.Xamarin.iOS { using Foundation; using OxyPlot; using UIKit; /// <summary> /// Provides a view that can show a <see cref="PlotModel" />. /// </summary> [Register("PlotView")] public class PlotView : UIView, IPlotView { /// <summary> /// The current plot model. /// </summary> private PlotModel model; /// <summary> /// The default plot controller. /// </summary> private IPlotController defaultController; /// <summary> /// The pan zoom gesture recognizer /// </summary> private readonly PanZoomGestureRecognizer panZoomGesture = new PanZoomGestureRecognizer(); /// <summary> /// The tap gesture recognizer /// </summary> private readonly UITapGestureRecognizer tapGesture = new UITapGestureRecognizer(); /// <summary> /// Initializes a new instance of the <see cref="OxyPlot.Xamarin.iOS.PlotView"/> class. /// </summary> public PlotView() { this.Initialize (); } /// <summary> /// Initializes a new instance of the <see cref="OxyPlot.Xamarin.iOS.PlotView"/> class. /// </summary> /// <param name="frame">The initial frame.</param> public PlotView(CoreGraphics.CGRect frame) : base(frame) { this.Initialize (); } /// <summary> /// Initializes a new instance of the <see cref="OxyPlot.Xamarin.iOS.PlotView"/> class. /// </summary> /// <param name="coder">Coder.</param> [Export ("initWithCoder:")] public PlotView(NSCoder coder) : base (coder) { this.Initialize (); } /// <summary> /// Uses the new layout. /// </summary> /// <returns><c>true</c>, if new layout was used, <c>false</c> otherwise.</returns> [Export ("requiresConstraintBasedLayout")] private bool UseNewLayout () { return true; } /// <summary> /// Initialize the view. /// </summary> private void Initialize() { this.UserInteractionEnabled = true; this.MultipleTouchEnabled = true; this.BackgroundColor = UIColor.White; this.KeepAspectRatioWhenPinching = true; this.panZoomGesture.AddTarget(this.HandlePanZoomGesture); this.tapGesture.AddTarget(this.HandleTapGesture); //Prevent panZoom and tap gestures from being recognized simultaneously this.tapGesture.RequireGestureRecognizerToFail(this.panZoomGesture); // Do not intercept touches on overlapping views this.panZoomGesture.ShouldReceiveTouch += (recognizer, touch) => touch.View == this; this.tapGesture.ShouldReceiveTouch += (recognizer, touch) => touch.View == this; } /// <summary> /// Gets or sets the <see cref="PlotModel"/> to show in the view. /// </summary> /// <value>The <see cref="PlotModel"/>.</value> public PlotModel Model { get { return this.model; } set { if (this.model != value) { if (this.model != null) { ((IPlotModel)this.model).AttachPlotView(null); this.model = null; } if (value != null) { ((IPlotModel)value).AttachPlotView(this); this.model = value; } this.InvalidatePlot(); } } } /// <summary> /// Gets or sets the <see cref="IPlotController"/> that handles input events. /// </summary> /// <value>The <see cref="IPlotController"/>.</value> public IPlotController Controller { get; set; } /// <summary> /// Gets the actual model in the view. /// </summary> /// <value> /// The actual model. /// </value> Model IView.ActualModel { get { return this.Model; } } /// <summary> /// Gets the actual <see cref="PlotModel"/> to show. /// </summary> /// <value>The actual model.</value> public PlotModel ActualModel { get { return this.Model; } } /// <summary> /// Gets the actual controller. /// </summary> /// <value> /// The actual <see cref="IController" />. /// </value> IController IView.ActualController { get { return this.ActualController; } } /// <summary> /// Gets the coordinates of the client area of the view. /// </summary> public OxyRect ClientArea { get { // TODO return new OxyRect(0, 0, 100, 100); } } /// <summary> /// Gets the actual <see cref="IPlotController"/>. /// </summary> /// <value>The actual plot controller.</value> public IPlotController ActualController { get { return this.Controller ?? (this.defaultController ?? (this.defaultController = new PlotController())); } } /// <summary> /// Gets or sets a value indicating whether this <see cref="OxyPlot.Xamarin.iOS.PlotView"/> keeps the aspect ratio when pinching. /// </summary> /// <value><c>true</c> if keep aspect ratio when pinching; otherwise, <c>false</c>.</value> public bool KeepAspectRatioWhenPinching { get { return this.panZoomGesture.KeepAspectRatioWhenPinching; } set { this.panZoomGesture.KeepAspectRatioWhenPinching = value; } } /// <summary> /// How far apart touch points must be on a certain axis to enable scaling that axis. /// (only applies if KeepAspectRatioWhenPinching == false) /// </summary> public double ZoomThreshold { get { return this.panZoomGesture.ZoomThreshold; } set { this.panZoomGesture.ZoomThreshold = value; } } /// <summary> /// If <c>true</c>, and KeepAspectRatioWhenPinching is <c>false</c>, a zoom-out gesture /// can turn into a zoom-in gesture if the fingers cross. Setting to <c>false</c> will /// instead simply stop the zoom at that point. /// </summary> public bool AllowPinchPastZero { get { return this.panZoomGesture.AllowPinchPastZero; } set { this.panZoomGesture.AllowPinchPastZero = value; } } /// <summary> /// Hides the tracker. /// </summary> public void HideTracker() { } /// <summary> /// Hides the zoom rectangle. /// </summary> public void HideZoomRectangle() { } /// <summary> /// Invalidates the plot (not blocking the UI thread) /// </summary> /// <param name="updateData">If set to <c>true</c> update data.</param> public void InvalidatePlot(bool updateData = true) { var actualModel = this.model; if (actualModel != null) { // TODO: update the model on a background thread ((IPlotModel)actualModel).Update(updateData); } this.SetNeedsDisplay(); } /// <summary> /// Sets the cursor type. /// </summary> /// <param name="cursorType">The cursor type.</param> public void SetCursorType(CursorType cursorType) { // No cursor on iOS } /// <summary> /// Shows the tracker. /// </summary> /// <param name="trackerHitResult">The tracker data.</param> public void ShowTracker(TrackerHitResult trackerHitResult) { // TODO: how to show a tracker on iOS // the tracker must be moved away from the finger... } /// <summary> /// Shows the zoom rectangle. /// </summary> /// <param name="rectangle">The rectangle.</param> public void ShowZoomRectangle(OxyRect rectangle) { // Not needed - better with pinch events on iOS? } /// <summary> /// Stores text on the clipboard. /// </summary> /// <param name="text">The text.</param> public void SetClipboardText(string text) { UIPasteboard.General.SetValue(new NSString(text), "public.utf8-plain-text"); } /// <summary> /// Draws the content of the view. /// </summary> /// <param name="rect">The rectangle to draw.</param> public override void Draw(CoreGraphics.CGRect rect) { var actualModel = (IPlotModel)this.model; if (actualModel != null) { var context = UIGraphics.GetCurrentContext (); using (var renderer = new CoreGraphicsRenderContext(context)) { if (actualModel.Background.IsVisible()) { context.SetFillColor (actualModel.Background.ToCGColor ()); context.FillRect (rect); } actualModel.Render(renderer, rect.Width, rect.Height); } } } /// <summary> /// Method invoked when a motion (a shake) has started. /// </summary> /// <param name="motion">The motion subtype.</param> /// <param name="evt">The event arguments.</param> public override void MotionBegan(UIEventSubtype motion, UIEvent evt) { base.MotionBegan(motion, evt); if (motion == UIEventSubtype.MotionShake) { this.ActualController.HandleGesture(this, new OxyShakeGesture(), new OxyKeyEventArgs()); } } /// <summary> /// Used to add/remove the gesture recognizer so that it /// doesn't prevent the PlotView from being garbage-collected. /// </summary> /// <param name="newsuper">New superview</param> public override void WillMoveToSuperview (UIView newsuper) { if (newsuper == null) { this.RemoveGestureRecognizer (this.panZoomGesture); this.RemoveGestureRecognizer (this.tapGesture); } else if (this.Superview == null) { this.AddGestureRecognizer (this.panZoomGesture); this.AddGestureRecognizer (this.tapGesture); } base.WillMoveToSuperview (newsuper); } private void HandlePanZoomGesture() { switch (this.panZoomGesture.State) { case UIGestureRecognizerState.Began: this.ActualController.HandleTouchStarted(this, this.panZoomGesture.TouchEventArgs); break; case UIGestureRecognizerState.Changed: this.ActualController.HandleTouchDelta(this, this.panZoomGesture.TouchEventArgs); break; case UIGestureRecognizerState.Ended: case UIGestureRecognizerState.Cancelled: this.ActualController.HandleTouchCompleted(this, this.panZoomGesture.TouchEventArgs); break; } } private void HandleTapGesture() { var location = this.tapGesture.LocationInView(this); this.ActualController.HandleTouchStarted(this, location.ToTouchEventArgs()); this.ActualController.HandleTouchCompleted(this, location.ToTouchEventArgs()); } } }
using System; using System.Collections; namespace XmlNotepad { public class CommandEventArgs : EventArgs { Command cmd; public CommandEventArgs(Command cmd) { this.cmd = cmd; } public Command Command { get { return this.cmd; } } } public class UndoManager { ArrayList stack = new ArrayList(); int pos; int max; Command exec = null; CompoundCommand compound; public event EventHandler StateChanged; public event EventHandler<CommandEventArgs> CommandDone; public event EventHandler<CommandEventArgs> CommandUndone; public event EventHandler<CommandEventArgs> CommandRedone; public UndoManager(int maxHistory) { this.stack = new ArrayList(); this.max = maxHistory; } public void Clear(){ if (stack.Count>0){ pos = 0; stack.Clear(); if (StateChanged != null){ StateChanged(this, EventArgs.Empty); } } } public Command Executing { get { return this.exec; } } public bool CanUndo{ get { return pos>0; } } public bool CanRedo{ get { return pos < stack.Count; } } public Command Current { get { if (pos>=0 && pos < stack.Count){ return (Command)stack[pos]; } return null; } } void Add(Command cmd) { if (pos < stack.Count) { stack.RemoveRange(pos, stack.Count - pos); } System.Diagnostics.Trace.WriteLine(cmd.Name); stack.Add(cmd); if (stack.Count > this.max) { stack.RemoveAt(0); } else { pos++; } } public void Push(Command cmd) { if (cmd.IsNoop) return; // do nothing! if (this.compound != null) { this.compound.Add(cmd); } else { Add(cmd); } // Must do command after adding it to the command stack! Command saved = this.exec; try { this.exec = cmd; cmd.Do(); } finally { this.exec = saved; } if (StateChanged != null) { StateChanged(this, EventArgs.Empty); } if (CommandDone != null) { CommandDone(this, new CommandEventArgs(cmd)); } } public Command Undo(){ if (pos>0){ pos--; Command cmd = this.Current; if (cmd != null && !cmd.IsNoop){ Command saved = this.exec; try { this.exec = cmd; cmd.Undo(); } finally { this.exec = saved; } if (StateChanged != null) { StateChanged(this, EventArgs.Empty); } if (CommandUndone != null) { CommandUndone(this, new CommandEventArgs(cmd)); } } return cmd; } return null; } public Command Redo(){ if (pos < stack.Count){ Command cmd = this.Current; if (cmd != null && !cmd.IsNoop){ Command saved = this.exec; try { this.exec = cmd; cmd.Redo(); } finally { this.exec = saved; } if (StateChanged != null) { StateChanged(this, new CommandEventArgs(cmd)); } if (CommandRedone != null) { CommandRedone(this, new CommandEventArgs(cmd)); } } pos++; return cmd; } return null; } public Command Peek(){ if (pos>0 && pos-1 < stack.Count){ return (Command)stack[pos-1]; } return null; } public Command Pop(){ // remove command without undoing it. if (pos > 0) { pos--; if (pos < stack.Count) { stack.RemoveAt(pos); } if (StateChanged != null) { StateChanged(this, EventArgs.Empty); } } return this.Current; } public void Merge(CompoundCommand cmd) { // Replace the current command without upsetting rest of the redo stack // and insert the current command into this compound command. Command current = Peek(); if (current != null) { stack.Insert(pos-1, cmd); stack.RemoveAt(pos); cmd.Do(); cmd.Insert(current); } else { Push(cmd); } } public CompoundCommand OpenCompoundAction(string name) { this.compound = new CompoundCommand(name); Add(this.compound); return this.compound; } public void CloseCompoundAction() { this.compound = null; } } public abstract class Command { public abstract string Name { get; } public abstract void Do(); public abstract void Undo(); public abstract void Redo(); public abstract bool IsNoop { get; } } public class CompoundCommand : Command { ArrayList commands = new ArrayList(); string name; public CompoundCommand(string name) { this.name = name; } public override string Name { get { return name; } } public void Add(Command cmd) { commands.Add(cmd); } public int Count { get { return commands.Count; } } public override void Do() { if (this.IsNoop) return; foreach (Command cmd in this.commands) { cmd.Do(); } } public override void Undo() { // Must undo in reverse order! for (int i = this.commands.Count - 1; i >= 0; i--) { Command cmd = (Command)this.commands[i]; cmd.Undo(); } } public override void Redo() { foreach (Command cmd in this.commands) { cmd.Redo(); } } public override bool IsNoop { get { foreach (Command cmd in this.commands) { if (!cmd.IsNoop) return false; } return true; } } public void Insert(Command cmd) { commands.Insert(0, cmd); } } }
namespace YAMP { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; /// <summary> /// Provides internal access to the elements and handles the element registration and variable assignment. /// </summary> sealed class Elements : IElementMapping { #region Fields readonly IDictionary<String, Operator> _binaryOperators; readonly IDictionary<String, Operator> _unaryOperators; readonly List<Expression> _expressions; readonly IDictionary<String, Keyword> _keywords; readonly IDictionary<Guid, Plugin> _plugins; #endregion #region ctor public Elements(ParseContext context) { _binaryOperators = new Dictionary<String, Operator>(); _unaryOperators = new Dictionary<String, Operator>(); _expressions = new List<Expression>(); _keywords = new Dictionary<String, Keyword>(); _plugins = new Dictionary<Guid, Plugin>(); } #endregion #region Properties /// <summary> /// Gets the function loader, if any. /// </summary> public IEnumerable<IFunctionLoader> Loaders { get { return _plugins.SelectMany(m => m.Value.Loaders); } } /// <summary> /// Gets the list of possible keywords. /// </summary> public String[] Keywords { get { return _keywords.Keys.ToArray(); } } #endregion #region Register elements /// <summary> /// Registers the IFunction, IConstant and IRegisterToken token classes at the specified context. /// </summary> /// <param name="context"> /// The context where the IFunction and IConstant instances will be placed. /// </param> /// <param name="assembly"> /// The assembly to load. /// </param> /// <returns>The ID for the assembly.</returns> public Guid RegisterAssembly(ParseContext context, Assembly assembly) { var plugin = new Plugin(context, assembly); plugin.Install(); _plugins.Add(plugin.Id, plugin); return plugin.Id; } /// <summary> /// Removes a previously added assembly. /// </summary> /// <param name="pluginId">The id of the plugin to remove.</param> public void RemoveAssembly(Guid pluginId) { if (_plugins.ContainsKey(pluginId)) { var plugin = _plugins[pluginId]; plugin.Uninstall(); _plugins.Remove(pluginId); } } #endregion #region Add elements /// <summary> /// Adds an operator to the dictionary. /// </summary> /// <param name="pattern">The operator pattern, i.e. += for add and assign.</param> /// <param name="op">The instance of the operator.</param> public void AddOperator(String pattern, Operator op) { //Operators implemented in Plugins will "repeat" if the Plugin is loaded a second time in the same ApplicationDomain, // since operators are added to ParseContext.Root (static variable), and never removed. //Check if it's the same implementation and only throw if not. if (!op.IsRightToLeft && op.Expressions == 1) { if (!_unaryOperators.ContainsKey(pattern)) { _unaryOperators.Add(pattern, op); } else { if (op.GetType() != _unaryOperators[pattern].GetType()) throw new ArgumentException(string.Format("Unary Operator {0} is repeated.", pattern)); } } else { if (!_binaryOperators.ContainsKey(pattern)) { _binaryOperators.Add(pattern, op); } else { if (op.GetType() != _binaryOperators[pattern].GetType()) throw new ArgumentException(string.Format("Binary Operator {0} is repeated.", pattern)); } } } /// <summary> /// Adds an expression to the list of expressions. /// </summary> /// <param name="exp">The instance of the expression.</param> public void AddExpression(Expression exp) { _expressions.Add(exp); } /// <summary> /// Adds a keyword to the dictionary. /// </summary> /// <param name="pattern">The exact keyword pattern, i.e. for for the for-loop.</param> /// <param name="keyword">The instance of the keyword.</param> public void AddKeyword(String pattern, Keyword keyword) { _keywords.Add(pattern, keyword); } #endregion #region Find elements /// <summary> /// Searches for the given keyword in the list of available keywords. Creates a class if the keyword is found. /// </summary> /// <param name="keyword">The keyword to look for.</param> /// <param name="engine">The engine to use.</param> /// <returns>Keyword that matches the given keyword.</returns> public Expression FindKeywordExpression(String keyword, ParseEngine engine) { if (_keywords.ContainsKey(keyword)) { return _keywords[keyword].Scan(engine); } return null; } /// <summary> /// Finds the exact keyword by its type. /// </summary> /// <typeparam name="T">The type of the keyword.</typeparam> /// <returns>The keyword or null.</returns> public T FindKeywordExpression<T>() where T : Keyword { foreach (var keyword in _keywords.Values) { if (keyword is T) { return (T)keyword; } } return null; } /// <summary> /// Finds the closest matching expression. /// </summary> /// <param name="engine">The engine to parse the query.</param> /// <returns>Expression that matches the current characters.</returns> public Expression FindExpression(ParseEngine engine) { foreach (var origin in _expressions) { var exp = origin.Scan(engine); if (exp != null) { return exp; } } return null; } /// <summary> /// Finds the exact expression by its type. /// </summary> /// <typeparam name="T">The type of the expression.</typeparam> /// <returns>The expression or null.</returns> public T FindExpression<T>() where T : Expression { foreach (var exp in _expressions) { if (exp is T) { return (T)exp; } } return null; } /// <summary> /// Finds the closest matching operator (all except left unary). /// </summary> /// <param name="engine">The engine to parse the query.</param> /// <returns>Operator that matches the current characters.</returns> public Operator FindOperator(ParseEngine engine) { var maxop = FindArbitraryOperator(_binaryOperators.Keys, engine); if (maxop.Length == 0) { return null; } return _binaryOperators[maxop].Create(engine); } /// <summary> /// Finds the closest matching left unary operator. /// </summary> /// <param name="engine">The engine to parse the query.</param> /// <returns>Operator that matches the current characters.</returns> public Operator FindLeftUnaryOperator(ParseEngine engine) { var maxop = FindArbitraryOperator(_unaryOperators.Keys, engine); if (maxop.Length == 0) { return null; } return _unaryOperators[maxop].Create(engine); } String FindArbitraryOperator(IEnumerable<String> operators, ParseEngine engine) { var maxop = String.Empty; var notfound = true; var chars = engine.Characters; var ptr = engine.Pointer; var rest = chars.Length - ptr; foreach (var op in operators) { if (op.Length <= rest && op.Length > maxop.Length) { notfound = false; for (var i = 0; !notfound && i < op.Length; i++) { notfound = (chars[ptr + i] != op[i]); } if (!notfound) { maxop = op; } } } return maxop; } /// <summary> /// Finds the exact operator by its type. /// </summary> /// <typeparam name="T">The type of the operator.</typeparam> /// <returns>The operator or null.</returns> public T FindOperator<T>() where T : Operator { foreach (var op in _binaryOperators.Values) { if (op is T) { return (T)op; } } foreach (var op in _unaryOperators.Values) { if (op is T) { return (T)op; } } return null; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using Microsoft.Build.Shared; using Shouldly; using Xunit; namespace Microsoft.Build.UnitTests { sealed public class AssemblyNameEx_Tests { /// <summary> /// Delegate defines a function that produces an AssemblyNameExtension from a string. /// </summary> /// <param name="name"></param> /// <returns></returns> internal delegate AssemblyNameExtension ProduceAssemblyNameEx(string name); private static string[] s_assemblyStrings = { "System.Xml, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Xml, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.XML, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.XM, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.XM, PublicKeyToken=b03f5f7f11d50a3a", "System.XM, Version=2.0.0.0, Culture=neutral", "System.XM, Version=2.0.0.0", "System.XM, PublicKeyToken=b03f5f7f11d50a3a", "System.XM, Culture=neutral", "System.Xml", "System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing" }; private static string[] s_assembliesForPartialMatch = { "System.Xml, Version=10.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a, Retargetable=Yes", "System.Xml, Version=10.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a, Retargetable=No", "System.Xml, Culture=en, PublicKeyToken=b03f5f7f11d50a3a", "System.Xml, Version=10.0.0.0, PublicKeyToken=b03f5f7f11d50a3a", "System.Xml, Version=10.0.0.0, Culture=en" }; /// <summary> /// All the different ways the same assembly name can be represented. /// </summary> private static ProduceAssemblyNameEx[] s_producers = { new ProduceAssemblyNameEx(ProduceAsString), new ProduceAssemblyNameEx(ProduceAsAssemblyName), new ProduceAssemblyNameEx(ProduceAsBoth), new ProduceAssemblyNameEx(ProduceAsLowerString), new ProduceAssemblyNameEx(ProduceAsLowerAssemblyName), new ProduceAssemblyNameEx(ProduceAsLowerBoth) }; private static AssemblyNameExtension ProduceAsString(string name) { return new AssemblyNameExtension(name); } private static AssemblyNameExtension ProduceAsLowerString(string name) { return new AssemblyNameExtension(name.ToLower()); } private static AssemblyNameExtension ProduceAsAssemblyName(string name) { return new AssemblyNameExtension(new AssemblyName(name)); } private static AssemblyNameExtension ProduceAsLowerAssemblyName(string name) { return new AssemblyNameExtension(new AssemblyName(name.ToLower())); } private static AssemblyNameExtension ProduceAsBoth(string name) { AssemblyNameExtension result = new AssemblyNameExtension(new AssemblyName(name)); // Force the string version to be produced too. string backToString = result.FullName; return result; } private static AssemblyNameExtension ProduceAsLowerBoth(string name) { return ProduceAsBoth(name.ToLower()); } /// <summary> /// General base name comparison validator. /// </summary> [Fact] public void CompareBaseName() { // For each pair of assembly strings... foreach (string assemblyString1 in s_assemblyStrings) { AssemblyName baseName1 = new AssemblyName(assemblyString1); foreach (string assemblyString2 in s_assemblyStrings) { AssemblyName baseName2 = new AssemblyName(assemblyString2); // ...and for each pair of production methods... foreach (ProduceAssemblyNameEx produce1 in s_producers) { foreach (ProduceAssemblyNameEx produce2 in s_producers) { AssemblyNameExtension a1 = produce1(assemblyString1); AssemblyNameExtension a2 = produce2(assemblyString2); int result = a1.CompareBaseNameTo(a2); int resultBaseline = String.Compare(baseName1.Name, baseName2.Name, StringComparison.OrdinalIgnoreCase); if (resultBaseline != result) { Assert.Equal(resultBaseline, result); } } } } } } /// <summary> /// General compareTo validator /// </summary> [Fact] public void CompareTo() { // For each pair of assembly strings... foreach (string assemblyString1 in s_assemblyStrings) { AssemblyName baseName1 = new AssemblyName(assemblyString1); foreach (string assemblyString2 in s_assemblyStrings) { AssemblyName baseName2 = new AssemblyName(assemblyString2); // ...and for each pair of production methods... foreach (ProduceAssemblyNameEx produce1 in s_producers) { foreach (ProduceAssemblyNameEx produce2 in s_producers) { AssemblyNameExtension a1 = produce1(assemblyString1); AssemblyNameExtension a2 = produce2(assemblyString2); int result = a1.CompareTo(a2); if (a1.Equals(a2)) { Assert.Equal(0, result); } if (a1.CompareBaseNameTo(a2) != 0) { Assert.Equal(a1.CompareBaseNameTo(a2), result); } if ( a1.CompareBaseNameTo(a2) == 0 // Only check version if basenames match && a1.Version != a2.Version ) { if (a1.Version == null) { // Expect -1 if a1.Version is null and the baseNames match Assert.Equal(-1, result); } else { Assert.Equal(a1.Version.CompareTo(a2.Version), result); } } int resultBaseline = String.Compare(a1.FullName, a2.FullName, StringComparison.OrdinalIgnoreCase); // Only check to see if the result and the resultBaseline match when the result baseline is 0 and the result is not 0. if (resultBaseline != result && resultBaseline == 0) { Assert.Equal(resultBaseline, result); } } } } } } [Fact] public void ExerciseMiscMethods() { AssemblyNameExtension a1 = s_producers[0](s_assemblyStrings[0]); Version newVersion = new Version(1, 2); a1.ReplaceVersion(newVersion); Assert.True(a1.Version.Equals(newVersion)); Assert.NotNull(a1.ToString()); } [Fact] public void EscapeDisplayNameCharacters() { // /// Those characters are Equals(=), Comma(,), Quote("), Apostrophe('), Backslash(\). string displayName = @"Hello,""Don't"" eat the \CAT"; Assert.Equal(0, String.Compare(AssemblyNameExtension.EscapeDisplayNameCharacters(displayName), @"Hello\,\""Don\'t\"" eat the \\CAT", StringComparison.OrdinalIgnoreCase)); } /// <summary> /// General equals comparison validator. /// </summary> [Fact] public void AreEquals() { // For each pair of assembly strings... foreach (string assemblyString1 in s_assemblyStrings) { AssemblyName baseName1 = new AssemblyName(assemblyString1); foreach (string assemblyString2 in s_assemblyStrings) { AssemblyName baseName2 = new AssemblyName(assemblyString2); // ...and for each pair of production methods... foreach (ProduceAssemblyNameEx produce1 in s_producers) { foreach (ProduceAssemblyNameEx produce2 in s_producers) { AssemblyNameExtension a1 = produce1(assemblyString1); AssemblyNameExtension a2 = produce2(assemblyString2); // Baseline is a mismatch which is known to exercise // the full code path. AssemblyNameExtension a3 = ProduceAsAssemblyName(assemblyString1); AssemblyNameExtension a4 = ProduceAsString(assemblyString2); bool result = a1.Equals(a2); bool resultBaseline = a3.Equals(a4); if (result != resultBaseline) { Assert.Equal(resultBaseline, result); } } } } } } /// <summary> /// General equals comparison validator when we are ignoring the version numbers in the name. /// </summary> [Fact] public void EqualsIgnoreVersion() { // For each pair of assembly strings... foreach (string assemblyString1 in s_assemblyStrings) { AssemblyName baseName1 = new AssemblyName(assemblyString1); foreach (string assemblyString2 in s_assemblyStrings) { AssemblyName baseName2 = new AssemblyName(assemblyString2); // ...and for each pair of production methods... foreach (ProduceAssemblyNameEx produce1 in s_producers) { foreach (ProduceAssemblyNameEx produce2 in s_producers) { AssemblyNameExtension a1 = produce1(assemblyString1); AssemblyNameExtension a2 = produce2(assemblyString2); // Baseline is a mismatch which is known to exercise // the full code path. AssemblyNameExtension a3 = ProduceAsAssemblyName(assemblyString1); AssemblyNameExtension a4 = ProduceAsString(assemblyString2); bool result = a1.EqualsIgnoreVersion(a2); bool resultBaseline = a3.EqualsIgnoreVersion(a4); if (result != resultBaseline) { Assert.Equal(resultBaseline, result); } } } } } } /// <summary> /// This repros a bug that was found while coding AssemblyNameExtension. /// </summary> [Fact] public void CompareBaseNameRealCase1() { AssemblyNameExtension a1 = ProduceAsBoth("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); AssemblyNameExtension a2 = ProduceAsString("System.Drawing"); int result = a1.CompareBaseNameTo(a2); // Base names should be equal. Assert.Equal(0, result); } /// <summary> /// Verify an exception is thrown when the simple name is not in the itemspec. /// /// </summary> [Fact] public void CreateAssemblyNameExtensionWithNoSimpleName() { // Mono does not throw on this string if (!NativeMethodsShared.IsMono) { Assert.Throws<FileLoadException>(() => { AssemblyNameExtension extension = new AssemblyNameExtension("Version=2.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a", true); } ); } } /// <summary> /// Verify an exception is thrown when the simple name is not in the itemspec. /// </summary> [Fact] public void CreateAssemblyNameExtensionWithNoSimpleName2() { // Mono does not throw on this string if (!NativeMethodsShared.IsMono) { Assert.Throws<FileLoadException>(() => { AssemblyNameExtension extension = new AssemblyNameExtension("Version=2.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a"); AssemblyNameExtension extension2 = new AssemblyNameExtension("A, Version=2.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a"); extension2.PartialNameCompare(extension); } ); } } /// <summary> /// Create an assembly name extension providing the name, version, culture, and public key. Also test cases /// where the public key is the only item specified /// </summary> [Fact] public void CreateAssemblyNameWithNameAndVersionCulturePublicKey() { AssemblyNameExtension extension = new AssemblyNameExtension("A, Version=2.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a"); Assert.Equal("A", extension.Name); Assert.True(extension.Version.Equals(new Version("2.0.0.0"))); Assert.True(extension.CultureInfo.Equals(new CultureInfo("en"))); Assert.Contains("b03f5f7f11d50a3a", extension.FullName); extension = new AssemblyNameExtension("A, Version=2.0.0.0, PublicKeyToken=b03f5f7f11d50a3a"); Assert.Equal("A", extension.Name); Assert.True(extension.Version.Equals(new Version("2.0.0.0"))); Assert.True(Object.ReferenceEquals(extension.CultureInfo, null)); Assert.Contains("b03f5f7f11d50a3a", extension.FullName); extension = new AssemblyNameExtension("A, Culture=en, PublicKeyToken=b03f5f7f11d50a3a"); Assert.Equal("A", extension.Name); Assert.True(Object.ReferenceEquals(extension.Version, null)); Assert.True(extension.CultureInfo.Equals(new CultureInfo("en"))); Assert.Contains("b03f5f7f11d50a3a", extension.FullName); extension = new AssemblyNameExtension("A, PublicKeyToken=b03f5f7f11d50a3a"); Assert.Equal("A", extension.Name); Assert.True(Object.ReferenceEquals(extension.Version, null)); Assert.True(Object.ReferenceEquals(extension.CultureInfo, null)); Assert.Contains("b03f5f7f11d50a3a", extension.FullName); extension = new AssemblyNameExtension("A"); Assert.Equal("A", extension.Name); Assert.True(Object.ReferenceEquals(extension.Version, null)); Assert.True(Object.ReferenceEquals(extension.CultureInfo, null)); } /// <summary> /// Make sure processor architecture is seen when it is in the string. /// </summary> [Fact] public void CreateAssemblyNameWithNameAndProcessorArchitecture() { AssemblyNameExtension extension = new AssemblyNameExtension("A, Version=2.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a, ProcessorArchitecture=MSIL"); Assert.Equal("A", extension.Name); Assert.True(extension.Version.Equals(new Version("2.0.0.0"))); Assert.True(extension.CultureInfo.Equals(new CultureInfo("en"))); Assert.Contains("b03f5f7f11d50a3a", extension.FullName); Assert.Contains("MSIL", extension.FullName); Assert.True(extension.HasProcessorArchitectureInFusionName); extension = new AssemblyNameExtension("A, Version=2.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a"); Assert.Equal("A", extension.Name); Assert.True(extension.Version.Equals(new Version("2.0.0.0"))); Assert.True(extension.CultureInfo.Equals(new CultureInfo("en"))); Assert.Contains("b03f5f7f11d50a3a", extension.FullName); Assert.False(extension.HasProcessorArchitectureInFusionName); } /// <summary> /// Verify partial matching on the simple name works /// </summary> [Fact] public void TestAssemblyPatialMatchSimpleName() { AssemblyNameExtension assemblyNameToMatch = new AssemblyNameExtension("System.Xml"); AssemblyNameExtension assemblyNameToNotMatch = new AssemblyNameExtension("System.Xmla"); foreach (string assembly in s_assembliesForPartialMatch) { AssemblyNameExtension assemblyToCompare = new AssemblyNameExtension(assembly); Assert.True(assemblyNameToMatch.PartialNameCompare(assemblyToCompare)); Assert.True(assemblyNameToMatch.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName)); } } /// <summary> /// Verify partial matching on the simple name and version /// </summary> [Fact] public void TestAssemblyPatialMatchSimpleNameVersion() { AssemblyNameExtension assemblyNameToMatchVersion = new AssemblyNameExtension("System.Xml, Version=10.0.0.0"); AssemblyNameExtension assemblyNameToNotMatch = new AssemblyNameExtension("System.Xml, Version=5.0.0.0"); AssemblyNameExtension assemblyMatchNoVersion = new AssemblyNameExtension("System.Xml"); foreach (string assembly in s_assembliesForPartialMatch) { AssemblyNameExtension assemblyToCompare = new AssemblyNameExtension(assembly); // If there is a version make sure the assembly name with the correct version matches // Make sure the assembly with the wrong version does not match if (assemblyToCompare.Version != null) { Assert.True(assemblyNameToMatchVersion.PartialNameCompare(assemblyToCompare)); Assert.True(assemblyNameToMatchVersion.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.Version)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.Version)); // Matches because version is not specified Assert.True(assemblyMatchNoVersion.PartialNameCompare(assemblyToCompare)); Assert.True(assemblyMatchNoVersion.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.Version)); } else { // If there is no version make names with a version specified do not match Assert.False(assemblyNameToMatchVersion.PartialNameCompare(assemblyToCompare)); Assert.False(assemblyNameToMatchVersion.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.Version)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.Version)); // Matches because version is not specified Assert.True(assemblyMatchNoVersion.PartialNameCompare(assemblyToCompare)); Assert.True(assemblyMatchNoVersion.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.Version)); } } } /// <summary> /// Verify partial matching on the simple name and culture /// </summary> [Fact] public void TestAssemblyPatialMatchSimpleNameCulture() { AssemblyNameExtension assemblyNameToMatchCulture = new AssemblyNameExtension("System.Xml, Culture=en"); AssemblyNameExtension assemblyNameToNotMatch = new AssemblyNameExtension("System.Xml, Culture=de-DE"); AssemblyNameExtension assemblyMatchNoVersion = new AssemblyNameExtension("System.Xml"); foreach (string assembly in s_assembliesForPartialMatch) { AssemblyNameExtension assemblyToCompare = new AssemblyNameExtension(assembly); // If there is a version make sure the assembly name with the correct culture matches // Make sure the assembly with the wrong culture does not match if (assemblyToCompare.CultureInfo != null) { Assert.True(assemblyNameToMatchCulture.PartialNameCompare(assemblyToCompare)); Assert.True(assemblyNameToMatchCulture.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.Culture)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.Culture)); // Matches because culture is not specified Assert.True(assemblyMatchNoVersion.PartialNameCompare(assemblyToCompare)); Assert.True(assemblyMatchNoVersion.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.Culture)); } else { // If there is no version make names with a culture specified do not match Assert.False(assemblyNameToMatchCulture.PartialNameCompare(assemblyToCompare)); Assert.False(assemblyNameToMatchCulture.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.Culture)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.Culture)); // Matches because culture is not specified Assert.True(assemblyMatchNoVersion.PartialNameCompare(assemblyToCompare)); Assert.True(assemblyMatchNoVersion.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.Culture)); } } } /// <summary> /// Verify partial matching on the simple name and PublicKeyToken /// </summary> [Fact] public void TestAssemblyPatialMatchSimpleNamePublicKeyToken() { AssemblyNameExtension assemblyNameToMatchPublicToken = new AssemblyNameExtension("System.Xml, PublicKeyToken=b03f5f7f11d50a3a"); AssemblyNameExtension assemblyNameToNotMatch = new AssemblyNameExtension("System.Xml, PublicKeyToken=b03f5f7f11d50a3b"); AssemblyNameExtension assemblyMatchNoVersion = new AssemblyNameExtension("System.Xml"); foreach (string assembly in s_assembliesForPartialMatch) { AssemblyNameExtension assemblyToCompare = new AssemblyNameExtension(assembly); // If there is a version make sure the assembly name with the correct publicKeyToken matches // Make sure the assembly with the wrong publicKeyToken does not match if (assemblyToCompare.GetPublicKeyToken() != null) { Assert.True(assemblyNameToMatchPublicToken.PartialNameCompare(assemblyToCompare)); Assert.True(assemblyNameToMatchPublicToken.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.PublicKeyToken)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.PublicKeyToken)); // Matches because publicKeyToken is not specified Assert.True(assemblyMatchNoVersion.PartialNameCompare(assemblyToCompare)); Assert.True(assemblyMatchNoVersion.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.PublicKeyToken)); } else { // If there is no version make names with a publicKeyToken specified do not match Assert.False(assemblyNameToMatchPublicToken.PartialNameCompare(assemblyToCompare)); Assert.False(assemblyNameToMatchPublicToken.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.PublicKeyToken)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare)); Assert.False(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.PublicKeyToken)); // Matches because publicKeyToken is not specified Assert.True(assemblyMatchNoVersion.PartialNameCompare(assemblyToCompare)); Assert.True(assemblyMatchNoVersion.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName | PartialComparisonFlags.PublicKeyToken)); } } } /// <summary> /// Verify partial matching on the simple name and retargetable /// </summary> [Fact] public void TestAssemblyPartialMatchSimpleNameRetargetable() { AssemblyNameExtension assemblyNameToMatchRetargetable = new AssemblyNameExtension("System.Xml, Version=10.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a, Retargetable=Yes"); AssemblyNameExtension assemblyNameToNotMatch = new AssemblyNameExtension("System.Xml, Version=10.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a, Retargetable=No"); AssemblyNameExtension assemblyMatchNoRetargetable = new AssemblyNameExtension("System.Xml"); foreach (string assembly in s_assembliesForPartialMatch) { AssemblyNameExtension assemblyToCompare = new AssemblyNameExtension(assembly); if (assemblyToCompare.FullName.IndexOf("Retargetable=Yes", StringComparison.OrdinalIgnoreCase) >= 0) { Assert.True(assemblyNameToMatchRetargetable.PartialNameCompare(assemblyToCompare)); Assert.True(assemblyNameToMatchRetargetable.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName, true)); Assert.True(assemblyToCompare.PartialNameCompare(assemblyNameToNotMatch)); Assert.False(assemblyToCompare.PartialNameCompare(assemblyNameToNotMatch, PartialComparisonFlags.SimpleName, true)); Assert.False(assemblyToCompare.PartialNameCompare(assemblyMatchNoRetargetable)); Assert.False(assemblyToCompare.PartialNameCompare(assemblyMatchNoRetargetable, PartialComparisonFlags.SimpleName, true)); Assert.True(assemblyMatchNoRetargetable.PartialNameCompare(assemblyToCompare)); Assert.False(assemblyMatchNoRetargetable.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName, true)); } else { Assert.False(assemblyNameToMatchRetargetable.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName, true)); // Match because retargetable false is the same as no retargetable bit bool match = assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare); if (assemblyToCompare.FullName.IndexOf("System.Xml, Version=10.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a", StringComparison.OrdinalIgnoreCase) >= 0) { Assert.True(match); } else { Assert.False(match); } Assert.True(assemblyNameToNotMatch.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName, true)); Assert.True(assemblyMatchNoRetargetable.PartialNameCompare(assemblyToCompare)); Assert.True(assemblyMatchNoRetargetable.PartialNameCompare(assemblyToCompare, PartialComparisonFlags.SimpleName, true)); } } } /// <summary> /// Make sure that our assemblyNameComparers correctly work. /// </summary> [Fact] public void VerifyAssemblyNameComparers() { AssemblyNameExtension a = new AssemblyNameExtension("System.Xml, Version=10.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a, Retargetable=Yes"); AssemblyNameExtension b = new AssemblyNameExtension("System.Xml, Version=10.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a, Retargetable=No"); AssemblyNameExtension c = new AssemblyNameExtension("System.Xml, Version=10.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a, Retargetable=Yes"); AssemblyNameExtension d = new AssemblyNameExtension("System.Xml, Version=9.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a, Retargetable=No"); AssemblyNameExtension e = new AssemblyNameExtension("System.Xml, Version=11.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a, Retargetable=No"); Assert.True(AssemblyNameComparer.GenericComparer.Equals(a, b)); Assert.False(AssemblyNameComparer.GenericComparer.Equals(a, d)); Assert.False(AssemblyNameComparer.GenericComparerConsiderRetargetable.Equals(a, b)); Assert.True(AssemblyNameComparer.GenericComparerConsiderRetargetable.Equals(a, c)); Assert.False(AssemblyNameComparer.GenericComparerConsiderRetargetable.Equals(a, d)); Assert.Equal(0, AssemblyNameComparer.Comparer.Compare(a, b)); Assert.True(AssemblyNameComparer.Comparer.Compare(a, d) > 0); Assert.True(AssemblyNameComparer.Comparer.Compare(a, e) < 0); Assert.Equal(0, AssemblyNameComparer.ComparerConsiderRetargetable.Compare(a, c)); Assert.True(AssemblyNameComparer.ComparerConsiderRetargetable.Compare(a, b) > 0); Assert.True(AssemblyNameComparer.ComparerConsiderRetargetable.Compare(a, d) > 0); Assert.True(AssemblyNameComparer.ComparerConsiderRetargetable.Compare(a, e) < 0); } /// <summary> /// Make sure the reverse version comparer will compare the version in a way that would sort them in reverse order. /// </summary> [Fact] public void VerifyReverseVersionComparer() { AssemblyNameExtension x = new AssemblyNameExtension("System, Version=2.0.0.0"); AssemblyNameExtension y = new AssemblyNameExtension("System, Version=1.0.0.0"); AssemblyNameExtension z = new AssemblyNameExtension("System, Version=2.0.0.0"); AssemblyNameExtension a = new AssemblyNameExtension("Zar, Version=3.0.0.0"); AssemblyNameReverseVersionComparer reverseComparer = new AssemblyNameReverseVersionComparer(); Assert.Equal(-1, reverseComparer.Compare(x, y)); Assert.Equal(1, reverseComparer.Compare(y, x)); Assert.Equal(0, reverseComparer.Compare(x, z)); Assert.Equal(0, reverseComparer.Compare(null, null)); Assert.Equal(-1, reverseComparer.Compare(x, null)); Assert.Equal(1, reverseComparer.Compare(null, y)); Assert.Equal(-1, reverseComparer.Compare(a, x)); List<AssemblyNameExtension> assemblies = new List<AssemblyNameExtension>(); assemblies.Add(y); assemblies.Add(x); assemblies.Add(z); assemblies.Sort(AssemblyNameReverseVersionComparer.GenericComparer); Assert.True(assemblies[0].Equals(x)); Assert.True(assemblies[1].Equals(z)); Assert.True(assemblies[2].Equals(y)); } [Theory] [InlineData("System.Xml")] [InlineData("System.XML, Version=2.0.0.0")] [InlineData("System.Xml, Culture=de-DE")] [InlineData("System.Xml, Version=10.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a, Retargetable=Yes")] [InlineData("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public void VerifyAssemblyNameExSerialization(string assemblyName) { AssemblyNameExtension assemblyNameOriginal = new AssemblyNameExtension(assemblyName); AssemblyNameExtension assemblyNameDeserialized; byte[] bytes; using (MemoryStream ms = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, assemblyNameOriginal); bytes = ms.ToArray(); } using (MemoryStream ms = new MemoryStream(bytes)) { BinaryFormatter formatter = new BinaryFormatter(); assemblyNameDeserialized = (AssemblyNameExtension) formatter.Deserialize(ms); } assemblyNameDeserialized.ShouldBe(assemblyNameOriginal); } [Fact] public void VerifyAssemblyNameExSerializationWithRemappedFrom() { AssemblyNameExtension assemblyNameOriginal = new AssemblyNameExtension("System.Xml, Version=10.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a"); AssemblyNameExtension assemblyRemappedFrom = new AssemblyNameExtension("System.Xml, Version=9.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a"); assemblyRemappedFrom.MarkImmutable(); assemblyNameOriginal.AddRemappedAssemblyName(assemblyRemappedFrom); assemblyNameOriginal.RemappedFromEnumerator.Count().ShouldBe(1); AssemblyNameExtension assemblyNameDeserialized; byte[] bytes; using (MemoryStream ms = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, assemblyNameOriginal); bytes = ms.ToArray(); } using (MemoryStream ms = new MemoryStream(bytes)) { BinaryFormatter formatter = new BinaryFormatter(); assemblyNameDeserialized = (AssemblyNameExtension)formatter.Deserialize(ms); } assemblyNameDeserialized.Equals(assemblyNameOriginal).ShouldBeTrue(); assemblyNameDeserialized.RemappedFromEnumerator.Count().ShouldBe(1); assemblyNameDeserialized.RemappedFromEnumerator.First().ShouldBe(assemblyRemappedFrom); } } }
// 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.Automation { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ModuleOperations. /// </summary> public static partial class ModuleOperationsExtensions { /// <summary> /// Delete the module by name. /// <see href="http://aka.ms/azureautomationsdk/moduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='moduleName'> /// The module name. /// </param> public static void Delete(this IModuleOperations operations, string resourceGroupName, string automationAccountName, string moduleName) { operations.DeleteAsync(resourceGroupName, automationAccountName, moduleName).GetAwaiter().GetResult(); } /// <summary> /// Delete the module by name. /// <see href="http://aka.ms/azureautomationsdk/moduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='moduleName'> /// The module name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IModuleOperations operations, string resourceGroupName, string automationAccountName, string moduleName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, automationAccountName, moduleName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieve the module identified by module name. /// <see href="http://aka.ms/azureautomationsdk/moduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='moduleName'> /// The module name. /// </param> public static Module Get(this IModuleOperations operations, string resourceGroupName, string automationAccountName, string moduleName) { return operations.GetAsync(resourceGroupName, automationAccountName, moduleName).GetAwaiter().GetResult(); } /// <summary> /// Retrieve the module identified by module name. /// <see href="http://aka.ms/azureautomationsdk/moduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='moduleName'> /// The module name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Module> GetAsync(this IModuleOperations operations, string resourceGroupName, string automationAccountName, string moduleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, automationAccountName, moduleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create or Update the module identified by module name. /// <see href="http://aka.ms/azureautomationsdk/moduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='moduleName'> /// The name of module. /// </param> /// <param name='parameters'> /// The create or update parameters for module. /// </param> public static Module CreateOrUpdate(this IModuleOperations operations, string resourceGroupName, string automationAccountName, string moduleName, ModuleCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, automationAccountName, moduleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Create or Update the module identified by module name. /// <see href="http://aka.ms/azureautomationsdk/moduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='moduleName'> /// The name of module. /// </param> /// <param name='parameters'> /// The create or update parameters for module. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Module> CreateOrUpdateAsync(this IModuleOperations operations, string resourceGroupName, string automationAccountName, string moduleName, ModuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, automationAccountName, moduleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update the module identified by module name. /// <see href="http://aka.ms/azureautomationsdk/moduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='moduleName'> /// The name of module. /// </param> /// <param name='parameters'> /// The update parameters for module. /// </param> public static Module Update(this IModuleOperations operations, string resourceGroupName, string automationAccountName, string moduleName, ModuleUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, automationAccountName, moduleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Update the module identified by module name. /// <see href="http://aka.ms/azureautomationsdk/moduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='moduleName'> /// The name of module. /// </param> /// <param name='parameters'> /// The update parameters for module. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Module> UpdateAsync(this IModuleOperations operations, string resourceGroupName, string automationAccountName, string moduleName, ModuleUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, automationAccountName, moduleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieve a list of modules. /// <see href="http://aka.ms/azureautomationsdk/moduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> public static IPage<Module> ListByAutomationAccount(this IModuleOperations operations, string resourceGroupName, string automationAccountName) { return operations.ListByAutomationAccountAsync(resourceGroupName, automationAccountName).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of modules. /// <see href="http://aka.ms/azureautomationsdk/moduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Module>> ListByAutomationAccountAsync(this IModuleOperations operations, string resourceGroupName, string automationAccountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAutomationAccountWithHttpMessagesAsync(resourceGroupName, automationAccountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieve a list of modules. /// <see href="http://aka.ms/azureautomationsdk/moduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Module> ListByAutomationAccountNext(this IModuleOperations operations, string nextPageLink) { return operations.ListByAutomationAccountNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of modules. /// <see href="http://aka.ms/azureautomationsdk/moduleoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Module>> ListByAutomationAccountNextAsync(this IModuleOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAutomationAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
//------------------------------------------------------------------------------ // <copyright file="DataControlField.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Drawing.Design; /// <devdoc> /// Creates a field and is the base class for all <see cref='System.Web.UI.WebControls.DataControlField'/> types. /// </devdoc> [ TypeConverterAttribute(typeof(ExpandableObjectConverter)), DefaultProperty("HeaderText") ] public abstract class DataControlField : IStateManager, IDataSourceViewSchemaAccessor { private TableItemStyle _itemStyle; private TableItemStyle _headerStyle; private TableItemStyle _footerStyle; private Style _controlStyle; private StateBag _statebag; private bool _trackViewState; private bool _sortingEnabled; private Control _control; private object _dataSourceViewSchema; internal event EventHandler FieldChanged; /// <devdoc> /// <para>Initializes a new instance of the System.Web.UI.WebControls.Field class.</para> /// </devdoc> protected DataControlField() { _statebag = new StateBag(); _dataSourceViewSchema = null; } /// <devdoc> /// <para>Gets or sets the text rendered as the AbbreviatedText in some controls.</para> /// </devdoc> [ Localizable(true), WebCategory("Accessibility"), DefaultValue(""), WebSysDescription(SR.DataControlField_AccessibleHeaderText) ] public virtual string AccessibleHeaderText { get { object o = ViewState["AccessibleHeaderText"]; if (o != null) return(string)o; return String.Empty; } set { if (!String.Equals(value, ViewState["AccessibleHeaderText"])) { ViewState["AccessibleHeaderText"] = value; OnFieldChanged(); } } } /// <devdoc> /// <para>Gets the style properties for the controls inside this field.</para> /// </devdoc> [ WebCategory("Styles"), DefaultValue(null), WebSysDescription(SR.DataControlField_ControlStyle), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty) ] public Style ControlStyle { get { if (_controlStyle == null) { _controlStyle = new Style(); if (IsTrackingViewState) ((IStateManager)_controlStyle).TrackViewState(); } return _controlStyle; } } /// <summary> /// This property is accessed by <see cref='System.Web.UI.WebControls.DataControlFieldCell'/>. /// Any child classes which define <see cref='System.Web.UI.Control.ValidateRequestMode'/> should be wrapping this so that /// <see cref='System.Web.UI.WebControls.DataControlFieldCell'/> gets the correct value. /// </summary> protected internal virtual ValidateRequestMode ValidateRequestMode { get { object o = ViewState["ValidateRequestMode"]; if (o != null) return (ValidateRequestMode)o; return ValidateRequestMode.Inherit; } set { if (value < ValidateRequestMode.Inherit || value > ValidateRequestMode.Enabled) { throw new ArgumentOutOfRangeException("value"); } if (value != ValidateRequestMode) { ViewState["ValidateRequestMode"] = value; OnFieldChanged(); } } } internal Style ControlStyleInternal { get { return _controlStyle; } } protected Control Control { get { return _control; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected bool DesignMode { get { if (_control != null) { return _control.DesignMode; } return false; } } /// <devdoc> /// <para>Gets the style properties for the footer item.</para> /// </devdoc> [ WebCategory("Styles"), DefaultValue(null), WebSysDescription(SR.DataControlField_FooterStyle), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty) ] public TableItemStyle FooterStyle { get { if (_footerStyle == null) { _footerStyle = new TableItemStyle(); if (IsTrackingViewState) ((IStateManager)_footerStyle).TrackViewState(); } return _footerStyle; } } /// <devdoc> /// </devdoc> internal TableItemStyle FooterStyleInternal { get { return _footerStyle; } } /// <devdoc> /// <para> Gets or sets the text displayed in the footer of the /// System.Web.UI.WebControls.Field.</para> /// </devdoc> [ Localizable(true), WebCategory("Appearance"), DefaultValue(""), WebSysDescription(SR.DataControlField_FooterText) ] public virtual string FooterText { get { object o = ViewState["FooterText"]; if (o != null) return(string)o; return String.Empty; } set { if (!String.Equals(value, ViewState["FooterText"])) { ViewState["FooterText"] = value; OnFieldChanged(); } } } /// <devdoc> /// <para>Gets or sets the URL reference to an image to display /// instead of text on the header of this System.Web.UI.WebControls.Field /// .</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), Editor("System.Web.UI.Design.ImageUrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), UrlProperty(), WebSysDescription(SR.DataControlField_HeaderImageUrl) ] public virtual string HeaderImageUrl { get { object o = ViewState["HeaderImageUrl"]; if (o != null) return(string)o; return String.Empty; } set { if (!String.Equals(value, ViewState["HeaderImageUrl"])) { ViewState["HeaderImageUrl"] = value; OnFieldChanged(); } } } /// <devdoc> /// <para>Gets the style properties for the header of the System.Web.UI.WebControls.Field. This property is read-only.</para> /// </devdoc> [ WebCategory("Styles"), DefaultValue(null), WebSysDescription(SR.DataControlField_HeaderStyle), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty) ] public TableItemStyle HeaderStyle { get { if (_headerStyle == null) { _headerStyle = new TableItemStyle(); if (IsTrackingViewState) ((IStateManager)_headerStyle).TrackViewState(); } return _headerStyle; } } /// <devdoc> /// </devdoc> internal TableItemStyle HeaderStyleInternal { get { return _headerStyle; } } /// <devdoc> /// <para>Gets or sets the text displayed in the header of the /// System.Web.UI.WebControls.Field.</para> /// </devdoc> [ Localizable(true), WebCategory("Appearance"), DefaultValue(""), WebSysDescription(SR.DataControlField_HeaderText) ] public virtual string HeaderText { get { object o = ViewState["HeaderText"]; if (o != null) return(string)o; return String.Empty; } set { if (!String.Equals(value, ViewState["HeaderText"])) { ViewState["HeaderText"] = value; OnFieldChanged(); } } } /// <devdoc> /// <para>Gets or sets whether the field is visible in Insert mode. Turn off for auto-gen'd db fields</para> /// </devdoc> [ WebCategory("Behavior"), DefaultValue(true), WebSysDescription(SR.DataControlField_InsertVisible) ] public virtual bool InsertVisible { get { object o = ViewState["InsertVisible"]; if (o != null) return (bool)o; return true; } set { object oldValue = ViewState["InsertVisible"]; if (oldValue == null || value != (bool)oldValue) { ViewState["InsertVisible"] = value; OnFieldChanged(); } } } /// <devdoc> /// <para>Gets the style properties of an item within the System.Web.UI.WebControls.Field. This property is read-only.</para> /// </devdoc> [ WebCategory("Styles"), DefaultValue(null), WebSysDescription(SR.DataControlField_ItemStyle), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty) ] public TableItemStyle ItemStyle { get { if (_itemStyle == null) { _itemStyle = new TableItemStyle(); if (IsTrackingViewState) ((IStateManager)_itemStyle).TrackViewState(); } return _itemStyle; } } /// <devdoc> /// </devdoc> internal TableItemStyle ItemStyleInternal { get { return _itemStyle; } } [ WebCategory("Behavior"), DefaultValue(true), WebSysDescription(SR.DataControlField_ShowHeader) ] public virtual bool ShowHeader { get { object o = ViewState["ShowHeader"]; if (o != null) { return (bool)o; } return true; } set { object oldValue = ViewState["ShowHeader"]; if (oldValue == null || (bool)oldValue != value) { ViewState["ShowHeader"] = value; OnFieldChanged(); } } } /// <devdoc> /// <para>Gets or sets the expression used when this field is used to sort the data source> by.</para> /// </devdoc> [ WebCategory("Behavior"), DefaultValue(""), TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign), WebSysDescription(SR.DataControlField_SortExpression) ] public virtual string SortExpression { get { object o = ViewState["SortExpression"]; if (o != null) return(string)o; return String.Empty; } set { if (!String.Equals(value, ViewState["SortExpression"])) { ViewState["SortExpression"] = value; OnFieldChanged(); } } } /// <devdoc> /// <para>Gets the statebag for the System.Web.UI.WebControls.Field. This property is read-only.</para> /// </devdoc> protected StateBag ViewState { get { return _statebag; } } /// <devdoc> /// <para>Gets or sets a value to indicate whether the System.Web.UI.WebControls.Field is visible.</para> /// </devdoc> [ WebCategory("Behavior"), DefaultValue(true), WebSysDescription(SR.DataControlField_Visible) ] public bool Visible { get { object o = ViewState["Visible"]; if (o != null) return(bool)o; return true; } set { object oldValue = ViewState["Visible"]; if (oldValue == null || value != (bool)oldValue) { ViewState["Visible"] = value; OnFieldChanged(); } } } protected internal DataControlField CloneField() { DataControlField newField = CreateField(); CopyProperties(newField); return newField; } protected virtual void CopyProperties(DataControlField newField) { newField.AccessibleHeaderText = AccessibleHeaderText; newField.ControlStyle.CopyFrom(ControlStyle); newField.FooterStyle.CopyFrom(FooterStyle); newField.HeaderStyle.CopyFrom(HeaderStyle); newField.ItemStyle.CopyFrom(ItemStyle); newField.FooterText = FooterText; newField.HeaderImageUrl = HeaderImageUrl; newField.HeaderText = HeaderText; newField.InsertVisible = InsertVisible; newField.ShowHeader = ShowHeader; newField.SortExpression = SortExpression; newField.Visible = Visible; newField.ValidateRequestMode = ValidateRequestMode; } protected abstract DataControlField CreateField(); /// <devdoc> /// Extracts the value of the databound cell and inserts the value into the given dictionary /// </devdoc> public virtual void ExtractValuesFromCell(IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly) { return; } /// <devdoc> /// </devdoc> public virtual bool Initialize(bool sortingEnabled, Control control) { _sortingEnabled = sortingEnabled; _control = control; return false; } /// <devdoc> /// <para>Initializes a cell in the System.Web.UI.WebControls.Field.</para> /// </devdoc> public virtual void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex) { switch (cellType) { case DataControlCellType.Header: { WebControl headerControl = null; string sortExpression = SortExpression; bool sortableHeader = (_sortingEnabled && sortExpression.Length > 0); string headerImageUrl = HeaderImageUrl; string headerText = HeaderText; if (headerImageUrl.Length != 0) { if (sortableHeader) { ImageButton sortButton; IPostBackContainer container = _control as IPostBackContainer; if (container != null) { sortButton = new DataControlImageButton(container); ((DataControlImageButton)sortButton).EnableCallback(null); // no command argument for the callback uses Sort } else { sortButton = new ImageButton(); } sortButton.ImageUrl = HeaderImageUrl; sortButton.CommandName = DataControlCommands.SortCommandName; sortButton.CommandArgument = sortExpression; if (!(sortButton is DataControlImageButton)) { sortButton.CausesValidation = false; } sortButton.AlternateText = headerText; headerControl = sortButton; } else { Image headerImage = new Image(); headerImage.ImageUrl = headerImageUrl; headerControl = headerImage; headerImage.AlternateText = headerText; } } else { if (sortableHeader) { LinkButton sortButton; IPostBackContainer container = _control as IPostBackContainer; if (container != null) { sortButton = new DataControlLinkButton(container); ((DataControlLinkButton)sortButton).EnableCallback(null); // no command argument for the callback uses Sort } else { sortButton = new LinkButton(); } sortButton.Text = headerText; sortButton.CommandName = DataControlCommands.SortCommandName; sortButton.CommandArgument = sortExpression; if (!(sortButton is DataControlLinkButton)) { sortButton.CausesValidation = false; } headerControl = sortButton; } else { if (headerText.Length == 0) { // the browser does not render table borders for cells with nothing // in their content, so we add a non-breaking space. headerText = "&nbsp;"; } cell.Text = headerText; } } if (headerControl != null) { cell.Controls.Add(headerControl); } } break; case DataControlCellType.Footer: { string footerText = FooterText; if (footerText.Length == 0) { // the browser does not render table borders for cells with nothing // in their content, so we add a non-breaking space. footerText = "&nbsp;"; } cell.Text = footerText; } break; } } /// <devdoc> /// <para>Determines if the System.Web.UI.WebControls.Field is marked to save its state.</para> /// </devdoc> protected bool IsTrackingViewState { get { return _trackViewState; } } /// <devdoc> /// <para>Loads the state of the System.Web.UI.WebControls.Field.</para> /// </devdoc> protected virtual void LoadViewState(object savedState) { if (savedState != null) { object[] myState = (object[])savedState; if (myState[0] != null) ((IStateManager)ViewState).LoadViewState(myState[0]); if (myState[1] != null) ((IStateManager)ItemStyle).LoadViewState(myState[1]); if (myState[2] != null) ((IStateManager)HeaderStyle).LoadViewState(myState[2]); if (myState[3] != null) ((IStateManager)FooterStyle).LoadViewState(myState[3]); } } /// <devdoc> /// <para>Raises the FieldChanged event for a System.Web.UI.WebControls.Field.</para> /// </devdoc> protected virtual void OnFieldChanged() { if (FieldChanged != null) { FieldChanged(this, EventArgs.Empty); } } /// <devdoc> /// <para>Saves the current state of the System.Web.UI.WebControls.Field.</para> /// </devdoc> protected virtual object SaveViewState() { object propState = ((IStateManager)ViewState).SaveViewState(); object itemStyleState = (_itemStyle != null) ? ((IStateManager)_itemStyle).SaveViewState() : null; object headerStyleState = (_headerStyle != null) ? ((IStateManager)_headerStyle).SaveViewState() : null; object footerStyleState = (_footerStyle != null) ? ((IStateManager)_footerStyle).SaveViewState() : null; object controlStyleState = (_controlStyle != null) ? ((IStateManager)_controlStyle).SaveViewState() : null; if ((propState != null) || (itemStyleState != null) || (headerStyleState != null) || (footerStyleState != null) || (controlStyleState != null)) { return new object[5] { propState, itemStyleState, headerStyleState, footerStyleState, controlStyleState }; } return null; } internal void SetDirty() { _statebag.SetDirty(true); if (_itemStyle != null) { _itemStyle.SetDirty(); } if (_headerStyle != null) { _headerStyle.SetDirty(); } if (_footerStyle != null) { _footerStyle.SetDirty(); } if (_controlStyle != null) { _controlStyle.SetDirty(); } } /// <internalonly/> /// <devdoc> /// Return a textual representation of the column for UI-display purposes. /// </devdoc> public override string ToString() { string headerText = HeaderText.Trim(); return headerText.Length > 0 ? headerText : GetType().Name; } /// <devdoc> /// <para>Marks the starting point to begin tracking and saving changes to the /// control as part of the control viewstate.</para> /// </devdoc> protected virtual void TrackViewState() { _trackViewState = true; ((IStateManager)ViewState).TrackViewState(); if (_itemStyle != null) ((IStateManager)_itemStyle).TrackViewState(); if (_headerStyle != null) ((IStateManager)_headerStyle).TrackViewState(); if (_footerStyle != null) ((IStateManager)_footerStyle).TrackViewState(); if (_controlStyle != null) ((IStateManager)_controlStyle).TrackViewState(); } /// <devdoc> /// <para>Override with an empty body if the field's controls all support callback. /// Otherwise, override and throw a useful error message about why the field can't support callbacks.</para> /// </devdoc> public virtual void ValidateSupportsCallback() { throw new NotSupportedException(SR.GetString(SR.DataControlField_CallbacksNotSupported, Control.ID)); } /// <internalonly/> /// <devdoc> /// Return true if tracking state changes. /// </devdoc> bool IStateManager.IsTrackingViewState { get { return IsTrackingViewState; } } /// <internalonly/> /// <devdoc> /// Load previously saved state. /// </devdoc> void IStateManager.LoadViewState(object state) { LoadViewState(state); } /// <internalonly/> /// <devdoc> /// Start tracking state changes. /// </devdoc> void IStateManager.TrackViewState() { TrackViewState(); } /// <internalonly/> /// <devdoc> /// Return object containing state changes. /// </devdoc> object IStateManager.SaveViewState() { return SaveViewState(); } #region IDataSourceViewSchemaAccessor implementation /// <internalonly/> object IDataSourceViewSchemaAccessor.DataSourceViewSchema { get { return _dataSourceViewSchema; } set { _dataSourceViewSchema = value; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using System.Diagnostics; using System.Runtime.InteropServices; using ComTypes = System.Runtime.InteropServices.ComTypes; namespace System.Management.Automation.InteropServices { /// <summary> /// Part of ComEventHelpers APIs which allow binding /// managed delegates to COM's connection point based events. /// </summary> internal partial class ComEventsSink : IDispatch, ICustomQueryInterface { private Guid _iidSourceItf; private ComTypes.IConnectionPoint? _connectionPoint; private int _cookie; private ComEventsMethod? _methods; private ComEventsSink? _next; public ComEventsSink(object rcw, Guid iid) { _iidSourceItf = iid; this.Advise(rcw); } public static ComEventsSink? Find(ComEventsSink? sinks, ref Guid iid) { ComEventsSink? sink = sinks; while (sink != null && sink._iidSourceItf != iid) { sink = sink._next; } return sink; } public static ComEventsSink Add(ComEventsSink? sinks, ComEventsSink sink) { sink._next = sinks; return sink; } public static ComEventsSink? RemoveAll(ComEventsSink? sinks) { while (sinks != null) { sinks.Unadvise(); sinks = sinks._next; } return null; } public static ComEventsSink? Remove(ComEventsSink sinks, ComEventsSink sink) { Debug.Assert(sinks != null, "removing event sink from empty sinks collection"); Debug.Assert(sink != null, "specify event sink is null"); ComEventsSink? toReturn = sinks; if (sink == sinks) { toReturn = sinks._next; } else { ComEventsSink? current = sinks; while (current != null && current._next != sink) { current = current._next; } if (current != null) { current._next = sink._next; } } sink.Unadvise(); return toReturn; } public ComEventsMethod? RemoveMethod(ComEventsMethod method) { _methods = ComEventsMethod.Remove(_methods!, method); return _methods; } public ComEventsMethod? FindMethod(int dispid) { return ComEventsMethod.Find(_methods, dispid); } public ComEventsMethod AddMethod(int dispid) { ComEventsMethod method = new ComEventsMethod(dispid); _methods = ComEventsMethod.Add(_methods, method); return method; } int IDispatch.GetTypeInfoCount() { return 0; } ComTypes.ITypeInfo IDispatch.GetTypeInfo(int iTInfo, int lcid) { throw new NotImplementedException(); } void IDispatch.GetIDsOfNames(ref Guid iid, string[] names, int cNames, int lcid, int[] rgDispId) { throw new NotImplementedException(); } private const VarEnum VT_BYREF_VARIANT = VarEnum.VT_BYREF | VarEnum.VT_VARIANT; private const VarEnum VT_TYPEMASK = (VarEnum)0x0fff; private const VarEnum VT_BYREF_TYPEMASK = VT_TYPEMASK | VarEnum.VT_BYREF; private static unsafe ref Variant GetVariant(ref Variant pSrc) { if (pSrc.VariantType == VT_BYREF_VARIANT) { // For VB6 compatibility reasons, if the VARIANT is a VT_BYREF | VT_VARIANT that // contains another VARIANT with VT_BYREF | VT_VARIANT, then we need to extract the // inner VARIANT and use it instead of the outer one. Note that if the inner VARIANT // is VT_BYREF | VT_VARIANT | VT_ARRAY, it will pass the below test too. Span<Variant> pByRefVariant = new Span<Variant>(pSrc.AsByRefVariant.ToPointer(), 1); if ((pByRefVariant[0].VariantType & VT_BYREF_TYPEMASK) == VT_BYREF_VARIANT) { return ref pByRefVariant[0]; } } return ref pSrc; } unsafe void IDispatch.Invoke( int dispid, ref Guid riid, int lcid, InvokeFlags wFlags, ref ComTypes.DISPPARAMS pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { ComEventsMethod? method = FindMethod(dispid); if (method == null) { return; } // notice the unsafe pointers we are using. This is to avoid unnecessary // arguments marshalling. see code:ComEventsHelper#ComEventsArgsMarshalling const int InvalidIdx = -1; object[] args = new object[pDispParams.cArgs]; int[] byrefsMap = new int[pDispParams.cArgs]; bool[] usedArgs = new bool[pDispParams.cArgs]; int totalCount = pDispParams.cNamedArgs + pDispParams.cArgs; var vars = new Span<Variant>(pDispParams.rgvarg.ToPointer(), totalCount); var namedArgs = new Span<int>(pDispParams.rgdispidNamedArgs.ToPointer(), totalCount); // copy the named args (positional) as specified int i; int pos; for (i = 0; i < pDispParams.cNamedArgs; i++) { pos = namedArgs[i]; ref Variant pvar = ref GetVariant(ref vars[i]); args[pos] = pvar.ToObject()!; usedArgs[pos] = true; int byrefIdx = InvalidIdx; if (pvar.IsByRef) { byrefIdx = i; } byrefsMap[pos] = byrefIdx; } // copy the rest of the arguments in the reverse order pos = 0; for (; i < pDispParams.cArgs; i++) { // find the next unassigned argument while (usedArgs[pos]) { pos++; } ref Variant pvar = ref GetVariant(ref vars[pDispParams.cArgs - 1 - i]); args[pos] = pvar.ToObject()!; int byrefIdx = InvalidIdx; if (pvar.IsByRef) { byrefIdx = pDispParams.cArgs - 1 - i; } byrefsMap[pos] = byrefIdx; pos++; } // Do the actual delegate invocation object? result = method.Invoke(args); // convert result to VARIANT if (pVarResult != IntPtr.Zero) { Marshal.GetNativeVariantForObject(result, pVarResult); } // Now we need to marshal all the byrefs back for (i = 0; i < pDispParams.cArgs; i++) { int idxToPos = byrefsMap[i]; if (idxToPos == InvalidIdx) { continue; } ref Variant pvar = ref GetVariant(ref vars[idxToPos]); pvar.CopyFromIndirect(args[i]); } } CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) { ppv = IntPtr.Zero; if (iid == _iidSourceItf || iid == typeof(IDispatch).GUID) { ppv = Marshal.GetComInterfaceForObject(this, typeof(IDispatch), CustomQueryInterfaceMode.Ignore); return CustomQueryInterfaceResult.Handled; } return CustomQueryInterfaceResult.NotHandled; } private void Advise(object rcw) { Debug.Assert(_connectionPoint == null, "COM event sink is already advised"); ComTypes.IConnectionPointContainer cpc = (ComTypes.IConnectionPointContainer)rcw; ComTypes.IConnectionPoint cp; cpc.FindConnectionPoint(ref _iidSourceItf, out cp!); object sinkObject = this; cp.Advise(sinkObject, out _cookie); _connectionPoint = cp; } private void Unadvise() { Debug.Assert(_connectionPoint != null, "Can not unadvise from empty connection point"); if (_connectionPoint == null) return; try { _connectionPoint.Unadvise(_cookie); Marshal.ReleaseComObject(_connectionPoint); } catch { // swallow all exceptions on unadvise // the host may not be available at this point } finally { _connectionPoint = null; } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SAEON.Observations.Data { /// <summary> /// Strongly-typed collection for the UnitOfMeasure class. /// </summary> [Serializable] public partial class UnitOfMeasureCollection : ActiveList<UnitOfMeasure, UnitOfMeasureCollection> { public UnitOfMeasureCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>UnitOfMeasureCollection</returns> public UnitOfMeasureCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { UnitOfMeasure o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the UnitOfMeasure table. /// </summary> [Serializable] public partial class UnitOfMeasure : ActiveRecord<UnitOfMeasure>, IActiveRecord { #region .ctors and Default Settings public UnitOfMeasure() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public UnitOfMeasure(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public UnitOfMeasure(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public UnitOfMeasure(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("UnitOfMeasure", TableType.Table, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Guid; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @"(newid())"; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarCode = new TableSchema.TableColumn(schema); colvarCode.ColumnName = "Code"; colvarCode.DataType = DbType.AnsiString; colvarCode.MaxLength = 50; colvarCode.AutoIncrement = false; colvarCode.IsNullable = false; colvarCode.IsPrimaryKey = false; colvarCode.IsForeignKey = false; colvarCode.IsReadOnly = false; colvarCode.DefaultSetting = @""; colvarCode.ForeignKeyTableName = ""; schema.Columns.Add(colvarCode); TableSchema.TableColumn colvarUnit = new TableSchema.TableColumn(schema); colvarUnit.ColumnName = "Unit"; colvarUnit.DataType = DbType.AnsiString; colvarUnit.MaxLength = 100; colvarUnit.AutoIncrement = false; colvarUnit.IsNullable = false; colvarUnit.IsPrimaryKey = false; colvarUnit.IsForeignKey = false; colvarUnit.IsReadOnly = false; colvarUnit.DefaultSetting = @""; colvarUnit.ForeignKeyTableName = ""; schema.Columns.Add(colvarUnit); TableSchema.TableColumn colvarUnitSymbol = new TableSchema.TableColumn(schema); colvarUnitSymbol.ColumnName = "UnitSymbol"; colvarUnitSymbol.DataType = DbType.AnsiString; colvarUnitSymbol.MaxLength = 20; colvarUnitSymbol.AutoIncrement = false; colvarUnitSymbol.IsNullable = false; colvarUnitSymbol.IsPrimaryKey = false; colvarUnitSymbol.IsForeignKey = false; colvarUnitSymbol.IsReadOnly = false; colvarUnitSymbol.DefaultSetting = @""; colvarUnitSymbol.ForeignKeyTableName = ""; schema.Columns.Add(colvarUnitSymbol); TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema); colvarUserId.ColumnName = "UserId"; colvarUserId.DataType = DbType.Guid; colvarUserId.MaxLength = 0; colvarUserId.AutoIncrement = false; colvarUserId.IsNullable = false; colvarUserId.IsPrimaryKey = false; colvarUserId.IsForeignKey = true; colvarUserId.IsReadOnly = false; colvarUserId.DefaultSetting = @""; colvarUserId.ForeignKeyTableName = "aspnet_Users"; schema.Columns.Add(colvarUserId); TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema); colvarAddedAt.ColumnName = "AddedAt"; colvarAddedAt.DataType = DbType.DateTime; colvarAddedAt.MaxLength = 0; colvarAddedAt.AutoIncrement = false; colvarAddedAt.IsNullable = true; colvarAddedAt.IsPrimaryKey = false; colvarAddedAt.IsForeignKey = false; colvarAddedAt.IsReadOnly = false; colvarAddedAt.DefaultSetting = @"(getdate())"; colvarAddedAt.ForeignKeyTableName = ""; schema.Columns.Add(colvarAddedAt); TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema); colvarUpdatedAt.ColumnName = "UpdatedAt"; colvarUpdatedAt.DataType = DbType.DateTime; colvarUpdatedAt.MaxLength = 0; colvarUpdatedAt.AutoIncrement = false; colvarUpdatedAt.IsNullable = true; colvarUpdatedAt.IsPrimaryKey = false; colvarUpdatedAt.IsForeignKey = false; colvarUpdatedAt.IsReadOnly = false; colvarUpdatedAt.DefaultSetting = @"(getdate())"; colvarUpdatedAt.ForeignKeyTableName = ""; schema.Columns.Add(colvarUpdatedAt); TableSchema.TableColumn colvarRowVersion = new TableSchema.TableColumn(schema); colvarRowVersion.ColumnName = "RowVersion"; colvarRowVersion.DataType = DbType.Binary; colvarRowVersion.MaxLength = 0; colvarRowVersion.AutoIncrement = false; colvarRowVersion.IsNullable = false; colvarRowVersion.IsPrimaryKey = false; colvarRowVersion.IsForeignKey = false; colvarRowVersion.IsReadOnly = true; colvarRowVersion.DefaultSetting = @""; colvarRowVersion.ForeignKeyTableName = ""; schema.Columns.Add(colvarRowVersion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("UnitOfMeasure",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public Guid Id { get { return GetColumnValue<Guid>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("Code")] [Bindable(true)] public string Code { get { return GetColumnValue<string>(Columns.Code); } set { SetColumnValue(Columns.Code, value); } } [XmlAttribute("Unit")] [Bindable(true)] public string Unit { get { return GetColumnValue<string>(Columns.Unit); } set { SetColumnValue(Columns.Unit, value); } } [XmlAttribute("UnitSymbol")] [Bindable(true)] public string UnitSymbol { get { return GetColumnValue<string>(Columns.UnitSymbol); } set { SetColumnValue(Columns.UnitSymbol, value); } } [XmlAttribute("UserId")] [Bindable(true)] public Guid UserId { get { return GetColumnValue<Guid>(Columns.UserId); } set { SetColumnValue(Columns.UserId, value); } } [XmlAttribute("AddedAt")] [Bindable(true)] public DateTime? AddedAt { get { return GetColumnValue<DateTime?>(Columns.AddedAt); } set { SetColumnValue(Columns.AddedAt, value); } } [XmlAttribute("UpdatedAt")] [Bindable(true)] public DateTime? UpdatedAt { get { return GetColumnValue<DateTime?>(Columns.UpdatedAt); } set { SetColumnValue(Columns.UpdatedAt, value); } } [XmlAttribute("RowVersion")] [Bindable(true)] public byte[] RowVersion { get { return GetColumnValue<byte[]>(Columns.RowVersion); } set { SetColumnValue(Columns.RowVersion, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } public SAEON.Observations.Data.PhenomenonUOMCollection PhenomenonUOMRecords() { return new SAEON.Observations.Data.PhenomenonUOMCollection().Where(PhenomenonUOM.Columns.UnitOfMeasureID, Id).Load(); } #endregion #region ForeignKey Properties private SAEON.Observations.Data.AspnetUser _AspnetUser = null; /// <summary> /// Returns a AspnetUser ActiveRecord object related to this UnitOfMeasure /// /// </summary> public SAEON.Observations.Data.AspnetUser AspnetUser { // get { return SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId); } get { return _AspnetUser ?? (_AspnetUser = SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId)); } set { SetColumnValue("UserId", value.UserId); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(Guid varId,string varCode,string varUnit,string varUnitSymbol,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion) { UnitOfMeasure item = new UnitOfMeasure(); item.Id = varId; item.Code = varCode; item.Unit = varUnit; item.UnitSymbol = varUnitSymbol; item.UserId = varUserId; item.AddedAt = varAddedAt; item.UpdatedAt = varUpdatedAt; item.RowVersion = varRowVersion; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(Guid varId,string varCode,string varUnit,string varUnitSymbol,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion) { UnitOfMeasure item = new UnitOfMeasure(); item.Id = varId; item.Code = varCode; item.Unit = varUnit; item.UnitSymbol = varUnitSymbol; item.UserId = varUserId; item.AddedAt = varAddedAt; item.UpdatedAt = varUpdatedAt; item.RowVersion = varRowVersion; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CodeColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn UnitColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn UnitSymbolColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn UserIdColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn AddedAtColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn UpdatedAtColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn RowVersionColumn { get { return Schema.Columns[7]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string Code = @"Code"; public static string Unit = @"Unit"; public static string UnitSymbol = @"UnitSymbol"; public static string UserId = @"UserId"; public static string AddedAt = @"AddedAt"; public static string UpdatedAt = @"UpdatedAt"; public static string RowVersion = @"RowVersion"; } #endregion #region Update PK Collections public void SetPKValues() { } #endregion #region Deep Save public void DeepSave() { Save(); } #endregion } }
# CS_ARCH_ARM64, 0, None 0x08,0x03,0x31,0xd5 = mrs x8, trcstatr 0xc9,0x00,0x31,0xd5 = mrs x9, trcidr8 0xcb,0x01,0x31,0xd5 = mrs x11, trcidr9 0xd9,0x02,0x31,0xd5 = mrs x25, trcidr10 0xc7,0x03,0x31,0xd5 = mrs x7, trcidr11 0xc7,0x04,0x31,0xd5 = mrs x7, trcidr12 0xc6,0x05,0x31,0xd5 = mrs x6, trcidr13 0xfb,0x08,0x31,0xd5 = mrs x27, trcidr0 0xfd,0x09,0x31,0xd5 = mrs x29, trcidr1 0xe4,0x0a,0x31,0xd5 = mrs x4, trcidr2 0xe8,0x0b,0x31,0xd5 = mrs x8, trcidr3 0xef,0x0c,0x31,0xd5 = mrs x15, trcidr4 0xf4,0x0d,0x31,0xd5 = mrs x20, trcidr5 0xe6,0x0e,0x31,0xd5 = mrs x6, trcidr6 0xe6,0x0f,0x31,0xd5 = mrs x6, trcidr7 0x98,0x11,0x31,0xd5 = mrs x24, trcoslsr 0x92,0x15,0x31,0xd5 = mrs x18, trcpdsr 0xdc,0x7a,0x31,0xd5 = mrs x28, trcdevaff0 0xc5,0x7b,0x31,0xd5 = mrs x5, trcdevaff1 0xc5,0x7d,0x31,0xd5 = mrs x5, trclsr 0xcb,0x7e,0x31,0xd5 = mrs x11, trcauthstatus 0xcd,0x7f,0x31,0xd5 = mrs x13, trcdevarch 0xf2,0x72,0x31,0xd5 = mrs x18, trcdevid 0xf6,0x73,0x31,0xd5 = mrs x22, trcdevtype 0xee,0x74,0x31,0xd5 = mrs x14, trcpidr4 0xe5,0x75,0x31,0xd5 = mrs x5, trcpidr5 0xe5,0x76,0x31,0xd5 = mrs x5, trcpidr6 0xe9,0x77,0x31,0xd5 = mrs x9, trcpidr7 0xef,0x78,0x31,0xd5 = mrs x15, trcpidr0 0xe6,0x79,0x31,0xd5 = mrs x6, trcpidr1 0xeb,0x7a,0x31,0xd5 = mrs x11, trcpidr2 0xf4,0x7b,0x31,0xd5 = mrs x20, trcpidr3 0xf1,0x7c,0x31,0xd5 = mrs x17, trccidr0 0xe2,0x7d,0x31,0xd5 = mrs x2, trccidr1 0xf4,0x7e,0x31,0xd5 = mrs x20, trccidr2 0xe4,0x7f,0x31,0xd5 = mrs x4, trccidr3 0x0b,0x01,0x31,0xd5 = mrs x11, trcprgctlr 0x17,0x02,0x31,0xd5 = mrs x23, trcprocselr 0x0d,0x04,0x31,0xd5 = mrs x13, trcconfigr 0x17,0x06,0x31,0xd5 = mrs x23, trcauxctlr 0x09,0x08,0x31,0xd5 = mrs x9, trceventctl0r 0x10,0x09,0x31,0xd5 = mrs x16, trceventctl1r 0x04,0x0b,0x31,0xd5 = mrs x4, trcstallctlr 0x0e,0x0c,0x31,0xd5 = mrs x14, trctsctlr 0x18,0x0d,0x31,0xd5 = mrs x24, trcsyncpr 0x1c,0x0e,0x31,0xd5 = mrs x28, trcccctlr 0x0f,0x0f,0x31,0xd5 = mrs x15, trcbbctlr 0x21,0x00,0x31,0xd5 = mrs x1, trctraceidr 0x34,0x01,0x31,0xd5 = mrs x20, trcqctlr 0x42,0x00,0x31,0xd5 = mrs x2, trcvictlr 0x4c,0x01,0x31,0xd5 = mrs x12, trcviiectlr 0x50,0x02,0x31,0xd5 = mrs x16, trcvissctlr 0x48,0x03,0x31,0xd5 = mrs x8, trcvipcssctlr 0x5b,0x08,0x31,0xd5 = mrs x27, trcvdctlr 0x49,0x09,0x31,0xd5 = mrs x9, trcvdsacctlr 0x40,0x0a,0x31,0xd5 = mrs x0, trcvdarcctlr 0x8d,0x00,0x31,0xd5 = mrs x13, trcseqevr0 0x8b,0x01,0x31,0xd5 = mrs x11, trcseqevr1 0x9a,0x02,0x31,0xd5 = mrs x26, trcseqevr2 0x8e,0x06,0x31,0xd5 = mrs x14, trcseqrstevr 0x84,0x07,0x31,0xd5 = mrs x4, trcseqstr 0x91,0x08,0x31,0xd5 = mrs x17, trcextinselr 0xb5,0x00,0x31,0xd5 = mrs x21, trccntrldvr0 0xaa,0x01,0x31,0xd5 = mrs x10, trccntrldvr1 0xb4,0x02,0x31,0xd5 = mrs x20, trccntrldvr2 0xa5,0x03,0x31,0xd5 = mrs x5, trccntrldvr3 0xb1,0x04,0x31,0xd5 = mrs x17, trccntctlr0 0xa1,0x05,0x31,0xd5 = mrs x1, trccntctlr1 0xb1,0x06,0x31,0xd5 = mrs x17, trccntctlr2 0xa6,0x07,0x31,0xd5 = mrs x6, trccntctlr3 0xbc,0x08,0x31,0xd5 = mrs x28, trccntvr0 0xb7,0x09,0x31,0xd5 = mrs x23, trccntvr1 0xa9,0x0a,0x31,0xd5 = mrs x9, trccntvr2 0xa6,0x0b,0x31,0xd5 = mrs x6, trccntvr3 0xf8,0x00,0x31,0xd5 = mrs x24, trcimspec0 0xf8,0x01,0x31,0xd5 = mrs x24, trcimspec1 0xef,0x02,0x31,0xd5 = mrs x15, trcimspec2 0xea,0x03,0x31,0xd5 = mrs x10, trcimspec3 0xfd,0x04,0x31,0xd5 = mrs x29, trcimspec4 0xf2,0x05,0x31,0xd5 = mrs x18, trcimspec5 0xfd,0x06,0x31,0xd5 = mrs x29, trcimspec6 0xe2,0x07,0x31,0xd5 = mrs x2, trcimspec7 0x08,0x12,0x31,0xd5 = mrs x8, trcrsctlr2 0x00,0x13,0x31,0xd5 = mrs x0, trcrsctlr3 0x0c,0x14,0x31,0xd5 = mrs x12, trcrsctlr4 0x1a,0x15,0x31,0xd5 = mrs x26, trcrsctlr5 0x1d,0x16,0x31,0xd5 = mrs x29, trcrsctlr6 0x11,0x17,0x31,0xd5 = mrs x17, trcrsctlr7 0x00,0x18,0x31,0xd5 = mrs x0, trcrsctlr8 0x01,0x19,0x31,0xd5 = mrs x1, trcrsctlr9 0x11,0x1a,0x31,0xd5 = mrs x17, trcrsctlr10 0x15,0x1b,0x31,0xd5 = mrs x21, trcrsctlr11 0x01,0x1c,0x31,0xd5 = mrs x1, trcrsctlr12 0x08,0x1d,0x31,0xd5 = mrs x8, trcrsctlr13 0x18,0x1e,0x31,0xd5 = mrs x24, trcrsctlr14 0x00,0x1f,0x31,0xd5 = mrs x0, trcrsctlr15 0x22,0x10,0x31,0xd5 = mrs x2, trcrsctlr16 0x3d,0x11,0x31,0xd5 = mrs x29, trcrsctlr17 0x36,0x12,0x31,0xd5 = mrs x22, trcrsctlr18 0x26,0x13,0x31,0xd5 = mrs x6, trcrsctlr19 0x3a,0x14,0x31,0xd5 = mrs x26, trcrsctlr20 0x3a,0x15,0x31,0xd5 = mrs x26, trcrsctlr21 0x24,0x16,0x31,0xd5 = mrs x4, trcrsctlr22 0x2c,0x17,0x31,0xd5 = mrs x12, trcrsctlr23 0x21,0x18,0x31,0xd5 = mrs x1, trcrsctlr24 0x20,0x19,0x31,0xd5 = mrs x0, trcrsctlr25 0x31,0x1a,0x31,0xd5 = mrs x17, trcrsctlr26 0x28,0x1b,0x31,0xd5 = mrs x8, trcrsctlr27 0x2a,0x1c,0x31,0xd5 = mrs x10, trcrsctlr28 0x39,0x1d,0x31,0xd5 = mrs x25, trcrsctlr29 0x2c,0x1e,0x31,0xd5 = mrs x12, trcrsctlr30 0x2b,0x1f,0x31,0xd5 = mrs x11, trcrsctlr31 0x52,0x10,0x31,0xd5 = mrs x18, trcssccr0 0x4c,0x11,0x31,0xd5 = mrs x12, trcssccr1 0x43,0x12,0x31,0xd5 = mrs x3, trcssccr2 0x42,0x13,0x31,0xd5 = mrs x2, trcssccr3 0x55,0x14,0x31,0xd5 = mrs x21, trcssccr4 0x4a,0x15,0x31,0xd5 = mrs x10, trcssccr5 0x56,0x16,0x31,0xd5 = mrs x22, trcssccr6 0x57,0x17,0x31,0xd5 = mrs x23, trcssccr7 0x57,0x18,0x31,0xd5 = mrs x23, trcsscsr0 0x53,0x19,0x31,0xd5 = mrs x19, trcsscsr1 0x59,0x1a,0x31,0xd5 = mrs x25, trcsscsr2 0x51,0x1b,0x31,0xd5 = mrs x17, trcsscsr3 0x53,0x1c,0x31,0xd5 = mrs x19, trcsscsr4 0x4b,0x1d,0x31,0xd5 = mrs x11, trcsscsr5 0x45,0x1e,0x31,0xd5 = mrs x5, trcsscsr6 0x49,0x1f,0x31,0xd5 = mrs x9, trcsscsr7 0x61,0x10,0x31,0xd5 = mrs x1, trcsspcicr0 0x6c,0x11,0x31,0xd5 = mrs x12, trcsspcicr1 0x75,0x12,0x31,0xd5 = mrs x21, trcsspcicr2 0x6b,0x13,0x31,0xd5 = mrs x11, trcsspcicr3 0x63,0x14,0x31,0xd5 = mrs x3, trcsspcicr4 0x69,0x15,0x31,0xd5 = mrs x9, trcsspcicr5 0x65,0x16,0x31,0xd5 = mrs x5, trcsspcicr6 0x62,0x17,0x31,0xd5 = mrs x2, trcsspcicr7 0x9a,0x14,0x31,0xd5 = mrs x26, trcpdcr 0x08,0x20,0x31,0xd5 = mrs x8, trcacvr0 0x0f,0x22,0x31,0xd5 = mrs x15, trcacvr1 0x13,0x24,0x31,0xd5 = mrs x19, trcacvr2 0x08,0x26,0x31,0xd5 = mrs x8, trcacvr3 0x1c,0x28,0x31,0xd5 = mrs x28, trcacvr4 0x03,0x2a,0x31,0xd5 = mrs x3, trcacvr5 0x19,0x2c,0x31,0xd5 = mrs x25, trcacvr6 0x18,0x2e,0x31,0xd5 = mrs x24, trcacvr7 0x26,0x20,0x31,0xd5 = mrs x6, trcacvr8 0x23,0x22,0x31,0xd5 = mrs x3, trcacvr9 0x38,0x24,0x31,0xd5 = mrs x24, trcacvr10 0x23,0x26,0x31,0xd5 = mrs x3, trcacvr11 0x2c,0x28,0x31,0xd5 = mrs x12, trcacvr12 0x29,0x2a,0x31,0xd5 = mrs x9, trcacvr13 0x2e,0x2c,0x31,0xd5 = mrs x14, trcacvr14 0x23,0x2e,0x31,0xd5 = mrs x3, trcacvr15 0x55,0x20,0x31,0xd5 = mrs x21, trcacatr0 0x5a,0x22,0x31,0xd5 = mrs x26, trcacatr1 0x48,0x24,0x31,0xd5 = mrs x8, trcacatr2 0x56,0x26,0x31,0xd5 = mrs x22, trcacatr3 0x46,0x28,0x31,0xd5 = mrs x6, trcacatr4 0x5d,0x2a,0x31,0xd5 = mrs x29, trcacatr5 0x45,0x2c,0x31,0xd5 = mrs x5, trcacatr6 0x52,0x2e,0x31,0xd5 = mrs x18, trcacatr7 0x62,0x20,0x31,0xd5 = mrs x2, trcacatr8 0x73,0x22,0x31,0xd5 = mrs x19, trcacatr9 0x6d,0x24,0x31,0xd5 = mrs x13, trcacatr10 0x79,0x26,0x31,0xd5 = mrs x25, trcacatr11 0x72,0x28,0x31,0xd5 = mrs x18, trcacatr12 0x7d,0x2a,0x31,0xd5 = mrs x29, trcacatr13 0x69,0x2c,0x31,0xd5 = mrs x9, trcacatr14 0x72,0x2e,0x31,0xd5 = mrs x18, trcacatr15 0x9d,0x20,0x31,0xd5 = mrs x29, trcdvcvr0 0x8f,0x24,0x31,0xd5 = mrs x15, trcdvcvr1 0x8f,0x28,0x31,0xd5 = mrs x15, trcdvcvr2 0x8f,0x2c,0x31,0xd5 = mrs x15, trcdvcvr3 0xb3,0x20,0x31,0xd5 = mrs x19, trcdvcvr4 0xb6,0x24,0x31,0xd5 = mrs x22, trcdvcvr5 0xbb,0x28,0x31,0xd5 = mrs x27, trcdvcvr6 0xa1,0x2c,0x31,0xd5 = mrs x1, trcdvcvr7 0xdd,0x20,0x31,0xd5 = mrs x29, trcdvcmr0 0xc9,0x24,0x31,0xd5 = mrs x9, trcdvcmr1 0xc1,0x28,0x31,0xd5 = mrs x1, trcdvcmr2 0xc2,0x2c,0x31,0xd5 = mrs x2, trcdvcmr3 0xe5,0x20,0x31,0xd5 = mrs x5, trcdvcmr4 0xf5,0x24,0x31,0xd5 = mrs x21, trcdvcmr5 0xe5,0x28,0x31,0xd5 = mrs x5, trcdvcmr6 0xe1,0x2c,0x31,0xd5 = mrs x1, trcdvcmr7 0x15,0x30,0x31,0xd5 = mrs x21, trccidcvr0 0x18,0x32,0x31,0xd5 = mrs x24, trccidcvr1 0x18,0x34,0x31,0xd5 = mrs x24, trccidcvr2 0x0c,0x36,0x31,0xd5 = mrs x12, trccidcvr3 0x0a,0x38,0x31,0xd5 = mrs x10, trccidcvr4 0x09,0x3a,0x31,0xd5 = mrs x9, trccidcvr5 0x06,0x3c,0x31,0xd5 = mrs x6, trccidcvr6 0x14,0x3e,0x31,0xd5 = mrs x20, trccidcvr7 0x34,0x30,0x31,0xd5 = mrs x20, trcvmidcvr0 0x34,0x32,0x31,0xd5 = mrs x20, trcvmidcvr1 0x3a,0x34,0x31,0xd5 = mrs x26, trcvmidcvr2 0x21,0x36,0x31,0xd5 = mrs x1, trcvmidcvr3 0x2e,0x38,0x31,0xd5 = mrs x14, trcvmidcvr4 0x3b,0x3a,0x31,0xd5 = mrs x27, trcvmidcvr5 0x3d,0x3c,0x31,0xd5 = mrs x29, trcvmidcvr6 0x31,0x3e,0x31,0xd5 = mrs x17, trcvmidcvr7 0x4a,0x30,0x31,0xd5 = mrs x10, trccidcctlr0 0x44,0x31,0x31,0xd5 = mrs x4, trccidcctlr1 0x49,0x32,0x31,0xd5 = mrs x9, trcvmidcctlr0 0x4b,0x33,0x31,0xd5 = mrs x11, trcvmidcctlr1 0x96,0x70,0x31,0xd5 = mrs x22, trcitctrl 0xd7,0x78,0x31,0xd5 = mrs x23, trcclaimset 0xce,0x79,0x31,0xd5 = mrs x14, trcclaimclr 0x9c,0x10,0x11,0xd5 = msr trcoslar, x28 0xce,0x7c,0x11,0xd5 = msr trclar, x14 0x0a,0x01,0x11,0xd5 = msr trcprgctlr, x10 0x1b,0x02,0x11,0xd5 = msr trcprocselr, x27 0x18,0x04,0x11,0xd5 = msr trcconfigr, x24 0x08,0x06,0x11,0xd5 = msr trcauxctlr, x8 0x10,0x08,0x11,0xd5 = msr trceventctl0r, x16 0x1b,0x09,0x11,0xd5 = msr trceventctl1r, x27 0x1a,0x0b,0x11,0xd5 = msr trcstallctlr, x26 0x00,0x0c,0x11,0xd5 = msr trctsctlr, x0 0x0e,0x0d,0x11,0xd5 = msr trcsyncpr, x14 0x08,0x0e,0x11,0xd5 = msr trcccctlr, x8 0x06,0x0f,0x11,0xd5 = msr trcbbctlr, x6 0x37,0x00,0x11,0xd5 = msr trctraceidr, x23 0x25,0x01,0x11,0xd5 = msr trcqctlr, x5 0x40,0x00,0x11,0xd5 = msr trcvictlr, x0 0x40,0x01,0x11,0xd5 = msr trcviiectlr, x0 0x41,0x02,0x11,0xd5 = msr trcvissctlr, x1 0x40,0x03,0x11,0xd5 = msr trcvipcssctlr, x0 0x47,0x08,0x11,0xd5 = msr trcvdctlr, x7 0x52,0x09,0x11,0xd5 = msr trcvdsacctlr, x18 0x58,0x0a,0x11,0xd5 = msr trcvdarcctlr, x24 0x9c,0x00,0x11,0xd5 = msr trcseqevr0, x28 0x95,0x01,0x11,0xd5 = msr trcseqevr1, x21 0x90,0x02,0x11,0xd5 = msr trcseqevr2, x16 0x90,0x06,0x11,0xd5 = msr trcseqrstevr, x16 0x99,0x07,0x11,0xd5 = msr trcseqstr, x25 0x9d,0x08,0x11,0xd5 = msr trcextinselr, x29 0xb4,0x00,0x11,0xd5 = msr trccntrldvr0, x20 0xb4,0x01,0x11,0xd5 = msr trccntrldvr1, x20 0xb6,0x02,0x11,0xd5 = msr trccntrldvr2, x22 0xac,0x03,0x11,0xd5 = msr trccntrldvr3, x12 0xb4,0x04,0x11,0xd5 = msr trccntctlr0, x20 0xa4,0x05,0x11,0xd5 = msr trccntctlr1, x4 0xa8,0x06,0x11,0xd5 = msr trccntctlr2, x8 0xb0,0x07,0x11,0xd5 = msr trccntctlr3, x16 0xa5,0x08,0x11,0xd5 = msr trccntvr0, x5 0xbb,0x09,0x11,0xd5 = msr trccntvr1, x27 0xb5,0x0a,0x11,0xd5 = msr trccntvr2, x21 0xa8,0x0b,0x11,0xd5 = msr trccntvr3, x8 0xe6,0x00,0x11,0xd5 = msr trcimspec0, x6 0xfb,0x01,0x11,0xd5 = msr trcimspec1, x27 0xf7,0x02,0x11,0xd5 = msr trcimspec2, x23 0xef,0x03,0x11,0xd5 = msr trcimspec3, x15 0xed,0x04,0x11,0xd5 = msr trcimspec4, x13 0xf9,0x05,0x11,0xd5 = msr trcimspec5, x25 0xf3,0x06,0x11,0xd5 = msr trcimspec6, x19 0xfb,0x07,0x11,0xd5 = msr trcimspec7, x27 0x04,0x12,0x11,0xd5 = msr trcrsctlr2, x4 0x00,0x13,0x11,0xd5 = msr trcrsctlr3, x0 0x15,0x14,0x11,0xd5 = msr trcrsctlr4, x21 0x08,0x15,0x11,0xd5 = msr trcrsctlr5, x8 0x14,0x16,0x11,0xd5 = msr trcrsctlr6, x20 0x0b,0x17,0x11,0xd5 = msr trcrsctlr7, x11 0x12,0x18,0x11,0xd5 = msr trcrsctlr8, x18 0x18,0x19,0x11,0xd5 = msr trcrsctlr9, x24 0x0f,0x1a,0x11,0xd5 = msr trcrsctlr10, x15 0x15,0x1b,0x11,0xd5 = msr trcrsctlr11, x21 0x04,0x1c,0x11,0xd5 = msr trcrsctlr12, x4 0x1c,0x1d,0x11,0xd5 = msr trcrsctlr13, x28 0x03,0x1e,0x11,0xd5 = msr trcrsctlr14, x3 0x14,0x1f,0x11,0xd5 = msr trcrsctlr15, x20 0x2c,0x10,0x11,0xd5 = msr trcrsctlr16, x12 0x31,0x11,0x11,0xd5 = msr trcrsctlr17, x17 0x2a,0x12,0x11,0xd5 = msr trcrsctlr18, x10 0x2b,0x13,0x11,0xd5 = msr trcrsctlr19, x11 0x23,0x14,0x11,0xd5 = msr trcrsctlr20, x3 0x32,0x15,0x11,0xd5 = msr trcrsctlr21, x18 0x3a,0x16,0x11,0xd5 = msr trcrsctlr22, x26 0x25,0x17,0x11,0xd5 = msr trcrsctlr23, x5 0x39,0x18,0x11,0xd5 = msr trcrsctlr24, x25 0x25,0x19,0x11,0xd5 = msr trcrsctlr25, x5 0x24,0x1a,0x11,0xd5 = msr trcrsctlr26, x4 0x34,0x1b,0x11,0xd5 = msr trcrsctlr27, x20 0x25,0x1c,0x11,0xd5 = msr trcrsctlr28, x5 0x2a,0x1d,0x11,0xd5 = msr trcrsctlr29, x10 0x38,0x1e,0x11,0xd5 = msr trcrsctlr30, x24 0x34,0x1f,0x11,0xd5 = msr trcrsctlr31, x20 0x57,0x10,0x11,0xd5 = msr trcssccr0, x23 0x5b,0x11,0x11,0xd5 = msr trcssccr1, x27 0x5b,0x12,0x11,0xd5 = msr trcssccr2, x27 0x46,0x13,0x11,0xd5 = msr trcssccr3, x6 0x43,0x14,0x11,0xd5 = msr trcssccr4, x3 0x4c,0x15,0x11,0xd5 = msr trcssccr5, x12 0x47,0x16,0x11,0xd5 = msr trcssccr6, x7 0x46,0x17,0x11,0xd5 = msr trcssccr7, x6 0x54,0x18,0x11,0xd5 = msr trcsscsr0, x20 0x51,0x19,0x11,0xd5 = msr trcsscsr1, x17 0x4b,0x1a,0x11,0xd5 = msr trcsscsr2, x11 0x44,0x1b,0x11,0xd5 = msr trcsscsr3, x4 0x4e,0x1c,0x11,0xd5 = msr trcsscsr4, x14 0x56,0x1d,0x11,0xd5 = msr trcsscsr5, x22 0x43,0x1e,0x11,0xd5 = msr trcsscsr6, x3 0x4b,0x1f,0x11,0xd5 = msr trcsscsr7, x11 0x62,0x10,0x11,0xd5 = msr trcsspcicr0, x2 0x63,0x11,0x11,0xd5 = msr trcsspcicr1, x3 0x65,0x12,0x11,0xd5 = msr trcsspcicr2, x5 0x67,0x13,0x11,0xd5 = msr trcsspcicr3, x7 0x6b,0x14,0x11,0xd5 = msr trcsspcicr4, x11 0x6d,0x15,0x11,0xd5 = msr trcsspcicr5, x13 0x71,0x16,0x11,0xd5 = msr trcsspcicr6, x17 0x77,0x17,0x11,0xd5 = msr trcsspcicr7, x23 0x83,0x14,0x11,0xd5 = msr trcpdcr, x3 0x06,0x20,0x11,0xd5 = msr trcacvr0, x6 0x14,0x22,0x11,0xd5 = msr trcacvr1, x20 0x19,0x24,0x11,0xd5 = msr trcacvr2, x25 0x01,0x26,0x11,0xd5 = msr trcacvr3, x1 0x1c,0x28,0x11,0xd5 = msr trcacvr4, x28 0x0f,0x2a,0x11,0xd5 = msr trcacvr5, x15 0x19,0x2c,0x11,0xd5 = msr trcacvr6, x25 0x0c,0x2e,0x11,0xd5 = msr trcacvr7, x12 0x25,0x20,0x11,0xd5 = msr trcacvr8, x5 0x39,0x22,0x11,0xd5 = msr trcacvr9, x25 0x2d,0x24,0x11,0xd5 = msr trcacvr10, x13 0x2a,0x26,0x11,0xd5 = msr trcacvr11, x10 0x33,0x28,0x11,0xd5 = msr trcacvr12, x19 0x2a,0x2a,0x11,0xd5 = msr trcacvr13, x10 0x33,0x2c,0x11,0xd5 = msr trcacvr14, x19 0x22,0x2e,0x11,0xd5 = msr trcacvr15, x2 0x4f,0x20,0x11,0xd5 = msr trcacatr0, x15 0x4d,0x22,0x11,0xd5 = msr trcacatr1, x13 0x48,0x24,0x11,0xd5 = msr trcacatr2, x8 0x41,0x26,0x11,0xd5 = msr trcacatr3, x1 0x4b,0x28,0x11,0xd5 = msr trcacatr4, x11 0x48,0x2a,0x11,0xd5 = msr trcacatr5, x8 0x58,0x2c,0x11,0xd5 = msr trcacatr6, x24 0x46,0x2e,0x11,0xd5 = msr trcacatr7, x6 0x77,0x20,0x11,0xd5 = msr trcacatr8, x23 0x65,0x22,0x11,0xd5 = msr trcacatr9, x5 0x6b,0x24,0x11,0xd5 = msr trcacatr10, x11 0x6b,0x26,0x11,0xd5 = msr trcacatr11, x11 0x63,0x28,0x11,0xd5 = msr trcacatr12, x3 0x7c,0x2a,0x11,0xd5 = msr trcacatr13, x28 0x79,0x2c,0x11,0xd5 = msr trcacatr14, x25 0x64,0x2e,0x11,0xd5 = msr trcacatr15, x4 0x86,0x20,0x11,0xd5 = msr trcdvcvr0, x6 0x83,0x24,0x11,0xd5 = msr trcdvcvr1, x3 0x85,0x28,0x11,0xd5 = msr trcdvcvr2, x5 0x8b,0x2c,0x11,0xd5 = msr trcdvcvr3, x11 0xa9,0x20,0x11,0xd5 = msr trcdvcvr4, x9 0xae,0x24,0x11,0xd5 = msr trcdvcvr5, x14 0xaa,0x28,0x11,0xd5 = msr trcdvcvr6, x10 0xac,0x2c,0x11,0xd5 = msr trcdvcvr7, x12 0xc8,0x20,0x11,0xd5 = msr trcdvcmr0, x8 0xc8,0x24,0x11,0xd5 = msr trcdvcmr1, x8 0xd6,0x28,0x11,0xd5 = msr trcdvcmr2, x22 0xd6,0x2c,0x11,0xd5 = msr trcdvcmr3, x22 0xe5,0x20,0x11,0xd5 = msr trcdvcmr4, x5 0xf0,0x24,0x11,0xd5 = msr trcdvcmr5, x16 0xfb,0x28,0x11,0xd5 = msr trcdvcmr6, x27 0xf5,0x2c,0x11,0xd5 = msr trcdvcmr7, x21 0x08,0x30,0x11,0xd5 = msr trccidcvr0, x8 0x06,0x32,0x11,0xd5 = msr trccidcvr1, x6 0x09,0x34,0x11,0xd5 = msr trccidcvr2, x9 0x08,0x36,0x11,0xd5 = msr trccidcvr3, x8 0x03,0x38,0x11,0xd5 = msr trccidcvr4, x3 0x15,0x3a,0x11,0xd5 = msr trccidcvr5, x21 0x0c,0x3c,0x11,0xd5 = msr trccidcvr6, x12 0x07,0x3e,0x11,0xd5 = msr trccidcvr7, x7 0x24,0x30,0x11,0xd5 = msr trcvmidcvr0, x4 0x23,0x32,0x11,0xd5 = msr trcvmidcvr1, x3 0x29,0x34,0x11,0xd5 = msr trcvmidcvr2, x9 0x31,0x36,0x11,0xd5 = msr trcvmidcvr3, x17 0x2e,0x38,0x11,0xd5 = msr trcvmidcvr4, x14 0x2c,0x3a,0x11,0xd5 = msr trcvmidcvr5, x12 0x2a,0x3c,0x11,0xd5 = msr trcvmidcvr6, x10 0x23,0x3e,0x11,0xd5 = msr trcvmidcvr7, x3 0x4e,0x30,0x11,0xd5 = msr trccidcctlr0, x14 0x56,0x31,0x11,0xd5 = msr trccidcctlr1, x22 0x48,0x32,0x11,0xd5 = msr trcvmidcctlr0, x8 0x4f,0x33,0x11,0xd5 = msr trcvmidcctlr1, x15 0x81,0x70,0x11,0xd5 = msr trcitctrl, x1 0xc7,0x78,0x11,0xd5 = msr trcclaimset, x7 0xdd,0x79,0x11,0xd5 = msr trcclaimclr, x29
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Xml { public enum XmlNodeOrder { After = 1, Before = 0, Same = 2, Unknown = 3, } } namespace System.Xml.XPath { public partial interface IXPathNavigable { System.Xml.XPath.XPathNavigator CreateNavigator(); } public enum XmlCaseOrder { LowerFirst = 2, None = 0, UpperFirst = 1, } public enum XmlDataType { Number = 2, Text = 1, } public enum XmlSortOrder { Ascending = 1, Descending = 2, } public partial class XPathDocument : System.Xml.XPath.IXPathNavigable { public XPathDocument(System.IO.Stream stream) { } public XPathDocument(System.IO.TextReader textReader) { } public XPathDocument(string uri) { } public XPathDocument(string uri, System.Xml.XmlSpace space) { } public XPathDocument(System.Xml.XmlReader reader) { } public XPathDocument(System.Xml.XmlReader reader, System.Xml.XmlSpace space) { } public System.Xml.XPath.XPathNavigator CreateNavigator() { return default(System.Xml.XPath.XPathNavigator); } } public partial class XPathException : System.Exception { public XPathException() { } public XPathException(string message) { } public XPathException(string message, System.Exception innerException) { } } public abstract partial class XPathExpression { internal XPathExpression() { } public abstract string Expression { get; } public abstract System.Xml.XPath.XPathResultType ReturnType { get; } public abstract void AddSort(object expr, System.Collections.IComparer comparer); public abstract void AddSort(object expr, System.Xml.XPath.XmlSortOrder order, System.Xml.XPath.XmlCaseOrder caseOrder, string lang, System.Xml.XPath.XmlDataType dataType); public abstract System.Xml.XPath.XPathExpression Clone(); public static System.Xml.XPath.XPathExpression Compile(string xpath) { return default(System.Xml.XPath.XPathExpression); } public static System.Xml.XPath.XPathExpression Compile(string xpath, System.Xml.IXmlNamespaceResolver nsResolver) { return default(System.Xml.XPath.XPathExpression); } public abstract void SetContext(System.Xml.IXmlNamespaceResolver nsResolver); public abstract void SetContext(System.Xml.XmlNamespaceManager nsManager); } public abstract partial class XPathItem { internal XPathItem() { } public abstract bool IsNode { get; } public abstract object TypedValue { get; } public abstract string Value { get; } public abstract bool ValueAsBoolean { get; } public abstract System.DateTime ValueAsDateTime { get; } public abstract double ValueAsDouble { get; } public abstract int ValueAsInt { get; } public abstract long ValueAsLong { get; } public abstract System.Type ValueType { get; } public virtual object ValueAs(System.Type returnType) { return default(object); } public abstract object ValueAs(System.Type returnType, System.Xml.IXmlNamespaceResolver nsResolver); } public enum XPathNamespaceScope { All = 0, ExcludeXml = 1, Local = 2, } public abstract partial class XPathNavigator : System.Xml.XPath.XPathItem, System.Xml.IXmlNamespaceResolver, System.Xml.XPath.IXPathNavigable { protected XPathNavigator() { } public abstract string BaseURI { get; } public virtual bool CanEdit { get { return default(bool); } } public virtual bool HasAttributes { get { return default(bool); } } public virtual bool HasChildren { get { return default(bool); } } public virtual string InnerXml { get { return default(string); } set { } } public abstract bool IsEmptyElement { get; } public sealed override bool IsNode { get { return default(bool); } } public abstract string LocalName { get; } public abstract string Name { get; } public abstract string NamespaceURI { get; } public abstract System.Xml.XmlNameTable NameTable { get; } public static System.Collections.IEqualityComparer NavigatorComparer { get { return default(System.Collections.IEqualityComparer); } } public abstract System.Xml.XPath.XPathNodeType NodeType { get; } public virtual string OuterXml { get { return default(string); } set { } } public abstract string Prefix { get; } public override object TypedValue { get { return default(object); } } public virtual object UnderlyingObject { get { return default(object); } } public override bool ValueAsBoolean { get { return default(bool); } } public override System.DateTime ValueAsDateTime { get { return default(System.DateTime); } } public override double ValueAsDouble { get { return default(double); } } public override int ValueAsInt { get { return default(int); } } public override long ValueAsLong { get { return default(long); } } public override System.Type ValueType { get { return default(System.Type); } } public virtual string XmlLang { get { return default(string); } } public virtual System.Xml.XmlWriter AppendChild() { return default(System.Xml.XmlWriter); } public virtual void AppendChild(string newChild) { } public virtual void AppendChild(System.Xml.XmlReader newChild) { } public virtual void AppendChild(System.Xml.XPath.XPathNavigator newChild) { } public virtual void AppendChildElement(string prefix, string localName, string namespaceURI, string value) { } public abstract System.Xml.XPath.XPathNavigator Clone(); public virtual System.Xml.XmlNodeOrder ComparePosition(System.Xml.XPath.XPathNavigator nav) { return default(System.Xml.XmlNodeOrder); } public virtual System.Xml.XPath.XPathExpression Compile(string xpath) { return default(System.Xml.XPath.XPathExpression); } public virtual void CreateAttribute(string prefix, string localName, string namespaceURI, string value) { } public virtual System.Xml.XmlWriter CreateAttributes() { return default(System.Xml.XmlWriter); } public virtual System.Xml.XPath.XPathNavigator CreateNavigator() { return default(System.Xml.XPath.XPathNavigator); } public virtual void DeleteRange(System.Xml.XPath.XPathNavigator lastSiblingToDelete) { } public virtual void DeleteSelf() { } public virtual object Evaluate(string xpath) { return default(object); } public virtual object Evaluate(string xpath, System.Xml.IXmlNamespaceResolver resolver) { return default(object); } public virtual object Evaluate(System.Xml.XPath.XPathExpression expr) { return default(object); } public virtual object Evaluate(System.Xml.XPath.XPathExpression expr, System.Xml.XPath.XPathNodeIterator context) { return default(object); } public virtual string GetAttribute(string localName, string namespaceURI) { return default(string); } public virtual string GetNamespace(string name) { return default(string); } public virtual System.Collections.Generic.IDictionary<string, string> GetNamespacesInScope(System.Xml.XmlNamespaceScope scope) { return default(System.Collections.Generic.IDictionary<string, string>); } public virtual System.Xml.XmlWriter InsertAfter() { return default(System.Xml.XmlWriter); } public virtual void InsertAfter(string newSibling) { } public virtual void InsertAfter(System.Xml.XmlReader newSibling) { } public virtual void InsertAfter(System.Xml.XPath.XPathNavigator newSibling) { } public virtual System.Xml.XmlWriter InsertBefore() { return default(System.Xml.XmlWriter); } public virtual void InsertBefore(string newSibling) { } public virtual void InsertBefore(System.Xml.XmlReader newSibling) { } public virtual void InsertBefore(System.Xml.XPath.XPathNavigator newSibling) { } public virtual void InsertElementAfter(string prefix, string localName, string namespaceURI, string value) { } public virtual void InsertElementBefore(string prefix, string localName, string namespaceURI, string value) { } public virtual bool IsDescendant(System.Xml.XPath.XPathNavigator nav) { return default(bool); } public abstract bool IsSamePosition(System.Xml.XPath.XPathNavigator other); public virtual string LookupNamespace(string prefix) { return default(string); } public virtual string LookupPrefix(string namespaceURI) { return default(string); } public virtual bool Matches(string xpath) { return default(bool); } public virtual bool Matches(System.Xml.XPath.XPathExpression expr) { return default(bool); } public abstract bool MoveTo(System.Xml.XPath.XPathNavigator other); public virtual bool MoveToAttribute(string localName, string namespaceURI) { return default(bool); } public virtual bool MoveToChild(string localName, string namespaceURI) { return default(bool); } public virtual bool MoveToChild(System.Xml.XPath.XPathNodeType type) { return default(bool); } public virtual bool MoveToFirst() { return default(bool); } public abstract bool MoveToFirstAttribute(); public abstract bool MoveToFirstChild(); public bool MoveToFirstNamespace() { return default(bool); } public abstract bool MoveToFirstNamespace(System.Xml.XPath.XPathNamespaceScope namespaceScope); public virtual bool MoveToFollowing(string localName, string namespaceURI) { return default(bool); } public virtual bool MoveToFollowing(string localName, string namespaceURI, System.Xml.XPath.XPathNavigator end) { return default(bool); } public virtual bool MoveToFollowing(System.Xml.XPath.XPathNodeType type) { return default(bool); } public virtual bool MoveToFollowing(System.Xml.XPath.XPathNodeType type, System.Xml.XPath.XPathNavigator end) { return default(bool); } public abstract bool MoveToId(string id); public virtual bool MoveToNamespace(string name) { return default(bool); } public abstract bool MoveToNext(); public virtual bool MoveToNext(string localName, string namespaceURI) { return default(bool); } public virtual bool MoveToNext(System.Xml.XPath.XPathNodeType type) { return default(bool); } public abstract bool MoveToNextAttribute(); public bool MoveToNextNamespace() { return default(bool); } public abstract bool MoveToNextNamespace(System.Xml.XPath.XPathNamespaceScope namespaceScope); public abstract bool MoveToParent(); public abstract bool MoveToPrevious(); public virtual void MoveToRoot() { } public virtual System.Xml.XmlWriter PrependChild() { return default(System.Xml.XmlWriter); } public virtual void PrependChild(string newChild) { } public virtual void PrependChild(System.Xml.XmlReader newChild) { } public virtual void PrependChild(System.Xml.XPath.XPathNavigator newChild) { } public virtual void PrependChildElement(string prefix, string localName, string namespaceURI, string value) { } public virtual System.Xml.XmlReader ReadSubtree() { return default(System.Xml.XmlReader); } public virtual System.Xml.XmlWriter ReplaceRange(System.Xml.XPath.XPathNavigator lastSiblingToReplace) { return default(System.Xml.XmlWriter); } public virtual void ReplaceSelf(string newNode) { } public virtual void ReplaceSelf(System.Xml.XmlReader newNode) { } public virtual void ReplaceSelf(System.Xml.XPath.XPathNavigator newNode) { } public virtual System.Xml.XPath.XPathNodeIterator Select(string xpath) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator Select(string xpath, System.Xml.IXmlNamespaceResolver resolver) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator Select(System.Xml.XPath.XPathExpression expr) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator SelectAncestors(string name, string namespaceURI, bool matchSelf) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator SelectAncestors(System.Xml.XPath.XPathNodeType type, bool matchSelf) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator SelectChildren(string name, string namespaceURI) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator SelectChildren(System.Xml.XPath.XPathNodeType type) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator SelectDescendants(string name, string namespaceURI, bool matchSelf) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNodeIterator SelectDescendants(System.Xml.XPath.XPathNodeType type, bool matchSelf) { return default(System.Xml.XPath.XPathNodeIterator); } public virtual System.Xml.XPath.XPathNavigator SelectSingleNode(string xpath) { return default(System.Xml.XPath.XPathNavigator); } public virtual System.Xml.XPath.XPathNavigator SelectSingleNode(string xpath, System.Xml.IXmlNamespaceResolver resolver) { return default(System.Xml.XPath.XPathNavigator); } public virtual System.Xml.XPath.XPathNavigator SelectSingleNode(System.Xml.XPath.XPathExpression expression) { return default(System.Xml.XPath.XPathNavigator); } public virtual void SetTypedValue(object typedValue) { } public virtual void SetValue(string value) { } public override string ToString() { return default(string); } public override object ValueAs(System.Type returnType, System.Xml.IXmlNamespaceResolver nsResolver) { return default(object); } public virtual void WriteSubtree(System.Xml.XmlWriter writer) { } } public abstract partial class XPathNodeIterator : System.Collections.IEnumerable { protected XPathNodeIterator() { } public virtual int Count { get { return default(int); } } public abstract System.Xml.XPath.XPathNavigator Current { get; } public abstract int CurrentPosition { get; } public abstract System.Xml.XPath.XPathNodeIterator Clone(); public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } public abstract bool MoveNext(); } public enum XPathNodeType { All = 9, Attribute = 2, Comment = 8, Element = 1, Namespace = 3, ProcessingInstruction = 7, Root = 0, SignificantWhitespace = 5, Text = 4, Whitespace = 6, } public enum XPathResultType { Any = 5, Boolean = 2, Error = 6, Navigator = 1, NodeSet = 3, Number = 0, String = 1, } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: Monitor ** ** ** Purpose: Synchronizes access to a shared resource or region of code in a multi-threaded ** program. ** ** =============================================================================*/ namespace System.Threading { using System; using System.Security.Permissions; ////using System.Runtime.Remoting; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; ////using System.Runtime.Versioning; [HostProtection( Synchronization = true, ExternalThreading = true )] public static class Monitor { /*========================================================================= ** Obtain the monitor lock of obj. Will block if another thread holds the lock ** Will not block if the current thread holds the lock, ** however the caller must ensure that the same number of Exit ** calls are made as there were Enter calls. ** ** Exceptions: ArgumentNullException if object is null. =========================================================================*/ //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void Enter( Object obj ); //// // This should be made public in a future version. //// // Use a ref bool instead of out to ensure that unverifiable code must //// // initialize this value to something. If we used out, the value //// // could be uninitialized if we threw an exception in our prolog. //// [ResourceExposure( ResourceScope.None )] //// [MethodImpl( MethodImplOptions.InternalCall )] //// internal static extern void ReliableEnter( Object obj, ref bool tookLock ); public static void Enter( Object obj, ref bool lockTaken ) { if(obj == null) { throw new ArgumentNullException(); } // The input must be false. if (lockTaken == true) { lockTaken = false; throw new ArgumentException(); } //The output is true if the lock is acquired; otherwise, the output is // false. The output is set even if an exception occurs during the attempt // to acquire the lock. Enter(obj); lockTaken = true; } /*========================================================================= ** Release the monitor lock. If one or more threads are waiting to acquire the ** lock, and the current thread has executed as many Exits as ** Enters, one of the threads will be unblocked and allowed to proceed. ** ** Exceptions: ArgumentNullException if object is null. ** SynchronizationLockException if the current thread does not ** own the lock. =========================================================================*/ //// [ResourceExposure( ResourceScope.None )] //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] [MethodImpl( MethodImplOptions.InternalCall )] public static extern void Exit( Object obj ); /*========================================================================= ** Similar to Enter, but will never block. That is, if the current thread can ** acquire the monitor lock without blocking, it will do so and TRUE will ** be returned. Otherwise FALSE will be returned. ** ** Exceptions: ArgumentNullException if object is null. =========================================================================*/ public static bool TryEnter( Object obj ) { return TryEnterTimeout( obj, 0 ); } /*========================================================================= ** Version of TryEnter that will block, but only up to a timeout period ** expressed in milliseconds. If timeout == Timeout.Infinite the method ** becomes equivalent to Enter. ** ** Exceptions: ArgumentNullException if object is null. ** ArgumentException if timeout < 0. =========================================================================*/ public static bool TryEnter( Object obj, int millisecondsTimeout ) { return TryEnterTimeout( obj, millisecondsTimeout ); } public static bool TryEnter( Object obj, TimeSpan timeout ) { long tm = (long)timeout.TotalMilliseconds; if(tm < -1 || tm > (long)Int32.MaxValue) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return TryEnterTimeout( obj, (int)tm ); } //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern bool TryEnterTimeout( Object obj, int timeout ); /*======================================================================== ** Waits for notification from the object (via a Pulse/PulseAll). ** timeout indicates how long to wait before the method returns. ** This method acquires the monitor waithandle for the object ** If this thread holds the monitor lock for the object, it releases it. ** On exit from the method, it obtains the monitor lock back. ** If exitContext is true then the synchronization domain for the context ** (if in a synchronized context) is exited before the wait and reacquired ** ** Exceptions: ArgumentNullException if object is null. ========================================================================*/ //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern bool ObjWait( bool exitContext, int millisecondsTimeout, Object obj ); public static bool Wait( Object obj, int millisecondsTimeout, bool exitContext ) { if(obj == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "obj" ); #else throw new ArgumentNullException(); #endif } return ObjWait( exitContext, millisecondsTimeout, obj ); } public static bool Wait( Object obj, TimeSpan timeout, bool exitContext ) { long tm = (long)timeout.TotalMilliseconds; if(tm < -1 || tm > (long)Int32.MaxValue) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return Wait( obj, (int)tm, exitContext ); } public static bool Wait( Object obj, int millisecondsTimeout ) { return Wait( obj, millisecondsTimeout, false ); } public static bool Wait( Object obj, TimeSpan timeout ) { long tm = (long)timeout.TotalMilliseconds; if(tm < -1 || tm > (long)Int32.MaxValue) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return Wait( obj, (int)tm, false ); } public static bool Wait( Object obj ) { return Wait( obj, Timeout.Infinite, false ); } /*======================================================================== ** Sends a notification to a single waiting object. * Exceptions: SynchronizationLockException if this method is not called inside * a synchronized block of code. ========================================================================*/ //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern void ObjPulse( Object obj ); public static void Pulse( Object obj ) { if(obj == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "obj" ); #else throw new ArgumentNullException(); #endif } ObjPulse( obj ); } /*======================================================================== ** Sends a notification to all waiting objects. ========================================================================*/ //// [ResourceExposure( ResourceScope.None )] [MethodImpl( MethodImplOptions.InternalCall )] private static extern void ObjPulseAll( Object obj ); public static void PulseAll( Object obj ) { if(obj == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "obj" ); #else throw new ArgumentNullException(); #endif } ObjPulseAll( obj ); } } }
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.PartnerPack.ContinousJob { 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 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Xsl.XsltOld { using System.Globalization; using System.Diagnostics; using System.IO; using System.Xml.XPath; using MS.Internal.Xml.XPath; using System.Text; using System.Collections; using System.Collections.Generic; using System.Xml.Xsl.XsltOld.Debugger; using System.Reflection; using System.Security; internal sealed class Processor : IXsltProcessor { // // Static constants // private const int StackIncrement = 10; // // Execution result // internal enum ExecResult { Continue, // Continues next iteration immediately Interrupt, // Returns to caller, was processed enough Done // Execution finished } internal enum OutputResult { Continue, Interrupt, Overflow, Error, Ignore } private ExecResult _execResult; // // Compiled stylesheet // private Stylesheet _stylesheet; // Root of import tree of template managers private RootAction _rootAction; private Key[] _keyList; private List<TheQuery> _queryStore; // // Document Being transformed // private XPathNavigator _document; // // Execution action stack // private HWStack _actionStack; private HWStack _debuggerStack; // // Register for returning value from calling nested action // private StringBuilder _sharedStringBuilder; // // Output related member variables // private int _ignoreLevel; private StateMachine _xsm; private RecordBuilder _builder; private XsltOutput _output; private XmlNameTable _nameTable = new NameTable(); private XmlResolver _resolver; #pragma warning disable 618 private XsltArgumentList _args; #pragma warning restore 618 private Hashtable _scriptExtensions; private ArrayList _numberList; // // Template lookup action // private TemplateLookupAction _templateLookup = new TemplateLookupAction(); private IXsltDebugger _debugger; private Query[] _queryList; private ArrayList _sortArray; private Hashtable _documentCache; // NOTE: ValueOf() can call Matches() through XsltCompileContext.PreserveWhitespace(), // that's why we use two different contexts here, valueOfContext and matchesContext private XsltCompileContext _valueOfContext; private XsltCompileContext _matchesContext; internal XPathNavigator Current { get { ActionFrame frame = (ActionFrame)_actionStack.Peek(); return frame != null ? frame.Node : null; } } internal ExecResult ExecutionResult { get { return _execResult; } set { Debug.Assert(_execResult == ExecResult.Continue); _execResult = value; } } internal Stylesheet Stylesheet { get { return _stylesheet; } } internal XmlResolver Resolver { get { Debug.Assert(_resolver != null, "Constructor should create it if null passed"); return _resolver; } } internal ArrayList SortArray { get { Debug.Assert(_sortArray != null, "InitSortArray() wasn't called"); return _sortArray; } } internal Key[] KeyList { get { return _keyList; } } internal XPathNavigator GetNavigator(Uri ruri) { XPathNavigator result = null; if (_documentCache != null) { result = _documentCache[ruri] as XPathNavigator; if (result != null) { return result.Clone(); } } else { _documentCache = new Hashtable(); } Object input = _resolver.GetEntity(ruri, null, null); if (input is Stream) { XmlTextReaderImpl tr = new XmlTextReaderImpl(ruri.ToString(), (Stream)input); { tr.XmlResolver = _resolver; } // reader is closed by Compiler.LoadDocument() result = ((IXPathNavigable)Compiler.LoadDocument(tr)).CreateNavigator(); } else if (input is XPathNavigator) { result = (XPathNavigator)input; } else { throw XsltException.Create(SR.Xslt_CantResolve, ruri.ToString()); } _documentCache[ruri] = result.Clone(); return result; } internal void AddSort(Sort sortinfo) { Debug.Assert(_sortArray != null, "InitSortArray() wasn't called"); _sortArray.Add(sortinfo); } internal void InitSortArray() { if (_sortArray == null) { _sortArray = new ArrayList(); } else { _sortArray.Clear(); } } internal object GetGlobalParameter(XmlQualifiedName qname) { object parameter = _args.GetParam(qname.Name, qname.Namespace); if (parameter == null) { return null; } if ( parameter is XPathNodeIterator || parameter is XPathNavigator || parameter is Boolean || parameter is Double || parameter is String ) { // doing nothing } else if ( parameter is Int16 || parameter is UInt16 || parameter is Int32 || parameter is UInt32 || parameter is Int64 || parameter is UInt64 || parameter is Single || parameter is Decimal ) { parameter = XmlConvert.ToXPathDouble(parameter); } else { parameter = parameter.ToString(); } return parameter; } internal object GetExtensionObject(string nsUri) { return _args.GetExtensionObject(nsUri); } internal object GetScriptObject(string nsUri) { return _scriptExtensions[nsUri]; } internal RootAction RootAction { get { return _rootAction; } } internal XPathNavigator Document { get { return _document; } } #if DEBUG private bool _stringBuilderLocked = false; #endif internal StringBuilder GetSharedStringBuilder() { #if DEBUG Debug.Assert(!_stringBuilderLocked); #endif if (_sharedStringBuilder == null) { _sharedStringBuilder = new StringBuilder(); } else { _sharedStringBuilder.Length = 0; } #if DEBUG _stringBuilderLocked = true; #endif return _sharedStringBuilder; } internal void ReleaseSharedStringBuilder() { // don't clean stringBuilderLocked here. ToString() will happen after this call #if DEBUG _stringBuilderLocked = false; #endif } internal ArrayList NumberList { get { if (_numberList == null) { _numberList = new ArrayList(); } return _numberList; } } internal IXsltDebugger Debugger { get { return _debugger; } } internal HWStack ActionStack { get { return _actionStack; } } internal XsltOutput Output { get { return _output; } } // // Construction // public Processor( XPathNavigator doc, XsltArgumentList args, XmlResolver resolver, Stylesheet stylesheet, List<TheQuery> queryStore, RootAction rootAction, IXsltDebugger debugger ) { _stylesheet = stylesheet; _queryStore = queryStore; _rootAction = rootAction; _queryList = new Query[queryStore.Count]; { for (int i = 0; i < queryStore.Count; i++) { _queryList[i] = Query.Clone(queryStore[i].CompiledQuery.QueryTree); } } _xsm = new StateMachine(); _document = doc; _builder = null; _actionStack = new HWStack(StackIncrement); _output = _rootAction.Output; _resolver = resolver ?? XmlNullResolver.Singleton; _args = args ?? new XsltArgumentList(); _debugger = debugger; if (_debugger != null) { _debuggerStack = new HWStack(StackIncrement, /*limit:*/1000); _templateLookup = new TemplateLookupActionDbg(); } // Clone the compile-time KeyList if (_rootAction.KeyList != null) { _keyList = new Key[_rootAction.KeyList.Count]; for (int i = 0; i < _keyList.Length; i++) { _keyList[i] = _rootAction.KeyList[i].Clone(); } } _scriptExtensions = new Hashtable(_stylesheet.ScriptObjectTypes.Count); { foreach (DictionaryEntry entry in _stylesheet.ScriptObjectTypes) { string namespaceUri = (string)entry.Key; if (GetExtensionObject(namespaceUri) != null) { throw XsltException.Create(SR.Xslt_ScriptDub, namespaceUri); } _scriptExtensions.Add(namespaceUri, Activator.CreateInstance((Type)entry.Value, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, null, null)); } } this.PushActionFrame(_rootAction, /*nodeSet:*/null); } public ReaderOutput StartReader() { ReaderOutput output = new ReaderOutput(this); _builder = new RecordBuilder(output, _nameTable); return output; } public void Execute(Stream stream) { RecordOutput recOutput = null; switch (_output.Method) { case XsltOutput.OutputMethod.Text: recOutput = new TextOnlyOutput(this, stream); break; case XsltOutput.OutputMethod.Xml: case XsltOutput.OutputMethod.Html: case XsltOutput.OutputMethod.Other: case XsltOutput.OutputMethod.Unknown: recOutput = new TextOutput(this, stream); break; } _builder = new RecordBuilder(recOutput, _nameTable); Execute(); } public void Execute(TextWriter writer) { RecordOutput recOutput = null; switch (_output.Method) { case XsltOutput.OutputMethod.Text: recOutput = new TextOnlyOutput(this, writer); break; case XsltOutput.OutputMethod.Xml: case XsltOutput.OutputMethod.Html: case XsltOutput.OutputMethod.Other: case XsltOutput.OutputMethod.Unknown: recOutput = new TextOutput(this, writer); break; } _builder = new RecordBuilder(recOutput, _nameTable); Execute(); } public void Execute(XmlWriter writer) { _builder = new RecordBuilder(new WriterOutput(this, writer), _nameTable); Execute(); } // // Execution part of processor // internal void Execute() { Debug.Assert(_actionStack != null); while (_execResult == ExecResult.Continue) { ActionFrame frame = (ActionFrame)_actionStack.Peek(); if (frame == null) { Debug.Assert(_builder != null); _builder.TheEnd(); ExecutionResult = ExecResult.Done; break; } // Execute the action which was on the top of the stack if (frame.Execute(this)) { _actionStack.Pop(); } } if (_execResult == ExecResult.Interrupt) { _execResult = ExecResult.Continue; } } // // Action frame support // internal ActionFrame PushNewFrame() { ActionFrame prent = (ActionFrame)_actionStack.Peek(); ActionFrame frame = (ActionFrame)_actionStack.Push(); if (frame == null) { frame = new ActionFrame(); _actionStack.AddToTop(frame); } Debug.Assert(frame != null); if (prent != null) { frame.Inherit(prent); } return frame; } internal void PushActionFrame(Action action, XPathNodeIterator nodeSet) { ActionFrame frame = PushNewFrame(); frame.Init(action, nodeSet); } internal void PushActionFrame(ActionFrame container) { this.PushActionFrame(container, container.NodeSet); } internal void PushActionFrame(ActionFrame container, XPathNodeIterator nodeSet) { ActionFrame frame = PushNewFrame(); frame.Init(container, nodeSet); } internal void PushTemplateLookup(XPathNodeIterator nodeSet, XmlQualifiedName mode, Stylesheet importsOf) { Debug.Assert(_templateLookup != null); _templateLookup.Initialize(mode, importsOf); PushActionFrame(_templateLookup, nodeSet); } internal string GetQueryExpression(int key) { Debug.Assert(key != Compiler.InvalidQueryKey); return _queryStore[key].CompiledQuery.Expression; } internal Query GetCompiledQuery(int key) { Debug.Assert(key != Compiler.InvalidQueryKey); TheQuery theQuery = _queryStore[key]; theQuery.CompiledQuery.CheckErrors(); Query expr = Query.Clone(_queryList[key]); expr.SetXsltContext(new XsltCompileContext(theQuery._ScopeManager, this)); return expr; } internal Query GetValueQuery(int key) { return GetValueQuery(key, null); } internal Query GetValueQuery(int key, XsltCompileContext context) { Debug.Assert(key != Compiler.InvalidQueryKey); TheQuery theQuery = _queryStore[key]; theQuery.CompiledQuery.CheckErrors(); Query expr = _queryList[key]; if (context == null) { context = new XsltCompileContext(theQuery._ScopeManager, this); } else { context.Reinitialize(theQuery._ScopeManager, this); } expr.SetXsltContext(context); return expr; } private XsltCompileContext GetValueOfContext() { if (_valueOfContext == null) { _valueOfContext = new XsltCompileContext(); } return _valueOfContext; } [Conditional("DEBUG")] private void RecycleValueOfContext() { if (_valueOfContext != null) { _valueOfContext.Recycle(); } } private XsltCompileContext GetMatchesContext() { if (_matchesContext == null) { _matchesContext = new XsltCompileContext(); } return _matchesContext; } [Conditional("DEBUG")] private void RecycleMatchesContext() { if (_matchesContext != null) { _matchesContext.Recycle(); } } internal String ValueOf(ActionFrame context, int key) { string result; Query query = this.GetValueQuery(key, GetValueOfContext()); object value = query.Evaluate(context.NodeSet); if (value is XPathNodeIterator) { XPathNavigator n = query.Advance(); result = n != null ? ValueOf(n) : string.Empty; } else { result = XmlConvert.ToXPathString(value); } RecycleValueOfContext(); return result; } internal String ValueOf(XPathNavigator n) { if (_stylesheet.Whitespace && n.NodeType == XPathNodeType.Element) { StringBuilder builder = this.GetSharedStringBuilder(); ElementValueWithoutWS(n, builder); this.ReleaseSharedStringBuilder(); return builder.ToString(); } return n.Value; } private void ElementValueWithoutWS(XPathNavigator nav, StringBuilder builder) { Debug.Assert(nav.NodeType == XPathNodeType.Element); bool preserve = this.Stylesheet.PreserveWhiteSpace(this, nav); if (nav.MoveToFirstChild()) { do { switch (nav.NodeType) { case XPathNodeType.Text: case XPathNodeType.SignificantWhitespace: builder.Append(nav.Value); break; case XPathNodeType.Whitespace: if (preserve) { builder.Append(nav.Value); } break; case XPathNodeType.Element: ElementValueWithoutWS(nav, builder); break; } } while (nav.MoveToNext()); nav.MoveToParent(); } } internal XPathNodeIterator StartQuery(XPathNodeIterator context, int key) { Query query = GetCompiledQuery(key); object result = query.Evaluate(context); if (result is XPathNodeIterator) { return new XPathSelectionIterator(context.Current, query); } throw XsltException.Create(SR.XPath_NodeSetExpected); } internal object Evaluate(ActionFrame context, int key) { return GetValueQuery(key).Evaluate(context.NodeSet); } internal object RunQuery(ActionFrame context, int key) { Query query = GetCompiledQuery(key); object value = query.Evaluate(context.NodeSet); XPathNodeIterator it = value as XPathNodeIterator; if (it != null) { return new XPathArrayIterator(it); } return value; } internal string EvaluateString(ActionFrame context, int key) { object objValue = Evaluate(context, key); string value = null; if (objValue != null) value = XmlConvert.ToXPathString(objValue); if (value == null) value = string.Empty; return value; } internal bool EvaluateBoolean(ActionFrame context, int key) { object objValue = Evaluate(context, key); if (objValue != null) { XPathNavigator nav = objValue as XPathNavigator; return nav != null ? Convert.ToBoolean(nav.Value, CultureInfo.InvariantCulture) : Convert.ToBoolean(objValue, CultureInfo.InvariantCulture); } else { return false; } } internal bool Matches(XPathNavigator context, int key) { // We don't use XPathNavigator.Matches() to avoid cloning of Query on each call Query query = this.GetValueQuery(key, GetMatchesContext()); try { bool result = query.MatchNode(context) != null; RecycleMatchesContext(); return result; } catch (XPathException) { throw XsltException.Create(SR.Xslt_InvalidPattern, this.GetQueryExpression(key)); } } // // Outputting part of processor // internal XmlNameTable NameTable { get { return _nameTable; } } internal bool CanContinue { get { return _execResult == ExecResult.Continue; } } internal bool ExecutionDone { get { return _execResult == ExecResult.Done; } } internal void ResetOutput() { Debug.Assert(_builder != null); _builder.Reset(); } internal bool BeginEvent(XPathNodeType nodeType, string prefix, string name, string nspace, bool empty) { return BeginEvent(nodeType, prefix, name, nspace, empty, null, true); } internal bool BeginEvent(XPathNodeType nodeType, string prefix, string name, string nspace, bool empty, Object htmlProps, bool search) { Debug.Assert(_xsm != null); int stateOutlook = _xsm.BeginOutlook(nodeType); if (_ignoreLevel > 0 || stateOutlook == StateMachine.Error) { _ignoreLevel++; return true; // We consumed the event, so pretend it was output. } switch (_builder.BeginEvent(stateOutlook, nodeType, prefix, name, nspace, empty, htmlProps, search)) { case OutputResult.Continue: _xsm.Begin(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); Debug.Assert(ExecutionResult == ExecResult.Continue); return true; case OutputResult.Interrupt: _xsm.Begin(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); ExecutionResult = ExecResult.Interrupt; return true; case OutputResult.Overflow: ExecutionResult = ExecResult.Interrupt; return false; case OutputResult.Error: _ignoreLevel++; return true; case OutputResult.Ignore: return true; default: Debug.Fail("Unexpected result of RecordBuilder.BeginEvent()"); return true; } } internal bool TextEvent(string text) { return this.TextEvent(text, false); } internal bool TextEvent(string text, bool disableOutputEscaping) { Debug.Assert(_xsm != null); if (_ignoreLevel > 0) { return true; } int stateOutlook = _xsm.BeginOutlook(XPathNodeType.Text); switch (_builder.TextEvent(stateOutlook, text, disableOutputEscaping)) { case OutputResult.Continue: _xsm.Begin(XPathNodeType.Text); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); Debug.Assert(ExecutionResult == ExecResult.Continue); return true; case OutputResult.Interrupt: _xsm.Begin(XPathNodeType.Text); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); ExecutionResult = ExecResult.Interrupt; return true; case OutputResult.Overflow: ExecutionResult = ExecResult.Interrupt; return false; case OutputResult.Error: case OutputResult.Ignore: return true; default: Debug.Fail("Unexpected result of RecordBuilder.TextEvent()"); return true; } } internal bool EndEvent(XPathNodeType nodeType) { Debug.Assert(_xsm != null); if (_ignoreLevel > 0) { _ignoreLevel--; return true; } int stateOutlook = _xsm.EndOutlook(nodeType); switch (_builder.EndEvent(stateOutlook, nodeType)) { case OutputResult.Continue: _xsm.End(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); return true; case OutputResult.Interrupt: _xsm.End(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State, "StateMachine.StateOnly(stateOutlook) == this.xsm.State"); ExecutionResult = ExecResult.Interrupt; return true; case OutputResult.Overflow: ExecutionResult = ExecResult.Interrupt; return false; case OutputResult.Error: case OutputResult.Ignore: default: Debug.Fail("Unexpected result of RecordBuilder.TextEvent()"); return true; } } internal bool CopyBeginEvent(XPathNavigator node, bool emptyflag) { switch (node.NodeType) { case XPathNodeType.Element: case XPathNodeType.Attribute: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: return BeginEvent(node.NodeType, node.Prefix, node.LocalName, node.NamespaceURI, emptyflag); case XPathNodeType.Namespace: // value instead of namespace here! return BeginEvent(XPathNodeType.Namespace, null, node.LocalName, node.Value, false); case XPathNodeType.Text: // Text will be copied in CopyContents(); break; case XPathNodeType.Root: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: case XPathNodeType.All: break; default: Debug.Fail("Invalid XPathNodeType in CopyBeginEvent"); break; } return true; } internal bool CopyTextEvent(XPathNavigator node) { switch (node.NodeType) { case XPathNodeType.Element: case XPathNodeType.Namespace: break; case XPathNodeType.Attribute: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: case XPathNodeType.Text: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: string text = node.Value; return TextEvent(text); case XPathNodeType.Root: case XPathNodeType.All: break; default: Debug.Fail("Invalid XPathNodeType in CopyTextEvent"); break; } return true; } internal bool CopyEndEvent(XPathNavigator node) { switch (node.NodeType) { case XPathNodeType.Element: case XPathNodeType.Attribute: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: case XPathNodeType.Namespace: return EndEvent(node.NodeType); case XPathNodeType.Text: // Text was copied in CopyContents(); break; case XPathNodeType.Root: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: case XPathNodeType.All: break; default: Debug.Fail("Invalid XPathNodeType in CopyEndEvent"); break; } return true; } internal static bool IsRoot(XPathNavigator navigator) { Debug.Assert(navigator != null); if (navigator.NodeType == XPathNodeType.Root) { return true; } else if (navigator.NodeType == XPathNodeType.Element) { XPathNavigator clone = navigator.Clone(); clone.MoveToRoot(); return clone.IsSamePosition(navigator); } else { return false; } } // // Builder stack // internal void PushOutput(RecordOutput output) { Debug.Assert(output != null); _builder.OutputState = _xsm.State; RecordBuilder lastBuilder = _builder; _builder = new RecordBuilder(output, _nameTable); _builder.Next = lastBuilder; _xsm.Reset(); } internal RecordOutput PopOutput() { Debug.Assert(_builder != null); RecordBuilder topBuilder = _builder; _builder = topBuilder.Next; _xsm.State = _builder.OutputState; topBuilder.TheEnd(); return topBuilder.Output; } internal bool SetDefaultOutput(XsltOutput.OutputMethod method) { if (Output.Method != method) { _output = _output.CreateDerivedOutput(method); return true; } return false; } internal object GetVariableValue(VariableAction variable) { int variablekey = variable.VarKey; if (variable.IsGlobal) { ActionFrame rootFrame = (ActionFrame)_actionStack[0]; object result = rootFrame.GetVariable(variablekey); if (result == VariableAction.BeingComputedMark) { throw XsltException.Create(SR.Xslt_CircularReference, variable.NameStr); } if (result != null) { return result; } // Variable wasn't evaluated yet int saveStackSize = _actionStack.Length; ActionFrame varFrame = PushNewFrame(); varFrame.Inherit(rootFrame); varFrame.Init(variable, rootFrame.NodeSet); do { bool endOfFrame = ((ActionFrame)_actionStack.Peek()).Execute(this); if (endOfFrame) { _actionStack.Pop(); } } while (saveStackSize < _actionStack.Length); Debug.Assert(saveStackSize == _actionStack.Length); result = rootFrame.GetVariable(variablekey); Debug.Assert(result != null, "Variable was just calculated and result can't be null"); return result; } else { return ((ActionFrame)_actionStack.Peek()).GetVariable(variablekey); } } internal void SetParameter(XmlQualifiedName name, object value) { Debug.Assert(1 < _actionStack.Length); ActionFrame parentFrame = (ActionFrame)_actionStack[_actionStack.Length - 2]; parentFrame.SetParameter(name, value); } internal void ResetParams() { ActionFrame frame = (ActionFrame)_actionStack[_actionStack.Length - 1]; frame.ResetParams(); } internal object GetParameter(XmlQualifiedName name) { Debug.Assert(2 < _actionStack.Length); ActionFrame parentFrame = (ActionFrame)_actionStack[_actionStack.Length - 3]; return parentFrame.GetParameter(name); } // ---------------------- Debugger stack ----------------------- internal class DebuggerFrame { internal ActionFrame actionFrame; internal XmlQualifiedName currentMode; } internal void PushDebuggerStack() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); DebuggerFrame dbgFrame = (DebuggerFrame)_debuggerStack.Push(); if (dbgFrame == null) { dbgFrame = new DebuggerFrame(); _debuggerStack.AddToTop(dbgFrame); } dbgFrame.actionFrame = (ActionFrame)_actionStack.Peek(); // In a case of next builtIn action. } internal void PopDebuggerStack() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); _debuggerStack.Pop(); } internal void OnInstructionExecute() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); DebuggerFrame dbgFrame = (DebuggerFrame)_debuggerStack.Peek(); Debug.Assert(dbgFrame != null, "PushDebuggerStack() wasn't ever called"); dbgFrame.actionFrame = (ActionFrame)_actionStack.Peek(); this.Debugger.OnInstructionExecute((IXsltProcessor)this); } internal XmlQualifiedName GetPrevioseMode() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); Debug.Assert(2 <= _debuggerStack.Length); return ((DebuggerFrame)_debuggerStack[_debuggerStack.Length - 2]).currentMode; } internal void SetCurrentMode(XmlQualifiedName mode) { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); ((DebuggerFrame)_debuggerStack[_debuggerStack.Length - 1]).currentMode = mode; } // ----------------------- IXsltProcessor : -------------------- int IXsltProcessor.StackDepth { get { return _debuggerStack.Length; } } IStackFrame IXsltProcessor.GetStackFrame(int depth) { return ((DebuggerFrame)_debuggerStack[depth]).actionFrame; } } }
/* Copyright (c) 2005-2006 Tomas Matousek and Martin Maly. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Text; using System.Data; using System.Collections; using System.Collections.Generic; using PHP.Core; using System.Diagnostics; namespace PHP.Library.Data { /// <summary> /// Abstract class implementing common functionality of PHP connection resources. /// </summary> public abstract class PhpDbConnection : PhpResource { #region Fields & Properties /// <summary> /// Connection string. /// </summary> public string/*!*/ ConnectionString { get { return connectionString; } } private string/*!*/ connectionString; /// <summary> /// Underlying database connection. /// </summary> public IDbConnection/*!*/Connection { get { return this.connection; } } protected IDbConnection/*!*/ connection; /// <summary> /// A result associated with this connection that possibly has not been closed yet. /// </summary> protected IDataReader pendingReader; /// <summary> /// Last result resource. /// </summary> public PhpDbResult LastResult { get { return lastResult; } } private PhpDbResult lastResult; /// <summary> /// Gets an exception thrown by last performed operation or a <B>null</B> reference /// if that operation succeeded. /// </summary> public Exception LastException { get { return lastException; } } private Exception lastException; /// <summary> /// Gets the number of rows affected by the last query executed on this connection. /// </summary> public int LastAffectedRows { get { if (lastResult == null) return -1; // SELECT gives -1, UPDATE/INSERT gives the number: return (lastResult.RecordsAffected >= 0) ? lastResult.RecordsAffected : lastResult.RowCount; } } #endregion /// <summary> /// Creates a new instance of <see cref="PhpDbConnection"/> with a specified connection. /// </summary> /// <param name="connectionString">Connection string.</param> /// <param name="connection">Database connection.</param> /// <param name="name">Connection resource name.</param> /// <exception cref="ArgumentNullException"><paramref name="connection"/> is a <B>null</B> reference.</exception> protected PhpDbConnection(string/*!*/ connectionString, IDbConnection/*!*/ connection, string/*!*/ name) : base(name, false) { if (connection == null) throw new ArgumentNullException("connection"); if (connectionString == null) throw new ArgumentNullException("connectionString"); this.connection = connection; this.connectionString = connectionString; } /// <summary> /// Gets a query result resource. /// </summary> /// <param name="connection">Database connection.</param> /// <param name="reader">Data reader to be used for result resource population.</param> /// <param name="convertTypes">Whether to convert data types to PHP ones.</param> /// <returns>Result resource holding all resulting data of the query.</returns> protected abstract PhpDbResult GetResult(PhpDbConnection/*!*/ connection, IDataReader/*!*/ reader, bool convertTypes); /// <summary> /// Creates a command instance. /// </summary> /// <returns>Instance of command specific for the database provider.</returns> protected abstract IDbCommand/*!*/ CreateCommand(); /// <summary> /// Builds a connection string. /// </summary> public static string/*!*/ BuildConnectionString(string server, string user, string password, string additionalSettings) { StringBuilder result = new StringBuilder(8); result.Append("server="); result.Append(server); // result.Append(";database="); // result.Append(database); result.Append(";user id="); result.Append(user); result.Append(";password="); result.Append(password); if (!String.IsNullOrEmpty(additionalSettings)) { result.Append(';'); result.AppendFormat(additionalSettings); } return result.ToString(); } /// <summary> /// Opens a database connection if it has not been opened yet. /// </summary> /// <returns><B>true</B> if successful.</returns> /// <exception cref="PhpException">Attempt to connect the database failed (Warning).</exception> /// <remarks> /// Sets <see cref="LastException"/> to <B>null</B> (on success) or to the exception object (on failure). /// </remarks> public bool Connect() { Debug.Assert(connection != null); if (connection.State == ConnectionState.Open) return true; connection.ConnectionString = this.ConnectionString; try { connection.Open(); lastException = null; } catch (Exception e) { lastException = e; PhpException.Throw(PhpError.Warning, LibResources.GetString("cannot_open_connection", GetExceptionMessage(e))); return false; } return true; } /// <summary> /// Closes connection and releases the resource. /// </summary> protected override void FreeManaged() { base.FreeManaged(); ClosePendingReader(); try { if (connection != null) { connection.Close(); } lastException = null; } catch (Exception e) { lastException = e; PhpException.Throw(PhpError.Warning, LibResources.GetString("error_closing_connection", GetExceptionMessage(e))); } connection = null; } /// <summary> /// Closes pending reader. /// </summary> public void ClosePendingReader() { if (pendingReader != null) { if (!pendingReader.IsClosed) pendingReader.Close(); pendingReader = null; } } /// <summary> /// Executes a query on the connection. /// </summary> /// <param name="query">The query.</param> /// <param name="convertTypes">Whether to convert data types to PHP ones.</param> /// <returns>PhpDbResult class representing the data read from database.</returns> /// <exception cref="ArgumentNullException"><paramref name="query"/> is a <B>null</B> reference.</exception> /// <exception cref="PhpException">Query execution failed (Warning).</exception> public PhpDbResult ExecuteQuery(string/*!*/ query, bool convertTypes) { if (query == null) throw new ArgumentNullException("query"); return ExecuteCommand(query, CommandType.Text, convertTypes, null, false); } /// <summary> /// Executes a stored procedure on the connection. /// </summary> /// <param name="procedureName">Procedure name.</param> /// <param name="parameters">Parameters.</param> /// <param name="skipResults">Whether to load results.</param> /// <returns>PhpDbResult class representing the data read from database.</returns> /// <exception cref="ArgumentNullException"><paramref name="procedureName"/> is a <B>null</B> reference.</exception> /// <exception cref="PhpException">Procedure execution failed (Warning).</exception> public PhpDbResult ExecuteProcedure(string/*!*/ procedureName, IEnumerable<IDataParameter> parameters, bool skipResults) { if (procedureName == null) throw new ArgumentNullException("procedureName"); return ExecuteCommand(procedureName, CommandType.StoredProcedure, true, parameters, skipResults); } /// <summary> /// Executes a command on the connection. /// </summary> /// <param name="commandText">Command text.</param> /// <param name="convertTypes">Whether to convert data types to PHP ones.</param> /// <param name="commandType">Command type.</param> /// <param name="parameters">Parameters.</param> /// <param name="skipResults">Whether to load results.</param> /// <returns>PhpDbResult class representing the data read from database.</returns> /// <exception cref="ArgumentNullException"><paramref name="commandText"/> is a <B>null</B> reference.</exception> /// <exception cref="PhpException">Command execution failed (Warning).</exception> public PhpDbResult ExecuteCommand(string/*!*/ commandText, CommandType commandType, bool convertTypes, IEnumerable<IDataParameter> parameters, bool skipResults) { if (commandText == null) throw new ArgumentNullException("commandText"); return (Connect()) ? ExecuteCommandInternal(commandText, commandType, convertTypes, parameters, skipResults) : null; } protected virtual PhpDbResult ExecuteCommandInternal(string/*!*/ commandText, CommandType commandType, bool convertTypes, IEnumerable<IDataParameter> parameters, bool skipResults) { ClosePendingReader(); // IDbCommand IDbCommand command = CreateCommand(); command.Connection = connection; command.CommandText = commandText; command.CommandType = commandType; if (parameters != null) { command.Parameters.Clear(); foreach (IDataParameter parameter in parameters) command.Parameters.Add(parameter); } // ExecuteReader PhpDbResult result = null; try { var/*!*/reader = this.pendingReader = command.ExecuteReader(); if (skipResults) { // reads all data: do { while (reader.Read()); } while (reader.NextResult()); } else { lastResult = null; // read all data into PhpDbResult: result = GetResult(this, reader, convertTypes); result.command = command; lastResult = result; } lastException = null; } catch (Exception e) { lastException = e; PhpException.Throw(PhpError.Warning, LibResources.GetString("command_execution_failed", GetExceptionMessage(e))); } // return result; } /// <summary> /// Reexecutes a command associated with a specified result resource to get schema of the command result. /// </summary> /// <param name="result">The result resource.</param> internal void ReexecuteSchemaQuery(PhpDbResult/*!*/ result) { if (!Connect() || result.Command == null) return; ClosePendingReader(); try { result.Reader = pendingReader = result.Command.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly); } catch (Exception e) { lastException = e; PhpException.Throw(PhpError.Warning, LibResources.GetString("command_execution_failed", GetExceptionMessage(e))); } } /// <summary> /// Changes the active database on opened connection. /// </summary> /// <param name="databaseName"></param> /// <returns>true if databse was changed; otherwise returns false</returns> public bool SelectDb(string databaseName) { ClosePendingReader(); try { if (this.connection.State == ConnectionState.Open) { connection.ChangeDatabase(databaseName); lastException = null; return true; } } catch (Exception e) { lastException = e; PhpException.Throw(PhpError.Warning, LibResources.GetString("database_selection_failed", GetExceptionMessage(e))); } return false; } /// <summary> /// Gets a message from an exception raised by the connector. /// Removes the ending dot. /// </summary> /// <param name="e">Exception.</param> /// <returns>The message.</returns> /// <exception cref="ArgumentNullException"><paramref name="e"/> is a <B>null</B> reference.</exception> public virtual string GetExceptionMessage(Exception/*!*/ e) { if (e == null) throw new ArgumentNullException("e"); return PhpException.ToErrorMessage(e.Message); } /// <summary> /// Gets the last error message. /// </summary> /// <returns>The message or an empty string if no error occured.</returns> public virtual string GetLastErrorMessage() { return (LastException != null) ? LastException.Message : String.Empty; } /// <summary> /// Gets the last error number. /// </summary> /// <returns>-1 on error, zero otherwise.</returns> /// <remarks>Should be implemented by the subclass if the respective provider supports error numbers.</remarks> public virtual int GetLastErrorNumber() { return (LastException != null) ? -1 : 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class AppendPrependTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsIntQueryAppend() { var q1 = from x1 in new int?[] { 2, 3, null, 2, null, 4, 5 } select x1; Assert.Equal(q1.Append(42), q1.Append(42)); Assert.Equal(q1.Append(42), q1.Concat(new int?[] { 42 })); } [Fact] public void SameResultsRepeatCallsIntQueryPrepend() { var q1 = from x1 in new int?[] { 2, 3, null, 2, null, 4, 5 } select x1; Assert.Equal(q1.Prepend(42), q1.Prepend(42)); Assert.Equal(q1.Prepend(42), (new int?[] { 42 }).Concat(q1)); } [Fact] public void SameResultsRepeatCallsStringQueryAppend() { var q1 = from x1 in new[] { "AAA", String.Empty, "q", "C", "#", "!@#$%^", "0987654321", "Calling Twice" } select x1; Assert.Equal(q1.Append("hi"), q1.Append("hi")); Assert.Equal(q1.Append("hi"), q1.Concat(new string[] { "hi" })); } [Fact] public void SameResultsRepeatCallsStringQueryPrepend() { var q1 = from x1 in new[] { "AAA", String.Empty, "q", "C", "#", "!@#$%^", "0987654321", "Calling Twice" } select x1; Assert.Equal(q1.Prepend("hi"), q1.Prepend("hi")); Assert.Equal(q1.Prepend("hi"), (new string[] { "hi" }).Concat(q1)); } [Fact] public void RepeatIteration() { var q = Enumerable.Range(3, 4).Append(12); Assert.Equal(q, q); q = q.Append(14); Assert.Equal(q, q); } [Fact] public void EmptyAppend() { int[] first = { }; Assert.Single(first.Append(42), 42); } [Fact] public void EmptyPrepend() { string[] first = { }; Assert.Single(first.Prepend("aa"), "aa"); } [Fact] public void PrependNoIteratingSourceBeforeFirstItem() { var ie = new List<int>(); var prepended = (from i in ie select i).Prepend(4); ie.Add(42); Assert.Equal(prepended, ie.Prepend(4)); } [Fact] public void ForcedToEnumeratorDoesntEnumeratePrepend() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Prepend(4); // Don't insist on this behaviour, but check it's correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateAppend() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Append(4); // Don't insist on this behaviour, but check it's correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateMultipleAppendsAndPrepends() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Append(4).Append(5).Prepend(-1).Prepend(-2); // Don't insist on this behaviour, but check it's correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void SourceNull() { Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Append(1)); Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Prepend(1)); } [Fact] public void Combined() { var v = "foo".Append('1').Append('2').Prepend('3').Concat("qq".Append('Q').Prepend('W')); Assert.Equal(v.ToArray(), "3foo12WqqQ".ToArray()); var v1 = "a".Append('b').Append('c').Append('d'); Assert.Equal(v1.ToArray(), "abcd".ToArray()); var v2 = "a".Prepend('b').Prepend('c').Prepend('d'); Assert.Equal(v2.ToArray(), "dcba".ToArray()); } [Fact] public void AppendCombinations() { var source = Enumerable.Range(0, 3).Append(3).Append(4); var app0a = source.Append(5); var app0b = source.Append(6); var app1aa = app0a.Append(7); var app1ab = app0a.Append(8); var app1ba = app0b.Append(9); var app1bb = app0b.Append(10); Assert.Equal(new[] { 0, 1, 2, 3, 4, 5 }, app0a); Assert.Equal(new[] { 0, 1, 2, 3, 4, 6 }, app0b); Assert.Equal(new[] { 0, 1, 2, 3, 4, 5, 7 }, app1aa); Assert.Equal(new[] { 0, 1, 2, 3, 4, 5, 8 }, app1ab); Assert.Equal(new[] { 0, 1, 2, 3, 4, 6, 9 }, app1ba); Assert.Equal(new[] { 0, 1, 2, 3, 4, 6, 10 }, app1bb); } [Fact] public void PrependCombinations() { var source = Enumerable.Range(2, 2).Prepend(1).Prepend(0); var pre0a = source.Prepend(5); var pre0b = source.Prepend(6); var pre1aa = pre0a.Prepend(7); var pre1ab = pre0a.Prepend(8); var pre1ba = pre0b.Prepend(9); var pre1bb = pre0b.Prepend(10); Assert.Equal(new[] { 5, 0, 1, 2, 3 }, pre0a); Assert.Equal(new[] { 6, 0, 1, 2, 3 }, pre0b); Assert.Equal(new[] { 7, 5, 0, 1, 2, 3 }, pre1aa); Assert.Equal(new[] { 8, 5, 0, 1, 2, 3 }, pre1ab); Assert.Equal(new[] { 9, 6, 0, 1, 2, 3 }, pre1ba); Assert.Equal(new[] { 10, 6, 0, 1, 2, 3 }, pre1bb); } [Fact] public void Append1ToArrayToList() { var source = Enumerable.Range(0, 2).Append(2); Assert.Equal(Enumerable.Range(0, 3), source.ToList()); Assert.Equal(Enumerable.Range(0, 3), source.ToArray()); source = Enumerable.Range(0, 2).ToList().Append(2); Assert.Equal(Enumerable.Range(0, 3), source.ToList()); Assert.Equal(Enumerable.Range(0, 3), source.ToArray()); source = NumberRangeGuaranteedNotCollectionType(0, 2).Append(2); Assert.Equal(Enumerable.Range(0, 3), source.ToList()); Assert.Equal(Enumerable.Range(0, 3), source.ToArray()); } [Fact] public void Prepend1ToArrayToList() { var source = Enumerable.Range(1, 2).Prepend(0); Assert.Equal(Enumerable.Range(0, 3), source.ToList()); Assert.Equal(Enumerable.Range(0, 3), source.ToArray()); source = Enumerable.Range(1, 2).ToList().Prepend(0); Assert.Equal(Enumerable.Range(0, 3), source.ToList()); Assert.Equal(Enumerable.Range(0, 3), source.ToArray()); source = NumberRangeGuaranteedNotCollectionType(1, 2).Prepend(0); Assert.Equal(Enumerable.Range(0, 3), source.ToList()); Assert.Equal(Enumerable.Range(0, 3), source.ToArray()); } [Fact] public void AppendNToArrayToList() { var source = Enumerable.Range(0, 2).Append(2).Append(3); Assert.Equal(Enumerable.Range(0, 4), source.ToList()); Assert.Equal(Enumerable.Range(0, 4), source.ToArray()); source = Enumerable.Range(0, 2).ToList().Append(2).Append(3); Assert.Equal(Enumerable.Range(0, 4), source.ToList()); Assert.Equal(Enumerable.Range(0, 4), source.ToArray()); source = NumberRangeGuaranteedNotCollectionType(0, 2).Append(2).Append(3); Assert.Equal(Enumerable.Range(0, 4), source.ToList()); Assert.Equal(Enumerable.Range(0, 4), source.ToArray()); } [Fact] public void PrependNToArrayToList() { var source = Enumerable.Range(2, 2).Prepend(1).Prepend(0); Assert.Equal(Enumerable.Range(0, 4), source.ToList()); Assert.Equal(Enumerable.Range(0, 4), source.ToArray()); source = Enumerable.Range(2, 2).ToList().Prepend(1).Prepend(0); Assert.Equal(Enumerable.Range(0, 4), source.ToList()); Assert.Equal(Enumerable.Range(0, 4), source.ToArray()); source = NumberRangeGuaranteedNotCollectionType(2, 2).Prepend(1).Prepend(0); Assert.Equal(Enumerable.Range(0, 4), source.ToList()); Assert.Equal(Enumerable.Range(0, 4), source.ToArray()); } [Fact] public void AppendPrependToArrayToList() { var source = Enumerable.Range(2, 2).Prepend(1).Append(4).Prepend(0).Append(5); Assert.Equal(Enumerable.Range(0, 6), source.ToList()); Assert.Equal(Enumerable.Range(0, 6), source.ToArray()); source = Enumerable.Range(2, 2).ToList().Prepend(1).Append(4).Prepend(0).Append(5); Assert.Equal(Enumerable.Range(0, 6), source.ToList()); Assert.Equal(Enumerable.Range(0, 6), source.ToArray()); source = NumberRangeGuaranteedNotCollectionType(2, 2).Append(4).Prepend(1).Append(5).Prepend(0); Assert.Equal(Enumerable.Range(0, 6), source.ToList()); Assert.Equal(Enumerable.Range(0, 6), source.ToArray()); source = NumberRangeGuaranteedNotCollectionType(2, 2).Prepend(1).Prepend(0).Append(4).Append(5); Assert.Equal(Enumerable.Range(0, 6), source.ToList()); Assert.Equal(Enumerable.Range(0, 6), source.ToArray()); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Globalization; using System.ComponentModel; using System.Collections.Generic; using Medivh.Json.Linq; using Medivh.Json.Utilities; using Medivh.Json.Serialization; #if NET20 using Medivh.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Medivh.Json.Schema { /// <summary> /// <para> /// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>. /// </para> /// <note type="caution"> /// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details. /// </note> /// </summary> [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] public class JsonSchemaGenerator { /// <summary> /// Gets or sets how undefined schemas are handled by the serializer. /// </summary> public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; } private IContractResolver _contractResolver; /// <summary> /// Gets or sets the contract resolver. /// </summary> /// <value>The contract resolver.</value> public IContractResolver ContractResolver { get { if (_contractResolver == null) { return DefaultContractResolver.Instance; } return _contractResolver; } set { _contractResolver = value; } } private class TypeSchema { public Type Type { get; private set; } public JsonSchema Schema { get; private set; } public TypeSchema(Type type, JsonSchema schema) { ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(schema, nameof(schema)); Type = type; Schema = schema; } } private JsonSchemaResolver _resolver; private readonly IList<TypeSchema> _stack = new List<TypeSchema>(); private JsonSchema _currentSchema; private JsonSchema CurrentSchema { get { return _currentSchema; } } private void Push(TypeSchema typeSchema) { _currentSchema = typeSchema.Schema; _stack.Add(typeSchema); _resolver.LoadedSchemas.Add(typeSchema.Schema); } private TypeSchema Pop() { TypeSchema popped = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); TypeSchema newValue = _stack.LastOrDefault(); if (newValue != null) { _currentSchema = newValue.Schema; } else { _currentSchema = null; } return popped; } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type) { return Generate(type, new JsonSchemaResolver(), false); } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type, JsonSchemaResolver resolver) { return Generate(type, resolver, false); } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type, bool rootSchemaNullable) { return Generate(type, new JsonSchemaResolver(), rootSchemaNullable); } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param> /// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable) { ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(resolver, nameof(resolver)); _resolver = resolver; return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false); } private string GetTitle(Type type) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title)) { return containerAttribute.Title; } return null; } private string GetDescription(Type type) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description)) { return containerAttribute.Description; } #if !(DOTNET || PORTABLE40 || PORTABLE) DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type); if (descriptionAttribute != null) { return descriptionAttribute.Description; } #endif return null; } private string GetTypeId(Type type, bool explicitOnly) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id)) { return containerAttribute.Id; } if (explicitOnly) { return null; } switch (UndefinedSchemaIdHandling) { case UndefinedSchemaIdHandling.UseTypeName: return type.FullName; case UndefinedSchemaIdHandling.UseAssemblyQualifiedName: return type.AssemblyQualifiedName; default: return null; } } private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { ValidationUtils.ArgumentNotNull(type, nameof(type)); string resolvedId = GetTypeId(type, false); string explicitId = GetTypeId(type, true); if (!string.IsNullOrEmpty(resolvedId)) { JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId); if (resolvedSchema != null) { // resolved schema is not null but referencing member allows nulls // change resolved schema to allow nulls. hacky but what are ya gonna do? if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null)) { resolvedSchema.Type |= JsonSchemaType.Null; } if (required && resolvedSchema.Required != true) { resolvedSchema.Required = true; } return resolvedSchema; } } // test for unresolved circular reference if (_stack.Any(tc => tc.Type == type)) { throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); } JsonContract contract = ContractResolver.ResolveContract(type); JsonConverter converter; if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null) { JsonSchema converterSchema = converter.GetSchema(); if (converterSchema != null) { return converterSchema; } } Push(new TypeSchema(type, new JsonSchema())); if (explicitId != null) { CurrentSchema.Id = explicitId; } if (required) { CurrentSchema.Required = true; } CurrentSchema.Title = GetTitle(type); CurrentSchema.Description = GetDescription(type); if (converter != null) { // todo: Add GetSchema to JsonConverter and use here? CurrentSchema.Type = JsonSchemaType.Any; } else { switch (contract.ContractType) { case JsonContractType.Object: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateObjectSchema(type, (JsonObjectContract)contract); break; case JsonContractType.Array: CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired); CurrentSchema.Id = GetTypeId(type, false); JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetCachedAttribute<JsonArrayAttribute>(type); bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems); Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { CurrentSchema.Items = new List<JsonSchema>(); CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false)); } break; case JsonContractType.Primitive: CurrentSchema.Type = GetJsonSchemaType(type, valueRequired); if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof(FlagsAttribute), true)) { CurrentSchema.Enum = new List<JToken>(); IList<EnumValue<long>> enumValues = EnumUtils.GetNamesAndValues<long>(type); foreach (EnumValue<long> enumValue in enumValues) { JToken value = JToken.FromObject(enumValue.Value); CurrentSchema.Enum.Add(value); } } break; case JsonContractType.String: JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType)) ? JsonSchemaType.String : AddNullType(JsonSchemaType.String, valueRequired); CurrentSchema.Type = schemaType; break; case JsonContractType.Dictionary: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); Type keyType; Type valueType; ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType); if (keyType != null) { JsonContract keyContract = ContractResolver.ResolveContract(keyType); // can be converted to a string if (keyContract.ContractType == JsonContractType.Primitive) { CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false); } } break; #if !(DOTNET || PORTABLE || PORTABLE40) case JsonContractType.Serializable: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateISerializableContract(type, (JsonISerializableContract)contract); break; #endif #if !(NET35 || NET20 || PORTABLE40) case JsonContractType.Dynamic: #endif case JsonContractType.Linq: CurrentSchema.Type = JsonSchemaType.Any; break; default: throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } } return Pop().Schema; } private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired) { if (valueRequired != Required.Always) { return type | JsonSchemaType.Null; } return type; } private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag) { return ((value & flag) == flag); } private void GenerateObjectSchema(Type type, JsonObjectContract contract) { CurrentSchema.Properties = new Dictionary<string, JsonSchema>(); foreach (JsonProperty property in contract.Properties) { if (!property.Ignored) { bool optional = property.NullValueHandling == NullValueHandling.Ignore || HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) || property.ShouldSerialize != null || property.GetIsSpecified != null; JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional); if (property.DefaultValue != null) { propertySchema.Default = JToken.FromObject(property.DefaultValue); } CurrentSchema.Properties.Add(property.PropertyName, propertySchema); } } if (type.IsSealed()) { CurrentSchema.AllowAdditionalProperties = false; } } #if !(DOTNET || PORTABLE || PORTABLE40) private void GenerateISerializableContract(Type type, JsonISerializableContract contract) { CurrentSchema.AllowAdditionalProperties = true; } #endif internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag) { // default value is Any if (value == null) { return true; } bool match = ((value & flag) == flag); if (match) { return true; } // integer is a subset of float if (flag == JsonSchemaType.Integer && (value & JsonSchemaType.Float) == JsonSchemaType.Float) { return true; } return false; } private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired) { JsonSchemaType schemaType = JsonSchemaType.None; if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type)) { schemaType = JsonSchemaType.Null; if (ReflectionUtils.IsNullableType(type)) { type = Nullable.GetUnderlyingType(type); } } PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type); switch (typeCode) { case PrimitiveTypeCode.Empty: case PrimitiveTypeCode.Object: return schemaType | JsonSchemaType.String; #if !(DOTNET || PORTABLE) case PrimitiveTypeCode.DBNull: return schemaType | JsonSchemaType.Null; #endif case PrimitiveTypeCode.Boolean: return schemaType | JsonSchemaType.Boolean; case PrimitiveTypeCode.Char: return schemaType | JsonSchemaType.String; case PrimitiveTypeCode.SByte: case PrimitiveTypeCode.Byte: case PrimitiveTypeCode.Int16: case PrimitiveTypeCode.UInt16: case PrimitiveTypeCode.Int32: case PrimitiveTypeCode.UInt32: case PrimitiveTypeCode.Int64: case PrimitiveTypeCode.UInt64: #if !(PORTABLE || NET35 || NET20) case PrimitiveTypeCode.BigInteger: #endif return schemaType | JsonSchemaType.Integer; case PrimitiveTypeCode.Single: case PrimitiveTypeCode.Double: case PrimitiveTypeCode.Decimal: return schemaType | JsonSchemaType.Float; // convert to string? case PrimitiveTypeCode.DateTime: #if !NET20 case PrimitiveTypeCode.DateTimeOffset: #endif return schemaType | JsonSchemaType.String; case PrimitiveTypeCode.String: case PrimitiveTypeCode.Uri: case PrimitiveTypeCode.Guid: case PrimitiveTypeCode.TimeSpan: case PrimitiveTypeCode.Bytes: return schemaType | JsonSchemaType.String; default: throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type)); } } } }
// 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.IO.PortsTests; using System.Threading; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class ReceivedBytesThreshold_Property : PortsTest { //Maximum random value to use for ReceivedBytesThreshold private const int MAX_RND_THRESHOLD = 16; //Minimum random value to use for ReceivedBytesThreshold private const int MIN_RND_THRESHOLD = 2; //Maximum time to wait for all of the expected events to be firered private const int MAX_TIME_WAIT = 2000; #region Test Cases [ConditionalFact(nameof(HasNullModem))] public void ReceivedBytesThreshold_Default() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); SerialPortProperties serPortProp = new SerialPortProperties(); com1.Open(); com2.Open(); com1.DataReceived += rcvEventHandler.HandleEvent; serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); Debug.WriteLine("Verifying default ReceivedBytesThreshold"); com2.Write(new byte[1], 0, 1); rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT); com1.DiscardInBuffer(); serPortProp.VerifyPropertiesAndPrint(com1); rcvEventHandler.Validate(SerialData.Chars, 1, 0); } } [ConditionalFact(nameof(HasNullModem))] public void ReceivedBytesThreshold_Rnd_ExactWrite() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); SerialPortProperties serPortProp = new SerialPortProperties(); Random rndGen = new Random(-55); int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); com1.ReceivedBytesThreshold = receivedBytesThreshold; com1.Open(); com2.Open(); com1.DataReceived += rcvEventHandler.HandleEvent; serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); Debug.WriteLine("Verifying writing exactly the number of bytes of ReceivedBytesThreshold"); com2.Write(new byte[com1.ReceivedBytesThreshold], 0, com1.ReceivedBytesThreshold); rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT); com1.DiscardInBuffer(); serPortProp.VerifyPropertiesAndPrint(com1); rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); } } [ConditionalFact(nameof(HasNullModem))] public void ReceivedBytesThreshold_Rnd_MultipleWrite() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); SerialPortProperties serPortProp = new SerialPortProperties(); Random rndGen = new Random(-55); int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); com1.ReceivedBytesThreshold = receivedBytesThreshold; com1.Open(); com2.Open(); com1.DataReceived += rcvEventHandler.HandleEvent; serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); Debug.WriteLine("Verifying writing the number of bytes of ReceivedBytesThreshold after several write calls"); com2.Write(new byte[(int)Math.Floor(com1.ReceivedBytesThreshold / 2.0)], 0, (int)Math.Floor(com1.ReceivedBytesThreshold / 2.0)); com2.Write(new byte[(int)Math.Ceiling(com1.ReceivedBytesThreshold / 2.0)], 0, (int)Math.Ceiling(com1.ReceivedBytesThreshold / 2.0)); rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT); com1.DiscardInBuffer(); serPortProp.VerifyPropertiesAndPrint(com1); rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); } } [ConditionalFact(nameof(HasNullModem))] public void ReceivedBytesThreshold_Above_Exact() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); SerialPortProperties serPortProp = new SerialPortProperties(); Random rndGen = new Random(-55); int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); com1.ReceivedBytesThreshold = receivedBytesThreshold + 1; com1.Open(); com2.Open(); com1.DataReceived += rcvEventHandler.HandleEvent; serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); Debug.WriteLine("Verifying writing less then number of bytes of ReceivedBytesThreshold then setting " + "ReceivedBytesThreshold to the number of bytes written"); com2.Write(new byte[receivedBytesThreshold], 0, receivedBytesThreshold); TCSupport.WaitForReadBufferToLoad(com1, receivedBytesThreshold); if (0 != rcvEventHandler.NumEventsHandled) { Fail("ERROR!!! Unexpected ReceivedEvent was fired NumEventsHandled={0}", rcvEventHandler.NumEventsHandled); } else { com1.ReceivedBytesThreshold = receivedBytesThreshold; rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT); } com1.DiscardInBuffer(); serPortProp.VerifyPropertiesAndPrint(com1); rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); } } [ConditionalFact(nameof(HasNullModem))] public void ReceivedBytesThreshold_Above_Below() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); SerialPortProperties serPortProp = new SerialPortProperties(); Random rndGen = new Random(-55); int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); com1.ReceivedBytesThreshold = receivedBytesThreshold + 1; com1.Open(); com2.Open(); com1.DataReceived += rcvEventHandler.HandleEvent; serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold - 1); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); Debug.WriteLine("Verifying writing less then number of bytes of ReceivedBytesThreshold then setting " + "ReceivedBytesThreshold to less then the number of bytes written"); com2.Write(new byte[receivedBytesThreshold], 0, receivedBytesThreshold); TCSupport.WaitForReadBufferToLoad(com1, receivedBytesThreshold); if (0 != rcvEventHandler.NumEventsHandled) { Fail("ERROR!!! Unexpected ReceivedEvent was firered NumEventsHandled={0}", rcvEventHandler.NumEventsHandled); } else { com1.ReceivedBytesThreshold = receivedBytesThreshold - 1; rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT); } com1.DiscardInBuffer(); serPortProp.VerifyPropertiesAndPrint(com1); rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); } } [ConditionalFact(nameof(HasNullModem))] public void ReceivedBytesThreshold_Above_1() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); SerialPortProperties serPortProp = new SerialPortProperties(); Random rndGen = new Random(-55); int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); com1.ReceivedBytesThreshold = receivedBytesThreshold + 1; com1.Open(); com2.Open(); com1.DataReceived += rcvEventHandler.HandleEvent; serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("ReceivedBytesThreshold", 1); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); Debug.WriteLine("Verifying writing less then number of bytes of ReceivedBytesThreshold then " + "setting ReceivedBytesThreshold to 1"); com2.Write(new byte[receivedBytesThreshold], 0, receivedBytesThreshold); TCSupport.WaitForReadBufferToLoad(com1, receivedBytesThreshold); if (0 != rcvEventHandler.NumEventsHandled) { Fail("ERROR!!! Unexpected ReceivedEvent was firered NumEventsHandled={0}", rcvEventHandler.NumEventsHandled); } else { com1.ReceivedBytesThreshold = 1; rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT); } com1.DiscardInBuffer(); serPortProp.VerifyPropertiesAndPrint(com1); rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); } } [ConditionalFact(nameof(HasNullModem))] public void ReceivedBytesThreshold_Int32MinValue() { Debug.WriteLine("Verifying Int32.MinValue ReceivedBytesThreshold"); VerifyException(int.MinValue, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasNullModem))] public void ReceivedBytesThreshold_Neg1() { Debug.WriteLine("Verifying -1 ReceivedBytesThreshold"); VerifyException(-1, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasNullModem))] public void ReceivedBytesThreshold_0() { Debug.WriteLine("Verifying 0 ReceivedBytesThreshold"); VerifyException(0, typeof(ArgumentOutOfRangeException)); } #endregion #region Verification for Test Cases private void VerifyException(int receivedBytesThreshold, Type expectedException) { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { VerifyExceptionAtOpen(com, receivedBytesThreshold, expectedException); if (com.IsOpen) com.Close(); VerifyExceptionAfterOpen(com, receivedBytesThreshold, expectedException); } } private void VerifyExceptionAtOpen(SerialPort com, int receivedBytesThreshold, Type expectedException) { int origReceivedBytesThreshold = com.ReceivedBytesThreshold; SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); try { com.ReceivedBytesThreshold = receivedBytesThreshold; if (null != expectedException) { Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); } } catch (Exception e) { if (null == expectedException) { Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } serPortProp.VerifyPropertiesAndPrint(com); com.ReceivedBytesThreshold = origReceivedBytesThreshold; } private void VerifyExceptionAfterOpen(SerialPort com, int receivedBytesThreshold, Type expectedException) { SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); try { com.ReceivedBytesThreshold = receivedBytesThreshold; if (null != expectedException) { Fail("ERROR!!! Expected setting the ReceivedBytesThreshold after Open() to throw {0} and nothing was thrown", expectedException); } } catch (Exception e) { if (null == expectedException) { Fail("ERROR!!! Expected setting the ReceivedBytesThreshold after Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { Fail("ERROR!!! Expected setting the ReceivedBytesThreshold after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } serPortProp.VerifyPropertiesAndPrint(com); } private class ReceivedEventHandler { private readonly List<SerialData> _eventType = new List<SerialData>(); private readonly List<SerialPort> Source = new List<SerialPort>(); private readonly List<int> _bytesToRead = new List<int>(); public int NumEventsHandled; private readonly SerialPort _com; public ReceivedEventHandler(SerialPort com) { _com = com; NumEventsHandled = 0; } public void HandleEvent(object source, SerialDataReceivedEventArgs e) { lock (this) { try { _bytesToRead.Add(_com.BytesToRead); _eventType.Add(e.EventType); Source.Add((SerialPort)source); NumEventsHandled++; } catch (Exception exp) { Debug.WriteLine(exp); Debug.WriteLine(exp.StackTrace); } Monitor.Pulse(this); } } public void Validate(SerialData eventType, int bytesToRead, int eventIndex) { lock (this) { if (eventIndex >= NumEventsHandled) { Fail("ERROR!!! Expected EvenIndex={0} is greater then the number of events handled {1}", eventIndex, NumEventsHandled); } Assert.Equal(eventType, _eventType[eventIndex]); if (bytesToRead > _bytesToRead[eventIndex]) { Fail("ERROR!!! Expected BytesToRead={0} actual={1}", bytesToRead, _bytesToRead[eventIndex]); } if (_com != Source[eventIndex]) { Fail("ERROR!!! Expected {0} source actual={1}", _com.BaseStream, Source[eventIndex]); } } } public void WaitForEvent(SerialData eventType, int timeout) { WaitForEvent(eventType, 1, timeout); } public void WaitForEvent(SerialData eventType, int numEvents, int timeout) { lock (this) { if (EventExists(eventType, numEvents)) { return; } Stopwatch sw = new Stopwatch(); sw.Start(); do { Monitor.Wait(this, (int)(timeout - sw.ElapsedMilliseconds)); if (EventExists(eventType, numEvents)) { return; } } while (sw.ElapsedMilliseconds < timeout); sw.Stop(); } Fail("Event wait timeout ({0})", eventType); } public bool EventExists(SerialData eventType, int numEvents) { int numOccurrences = 0; for (int i = 0; i < NumEventsHandled; i++) { if (eventType == _eventType[i]) { numOccurrences++; } } return numOccurrences >= numEvents; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Xunit; namespace Test { public class SingleSingleOrDefaultTests { public static IEnumerable<object[]> SingleSpecificData(int[] counts) { Func<int, IEnumerable<int>> positions = x => new[] { 0, x / 2, Math.Max(0, x - 1) }.Distinct(); foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), positions)) yield return results; foreach (object[] results in Sources.Ranges(counts.Cast<int>(), positions)) yield return results; } public static IEnumerable<object[]> SingleData(int[] elements, int[] counts) { foreach (int element in elements) { foreach (object[] results in UnorderedSources.Ranges(element, counts.Cast<int>())) { yield return new object[] { results[0], results[1], element }; } foreach (object[] results in Sources.Ranges(element, counts.Cast<int>())) { yield return new object[] { results[0], results[1], element }; } } } // // Single and SingleOrDefault // [Theory] [MemberData("SingleData", new int[] { 0, 2, 16, 1024 * 1024 }, new int[] { 1 })] public static void Single(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; Assert.Equal(element, query.Single()); Assert.Equal(element, query.Single(x => true)); } [Theory] [MemberData("SingleData", new int[] { 0, 2, 16, 1024 * 1024 }, new int[] { 0, 1 })] public static void SingleOrDefault(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; Assert.Equal(count >= 1 ? element : default(int), query.SingleOrDefault()); Assert.Equal(count >= 1 ? element : default(int), query.SingleOrDefault(x => true)); } [Theory] [MemberData("SingleData", new int[] { 0, 1024 * 1024 }, new int[] { 0 })] public static void Single_Empty(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; Assert.Throws<InvalidOperationException>(() => query.Single()); Assert.Throws<InvalidOperationException>(() => query.Single(x => true)); } [Theory] [MemberData("SingleData", new int[] { 0 }, new int[] { 0, 1, 2, 16 })] public static void Single_NoMatch(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.Throws<InvalidOperationException>(() => query.Single(x => !seen.Add(x))); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("SingleData", new int[] { 0 }, new int[] { 1024 * 4, 1024 * 1024 })] public static void Single_NoMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element) { Single_NoMatch(labeled, count, element); } [Theory] [MemberData("SingleData", new int[] { 0 }, new int[] { 0, 1, 2, 16 })] public static void SingleOrDefault_NoMatch(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.Equal(default(int), query.SingleOrDefault(x => !seen.Add(x))); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("SingleData", new int[] { 0 }, new int[] { 1024 * 4, 1024 * 1024 })] public static void SingleOrDefault_NoMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element) { SingleOrDefault_NoMatch(labeled, count, element); } [Theory] [MemberData("SingleData", new int[] { 0 }, new int[] { 2, 16 })] public static void Single_AllMatch(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; Assert.Throws<InvalidOperationException>(() => query.Single(x => true)); } [Theory] [OuterLoop] [MemberData("SingleData", new int[] { 0 }, new int[] { 1024 * 4, 1024 * 1024 })] public static void Single_AllMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element) { Single_AllMatch(labeled, count, element); } [Theory] [MemberData("SingleData", new int[] { 0 }, new int[] { 2, 16 })] public static void SingleOrDefault_AllMatch(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; Assert.Throws<InvalidOperationException>(() => query.SingleOrDefault(x => true)); } [Theory] [OuterLoop] [MemberData("SingleData", new int[] { 0 }, new int[] { 1024 * 4, 1024 * 1024 })] public static void SingleOrDefault_AllMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element) { SingleOrDefault_AllMatch(labeled, count, element); } [Theory] [MemberData("SingleSpecificData", (object)(new int[] { 1, 2, 16 }))] public static void Single_OneMatch(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.Equal(element, query.Single(x => seen.Add(x) && x == element)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("SingleSpecificData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))] public static void Single_OneMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element) { Single_OneMatch(labeled, count, element); } [Theory] [MemberData("SingleSpecificData", (object)(new int[] { 0, 1, 2, 16 }))] public static void SingleOrDefault_OneMatch(Labeled<ParallelQuery<int>> labeled, int count, int element) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.Equal(element, query.SingleOrDefault(x => seen.Add(x) && x == element)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("SingleSpecificData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))] public static void SingleOrDefault_OneMatch_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int element) { SingleOrDefault_OneMatch(labeled, count, element); } [Theory] [MemberData("Ranges", (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))] public static void Single_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Single()); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Single(x => true)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).SingleOrDefault()); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).SingleOrDefault(x => true)); } [Theory] [MemberData("Ranges", (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))] public static void Single_AggregateException(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Single(x => { throw new DeliberateTestException(); })); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.SingleOrDefault(x => { throw new DeliberateTestException(); })); } [Fact] public static void Single_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Single()); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).SingleOrDefault()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().Single(null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().SingleOrDefault(null)); } } }
// AttributeMetadata.cs // using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Xml; namespace Xrm.Sdk.Metadata { public static partial class MetadataSerialiser { public static AttributeMetadata DeSerialiseAttributeMetadata(AttributeMetadata item, XmlNode attribute) { // Get the attributemetadata foreach (XmlNode node in attribute.ChildNodes) { Dictionary<string, object> itemValues = (Dictionary<string, object>)(object)item; string localName = XmlHelper.GetLocalName(node); string fieldName = localName.Substr(0, 1).ToLowerCase() + localName.Substr(1); // Check nil and don't set the value to save time/space if (node.Attributes.Count == 1 && node.Attributes[0].Name == "i:nil") { continue; } // Non Type Specific properties switch (localName) { // String values case "AttributeOf": case "DeprecatedVersion": case "EntityLogicalName": case "LogicalName": case "SchemaName": case "CalculationOf": itemValues[fieldName] = XmlHelper.GetNodeTextValue(node); break; // Bool values case "CanBeSecuredForCreate": case "CanBeSecuredForRead": case "CanBeSecuredForUpdate": case "CanModifyAdditionalSettings": case "IsAuditEnabled": case "IsCustomAttribute": case "IsCustomizable": case "IsManaged": case "IsPrimaryId": case "IsPrimaryName": case "IsRenameable": case "IsSecured": case "IsValidForAdvancedFind": case "IsValidForCreate": case "IsValidForRead": case "IsValidForUpdate": case "DefaultValue": itemValues[fieldName] = Attribute.DeSerialise(node, AttributeTypes.Boolean_); break; // Int Values case "ColumnNumber": case "Precision": case "DefaultFormValue": case "MaxLength": case "PrecisionSource": itemValues[fieldName] = Attribute.DeSerialise(node, AttributeTypes.Int_); break; // Label case "Description": case "DisplayName": Label label = new Label(); itemValues[fieldName] = MetadataSerialiser.DeSerialiseLabel(label,node); break; //OptionSet case "OptionSet": OptionSetMetadata options= new OptionSetMetadata(); itemValues[fieldName] = MetadataSerialiser.DeSerialiseOptionSetMetadata(options, node); break; case "AttributeType": item.AttributeType = (AttributeTypeCode)(object)XmlHelper.GetNodeTextValue(node); break; //Guid // LinkedAttributeId //AttributeRequiredLevel //RequiredLevel //DateTime //MaxSupportedValue (DateTimeAttributeMetadata) //MinSupportedValue (DateTimeAttributeMetadata) //decimal //MaxValue (DecimalAttributeMetadata) //IntegerFormat //Format //string[] //Targets } // Type sepcific attributes //Boolean //DefaultValue (OptionSetMetadata) //int // MaxValue (IntegerAttributeMetadata) // MinValue (IntegerAttributeMetadata) // StringFormat //Format (MemoAttributeMetadata,StringAttributeMetadata) //double //MaxValue (DoubleAttributeMetadata, MoneyAttributeMetadata) //MinValue (DoubleAttributeMetadata, MoneyAttributeMetadata) //DateTimeFormat //Format (DateTimeAttributeMetadata) //long //MaxValue (BigIntAttributeMetadata) //MinValue (BigIntAttributeMetadata) } return item; } } [Imported] [IgnoreNamespace] [ScriptName("Object")] public class AttributeMetadata { // Summary: // Gets the name of that attribute that this attribute extends. // // Returns: // Type: Returns_String The attribute name. public string AttributeOf; // // Summary: // Gets the type for the attribute. // // Returns: // Type: Returns_Nullable<Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode> The // attribute type. public AttributeTypeCode AttributeType; // Summary: // Gets whether field security can be applied to prevent a user from adding // data to this attribute. // // Returns: // Type: Returns_Nullable<Returns_Boolean>true if the field security can be // applied; otherwise, false. public bool? CanBeSecuredForCreate; // // Summary: // Gets whether field level security can be applied to prevent a user from viewing // data from this attribute. // // Returns: // Type: Returns_Nullable<Returns_Boolean>true if the field security can be // applied; otherwise, false. public bool? CanBeSecuredForRead; // // Summary: // Gets whether field level security can be applied to prevent a user from updating // data for this attribute. // // Returns: // Type: Returns_Nullable<Returns_Boolean>true if the field security can be // applied; otherwise, false. public bool? CanBeSecuredForUpdate; // // Summary: // Gets or sets the property that determines whether any settings not controlled // by managed properties can be changed. // // Returns: // Type: Microsoft.Xrm.Sdk.BooleanManagedPropertyThe property that determines // whether any settings not controlled by managed properties can be changed. public bool? CanModifyAdditionalSettings; // // Summary: // Gets an organization specific id for the attribute used for auditing. // // Returns: // Type: Returns_Nullable<Returns_Int32> The organization specific id for the // attribute used for auditing. public int? ColumnNumber; // // Summary: // Gets the pn_microsoftcrm version that the attribute was deprecated in. // // Returns: // Type: Returns_String The pn_microsoftcrm version that the attribute was deprecated // in. public string DeprecatedVersion; // // Summary: // Gets or sets the description of the attribute. // // Returns: // Type: Microsoft.Xrm.Sdk.LabelThe description of the attribute. public Label Description; // // Summary: // Gets or sets the display name for the attribute. // // Returns: // Type: Microsoft.Xrm.Sdk.LabelThe display name of the attribute. public Label DisplayName; // // Summary: // Gets the logical name of the entity that contains the attribute. // // Returns: // Type: Returns_String The logical name of the entity that contains the attribute. public string EntityLogicalName; // // Summary: // Gets or sets the property that determines whether the attribute is enabled // for auditing. // // Returns: // Type: Microsoft.Xrm.Sdk.BooleanManagedProperty The property that determines // whether the attribute is enabled for auditing. public bool? IsAuditEnabled; // // Summary: // Gets whether the attribute is a custom attribute. // // Returns: // Type: Returns_Nullable<Returns_Boolean>true if the attribute is a custom // attribute; otherwise, false. public bool? IsCustomAttribute; // // Summary: // Gets or sets the property that determines whether the attribute allows customization. // // Returns: // Type: Microsoft.Xrm.Sdk.BooleanManagedPropertyThe property that determines // whether the attribute allows customization. public bool? IsCustomizable; // // Summary: // Gets whether the attribute is part of a managed solution. // // Returns: // Type: Returns_Nullable<Returns_Boolean>true if the attribute is part of a // managed solution; otherwise, false. public bool? IsManaged; // // Summary: // Gets whether the attribute represents the unique identifier for the record. // // Returns: // Type: Returns_Nullable<Returns_Boolean>true if the attribute is the unique // identifier for the record; otherwise, false. public bool? IsPrimaryId; // // Summary: // Gets or sets whether the attribute represents the primary attribute for the // entity. // // Returns: // Type: Returns_Nullable<Returns_Boolean>true if the attribute is primary attribute // for the entity; otherwise, false. public bool? IsPrimaryName; // // Summary: // Gets or sets the property that determines whether the attribute display name // can be changed. // // Returns: // Type: Microsoft.Xrm.Sdk.BooleanManagedPropertyThe property that determines // whether the attribute display name can be changed. public bool? IsRenameable; // // Summary: // Gets or sets whether the attribute is secured for field level security. // // Returns: // Type: Returns_Nullable<Returns_Boolean>true if the attribute is secured for // field level security; otherwise, false. public bool? IsSecured; // // Summary: // Gets or sets the property that determines whether the attribute appears in // Advanced Find. // // Returns: // Type: Microsoft.Xrm.Sdk.BooleanManagedPropertyThe property that determines // whether the attribute appears in Advanced Find. public bool? IsValidForAdvancedFind; // // Summary: // Gets whether the value can be set when a record is created. // // Returns: // Type: Returns_Nullable<Returns_Boolean>true if the value can be set when // a record is created; otherwise, false. public bool? IsValidForCreate; // // Summary: // Gets whether the value can be retrieved. // // Returns: // Type: Returns_Nullable<Returns_Boolean>true if the value can be retrieved; // otherwise, false. public bool? IsValidForRead; // // Summary: // Gets whether the value can be updated. // // Returns: // Type: Returns_Nullable<Returns_Boolean>true if the value can be updated; // otherwise, false. public bool? IsValidForUpdate; // // Summary: // Gets or sets an attribute that is linked between Appointments and Recurring // appointments. // // Returns: // Type: Returns_Nullable<Returns_Guid> The attribute id that is linked between // Appointments and Recurring appointments. public Guid LinkedAttributeId; // // Summary: // Gets or sets the logical name for the attribute. // // Returns: // Type: Returns_String The logical name for the attribute. public string LogicalName; // // Summary: // Gets or sets the property that determines the data entry requirement level // enforced for the attribute. // // Returns: // Type: Microsoft.Xrm.Sdk.Metadata.AttributeRequiredLevelManagedPropertyThe // property that determines the data entry requirement level enforced for the // attribute. public AttributeRequiredLevel RequiredLevel; // // Summary: // Gets or sets the schema name for the attribute. // // Returns: // Type: Returns_String The schema name for the attribute. public string SchemaName; } }
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 Lexfy.Web.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Net.Sockets { public partial class SocketAsyncEventArgs : EventArgs, IDisposable { private IntPtr _acceptedFileDescriptor; private int _socketAddressSize; private SocketFlags _receivedFlags; private Action<int, byte[], int, SocketFlags, SocketError> _transferCompletionCallback; internal int? SendPacketsDescriptorCount { get { return null; } } private void InitializeInternals() { // No-op for *nix. } private void FreeInternals(bool calledFromFinalizer) { // No-op for *nix. } private void SetupSingleBuffer() { // No-op for *nix. } private void SetupMultipleBuffers() { // No-op for *nix. } private void SetupSendPacketsElements() { // No-op for *nix. } private void InnerComplete() { // No-op for *nix. } private void InnerStartOperationAccept(bool userSuppliedBuffer) { _acceptedFileDescriptor = (IntPtr)(-1); } private void AcceptCompletionCallback(IntPtr acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError) { _acceptedFileDescriptor = acceptedFileDescriptor; Debug.Assert(socketAddress == null || socketAddress == _acceptBuffer, $"Unexpected socketAddress: {socketAddress}"); _acceptAddressBufferCount = socketAddressSize; CompletionCallback(0, socketError); } internal unsafe SocketError DoOperationAccept(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, out int bytesTransferred) { if (_buffer != null) { throw new PlatformNotSupportedException(SR.net_sockets_accept_receive_notsupported); } Debug.Assert(acceptHandle == null, $"Unexpected acceptHandle: {acceptHandle}"); bytesTransferred = 0; return handle.AsyncContext.AcceptAsync(_acceptBuffer, _acceptAddressBufferCount / 2, AcceptCompletionCallback); } private void InnerStartOperationConnect() { // No-op for *nix. } private void ConnectCompletionCallback(SocketError socketError) { CompletionCallback(0, socketError); } internal unsafe SocketError DoOperationConnect(Socket socket, SafeCloseSocket handle, out int bytesTransferred) { bytesTransferred = 0; return handle.AsyncContext.ConnectAsync(_socketAddress.Buffer, _socketAddress.Size, ConnectCompletionCallback); } internal SocketError DoOperationDisconnect(Socket socket, SafeCloseSocket handle) { throw new PlatformNotSupportedException(SR.net_sockets_disconnect_notsupported); } private void InnerStartOperationDisconnect() { throw new PlatformNotSupportedException(SR.net_sockets_disconnect_notsupported); } private Action<int, byte[], int, SocketFlags, SocketError> TransferCompletionCallback => _transferCompletionCallback ?? (_transferCompletionCallback = TransferCompletionCallbackCore); private void TransferCompletionCallbackCore(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError) { Debug.Assert(socketAddress == null || socketAddress == _socketAddress.Buffer, $"Unexpected socketAddress: {socketAddress}"); _socketAddressSize = socketAddressSize; _receivedFlags = receivedFlags; CompletionCallback(bytesTransferred, socketError); } private void InnerStartOperationReceive() { _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; } internal unsafe SocketError DoOperationReceive(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred) { SocketError errorCode; if (_buffer != null) { errorCode = handle.AsyncContext.ReceiveAsync(_buffer, _offset, _count, _socketFlags, TransferCompletionCallback); } else { errorCode = handle.AsyncContext.ReceiveAsync(_bufferList, _socketFlags, TransferCompletionCallback); } flags = _socketFlags; bytesTransferred = 0; return errorCode; } private void InnerStartOperationReceiveFrom() { _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; } internal unsafe SocketError DoOperationReceiveFrom(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred) { SocketError errorCode; if (_buffer != null) { errorCode = handle.AsyncContext.ReceiveFromAsync(_buffer, _offset, _count, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback); } else { errorCode = handle.AsyncContext.ReceiveFromAsync(_bufferList, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback); } flags = _socketFlags; bytesTransferred = 0; return errorCode; } private void InnerStartOperationReceiveMessageFrom() { _receiveMessageFromPacketInfo = default(IPPacketInformation); _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; } private void ReceiveMessageFromCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode) { Debug.Assert(_socketAddress != null, "Expected non-null _socketAddress"); Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress, $"Unexpected socketAddress: {socketAddress}"); _socketAddressSize = socketAddressSize; _receivedFlags = receivedFlags; _receiveMessageFromPacketInfo = ipPacketInformation; CompletionCallback(bytesTransferred, errorCode); } internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeCloseSocket handle, out int bytesTransferred) { bool isIPv4, isIPv6; Socket.GetIPProtocolInformation(socket.AddressFamily, _socketAddress, out isIPv4, out isIPv6); bytesTransferred = 0; return handle.AsyncContext.ReceiveMessageFromAsync(_buffer, _offset, _count, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, isIPv4, isIPv6, ReceiveMessageFromCompletionCallback); } private void InnerStartOperationSend() { _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; } internal unsafe SocketError DoOperationSend(SafeCloseSocket handle, out int bytesTransferred) { SocketError errorCode; if (_buffer != null) { errorCode = handle.AsyncContext.SendAsync(_buffer, _offset, _count, _socketFlags, TransferCompletionCallback); } else { errorCode = handle.AsyncContext.SendAsync(_bufferList, _socketFlags, TransferCompletionCallback); } bytesTransferred = 0; return errorCode; } private void InnerStartOperationSendPackets() { throw new PlatformNotSupportedException(); } internal SocketError DoOperationSendPackets(Socket socket, SafeCloseSocket handle) { throw new PlatformNotSupportedException(); } private void InnerStartOperationSendTo() { _receivedFlags = System.Net.Sockets.SocketFlags.None; _socketAddressSize = 0; } internal SocketError DoOperationSendTo(SafeCloseSocket handle, out int bytesTransferred) { SocketError errorCode; if (_buffer != null) { errorCode = handle.AsyncContext.SendToAsync(_buffer, _offset, _count, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback); } else { errorCode = handle.AsyncContext.SendToAsync(_bufferList, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback); } bytesTransferred = 0; return errorCode; } internal void LogBuffer(int size) { if (_buffer != null) { SocketsEventSource.Dump(_buffer, _offset, size); } else if (_acceptBuffer != null) { SocketsEventSource.Dump(_acceptBuffer, 0, size); } } internal void LogSendPacketsBuffers(int size) { throw new PlatformNotSupportedException(); } private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress) { System.Buffer.BlockCopy(_acceptBuffer, 0, remoteSocketAddress.Buffer, 0, _acceptAddressBufferCount); _acceptSocket = _currentSocket.CreateAcceptSocket( SafeCloseSocket.CreateSocket(_acceptedFileDescriptor), _currentSocket._rightEndPoint.Create(remoteSocketAddress)); return SocketError.Success; } private SocketError FinishOperationConnect() { // No-op for *nix. return SocketError.Success; } private unsafe int GetSocketAddressSize() { return _socketAddressSize; } private unsafe void FinishOperationReceiveMessageFrom() { // No-op for *nix. } private void FinishOperationSendPackets() { throw new PlatformNotSupportedException(); } private void CompletionCallback(int bytesTransferred, SocketError socketError) { if (socketError == SocketError.Success) { FinishOperationSuccess(socketError, bytesTransferred, _receivedFlags); } else { if (_currentSocket.CleanedUp) { socketError = SocketError.OperationAborted; } FinishOperationAsyncFailure(socketError, bytesTransferred, _receivedFlags); } } } }
/* * SubSonic - http://subsonicproject.com * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. */ using System; using System.Collections; using System.IO; using System.Net; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web; using SubSonic.Utilities; namespace SubSonic.Sugar { /// <summary> /// Summary for the Web class /// </summary> public static class Web { /// <summary> /// Whether or not the request originated from the local network, or more specifically from localhost or a NAT address. /// This property is only accurate if NAT addresses are a valid indicators of a request being from within the internal network. /// </summary> /// <value> /// <c>true</c> if this instance is local network request; otherwise, <c>false</c>. /// </value> public static bool IsLocalNetworkRequest { get { if(HttpContext.Current != null) { if(HttpContext.Current.Request.IsLocal) return true; string hostPrefix = HttpContext.Current.Request.UserHostAddress; string[] ipClass = hostPrefix.Split(new char[] {'.'}); int classA = Convert.ToInt16(ipClass[0]); int classB = Convert.ToInt16(ipClass[1]); if(classA == 10 || classA == 127) return true; if(classA == 192 && classB == 168) return true; return classA == 172 && (classB > 15 && classB < 33); } return false; } } /// <summary> /// Queries the string. /// </summary> /// <typeparam name="t"></typeparam> /// <param name="param">The param.</param> /// <returns></returns> public static t QueryString<t>(string param) { t result = default(t); if(HttpContext.Current.Request.QueryString[param] != null) { object paramValue = HttpContext.Current.Request[param]; result = (t)Utility.ChangeType(paramValue, typeof(t)); } return result; } /// <summary> /// Cookies the specified param. /// </summary> /// <typeparam name="t"></typeparam> /// <param name="param">The param.</param> /// <returns></returns> public static t Cookie<t>(string param) { t result = default(t); HttpCookie cookie = HttpContext.Current.Request.Cookies[param]; if(cookie != null) { string paramValue = cookie.Value; result = (t)Utility.ChangeType(paramValue, typeof(t)); } return result; } /// <summary> /// Sessions the value. /// </summary> /// <typeparam name="t"></typeparam> /// <param name="param">The param.</param> /// <returns></returns> public static t SessionValue<t>(string param) { t result = default(t); if(HttpContext.Current.Session[param] != null) { object paramValue = HttpContext.Current.Session[param]; result = (t)Utility.ChangeType(paramValue, typeof(t)); } return result; } //many thanks to ASP Alliance for the code below //http://authors.aspalliance.com/olson/methods/ /// <summary> /// Fetches a web page /// </summary> /// <param name="url">The URL.</param> /// <returns></returns> public static string ReadWebPage(string url) { string webPage; WebRequest request = WebRequest.Create(url); using(Stream stream = request.GetResponse().GetResponseStream()) { StreamReader sr = new StreamReader(stream); webPage = sr.ReadToEnd(); sr.Close(); } return webPage; } /// <summary> /// Gets DNS information about a url and puts it in an array of strings /// </summary> /// <param name="url">either an ip address or a host name</param> /// <returns> /// a list with the host name, all the aliases, and all the addresses. /// </returns> public static string[] DNSLookup(string url) { ArrayList al = new ArrayList(); //check whether url is ipaddress or hostname IPHostEntry ipEntry = Dns.GetHostEntry(url); al.Add("HostName," + ipEntry.HostName); foreach(string name in ipEntry.Aliases) al.Add("Aliases," + name); foreach(IPAddress ip in ipEntry.AddressList) al.Add("Address," + ip); string[] ipInfo = (string[])al.ToArray(typeof(string)); return ipInfo; } /// <summary> /// Return the images links in a given URL as an array of strings. /// </summary> /// <param name="url">The URL.</param> /// <param name="returnWithTag">if set to <c>true</c> the string are returned as an XHTML compliant img tag; otherwise returns a list of img URLs only</param> /// <returns>string array of all images on a page</returns> public static string[] ScrapeImages(string url, bool returnWithTag) { //get the content of the url //ReadWebPage is another method in this useful methods collection string htmlPage = ReadWebPage(url); //set up the regex for finding images StringBuilder imgPattern = new StringBuilder(); imgPattern.Append("<img[^>]+"); //start 'img' tag imgPattern.Append("src\\s*=\\s*"); //start src property //three possibilities for what src property -- //(1) enclosed in double quotes //(2) enclosed in single quotes //(3) enclosed in spaces imgPattern.Append("(?:\"(?<src>[^\"]*)\"|'(?<src>[^']*)'|(?<src>[^\"'>\\s]+))"); imgPattern.Append("[^>]*>"); //end of tag Regex imgRegex = new Regex(imgPattern.ToString(), RegexOptions.IgnoreCase); //look for matches Match imgcheck = imgRegex.Match(htmlPage); ArrayList imagelist = new ArrayList(); //add base href for relative urls imagelist.Add("<BASE href=\"" + url + "\">" + url); while(imgcheck.Success) { string src = imgcheck.Groups["src"].Value; string image = returnWithTag ? "<img src=\"" + src + "\" alt=\"\" />" : src; imagelist.Add(image); imgcheck = imgcheck.NextMatch(); } string[] images = new string[imagelist.Count]; imagelist.CopyTo(images); return images; } /// <summary> /// Return the images links in a given URL as an array of XHTML-compliant img tags. /// </summary> /// <param name="url">The URL to extract the images from.</param> /// <returns></returns> public static string[] ScrapeImages(string url) { return ScrapeImages(url, true); } /// <summary> /// Scrapes a web page and parses out all the links. /// </summary> /// <param name="url">The URL.</param> /// <param name="makeLinkable">if set to <c>true</c> [make linkable].</param> /// <returns></returns> public static string[] ScrapeLinks(string url, bool makeLinkable) { //get the content of the url //ReadWebPage is another method in this useful methods collection string htmlPage = ReadWebPage(url); //set up the regex for finding the link urls StringBuilder hrefPattern = new StringBuilder(); hrefPattern.Append("<a[^>]+"); //start 'a' tag and anything that comes before 'href' tag hrefPattern.Append("href\\s*=\\s*"); //start href property //three possibilities for what href property -- //(1) enclosed in double quotes //(2) enclosed in single quotes //(3) enclosed in spaces hrefPattern.Append("(?:\"(?<href>[^\"]*)\"|'(?<href>[^']*)'|(?<href>[^\"'>\\s]+))"); hrefPattern.Append("[^>]*>.*?</a>"); //end of 'a' tag Regex hrefRegex = new Regex(hrefPattern.ToString(), RegexOptions.IgnoreCase); //look for matches Match hrefcheck = hrefRegex.Match(htmlPage); ArrayList linklist = new ArrayList(); //add base href for relative links linklist.Add("<BASE href=\"" + url + "\">" + url); while(hrefcheck.Success) { string href = hrefcheck.Groups["href"].Value; //link url string link = (makeLinkable) ? "<a href=\"" + href + "\" target=\"_blank\">" + href + "</a>" : href; linklist.Add(link); hrefcheck = hrefcheck.NextMatch(); } string[] links = new string[linklist.Count]; linklist.CopyTo(links); return links; } /// <summary> /// Calls the Gravatar service to and returns an HTML <img></img> tag for use on your pages. /// </summary> /// <param name="email">The email of the user</param> /// <param name="size">The size of the Gravatar image - 60 is standard</param> /// <returns>HTML image tag</returns> public static string GetGravatar(string email, int size) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] result = md5.ComputeHash(Encoding.ASCII.GetBytes(email)); StringBuilder hash = new StringBuilder(); for(int i = 0; i < result.Length; i++) hash.Append(result[i].ToString("x2")); StringBuilder image = new StringBuilder(); image.Append("<img src=\""); image.Append("http://www.gravatar.com/avatar.php?"); image.Append("gravatar_id=" + hash); image.Append("&amp;rating=G"); image.Append("&amp;size=" + size); image.Append("&amp;default="); image.Append(HttpContext.Current.Server.UrlEncode("http://example.com/noavatar.gif")); image.Append("\" alt=\"\" />"); return image.ToString(); } /// <summary> /// Given a valid email address, returns a short javascript block that will emit a valid /// mailto: link that can't be picked up by address harvesters. Call this method where you /// would normally place the link in your html code. /// </summary> /// <param name="emailText">The email address to convert to spam-free format</param> /// <returns></returns> public static string CreateSpamFreeEmailLink(string emailText) { if(!String.IsNullOrEmpty(emailText)) { string[] parts = emailText.Split(new char[] {'@'}); if(parts.Length == 2) { StringBuilder sb = new StringBuilder(); sb.Append("<script type='text/javascript'>"); sb.Append("var m = '" + parts[0] + "';"); sb.Append("var a = '" + parts[1] + "';"); sb.Append("var l = '" + emailText + "';"); sb.Append("document.write('<a href=\"mailto:' + m + '@' + a + '\">' + l + '</a>');"); sb.Append("</script>"); return sb.ToString(); } } return String.Empty; } /// <summary> /// A simple utility to output Lorem Ipsum text to your page. /// </summary> /// <param name="count">int count, the number of either paragraphs, words, or characters you would like to display.</param> /// <param name="method">string method, 'p' for paragraphs or 'w' for words or 'c'c for characters</param> /// <returns> /// string with the resulting lorem ipsum text /// </returns> public static string GenerateLoremIpsum(int count, string method) { Random r = new Random(); if(method.ToLower() == "p" && count > 1000) throw new ArgumentOutOfRangeException("count", "Sorry, lorem ipsum control only allows 1000 or less paragraphs."); string loremIpsum = LoadTextFromManifest("loremIpsum.txt"); if(null == loremIpsum) throw new Exception("Could not load loremipsum.txt"); StringBuilder sb = new StringBuilder(); if(String.IsNullOrEmpty(method) || method.ToLower() == "p" || (method.ToLower() != "p" && method.ToLower() != "c" && method.ToLower() != "w")) { char[] split = {'|'}; string[] paras = loremIpsum.Split(split); ArrayList paraList = new ArrayList(); //need a nonfixed array foreach(string s in paras) paraList.Add(s); int parasLength = paras.Length; if(count > parasLength) { int needmore = count - parasLength; for(int x = 0; x < needmore; x++) { int pickme = r.Next(0, parasLength - 1); paraList.Add(paras[pickme]); } } for(int i = 0; i < count; i++) { sb.Append("<p>"); sb.Append(paraList[i]); sb.Append("</p>"); } } if(method.ToLower() == "c") { int loremLength = loremIpsum.Length; if(count > loremLength) { int needmore = (count / loremLength); for(int x = 0; x < needmore; x++) { string newLoremIpsum = loremIpsum; loremIpsum += " "; loremIpsum += newLoremIpsum; } } //note: I don't catch the exception here sb.Append(Utility.ShortenText(loremIpsum, count)); } if(method.ToLower() == "w") { string[] words = loremIpsum.Split(' '); ArrayList wordList = new ArrayList(); //need a nonfixed array foreach(string s in words) wordList.Add(s); int wordLength = words.Length; if(count > wordLength) { int needmore = count - wordLength; for(int x = 0; x < needmore; x++) { int pickme = r.Next(0, wordLength - 1); wordList.Add(words[pickme]); } } for(int i = 0; i < count; i++) { sb.Append(wordList[i]); sb.Append(" "); } } return sb.ToString(); } /// <summary> /// Loads the text from manifest. /// </summary> /// <param name="templateFileName">Name of the template file.</param> /// <returns></returns> private static string LoadTextFromManifest(string templateFileName) { string templateText = null; Assembly asm = Assembly.GetExecutingAssembly(); using(Stream stream = asm.GetManifestResourceStream("SubSonic.Sugar." + templateFileName)) { if(stream != null) { StreamReader sReader = new StreamReader(stream); templateText = sReader.ReadToEnd(); sReader.Close(); } } return templateText; } } }
--- /dev/null 2016-04-23 16:15:35.000000000 -0400 +++ src/mscorlib/src/Microsoft/Win32/Interop.Errors.cs 2016-04-23 16:17:15.624740000 -0400 @@ -0,0 +1,207 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + /// <summary>Common Unix errno error codes.</summary> + internal enum Error + { + // These values were defined in src/Native/System.Native/fxerrno.h + // + // They compare against values obtained via Interop.Sys.GetLastError() not Marshal.GetLastWin32Error() + // which obtains the raw errno that varies between unixes. The strong typing as an enum is meant to + // prevent confusing the two. Casting to or from int is suspect. Use GetLastErrorInfo() if you need to + // correlate these to the underlying platform values or obtain the corresponding error message. + // + + SUCCESS = 0, + + E2BIG = 0x10001, // Argument list too long. + EACCES = 0x10002, // Permission denied. + EADDRINUSE = 0x10003, // Address in use. + EADDRNOTAVAIL = 0x10004, // Address not available. + EAFNOSUPPORT = 0x10005, // Address family not supported. + EAGAIN = 0x10006, // Resource unavailable, try again (same value as EWOULDBLOCK), + EALREADY = 0x10007, // Connection already in progress. + EBADF = 0x10008, // Bad file descriptor. + EBADMSG = 0x10009, // Bad message. + EBUSY = 0x1000A, // Device or resource busy. + ECANCELED = 0x1000B, // Operation canceled. + ECHILD = 0x1000C, // No child processes. + ECONNABORTED = 0x1000D, // Connection aborted. + ECONNREFUSED = 0x1000E, // Connection refused. + ECONNRESET = 0x1000F, // Connection reset. + EDEADLK = 0x10010, // Resource deadlock would occur. + EDESTADDRREQ = 0x10011, // Destination address required. + EDOM = 0x10012, // Mathematics argument out of domain of function. + EDQUOT = 0x10013, // Reserved. + EEXIST = 0x10014, // File exists. + EFAULT = 0x10015, // Bad address. + EFBIG = 0x10016, // File too large. + EHOSTUNREACH = 0x10017, // Host is unreachable. + EIDRM = 0x10018, // Identifier removed. + EILSEQ = 0x10019, // Illegal byte sequence. + EINPROGRESS = 0x1001A, // Operation in progress. + EINTR = 0x1001B, // Interrupted function. + EINVAL = 0x1001C, // Invalid argument. + EIO = 0x1001D, // I/O error. + EISCONN = 0x1001E, // Socket is connected. + EISDIR = 0x1001F, // Is a directory. + ELOOP = 0x10020, // Too many levels of symbolic links. + EMFILE = 0x10021, // File descriptor value too large. + EMLINK = 0x10022, // Too many links. + EMSGSIZE = 0x10023, // Message too large. + EMULTIHOP = 0x10024, // Reserved. + ENAMETOOLONG = 0x10025, // Filename too long. + ENETDOWN = 0x10026, // Network is down. + ENETRESET = 0x10027, // Connection aborted by network. + ENETUNREACH = 0x10028, // Network unreachable. + ENFILE = 0x10029, // Too many files open in system. + ENOBUFS = 0x1002A, // No buffer space available. + ENODEV = 0x1002C, // No such device. + ENOENT = 0x1002D, // No such file or directory. + ENOEXEC = 0x1002E, // Executable file format error. + ENOLCK = 0x1002F, // No locks available. + ENOLINK = 0x10030, // Reserved. + ENOMEM = 0x10031, // Not enough space. + ENOMSG = 0x10032, // No message of the desired type. + ENOPROTOOPT = 0x10033, // Protocol not available. + ENOSPC = 0x10034, // No space left on device. + ENOSYS = 0x10037, // Function not supported. + ENOTCONN = 0x10038, // The socket is not connected. + ENOTDIR = 0x10039, // Not a directory or a symbolic link to a directory. + ENOTEMPTY = 0x1003A, // Directory not empty. + ENOTSOCK = 0x1003C, // Not a socket. + ENOTSUP = 0x1003D, // Not supported (same value as EOPNOTSUP). + ENOTTY = 0x1003E, // Inappropriate I/O control operation. + ENXIO = 0x1003F, // No such device or address. + EOVERFLOW = 0x10040, // Value too large to be stored in data type. + EPERM = 0x10042, // Operation not permitted. + EPIPE = 0x10043, // Broken pipe. + EPROTO = 0x10044, // Protocol error. + EPROTONOSUPPORT = 0x10045, // Protocol not supported. + EPROTOTYPE = 0x10046, // Protocol wrong type for socket. + ERANGE = 0x10047, // Result too large. + EROFS = 0x10048, // Read-only file system. + ESPIPE = 0x10049, // Invalid seek. + ESRCH = 0x1004A, // No such process. + ESTALE = 0x1004B, // Reserved. + ETIMEDOUT = 0x1004D, // Connection timed out. + ETXTBSY = 0x1004E, // Text file busy. + EXDEV = 0x1004F, // Cross-device link. + ESOCKTNOSUPPORT = 0x1005E, // Socket type not supported. + EPFNOSUPPORT = 0x10060, // Protocol family not supported. + ESHUTDOWN = 0x1006C, // Socket shutdown. + EHOSTDOWN = 0x10070, // Host is down. + ENODATA = 0x10071, // No data available. + + // POSIX permits these to have the same value and we make them always equal so + // that CoreFX cannot introduce a dependency on distinguishing between them that + // would not work on all platforms. + EOPNOTSUPP = ENOTSUP, // Operation not supported on socket. + EWOULDBLOCK = EAGAIN, // Operation would block. + } + + + // Represents a platform-agnostic Error and underlying platform-specific errno + internal struct ErrorInfo + { + private Error _error; + private int _rawErrno; + + internal ErrorInfo(int errno) + { + _error = Interop.Sys.ConvertErrorPlatformToPal(errno); + _rawErrno = errno; + } + + internal ErrorInfo(Error error) + { + _error = error; + _rawErrno = -1; + } + + internal Error Error + { + get { return _error; } + } + + internal int RawErrno + { + get { return _rawErrno == -1 ? (_rawErrno = Interop.Sys.ConvertErrorPalToPlatform(_error)) : _rawErrno; } + } + + internal string GetErrorMessage() + { + return Interop.Sys.StrError(RawErrno); + } + + public override string ToString() + { + return string.Format( + "RawErrno: {0} Error: {1} GetErrorMessage: {2}", // No localization required; text is member names used for debugging purposes + RawErrno, Error, GetErrorMessage()); + } + } + + internal partial class Sys + { + internal static Error GetLastError() + { + return ConvertErrorPlatformToPal(Marshal.GetLastWin32Error()); + } + + internal static ErrorInfo GetLastErrorInfo() + { + return new ErrorInfo(Marshal.GetLastWin32Error()); + } + + internal static unsafe string StrError(int platformErrno) + { + int maxBufferLength = 1024; // should be long enough for most any UNIX error + byte* buffer = stackalloc byte[maxBufferLength]; + byte* message = StrErrorR(platformErrno, buffer, maxBufferLength); + + if (message == null) + { + // This means the buffer was not large enough, but still contains + // as much of the error message as possible and is guaranteed to + // be null-terminated. We're not currently resizing/retrying because + // maxBufferLength is large enough in practice, but we could do + // so here in the future if necessary. + message = buffer; + } + + return Marshal.PtrToStringAnsi((IntPtr)message); + } + + [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPlatformToPal")] + internal static extern Error ConvertErrorPlatformToPal(int platformErrno); + + [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPalToPlatform")] + internal static extern int ConvertErrorPalToPlatform(Error error); + + [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_StrErrorR")] + private static unsafe extern byte* StrErrorR(int platformErrno, byte* buffer, int bufferSize); + } +} + +// NOTE: extension method can't be nested inside Interop class. +internal static class InteropErrorExtensions +{ + // Intended usage is e.g. Interop.Error.EFAIL.Info() for brevity + // vs. new Interop.ErrorInfo(Interop.Error.EFAIL) for synthesizing + // errors. Errors originated from the system should be obtained + // via GetLastErrorInfo(), not GetLastError().Info() as that will + // convert twice, which is not only inefficient but also lossy if + // we ever encounter a raw errno that no equivalent in the Error + // enum. + public static Interop.ErrorInfo Info(this Interop.Error error) + { + return new Interop.ErrorInfo(error); + } +}
//------------------------------------------------------------------------------ // <copyright file="TextRenderer.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System.Internal; using System; using System.Drawing; using System.Windows.Forms.Internal; using System.Diagnostics; /// <include file='doc\TextRenderer.uex' path='docs/doc[@for="TextRenderer"]/*' /> /// <devdoc> /// <para> /// This class provides API for drawing GDI text. /// </para> /// </devdoc> public sealed class TextRenderer { //cannot instantiate private TextRenderer() { } /// <include file='doc\TextRenderer.uex' path='docs/doc[@for="TextRenderer.DrawText"]/*' /> public static void DrawText(IDeviceContext dc, string text, Font font, Point pt, Color foreColor) { if (dc == null) { throw new ArgumentNullException("dc"); } WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); IntPtr hdc = dc.GetHdc(); try { using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc )) { using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { wg.DrawText(text, wf, pt, foreColor); } } } finally { dc.ReleaseHdc(); } } /// <include file='doc\TextRenderer.uex' path='docs/doc[@for="TextRenderer.DrawText1"]/*' /> public static void DrawText(IDeviceContext dc, string text, Font font, Point pt, Color foreColor, Color backColor) { if (dc == null) { throw new ArgumentNullException("dc"); } WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); IntPtr hdc = dc.GetHdc(); try { using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc )) { using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { wg.DrawText(text, wf, pt, foreColor, backColor); } } } finally { dc.ReleaseHdc(); } } /// <include file='doc\TextRenderer.uex' path='docs/doc[@for="TextRenderer.DrawText2"]/*' /> public static void DrawText(IDeviceContext dc, string text, Font font, Point pt, Color foreColor, TextFormatFlags flags) { if (dc == null) { throw new ArgumentNullException("dc"); } WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, flags )) { using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { wgr.WindowsGraphics.DrawText(text, wf, pt, foreColor, GetIntTextFormatFlags(flags)); } } } /// <include file='doc\TextRenderer.uex' path='docs/doc[@for="TextRenderer.DrawText3"]/*' /> public static void DrawText(IDeviceContext dc, string text, Font font, Point pt, Color foreColor, Color backColor, TextFormatFlags flags) { if (dc == null) { throw new ArgumentNullException("dc"); } WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, flags )) { using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { wgr.WindowsGraphics.DrawText(text, wf, pt, foreColor, backColor, GetIntTextFormatFlags(flags)); } } } /// <include file='doc\TextRenderer.uex' path='docs/doc[@for="TextRenderer.DrawText4"]/*' /> public static void DrawText(IDeviceContext dc, string text, Font font, Rectangle bounds, Color foreColor) { if (dc == null) { throw new ArgumentNullException("dc"); } WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); IntPtr hdc = dc.GetHdc(); try { using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc )) { using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { wg.DrawText(text, wf, bounds, foreColor); } } } finally { dc.ReleaseHdc(); } } /// <include file='doc\TextRenderer.uex' path='docs/doc[@for="TextRenderer.DrawText5"]/*' /> public static void DrawText(IDeviceContext dc, string text, Font font, Rectangle bounds, Color foreColor, Color backColor) { if (dc == null) { throw new ArgumentNullException("dc"); } WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); IntPtr hdc = dc.GetHdc(); try { using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc )) { using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { wg.DrawText(text, wf, bounds, foreColor, backColor); } } } finally { dc.ReleaseHdc(); } } /// <include file='doc\TextRenderer.uex' path='docs/doc[@for="TextRenderer.DrawText6"]/*' /> public static void DrawText(IDeviceContext dc, string text, Font font, Rectangle bounds, Color foreColor, TextFormatFlags flags) { if (dc == null) { throw new ArgumentNullException("dc"); } WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, flags )) { using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont( font, fontQuality )) { wgr.WindowsGraphics.DrawText( text, wf, bounds, foreColor, GetIntTextFormatFlags( flags ) ); } } } /// <include file='doc\TextRenderer.uex' path='docs/doc[@for="TextRenderer.DrawText7"]/*' /> public static void DrawText(IDeviceContext dc, string text, Font font, Rectangle bounds, Color foreColor, Color backColor, TextFormatFlags flags) { if (dc == null) { throw new ArgumentNullException("dc"); } WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, flags )) { using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont( font, fontQuality )) { wgr.WindowsGraphics.DrawText(text, wf, bounds, foreColor, backColor, GetIntTextFormatFlags(flags)); } } } private static IntTextFormatFlags GetIntTextFormatFlags(TextFormatFlags flags) { if( ((uint)flags & WindowsGraphics.GdiUnsupportedFlagMask) == 0 ) { return (IntTextFormatFlags) flags; } // Clear TextRenderer custom flags. IntTextFormatFlags windowsGraphicsSupportedFlags = (IntTextFormatFlags) ( ((uint)flags) & ~WindowsGraphics.GdiUnsupportedFlagMask ); return windowsGraphicsSupportedFlags; } /// MeasureText wrappers. public static Size MeasureText(string text, Font font ) { if (string.IsNullOrEmpty(text)) { return Size.Empty; } using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font)) { return WindowsGraphicsCacheManager.MeasurementGraphics.MeasureText(text, wf); } } public static Size MeasureText(string text, Font font, Size proposedSize ) { if (string.IsNullOrEmpty(text)) { return Size.Empty; } using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font)) { return WindowsGraphicsCacheManager.MeasurementGraphics.MeasureText(text, WindowsGraphicsCacheManager.GetWindowsFont(font), proposedSize); } } public static Size MeasureText(string text, Font font, Size proposedSize, TextFormatFlags flags ) { if (string.IsNullOrEmpty(text)) { return Size.Empty; } using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font)) { return WindowsGraphicsCacheManager.MeasurementGraphics.MeasureText(text, wf, proposedSize, GetIntTextFormatFlags(flags)); } } public static Size MeasureText(IDeviceContext dc, string text, Font font) { if (dc == null) { throw new ArgumentNullException("dc"); } if (string.IsNullOrEmpty(text)) { return Size.Empty; } WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); IntPtr hdc = dc.GetHdc(); try { using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc )) { using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { return wg.MeasureText(text, wf); } } } finally { dc.ReleaseHdc(); } } public static Size MeasureText(IDeviceContext dc, string text, Font font, Size proposedSize ) { if (dc == null) { throw new ArgumentNullException("dc"); } if (string.IsNullOrEmpty(text)) { return Size.Empty; } WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); IntPtr hdc = dc.GetHdc(); try { using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc )) { using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { return wg.MeasureText(text, wf, proposedSize); } } } finally { dc.ReleaseHdc(); } } public static Size MeasureText(IDeviceContext dc, string text, Font font, Size proposedSize, TextFormatFlags flags ) { if (dc == null) { throw new ArgumentNullException("dc"); } if (string.IsNullOrEmpty(text)) { return Size.Empty; } WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, flags)) { using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { return wgr.WindowsGraphics.MeasureText(text, wf, proposedSize, GetIntTextFormatFlags(flags)); } } } internal static Color DisabledTextColor(Color backColor) { //Theme specs -- if the backcolor is darker than Control, we use // ControlPaint.Dark(backcolor). Otherwise we use ControlDark. // see VS#357226 Color disabledTextForeColor = SystemColors.ControlDark; if (ControlPaint.IsDarker(backColor, SystemColors.Control)) { disabledTextForeColor = ControlPaint.Dark(backColor); } return disabledTextForeColor; } } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Xml.Linq; using WixSharp.Bootstrapper; using WixSharp.CommonTasks; using Xunit; using Xunit.Abstractions; using Xunit.Sdk; namespace WixSharp.Test { public class IssueFixesTest : WixLocator { /// <summary> /// Fixes the issue 803. /// </summary> [Fact] [Description("Issue #803")] public void Fix_Issue_803() { // ensure all types that expose their properties for serialization with [XML] have these properties public // "SqlDb" and "root" are serializable but not assignable by user var classesWithFaultsFields = typeof(Project).Assembly.GetTypes() .SelectMany(t => t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(p => p.Name != "SqlDb") .Where(p => p.GetCustomAttribute<WixSharp.XmlAttribute>() != null) .Select(x => $"{x.DeclaringType.Name}.{x.Name}")) .Concat( typeof(Project).Assembly.GetTypes() .Where(t => t != typeof(Error)) .SelectMany(t => t.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(p => p.Name != "root") .Where(p => p.GetCustomAttribute<WixSharp.XmlAttribute>() != null) .Select(x => $"{x.DeclaringType.Name}.{x.Name}"))) .ToArray(); Assert.Empty(classesWithFaultsFields); } [Fact] [Description("Issue #67")] public void Fix_Issue_67() { var project = new Project("MyProduct", new Dir("%ProgramFiles%")); project.LicenceFile = "license.rtf"; var file = project.BuildWxs(); } [Fact] [Description("Issue #995")] public void Fix_Issue_995() { Compiler.AutoGeneration.IgnoreWildCardEmptyDirectories = true; try { var project = new Project("myproduct", new Dir("%Desktop%"), new Dir("%ProgramFiles%")); project.BuildWxs(); } finally { Compiler.AutoGeneration.IgnoreWildCardEmptyDirectories = false; } } [Fact] [Description("Issue #656: ExeFileShortcut changing folder name ")] public void Fix_Issue_656() { // 'MySystem' should not be converted to 'MySystemFolder` var raw_path = @"[INSTALLDIR]\MySystem\MyProduct.exe"; var normalized_path = raw_path.NormalizeWixString(); Assert.Equal(raw_path, normalized_path); } [Fact] public void ListConsts() { var list = Compiler.GetMappedWixConstants(true); } [Fact] [Description("Issue #60")] public void Fix_Issue_60() { var project = new Project("MyProduct", new Dir("%ProgramFiles%", new File("abc.txt", new FilePermission("Guest", GenericPermission.All)))); project.AddAction(new WixQuietExecAction("cmd.exe", "/c \"echo abc\"")); var batchFile = project.BuildMsiCmd(); string cmd = System.IO.File.ReadAllLines(batchFile).First(); int firstPos = cmd.IndexOf("WixUtilExtension.dll"); int lastPos = cmd.LastIndexOf("WixUtilExtension.dll"); Assert.Equal(firstPos, lastPos); } [Fact] [Description("Issue #37")] public void Should_Preserve_ConstantsInAttrDefs() { var project = new Project("My Product", new Dir(@"%ProgramFiles%\MyCompany", new Dir("MyWebApp", new File(@"MyWebApp\Default.aspx", new IISVirtualDir { Name = "MyWebApp", AppName = "Test", WebSite = new WebSite("[IIS_SITE_NAME]", "[IIS_SITE_ADDRESS]:[IIS_SITE_PORT]"), WebAppPool = new WebAppPool("MyWebApp", "Identity=applicationPoolIdentity") })))); string wxs = project.BuildWxs(); var address = XDocument.Load(wxs) .FindSingle("WebAddress"); Assert.Equal("[IIS_SITE_ADDRESS]", address.ReadAttribute("IP")); Assert.Equal("[IIS_SITE_PORT]", address.ReadAttribute("Port")); } [Fact] [Description("Discussions #642332")] public void Should_Process_DirAttributes() { Dir dir1, dir2; var project = new Project("My Product", dir1 = new Dir(@"%ProgramFiles%\MyCompany", dir2 = new Dir("MyWebApp", new File("Default.aspx")))); dir1.AttributesDefinition = "DiskId=1"; dir2.AttributesDefinition = "DiskId=2"; string wxs = project.BuildWxs(); var dirs = XDocument.Load(wxs) .FindAll("Directory") .Where(x => x.HasAttribute("DiskId")) .ToArray(); Assert.Equal(2, dirs.Count()); Assert.True(dirs[0].HasAttribute("Name", "MyCompany")); Assert.True(dirs[0].HasAttribute("DiskId", "1")); Assert.True(dirs[1].HasAttribute("Name", "MyWebApp")); Assert.True(dirs[1].HasAttribute("DiskId", "2")); } [Fact] [Description("Discussions #642332")] public void Should_Process_DirAttributes_2() { var project = new Project("My Product", new Dir(@"%ProgramFiles%\MyCompany", new Dir("MyWebApp", new File("Default.aspx")))); project.Add(new EnvironmentVariable("someVar", "Some value") { AttributesDefinition = "DiskId=2" }); string wxs = project.BuildWxs(); var doc = XDocument.Load(wxs); } [Fact] [Description("Discussions #642263")] public void Should_CanInject_UserProfileNoiseAutomatically() { var project = new Project("TestProject", new Dir(@"%ProgramFiles%\My Company\My Product", new File(@"Files\notepad.exe")), new Dir(@"%CommonAppDataFolder%\Test Project", new File(@"Files\TextFile.txt")), new Dir(@"%PersonalFolder%\Test Project", new File(@"Files\Baskets.bbd"))); string wxs = project.BuildWxs(); var doc = XDocument.Load(wxs); } [Fact] [Description("Discussions #642263")] public void Should_CanInject_UserProfileNoise() { var project = new Project("TestProject", new Dir(@"%ProgramFiles%\My Company\My Product", new File(@"Files\notepad.exe")), new Dir(@"%CommonAppDataFolder%\Test Project", new File(@"Files\TextFile.txt")), new Dir(@"%PersonalFolder%\Test Project", new File(@"Files\Baskets.bbd"))); project.WixSourceGenerated += xml => { var dir = xml.FindAll("Directory") .Where(x => x.HasAttribute("Name", "PersonalFolder")) //.Where(x => x.HasAttribute("Name", v => v == "PersonalFolder")) .SelectMany(x => x.FindAll("Component")) .ForEach(comp => comp.InsertUserProfileRegValue() .InsertUserProfileRemoveFolder()); }; string wxs = project.BuildWxs(); var doc = XDocument.Load(wxs); } [Fact] [Description("Discussions #642263")] public void Should_Inject_RemoveFolder() { var project = new Project("TestProject", new Dir(@"%ProgramFiles%\My Company\My Product", new File(@"Files\notepad.exe")), new Dir(@"%CommonAppDataFolder%\Test Project", new File(@"Files\TextFile.txt")), new Dir(@"%PersonalFolder%\Test Project", new File(@"Files\Baskets.bbd"))); project.WixSourceGenerated += Project_WixSourceGenerated; string wxs = project.BuildWxs(); var doc = XDocument.Load(wxs); } void Project_WixSourceGenerated(XDocument document) { var dir = document.FindAll("Directory") .Where(x => x.HasAttribute("Name", "Test Project") && x.Parent.HasAttribute("Name", "PersonalFolder")) .First(); dir.FindFirst("Component") .AddElement("RemoveFolder", "On=uninstall; Id=" + dir.Attribute("Id").Value) .AddElement("RegistryValue", @"Root=HKCU; Key=Software\[Manufacturer]\[ProductName]; Type=string; Value=; KeyPath=yes"); } [Fact] [Description("Post 576142#post1428674")] public void Should_Handle_NonstandardProductVersions() { var project = new Project("MyProduct", new Dir(@"%ProgramFiles%\My Company\My Product", new File(this.GetType().Assembly.Location) ) ); project.GUID = new Guid("6f330b47-2577-43ad-9095-1861ba25889b"); project.Version = new Version("2014.1.26.0"); Compiler.BuildMsi(project); } [Fact] [Description("Issue #39")] public void Should_Handle_EmptyFeatures() { var binaries = new Feature("MyApp Binaries"); var docs = new Feature("MyApp Documentation"); var docs_01 = new Feature("Documentation 01"); var docs_02 = new Feature("Documentation 02"); var docs_03 = new Feature("Documentation 03"); docs.Children.Add(docs_01); docs.Children.Add(docs_02); docs.Children.Add(docs_03); binaries.Children.Add(docs); var project = new Project("MyProduct", new Dir(@"%ProgramFiles%\My Company\My Product", new File(binaries, @"Files\Bin\MyApp.exe"), new Dir(docs, @"Docs\Manual", new File(docs_01, @"Files\Docs\Manual_01.txt"), new File(docs_02, @"Files\Docs\Manual_02.txt"), new File(docs_03, @"Files\Docs\Manual_03.txt") ) ) ); project.GUID = new Guid("6f330b47-2577-43ad-9095-1861ba25889b"); var wsxfile = project.BuildWxs(); var doc = XDocument.Load(wsxfile); var product = doc.FindSingle("Product"); var rootFeature = doc.Select("Wix/Product/Feature"); Assert.NotNull(rootFeature); var docsFeature = rootFeature.Elements() .FirstOrDefault(e => e.HasLocalName("Feature") && e.HasAttribute("Title", value => value == "MyApp Documentation")); Assert.NotNull(docsFeature); var doc1Feature = docsFeature.Elements() .FirstOrDefault(e => e.HasLocalName("Feature") && e.HasAttribute("Title", value => value == "Documentation 01")); Assert.NotNull(doc1Feature); var doc2Feature = docsFeature.Elements() .FirstOrDefault(e => e.HasLocalName("Feature") && e.HasAttribute("Title", value => value == "Documentation 02")); Assert.NotNull(doc2Feature); var doc3Feature = docsFeature.Elements() .FirstOrDefault(e => e.HasLocalName("Feature") && e.HasAttribute("Title", value => value == "Documentation 03")); Assert.NotNull(doc3Feature); } [Fact] [Description("Issue #49")] public void Should_Fix_Issue_49() { { var project = new Project("MyProduct"); var rootDir = new Dir(@"%ProgramFiles%", new Dir(@"AAA\BBB", new File(this.GetType().Assembly.Location))); project.Dirs = new[] { rootDir }; project.UI = WUI.WixUI_InstallDir; var msi = project.BuildMsi(); } { var project = new Project("MyProduct"); var rootDir = new Dir(@"C:\", new Dir(@"Program Files (x86)\AAA\BBB", new File(this.GetType().Assembly.Location))); project.Dirs = new[] { rootDir }; project.UI = WUI.WixUI_InstallDir; var msi = project.BuildMsi(); //var msi = project.BuildWxs(); } { var project = new Project("MyProduct"); var rootDir = new Dir(@"C:\Program Files (x86)", new Dir(@"AAA\BBB", new File(this.GetType().Assembly.Location))); project.Dirs = new[] { rootDir }; project.BuildMsi(); } } } }
// 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.ObjectModel; using System.Diagnostics.Contracts; using System.IdentityModel.Policy; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Net.Security; using System.Runtime; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.ServiceModel.Description; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Threading; using System.Threading.Tasks; #if FEATURE_NETNATIVE using System.IdentityModel.Claims; using System.Runtime.InteropServices.WindowsRuntime; using System.ServiceModel.Diagnostics; using Windows.Networking; using Windows.Networking.Sockets; using Windows.Security.Cryptography.Certificates; #endif namespace System.ServiceModel.Channels { internal class SslStreamSecurityUpgradeProvider : StreamSecurityUpgradeProvider, IStreamUpgradeChannelBindingProvider { private SecurityTokenAuthenticator _clientCertificateAuthenticator; private SecurityTokenManager _clientSecurityTokenManager; private SecurityTokenProvider _serverTokenProvider; private EndpointIdentity _identity; private IdentityVerifier _identityVerifier; private X509Certificate2 _serverCertificate; private bool _requireClientCertificate; private string _scheme; private SslProtocols _sslProtocols; private bool _enableChannelBinding; private SslStreamSecurityUpgradeProvider(IDefaultCommunicationTimeouts timeouts, SecurityTokenManager clientSecurityTokenManager, bool requireClientCertificate, string scheme, IdentityVerifier identityVerifier, SslProtocols sslProtocols) : base(timeouts) { _identityVerifier = identityVerifier; _scheme = scheme; _clientSecurityTokenManager = clientSecurityTokenManager; _requireClientCertificate = requireClientCertificate; _sslProtocols = sslProtocols; } private SslStreamSecurityUpgradeProvider(IDefaultCommunicationTimeouts timeouts, SecurityTokenProvider serverTokenProvider, bool requireClientCertificate, SecurityTokenAuthenticator clientCertificateAuthenticator, string scheme, IdentityVerifier identityVerifier, SslProtocols sslProtocols) : base(timeouts) { _serverTokenProvider = serverTokenProvider; _requireClientCertificate = requireClientCertificate; _clientCertificateAuthenticator = clientCertificateAuthenticator; _identityVerifier = identityVerifier; _scheme = scheme; _sslProtocols = sslProtocols; } public static SslStreamSecurityUpgradeProvider CreateClientProvider( SslStreamSecurityBindingElement bindingElement, BindingContext context) { SecurityCredentialsManager credentialProvider = context.BindingParameters.Find<SecurityCredentialsManager>(); if (credentialProvider == null) { credentialProvider = ClientCredentials.CreateDefaultCredentials(); } SecurityTokenManager tokenManager = credentialProvider.CreateSecurityTokenManager(); return new SslStreamSecurityUpgradeProvider( context.Binding, tokenManager, bindingElement.RequireClientCertificate, context.Binding.Scheme, bindingElement.IdentityVerifier, bindingElement.SslProtocols); } public override EndpointIdentity Identity { get { if ((_identity == null) && (_serverCertificate != null)) { // this.identity = SecurityUtils.GetServiceCertificateIdentity(this.serverCertificate); throw ExceptionHelper.PlatformNotSupported("SslStreamSecurityUpgradeProvider.Identity - server certificate"); } return _identity; } } public IdentityVerifier IdentityVerifier { get { return _identityVerifier; } } public bool RequireClientCertificate { get { return _requireClientCertificate; } } public X509Certificate2 ServerCertificate { get { return _serverCertificate; } } public SecurityTokenAuthenticator ClientCertificateAuthenticator { get { if (_clientCertificateAuthenticator == null) { _clientCertificateAuthenticator = new X509SecurityTokenAuthenticator(X509ClientCertificateAuthentication.DefaultCertificateValidator); } return _clientCertificateAuthenticator; } } public SecurityTokenManager ClientSecurityTokenManager { get { return _clientSecurityTokenManager; } } public string Scheme { get { return _scheme; } } public SslProtocols SslProtocols { get { return _sslProtocols; } } public override T GetProperty<T>() { #if FEATURE_CORECLR if (typeof(T) == typeof(IChannelBindingProvider) || typeof(T) == typeof(IStreamUpgradeChannelBindingProvider)) { return (T)(object)this; } #endif //FEATURE_CORECLR return base.GetProperty<T>(); } #if FEATURE_CORECLR ChannelBinding IStreamUpgradeChannelBindingProvider.GetChannelBinding(StreamUpgradeInitiator upgradeInitiator, ChannelBindingKind kind) { if (upgradeInitiator == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("upgradeInitiator"); } SslStreamSecurityUpgradeInitiator sslUpgradeInitiator = upgradeInitiator as SslStreamSecurityUpgradeInitiator; if (sslUpgradeInitiator == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("upgradeInitiator", SR.Format(SR.UnsupportedUpgradeInitiator, upgradeInitiator.GetType())); } if (kind != ChannelBindingKind.Endpoint) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("kind", SR.Format(SR.StreamUpgradeUnsupportedChannelBindingKind, this.GetType(), kind)); } return sslUpgradeInitiator.ChannelBinding; } #endif // FEATURE_CORECLR void IChannelBindingProvider.EnableChannelBindingSupport() { _enableChannelBinding = true; } bool IChannelBindingProvider.IsChannelBindingSupportEnabled { get { return _enableChannelBinding; } } public override StreamUpgradeInitiator CreateUpgradeInitiator(EndpointAddress remoteAddress, Uri via) { ThrowIfDisposedOrNotOpen(); return new SslStreamSecurityUpgradeInitiator(this, remoteAddress, via); } protected override void OnAbort() { if (_clientCertificateAuthenticator != null) { SecurityUtils.AbortTokenAuthenticatorIfRequired(_clientCertificateAuthenticator); } CleanupServerCertificate(); } protected override void OnClose(TimeSpan timeout) { if (_clientCertificateAuthenticator != null) { SecurityUtils.CloseTokenAuthenticatorIfRequired(_clientCertificateAuthenticator, timeout); } CleanupServerCertificate(); } protected internal override Task OnCloseAsync(TimeSpan timeout) { OnClose(timeout); return TaskHelpers.CompletedTask(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return OnCloseAsync(timeout).ToApm(callback, state); } protected override void OnEndClose(IAsyncResult result) { result.ToApmEnd(); } private void SetupServerCertificate(SecurityToken token) { X509SecurityToken x509Token = token as X509SecurityToken; if (x509Token == null) { SecurityUtils.AbortTokenProviderIfRequired(_serverTokenProvider); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format( SR.InvalidTokenProvided, _serverTokenProvider.GetType(), typeof(X509SecurityToken)))); } _serverCertificate = new X509Certificate2(x509Token.Certificate); } private void CleanupServerCertificate() { if (_serverCertificate != null) { _serverCertificate.Dispose(); _serverCertificate = null; } } protected override void OnOpen(TimeSpan timeout) { using (CancellationTokenSource cts = new CancellationTokenSource(timeout)) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); SecurityUtils.OpenTokenAuthenticatorIfRequired(ClientCertificateAuthenticator, timeoutHelper.RemainingTime()); if (_serverTokenProvider != null) { SecurityUtils.OpenTokenProviderIfRequired(_serverTokenProvider, timeoutHelper.RemainingTime()); SecurityToken token = _serverTokenProvider.GetTokenAsync(cts.Token).GetAwaiter().GetResult(); SetupServerCertificate(token); SecurityUtils.CloseTokenProviderIfRequired(_serverTokenProvider, timeoutHelper.RemainingTime()); _serverTokenProvider = null; } } } protected internal override Task OnOpenAsync(TimeSpan timeout) { OnOpen(timeout); return TaskHelpers.CompletedTask(); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return OnOpenAsync(timeout).ToApm(callback, state); } protected override void OnEndOpen(IAsyncResult result) { result.ToApmEnd(); } } internal class SslStreamSecurityUpgradeInitiator : StreamSecurityUpgradeInitiatorBase { private SslStreamSecurityUpgradeProvider _parent; private SecurityMessageProperty _serverSecurity; private SecurityTokenProvider _clientCertificateProvider; private X509SecurityToken _clientToken; private SecurityTokenAuthenticator _serverCertificateAuthenticator; private ChannelBinding _channelBindingToken; #if !FEATURE_NETNATIVE private static LocalCertificateSelectionCallback s_clientCertificateSelectionCallback; #endif // !FEATURE_NETNATIVE public SslStreamSecurityUpgradeInitiator(SslStreamSecurityUpgradeProvider parent, EndpointAddress remoteAddress, Uri via) : base(FramingUpgradeString.SslOrTls, remoteAddress, via) { _parent = parent; InitiatorServiceModelSecurityTokenRequirement serverCertRequirement = new InitiatorServiceModelSecurityTokenRequirement(); serverCertRequirement.TokenType = SecurityTokenTypes.X509Certificate; serverCertRequirement.RequireCryptographicToken = true; serverCertRequirement.KeyUsage = SecurityKeyUsage.Exchange; serverCertRequirement.TargetAddress = remoteAddress; serverCertRequirement.Via = via; serverCertRequirement.TransportScheme = _parent.Scheme; serverCertRequirement.PreferSslCertificateAuthenticator = true; SecurityTokenResolver dummy; _serverCertificateAuthenticator = (parent.ClientSecurityTokenManager.CreateSecurityTokenAuthenticator(serverCertRequirement, out dummy)); if (parent.RequireClientCertificate) { InitiatorServiceModelSecurityTokenRequirement clientCertRequirement = new InitiatorServiceModelSecurityTokenRequirement(); clientCertRequirement.TokenType = SecurityTokenTypes.X509Certificate; clientCertRequirement.RequireCryptographicToken = true; clientCertRequirement.KeyUsage = SecurityKeyUsage.Signature; clientCertRequirement.TargetAddress = remoteAddress; clientCertRequirement.Via = via; clientCertRequirement.TransportScheme = _parent.Scheme; _clientCertificateProvider = parent.ClientSecurityTokenManager.CreateSecurityTokenProvider(clientCertRequirement); if (_clientCertificateProvider == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCredentialsUnableToCreateLocalTokenProvider, clientCertRequirement))); } } } #if !FEATURE_NETNATIVE private static LocalCertificateSelectionCallback ClientCertificateSelectionCallback { get { if (s_clientCertificateSelectionCallback == null) { s_clientCertificateSelectionCallback = new LocalCertificateSelectionCallback(SelectClientCertificate); } return s_clientCertificateSelectionCallback; } } #endif //!FEATURE_NETNATIVE internal ChannelBinding ChannelBinding { get { Fx.Assert(IsChannelBindingSupportEnabled, "A request for the ChannelBinding is not permitted without enabling ChannelBinding first (through the IChannelBindingProvider interface)"); return _channelBindingToken; } } internal bool IsChannelBindingSupportEnabled { get { return ((IChannelBindingProvider)_parent).IsChannelBindingSupportEnabled; } } internal override void Open(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.Open(timeoutHelper.RemainingTime()); if (_clientCertificateProvider != null) { SecurityUtils.OpenTokenProviderIfRequired(_clientCertificateProvider, timeoutHelper.RemainingTime()); using (CancellationTokenSource cts = new CancellationTokenSource(timeoutHelper.RemainingTime())) { _clientToken = (X509SecurityToken)_clientCertificateProvider.GetTokenAsync(cts.Token).GetAwaiter().GetResult(); } } } internal override async Task OpenAsync(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); await base.OpenAsync(timeoutHelper.RemainingTime()); if (_clientCertificateProvider != null) { SecurityUtils.OpenTokenProviderIfRequired(_clientCertificateProvider, timeoutHelper.RemainingTime()); using (CancellationTokenSource cts = new CancellationTokenSource(timeoutHelper.RemainingTime())) { _clientToken = (X509SecurityToken)(await _clientCertificateProvider.GetTokenAsync(cts.Token)); } } } internal override void Close(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.Close(timeoutHelper.RemainingTime()); if (_clientCertificateProvider != null) { SecurityUtils.CloseTokenProviderIfRequired(_clientCertificateProvider, timeoutHelper.RemainingTime()); } } internal override async Task CloseAsync(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); await base.CloseAsync(timeoutHelper.RemainingTime()); if (_clientCertificateProvider != null) { SecurityUtils.CloseTokenProviderIfRequired(_clientCertificateProvider, timeoutHelper.RemainingTime()); } } protected override Stream OnInitiateUpgrade(Stream stream, out SecurityMessageProperty remoteSecurity) { OutWrapper<SecurityMessageProperty> remoteSecurityWrapper = new OutWrapper<SecurityMessageProperty>(); Stream retVal = OnInitiateUpgradeAsync(stream, remoteSecurityWrapper).GetAwaiter().GetResult(); remoteSecurity = remoteSecurityWrapper.Value; return retVal; } #if FEATURE_NETNATIVE protected override async Task<Stream> OnInitiateUpgradeAsync(Stream stream, OutWrapper<SecurityMessageProperty> remoteSecurityWrapper) { if (WcfEventSource.Instance.SslOnInitiateUpgradeIsEnabled()) { WcfEventSource.Instance.SslOnInitiateUpgrade(); } // There is currently no way to convert a .Net X509Certificate2 to a UWP Certificate. The client certificate // needs to be provided by looking it up in the certificate store. E.g. // // factory.Credentials.ClientCertificate.SetCertificate( // StoreLocation.CurrentUser, // StoreName.My, // X509FindType.FindByThumbprint, // clientCertThumb); // // The certificate is retrieved using .Net api's and UWP api's. An artifical X509Extension is used to attach the // UWP certificate to the .Net X509Certificate2. This is then retrieved at the point of usage to use with UWP // networking api's. Certificate clientCertificate = null; if (_clientToken != null) { foreach (var extension in _clientToken.Certificate.Extensions) { var attachmentExtension = extension as X509CertificateInitiatorClientCredential.X509UwpCertificateAttachmentExtension; if (attachmentExtension != null && attachmentExtension.AttachedCertificate != null) { clientCertificate = attachmentExtension.AttachedCertificate; break; } } Contract.Assert(clientCertificate != null, "Missing UWP Certificate as an attachment to X509Certificate2"); } try { // Fetch the underlying raw transport object. For UWP, this will be a StreamSocket var connectionStream = stream as ConnectionStream; Contract.Assert(connectionStream !=null, "stream is either null or not a ConnectionStream"); var rtStreamSocket = connectionStream.Connection.GetCoreTransport() as StreamSocket; Contract.Assert(rtStreamSocket != null, "Core transport is either null or not a StreamSocket"); rtStreamSocket.Control.ClientCertificate = clientCertificate; // On CoreClr, we use SslStream which calls a callback with any problems with the server certificate, which // returns whether to accept the certificate or not. With SocketStream in UWP, any custom validation needs to // happen after the connection has successfully negotiated. Some certificate errors need to be set to be ignored // to allow the connection to be established so we can retrieve the server certificate and choose whether to // accept the server certificate or not. rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired); rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.IncompleteChain); rtStreamSocket.Control.IgnorableServerCertificateErrors.Add( ChainValidationResult.RevocationInformationMissing); rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.RevocationFailure); // SocketStream doesn't take a bitwise field of accepted protocols, but instead accepts a value specifying the highest // protocol that can be negotiated. A check is made for each of the protocols in order to see if they've been requested // by the binding and set the protection level to the UWP equivalent. This will have the effect of protectionLevel being // set to the most secure protocol that was specified by client code. After the connection is established, if a protocol // was negotiated which the binding didn't request, the connection needs to be aborted. This could happen for example if // the requested SslProtocols was SslProtocols.Tls11 | SslProtocols.Tls12 and the server only supported SSL3 | Tls10. In // this case, SocketProtectionLevel would be set to SocketProtectionLevel.Tls12, which would mean Tls10, Tls11 and Tls12 // are all acceptable protocols to negotiate. As the server is offering SSL3 | Tls10, the connection would be successfully // negotiated using Tls10 which isn't allowed according to the binding configuration. SocketProtectionLevel protectionLevel = SocketProtectionLevel.PlainSocket; if ((_parent.SslProtocols & SslProtocols.Tls) != SslProtocols.None) protectionLevel = SocketProtectionLevel.Tls10; if ((_parent.SslProtocols & SslProtocols.Tls11) != SslProtocols.None) protectionLevel = SocketProtectionLevel.Tls11; if ((_parent.SslProtocols & SslProtocols.Tls12) != SslProtocols.None) protectionLevel = SocketProtectionLevel.Tls12; // With SslStream, the hostname provided in the server certificate is provided to the client and verified in the callback. // With UWP StreamSocket, the hostname needs to be provided to the call to UpgradeToSslAsync. The code to fetch the identity // lives in the callback for CoreClr but needs to be pulled into this method for UWP. EndpointAddress remoteAddress = RemoteAddress; if (remoteAddress.Identity == null && remoteAddress.Uri != Via) { remoteAddress = new EndpointAddress(Via); } EndpointIdentity identity; if (!_parent.IdentityVerifier.TryGetIdentity(remoteAddress, out identity)) { SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity: identity, authContext: null, identityVerifier: GetType()); throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning( new MessageSecurityException(SR.Format(SR.IdentityCheckFailedForOutgoingMessage, identity, remoteAddress))); } Contract.Assert(identity.IdentityClaim.ClaimType == ClaimTypes.Dns); string dnsHostName = identity.IdentityClaim.Resource as string; // This is the actual call to negotiate an SSL connection await rtStreamSocket.UpgradeToSslAsync(protectionLevel, new HostName(dnsHostName)).AsTask(); // Verify that we didn't negotiate a protocol lower than the binding configuration specified. No need to check Tls12 // as it will only be negotiated if Tls12 was actually specified. var negotiatedProtectionLevel = rtStreamSocket.Information.ProtectionLevel; if ((negotiatedProtectionLevel == SocketProtectionLevel.Tls11 && (_parent.SslProtocols & SslProtocols.Tls11) == SslProtocols.None) || (negotiatedProtectionLevel == SocketProtectionLevel.Tls10 && (_parent.SslProtocols & SslProtocols.Tls) == SslProtocols.None)) { // Need to dispose StreamSocket as normally SslStream wouldn't end up in a usable state in this situation. As // post-upgrade validation is required in UWP, the connection needs to be Dispose'd to ensure it isn't used. rtStreamSocket.Dispose(); throw new SecurityNegotiationException(SR.Format(SR.SSLProtocolNegotiationFailed, _parent.SslProtocols, negotiatedProtectionLevel)); } X509Certificate2 serverCertificate = null; X509Certificate2[] chainCertificates = null; X509Chain chain = null; try { // Convert the UWP Certificate object to a .Net X509Certificate2. byte[] serverCertificateBlob = rtStreamSocket.Information.ServerCertificate.GetCertificateBlob().ToArray(); serverCertificate = new X509Certificate2(serverCertificateBlob); // The chain building and validation logic is done by SslStream in CoreClr. This section of code is based // on the SslStream implementation to try to maintain behavior parity. chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; var serverIntermediateCertificates = rtStreamSocket.Information.ServerIntermediateCertificates; chainCertificates = new X509Certificate2[serverIntermediateCertificates.Count]; for (int i = 0; i < chainCertificates.Length; i++) { chainCertificates[i] = new X509Certificate2(serverIntermediateCertificates[i].GetCertificateBlob().ToArray()); } chain.ChainPolicy.ExtraStore.AddRange(chainCertificates); chain.Build(serverCertificate); SslPolicyErrors policyErrors = SslPolicyErrors.None; foreach (var serverCertificateError in rtStreamSocket.Information.ServerCertificateErrors) { if (serverCertificateError == ChainValidationResult.InvalidName) { policyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch; continue; } if (serverCertificateError == ChainValidationResult.IncompleteChain) { policyErrors |= SslPolicyErrors.RemoteCertificateChainErrors; } } X509ChainStatus[] chainStatusArray = chain.ChainStatus; if (chainStatusArray != null && chainStatusArray.Length != 0) { policyErrors |= SslPolicyErrors.RemoteCertificateChainErrors; } if (!ValidateRemoteCertificate(this, serverCertificate, chain, policyErrors)) { // Need to dispose StreamSocket as normally SslStream wouldn't end up in a usable state in this situation. As // post-upgrade validation is required in UWP, the connection needs to be Dispose'd to ensure it isn't used. rtStreamSocket.Dispose(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityNegotiationException(SR.ssl_io_cert_validation)); } } finally { serverCertificate?.Dispose(); chain?.Dispose(); if (chainCertificates != null) { foreach (var chainCert in chainCertificates) { chainCert?.Dispose(); } } } } catch (SecurityTokenValidationException tokenValidationException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityNegotiationException(tokenValidationException.Message, tokenValidationException)); } catch (IOException ioException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException( SR.Format(SR.NegotiationFailedIO, ioException.Message), ioException)); } catch (Exception exception) { // In NET Native the WinRT API's can throw the base Exception // class with an HRESULT indicating the issue. However, custom // validation code can also throw Exception, and to be compatible // with the CoreCLR version, we must allow those exceptions to // propagate without wrapping them. We use the simple heuristic // that if an HRESULT has been set to other than the default, // the exception should be wrapped in SecurityNegotiationException. if (exception.HResult == __HResults.COR_E_EXCEPTION) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException( exception.Message, exception)); } remoteSecurityWrapper.Value = _serverSecurity; return stream; } #else // !FEATURE_NETNATIVE protected override async Task<Stream> OnInitiateUpgradeAsync(Stream stream, OutWrapper<SecurityMessageProperty> remoteSecurityWrapper) { if (WcfEventSource.Instance.SslOnInitiateUpgradeIsEnabled()) { WcfEventSource.Instance.SslOnInitiateUpgrade(); } X509CertificateCollection clientCertificates = null; LocalCertificateSelectionCallback selectionCallback = null; if (_clientToken != null) { clientCertificates = new X509CertificateCollection(); clientCertificates.Add(_clientToken.Certificate); selectionCallback = ClientCertificateSelectionCallback; } SslStream sslStream = new SslStream(stream, false, this.ValidateRemoteCertificate, selectionCallback); try { await sslStream.AuthenticateAsClientAsync(string.Empty, clientCertificates, _parent.SslProtocols, false); } catch (SecurityTokenValidationException tokenValidationException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(tokenValidationException.Message, tokenValidationException)); } catch (AuthenticationException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message, exception)); } catch (IOException ioException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException( SR.Format(SR.NegotiationFailedIO, ioException.Message), ioException)); } remoteSecurityWrapper.Value = _serverSecurity; if (this.IsChannelBindingSupportEnabled) { _channelBindingToken = ChannelBindingUtility.GetToken(sslStream); } return sslStream; } #endif //!FEATURE_NETNATIVE private static X509Certificate SelectClientCertificate(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { return localCertificates[0]; } private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // Note: add ref to handle since the caller will reset the cert after the callback return. X509Certificate2 certificate2 = new X509Certificate2(certificate); SecurityToken token = new X509SecurityToken(certificate2, false); ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = _serverCertificateAuthenticator.ValidateToken(token); _serverSecurity = new SecurityMessageProperty(); _serverSecurity.TransportToken = new SecurityTokenSpecification(token, authorizationPolicies); _serverSecurity.ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies); AuthorizationContext authzContext = _serverSecurity.ServiceSecurityContext.AuthorizationContext; _parent.IdentityVerifier.EnsureOutgoingIdentity(RemoteAddress, Via, authzContext); return true; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the RemRelMedicamentoClasificacion class. /// </summary> [Serializable] public partial class RemRelMedicamentoClasificacionCollection : ActiveList<RemRelMedicamentoClasificacion, RemRelMedicamentoClasificacionCollection> { public RemRelMedicamentoClasificacionCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>RemRelMedicamentoClasificacionCollection</returns> public RemRelMedicamentoClasificacionCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { RemRelMedicamentoClasificacion o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Rem_RelMedicamentoClasificacion table. /// </summary> [Serializable] public partial class RemRelMedicamentoClasificacion : ActiveRecord<RemRelMedicamentoClasificacion>, IActiveRecord { #region .ctors and Default Settings public RemRelMedicamentoClasificacion() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public RemRelMedicamentoClasificacion(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public RemRelMedicamentoClasificacion(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public RemRelMedicamentoClasificacion(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Rem_RelMedicamentoClasificacion", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdRelMedicamentoClasificacion = new TableSchema.TableColumn(schema); colvarIdRelMedicamentoClasificacion.ColumnName = "idRelMedicamentoClasificacion"; colvarIdRelMedicamentoClasificacion.DataType = DbType.Int32; colvarIdRelMedicamentoClasificacion.MaxLength = 0; colvarIdRelMedicamentoClasificacion.AutoIncrement = true; colvarIdRelMedicamentoClasificacion.IsNullable = false; colvarIdRelMedicamentoClasificacion.IsPrimaryKey = true; colvarIdRelMedicamentoClasificacion.IsForeignKey = false; colvarIdRelMedicamentoClasificacion.IsReadOnly = false; colvarIdRelMedicamentoClasificacion.DefaultSetting = @""; colvarIdRelMedicamentoClasificacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdRelMedicamentoClasificacion); TableSchema.TableColumn colvarIdMedicamento = new TableSchema.TableColumn(schema); colvarIdMedicamento.ColumnName = "idMedicamento"; colvarIdMedicamento.DataType = DbType.Int32; colvarIdMedicamento.MaxLength = 0; colvarIdMedicamento.AutoIncrement = false; colvarIdMedicamento.IsNullable = false; colvarIdMedicamento.IsPrimaryKey = false; colvarIdMedicamento.IsForeignKey = true; colvarIdMedicamento.IsReadOnly = false; colvarIdMedicamento.DefaultSetting = @"((0))"; colvarIdMedicamento.ForeignKeyTableName = "Sys_Medicamento"; schema.Columns.Add(colvarIdMedicamento); TableSchema.TableColumn colvarIdClasificacion = new TableSchema.TableColumn(schema); colvarIdClasificacion.ColumnName = "idClasificacion"; colvarIdClasificacion.DataType = DbType.Int32; colvarIdClasificacion.MaxLength = 0; colvarIdClasificacion.AutoIncrement = false; colvarIdClasificacion.IsNullable = false; colvarIdClasificacion.IsPrimaryKey = false; colvarIdClasificacion.IsForeignKey = true; colvarIdClasificacion.IsReadOnly = false; colvarIdClasificacion.DefaultSetting = @"((0))"; colvarIdClasificacion.ForeignKeyTableName = "Rem_Clasificacion"; schema.Columns.Add(colvarIdClasificacion); TableSchema.TableColumn colvarDosis = new TableSchema.TableColumn(schema); colvarDosis.ColumnName = "dosis"; colvarDosis.DataType = DbType.Double; colvarDosis.MaxLength = 0; colvarDosis.AutoIncrement = false; colvarDosis.IsNullable = false; colvarDosis.IsPrimaryKey = false; colvarDosis.IsForeignKey = false; colvarDosis.IsReadOnly = false; colvarDosis.DefaultSetting = @"((0))"; colvarDosis.ForeignKeyTableName = ""; schema.Columns.Add(colvarDosis); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Rem_RelMedicamentoClasificacion",schema); } } #endregion #region Props [XmlAttribute("IdRelMedicamentoClasificacion")] [Bindable(true)] public int IdRelMedicamentoClasificacion { get { return GetColumnValue<int>(Columns.IdRelMedicamentoClasificacion); } set { SetColumnValue(Columns.IdRelMedicamentoClasificacion, value); } } [XmlAttribute("IdMedicamento")] [Bindable(true)] public int IdMedicamento { get { return GetColumnValue<int>(Columns.IdMedicamento); } set { SetColumnValue(Columns.IdMedicamento, value); } } [XmlAttribute("IdClasificacion")] [Bindable(true)] public int IdClasificacion { get { return GetColumnValue<int>(Columns.IdClasificacion); } set { SetColumnValue(Columns.IdClasificacion, value); } } [XmlAttribute("Dosis")] [Bindable(true)] public double Dosis { get { return GetColumnValue<double>(Columns.Dosis); } set { SetColumnValue(Columns.Dosis, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a SysMedicamento ActiveRecord object related to this RemRelMedicamentoClasificacion /// /// </summary> public DalSic.SysMedicamento SysMedicamento { get { return DalSic.SysMedicamento.FetchByID(this.IdMedicamento); } set { SetColumnValue("idMedicamento", value.IdMedicamento); } } /// <summary> /// Returns a RemClasificacion ActiveRecord object related to this RemRelMedicamentoClasificacion /// /// </summary> public DalSic.RemClasificacion RemClasificacion { get { return DalSic.RemClasificacion.FetchByID(this.IdClasificacion); } set { SetColumnValue("idClasificacion", value.IdClasificacion); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdMedicamento,int varIdClasificacion,double varDosis) { RemRelMedicamentoClasificacion item = new RemRelMedicamentoClasificacion(); item.IdMedicamento = varIdMedicamento; item.IdClasificacion = varIdClasificacion; item.Dosis = varDosis; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdRelMedicamentoClasificacion,int varIdMedicamento,int varIdClasificacion,double varDosis) { RemRelMedicamentoClasificacion item = new RemRelMedicamentoClasificacion(); item.IdRelMedicamentoClasificacion = varIdRelMedicamentoClasificacion; item.IdMedicamento = varIdMedicamento; item.IdClasificacion = varIdClasificacion; item.Dosis = varDosis; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdRelMedicamentoClasificacionColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdMedicamentoColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdClasificacionColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn DosisColumn { get { return Schema.Columns[3]; } } #endregion #region Columns Struct public struct Columns { public static string IdRelMedicamentoClasificacion = @"idRelMedicamentoClasificacion"; public static string IdMedicamento = @"idMedicamento"; public static string IdClasificacion = @"idClasificacion"; public static string Dosis = @"dosis"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using PlayFab.Json.Utilities; using System.Globalization; namespace PlayFab.Json.Linq { /// <summary> /// Represents a JSON constructor. /// </summary> public class JConstructor : JContainer { private string _name; private readonly List<JToken> _values = new List<JToken>(); /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens { get { return _values; } } /// <summary> /// Gets or sets the name of this constructor. /// </summary> /// <value>The constructor name.</value> public string Name { get { return _name; } set { _name = value; } } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type { get { return JTokenType.Constructor; } } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class. /// </summary> public JConstructor() { } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class from another <see cref="JConstructor"/> object. /// </summary> /// <param name="other">A <see cref="JConstructor"/> object to copy from.</param> public JConstructor(JConstructor other) : base(other) { _name = other.Name; } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name and content. /// </summary> /// <param name="name">The constructor name.</param> /// <param name="content">The contents of the constructor.</param> public JConstructor(string name, params object[] content) : this(name, (object)content) { } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name and content. /// </summary> /// <param name="name">The constructor name.</param> /// <param name="content">The contents of the constructor.</param> public JConstructor(string name, object content) : this(name) { Add(content); } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name. /// </summary> /// <param name="name">The constructor name.</param> public JConstructor(string name) { ValidationUtils.ArgumentNotNullOrEmpty(name, "name"); _name = name; } internal override bool DeepEquals(JToken node) { JConstructor c = node as JConstructor; return (c != null && _name == c.Name && ContentsEqual(c)); } internal override JToken CloneToken() { return new JConstructor(this); } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartConstructor(_name); foreach (JToken token in Children()) { token.WriteTo(writer, converters); } writer.WriteEndConstructor(); } /// <summary> /// Gets the <see cref="JToken"/> with the specified key. /// </summary> /// <value>The <see cref="JToken"/> with the specified key.</value> public override JToken this[object key] { get { ValidationUtils.ArgumentNotNull(key, "o"); if (!(key is int)) throw new ArgumentException("Accessed JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); return GetItem((int)key); } set { ValidationUtils.ArgumentNotNull(key, "o"); if (!(key is int)) throw new ArgumentException("Set JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); SetItem((int)key, value); } } internal override int GetDeepHashCode() { return _name.GetHashCode() ^ ContentsHashCode(); } /// <summary> /// Loads an <see cref="JConstructor"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JConstructor"/>.</param> /// <returns>A <see cref="JConstructor"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public static new JConstructor Load(JsonReader reader) { if (reader.TokenType == JsonToken.None) { if (!reader.Read()) throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader."); } while (reader.TokenType == JsonToken.Comment) { reader.Read(); } if (reader.TokenType != JsonToken.StartConstructor) throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); JConstructor c = new JConstructor((string)reader.Value); c.SetLineInfo(reader as IJsonLineInfo); c.ReadTokenFrom(reader); return c; } } } #endif
///////////////////////////////////////////////////////////////////////////////// // Paint.NET // // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. // // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. // // See license-pdn.txt for full licensing and attribution details. // // // // Ported to Pinta by: Jonathan Pobst <monkey@jpobst.com> // ///////////////////////////////////////////////////////////////////////////////// using System; using Cairo; using Pinta.Gui.Widgets; using Pinta.Core; using Mono.Unix; namespace Pinta.Effects { public class GaussianBlurEffect : BaseEffect { public override string Icon { get { return "Menu.Effects.Blurs.GaussianBlur.png"; } } public override string Name { get { return Catalog.GetString ("Gaussian Blur"); } } public override bool IsConfigurable { get { return true; } } public override string EffectMenuCategory { get { return Catalog.GetString ("Blurs"); } } public GaussianBlurData Data { get { return EffectData as GaussianBlurData; } } public GaussianBlurEffect () { EffectData = new GaussianBlurData (); } public override bool LaunchConfiguration () { return EffectHelper.LaunchSimpleEffectDialog (this); } #region Algorithm Code Ported From PDN public static int[] CreateGaussianBlurRow (int amount) { int size = 1 + (amount * 2); int[] weights = new int[size]; for (int i = 0; i <= amount; ++i) { // 1 + aa - aa + 2ai - ii weights[i] = 16 * (i + 1); weights[weights.Length - i - 1] = weights[i]; } return weights; } public unsafe override void Render (ImageSurface src, ImageSurface dest, Gdk.Rectangle[] rois) { if (Data.Radius == 0) { // Copy src to dest return; } int r = Data.Radius; int[] w = CreateGaussianBlurRow (r); int wlen = w.Length; int localStoreSize = wlen * 6 * sizeof (long); byte* localStore = stackalloc byte[localStoreSize]; byte* p = localStore; long* waSums = (long*)p; p += wlen * sizeof (long); long* wcSums = (long*)p; p += wlen * sizeof (long); long* aSums = (long*)p; p += wlen * sizeof (long); long* bSums = (long*)p; p += wlen * sizeof (long); long* gSums = (long*)p; p += wlen * sizeof (long); long* rSums = (long*)p; p += wlen * sizeof (long); // Cache these for a massive performance boost int src_width = src.Width; int src_height = src.Height; ColorBgra* src_data_ptr = (ColorBgra*)src.DataPtr; foreach (Gdk.Rectangle rect in rois) { if (rect.Height >= 1 && rect.Width >= 1) { for (int y = rect.Top; y <= rect.GetBottom (); ++y) { //Memory.SetToZero (localStore, (ulong)localStoreSize); long waSum = 0; long wcSum = 0; long aSum = 0; long bSum = 0; long gSum = 0; long rSum = 0; ColorBgra* dstPtr = dest.GetPointAddressUnchecked (rect.Left, y); for (int wx = 0; wx < wlen; ++wx) { int srcX = rect.Left + wx - r; waSums[wx] = 0; wcSums[wx] = 0; aSums[wx] = 0; bSums[wx] = 0; gSums[wx] = 0; rSums[wx] = 0; if (srcX >= 0 && srcX < src_width) { for (int wy = 0; wy < wlen; ++wy) { int srcY = y + wy - r; if (srcY >= 0 && srcY < src_height) { ColorBgra c = src.GetPointUnchecked (src_data_ptr, src_width, srcX, srcY); int wp = w[wy]; waSums[wx] += wp; wp *= c.A + (c.A >> 7); wcSums[wx] += wp; wp >>= 8; aSums[wx] += wp * c.A; bSums[wx] += wp * c.B; gSums[wx] += wp * c.G; rSums[wx] += wp * c.R; } } int wwx = w[wx]; waSum += wwx * waSums[wx]; wcSum += wwx * wcSums[wx]; aSum += wwx * aSums[wx]; bSum += wwx * bSums[wx]; gSum += wwx * gSums[wx]; rSum += wwx * rSums[wx]; } } wcSum >>= 8; if (waSum == 0 || wcSum == 0) { dstPtr->Bgra = 0; } else { int alpha = (int)(aSum / waSum); int blue = (int)(bSum / wcSum); int green = (int)(gSum / wcSum); int red = (int)(rSum / wcSum); dstPtr->Bgra = ColorBgra.BgraToUInt32 (blue, green, red, alpha); } ++dstPtr; for (int x = rect.Left + 1; x <= rect.GetRight (); ++x) { for (int i = 0; i < wlen - 1; ++i) { waSums[i] = waSums[i + 1]; wcSums[i] = wcSums[i + 1]; aSums[i] = aSums[i + 1]; bSums[i] = bSums[i + 1]; gSums[i] = gSums[i + 1]; rSums[i] = rSums[i + 1]; } waSum = 0; wcSum = 0; aSum = 0; bSum = 0; gSum = 0; rSum = 0; int wx; for (wx = 0; wx < wlen - 1; ++wx) { long wwx = (long)w[wx]; waSum += wwx * waSums[wx]; wcSum += wwx * wcSums[wx]; aSum += wwx * aSums[wx]; bSum += wwx * bSums[wx]; gSum += wwx * gSums[wx]; rSum += wwx * rSums[wx]; } wx = wlen - 1; waSums[wx] = 0; wcSums[wx] = 0; aSums[wx] = 0; bSums[wx] = 0; gSums[wx] = 0; rSums[wx] = 0; int srcX = x + wx - r; if (srcX >= 0 && srcX < src_width) { for (int wy = 0; wy < wlen; ++wy) { int srcY = y + wy - r; if (srcY >= 0 && srcY < src_height) { ColorBgra c = src.GetPointUnchecked (src_data_ptr, src_width, srcX, srcY); int wp = w[wy]; waSums[wx] += wp; wp *= c.A + (c.A >> 7); wcSums[wx] += wp; wp >>= 8; aSums[wx] += wp * (long)c.A; bSums[wx] += wp * (long)c.B; gSums[wx] += wp * (long)c.G; rSums[wx] += wp * (long)c.R; } } int wr = w[wx]; waSum += (long)wr * waSums[wx]; wcSum += (long)wr * wcSums[wx]; aSum += (long)wr * aSums[wx]; bSum += (long)wr * bSums[wx]; gSum += (long)wr * gSums[wx]; rSum += (long)wr * rSums[wx]; } wcSum >>= 8; if (waSum == 0 || wcSum == 0) { dstPtr->Bgra = 0; } else { int alpha = (int)(aSum / waSum); int blue = (int)(bSum / wcSum); int green = (int)(gSum / wcSum); int red = (int)(rSum / wcSum); dstPtr->Bgra = ColorBgra.BgraToUInt32 (blue, green, red, alpha); } ++dstPtr; } } } } } #endregion public class GaussianBlurData : EffectData { [Caption ("Radius"), MinimumValue (0), MaximumValue (200)] public int Radius = 2; [Skip] public override bool IsDefault { get { return Radius == 0; } } } } }
// 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.IO; using System.Linq; using System.Xml; using Microsoft.Build.BackEnd; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.UnitTests.BackEnd; using Shouldly; using Xunit; using Xunit.Abstractions; using static Microsoft.Build.Engine.UnitTests.TestComparers.ProjectInstanceModelTestComparers; namespace Microsoft.Build.UnitTests.OM.Instance { /// <summary> /// Tests for ProjectInstance internal members /// </summary> public class ProjectInstance_Internal_Tests { private readonly ITestOutputHelper _output; public ProjectInstance_Internal_Tests(ITestOutputHelper output) { _output = output; } /// <summary> /// Read task registrations /// </summary> [Fact] public void GetTaskRegistrations() { try { string projectFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <UsingTask TaskName='t0' AssemblyFile='af0'/> <UsingTask TaskName='t1' AssemblyFile='af1a'/> <ItemGroup> <i Include='i0'/> </ItemGroup> <Import Project='{0}'/> </Project>"; string importContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <UsingTask TaskName='t1' AssemblyName='an1' Condition=""'$(p)'=='v'""/> <UsingTask TaskName='t2' AssemblyName='an2' Condition=""'@(i)'=='i0'""/> <UsingTask TaskName='t3' AssemblyFile='af' Condition='false'/> <PropertyGroup> <p>v</p> </PropertyGroup> </Project>"; string importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.targets", importContent); projectFileContent = String.Format(projectFileContent, importPath); ProjectInstance project = new Project(ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)))).CreateProjectInstance(); Assert.Equal(3, project.TaskRegistry.TaskRegistrations.Count); Assert.Equal(Path.Combine(Directory.GetCurrentDirectory(), "af0"), project.TaskRegistry.TaskRegistrations[new TaskRegistry.RegisteredTaskIdentity("t0", null)][0].TaskFactoryAssemblyLoadInfo.AssemblyFile); Assert.Equal(Path.Combine(Directory.GetCurrentDirectory(), "af1a"), project.TaskRegistry.TaskRegistrations[new TaskRegistry.RegisteredTaskIdentity("t1", null)][0].TaskFactoryAssemblyLoadInfo.AssemblyFile); Assert.Equal("an1", project.TaskRegistry.TaskRegistrations[new TaskRegistry.RegisteredTaskIdentity("t1", null)][1].TaskFactoryAssemblyLoadInfo.AssemblyName); Assert.Equal("an2", project.TaskRegistry.TaskRegistrations[new TaskRegistry.RegisteredTaskIdentity("t2", null)][0].TaskFactoryAssemblyLoadInfo.AssemblyName); } finally { ObjectModelHelpers.DeleteTempProjectDirectory(); } } /// <summary> /// InitialTargets and DefaultTargets with imported projects. /// DefaultTargets are not read from imported projects. /// InitialTargets are gathered from imports depth-first. /// </summary> [Fact] public void InitialTargetsDefaultTargets() { try { string projectFileContent = @" <Project DefaultTargets='d0a;d0b' InitialTargets='i0a;i0b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='{0}'/> <Import Project='{1}'/> </Project>"; string import1Content = @" <Project DefaultTargets='d1a;d1b' InitialTargets='i1a;i1b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='{0}'/> </Project>"; string import2Content = @"<Project DefaultTargets='d2a;2db' InitialTargets='i2a;i2b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'/>"; string import3Content = @"<Project DefaultTargets='d3a;d3b' InitialTargets='i3a;i3b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'/>"; string import2Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("import2.targets", import2Content); string import3Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("import3.targets", import3Content); import1Content = String.Format(import1Content, import3Path); string import1Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("import1.targets", import1Content); projectFileContent = String.Format(projectFileContent, import1Path, import2Path); ProjectInstance project = new Project(ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)))).CreateProjectInstance(); Helpers.AssertListsValueEqual(new string[] { "d0a", "d0b" }, project.DefaultTargets); Helpers.AssertListsValueEqual(new string[] { "i0a", "i0b", "i1a", "i1b", "i3a", "i3b", "i2a", "i2b" }, project.InitialTargets); } finally { ObjectModelHelpers.DeleteTempProjectDirectory(); } } /// <summary> /// InitialTargets and DefaultTargets with imported projects. /// DefaultTargets are not read from imported projects. /// InitialTargets are gathered from imports depth-first. /// </summary> [Fact] public void InitialTargetsDefaultTargetsEscaped() { try { string projectFileContent = @" <Project DefaultTargets='d0a%3bd0b' InitialTargets='i0a%3bi0b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> </Project>"; ProjectInstance project = new Project(ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)))).CreateProjectInstance(); Helpers.AssertListsValueEqual(new string[] { "d0a;d0b" }, project.DefaultTargets); Helpers.AssertListsValueEqual(new string[] { "i0a;i0b" }, project.InitialTargets); } finally { ObjectModelHelpers.DeleteTempProjectDirectory(); } } /// <summary> /// Read property group under target /// </summary> [Fact] public void GetPropertyGroupUnderTarget() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Target Name='t'> <PropertyGroup Condition='c1'> <p1 Condition='c2'>v1</p1> <p2/> </PropertyGroup> </Target> </Project> "; ProjectInstance p = GetProjectInstance(content); ProjectPropertyGroupTaskInstance propertyGroup = (ProjectPropertyGroupTaskInstance)(p.Targets["t"].Children[0]); Assert.Equal("c1", propertyGroup.Condition); List<ProjectPropertyGroupTaskPropertyInstance> properties = Helpers.MakeList(propertyGroup.Properties); Assert.Equal(2, properties.Count); Assert.Equal("c2", properties[0].Condition); Assert.Equal("v1", properties[0].Value); Assert.Equal(String.Empty, properties[1].Condition); Assert.Equal(String.Empty, properties[1].Value); } /// <summary> /// Read item group under target /// </summary> [Fact] public void GetItemGroupUnderTarget() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Target Name='t'> <ItemGroup Condition='c1'> <i Include='i1' Exclude='e1' Condition='c2'> <m Condition='c3'>m1</m> <n>n1</n> </i> <j Remove='r1'/> <k> <o>o1</o> </k> </ItemGroup> </Target> </Project> "; ProjectInstance p = GetProjectInstance(content); ProjectItemGroupTaskInstance itemGroup = (ProjectItemGroupTaskInstance)(p.Targets["t"].Children[0]); Assert.Equal("c1", itemGroup.Condition); List<ProjectItemGroupTaskItemInstance> items = Helpers.MakeList(itemGroup.Items); Assert.Equal(3, items.Count); Assert.Equal("i1", items[0].Include); Assert.Equal("e1", items[0].Exclude); Assert.Equal(String.Empty, items[0].Remove); Assert.Equal("c2", items[0].Condition); Assert.Equal(String.Empty, items[1].Include); Assert.Equal(String.Empty, items[1].Exclude); Assert.Equal("r1", items[1].Remove); Assert.Equal(String.Empty, items[1].Condition); Assert.Equal(String.Empty, items[2].Include); Assert.Equal(String.Empty, items[2].Exclude); Assert.Equal(String.Empty, items[2].Remove); Assert.Equal(String.Empty, items[2].Condition); List<ProjectItemGroupTaskMetadataInstance> metadata1 = Helpers.MakeList(items[0].Metadata); List<ProjectItemGroupTaskMetadataInstance> metadata2 = Helpers.MakeList(items[1].Metadata); List<ProjectItemGroupTaskMetadataInstance> metadata3 = Helpers.MakeList(items[2].Metadata); Assert.Equal(2, metadata1.Count); Assert.Empty(metadata2); Assert.Single(metadata3); Assert.Equal("c3", metadata1[0].Condition); Assert.Equal("m1", metadata1[0].Value); Assert.Equal(String.Empty, metadata1[1].Condition); Assert.Equal("n1", metadata1[1].Value); Assert.Equal(String.Empty, metadata3[0].Condition); Assert.Equal("o1", metadata3[0].Value); } /// <summary> /// Task registry accessor /// </summary> [Fact] public void GetTaskRegistry() { ProjectInstance p = GetSampleProjectInstance(); Assert.True(p.TaskRegistry != null); } /// <summary> /// Global properties accessor /// </summary> [Fact] public void GetGlobalProperties() { ProjectInstance p = GetSampleProjectInstance(); Assert.Equal("v1", p.GlobalPropertiesDictionary["g1"].EvaluatedValue); Assert.Equal("v2", p.GlobalPropertiesDictionary["g2"].EvaluatedValue); } /// <summary> /// ToolsVersion accessor /// </summary> [Fact] public void GetToolsVersion() { ProjectInstance p = GetSampleProjectInstance(); Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion); } [Fact] public void UsingExplicitToolsVersionShouldBeFalseWhenNoToolsetIsReferencedInProject() { var projectInstance = new ProjectInstance( new ProjectRootElement( XmlReader.Create(new StringReader("<Project></Project>")), ProjectCollection.GlobalProjectCollection.ProjectRootElementCache, false, false) ); projectInstance.UsingDifferentToolsVersionFromProjectFile.ShouldBeFalse(); } /// <summary> /// Toolset data is cloned properly /// </summary> [Fact] public void CloneToolsetData() { var projectCollection = new ProjectCollection(); CreateMockToolsetIfNotExists("TESTTV", projectCollection); ProjectInstance first = GetSampleProjectInstance(null, null, projectCollection, toolsVersion: "TESTTV"); ProjectInstance second = first.DeepCopy(); Assert.Equal(first.ToolsVersion, second.ToolsVersion); Assert.Equal(first.ExplicitToolsVersion, second.ExplicitToolsVersion); Assert.Equal(first.ExplicitToolsVersionSpecified, second.ExplicitToolsVersionSpecified); } /// <summary> /// Test ProjectInstance's surfacing of the sub-toolset version /// </summary> [Fact] public void GetSubToolsetVersion() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", null); ProjectInstance p = GetSampleProjectInstance(null, null, new ProjectCollection()); Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion); Assert.Equal(p.Toolset.DefaultSubToolsetVersion, p.SubToolsetVersion); if (p.Toolset.DefaultSubToolsetVersion == null) { Assert.Equal(MSBuildConstants.CurrentVisualStudioVersion, p.GetPropertyValue("VisualStudioVersion")); } else { Assert.Equal(p.Toolset.DefaultSubToolsetVersion, p.GetPropertyValue("VisualStudioVersion")); } } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } /// <summary> /// Test ProjectInstance's surfacing of the sub-toolset version when it is overridden by a value in the /// environment /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void GetSubToolsetVersion_FromEnvironment() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", "ABCD"); ProjectInstance p = GetSampleProjectInstance(null, null, new ProjectCollection()); Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion); Assert.Equal("ABCD", p.SubToolsetVersion); Assert.Equal("ABCD", p.GetPropertyValue("VisualStudioVersion")); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } /// <summary> /// Test ProjectInstance's surfacing of the sub-toolset version when it is overridden by a global property /// </summary> [Fact] public void GetSubToolsetVersion_FromProjectGlobalProperties() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", null); IDictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); globalProperties.Add("VisualStudioVersion", "ABCDE"); ProjectInstance p = GetSampleProjectInstance(null, globalProperties, new ProjectCollection()); Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion); Assert.Equal("ABCDE", p.SubToolsetVersion); Assert.Equal("ABCDE", p.GetPropertyValue("VisualStudioVersion")); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } /// <summary> /// Verify that if a sub-toolset version is passed to the constructor, it all other heuristic methods for /// getting the sub-toolset version. /// </summary> [Fact] public void GetSubToolsetVersion_FromConstructor() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", "ABC"); string projectContent = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Target Name='t'> <Message Text='Hello'/> </Target> </Project>"; ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectContent))); IDictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); globalProperties.Add("VisualStudioVersion", "ABCD"); IDictionary<string, string> projectCollectionGlobalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); projectCollectionGlobalProperties.Add("VisualStudioVersion", "ABCDE"); ProjectInstance p = new ProjectInstance(xml, globalProperties, ObjectModelHelpers.MSBuildDefaultToolsVersion, "ABCDEF", new ProjectCollection(projectCollectionGlobalProperties)); Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion); Assert.Equal("ABCDEF", p.SubToolsetVersion); Assert.Equal("ABCDEF", p.GetPropertyValue("VisualStudioVersion")); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } /// <summary> /// DefaultTargets accessor /// </summary> [Fact] public void GetDefaultTargets() { ProjectInstance p = GetSampleProjectInstance(); Helpers.AssertListsValueEqual(new string[] { "dt" }, p.DefaultTargets); } /// <summary> /// InitialTargets accessor /// </summary> [Fact] public void GetInitialTargets() { ProjectInstance p = GetSampleProjectInstance(); Helpers.AssertListsValueEqual(new string[] { "it" }, p.InitialTargets); } /// <summary> /// Cloning project clones targets /// </summary> [Fact] public void CloneTargets() { var hostServices = new HostServices(); ProjectInstance first = GetSampleProjectInstance(hostServices); ProjectInstance second = first.DeepCopy(); // Targets, tasks are immutable so we can expect the same objects Assert.True(Object.ReferenceEquals(first.Targets, second.Targets)); Assert.True(Object.ReferenceEquals(first.Targets["t"], second.Targets["t"])); var firstTasks = first.Targets["t"]; var secondTasks = second.Targets["t"]; Assert.True(Object.ReferenceEquals(firstTasks.Children[0], secondTasks.Children[0])); } /// <summary> /// Cloning project copies task registry /// </summary> [Fact] public void CloneTaskRegistry() { ProjectInstance first = GetSampleProjectInstance(); ProjectInstance second = first.DeepCopy(); // Task registry object should be immutable Assert.Same(first.TaskRegistry, second.TaskRegistry); } /// <summary> /// Cloning project copies global properties /// </summary> [Fact] public void CloneGlobalProperties() { ProjectInstance first = GetSampleProjectInstance(); ProjectInstance second = first.DeepCopy(); Assert.Equal("v1", second.GlobalPropertiesDictionary["g1"].EvaluatedValue); Assert.Equal("v2", second.GlobalPropertiesDictionary["g2"].EvaluatedValue); } /// <summary> /// Cloning project copies default targets /// </summary> [Fact] public void CloneDefaultTargets() { ProjectInstance first = GetSampleProjectInstance(); ProjectInstance second = first.DeepCopy(); Helpers.AssertListsValueEqual(new string[] { "dt" }, second.DefaultTargets); } /// <summary> /// Cloning project copies initial targets /// </summary> [Fact] public void CloneInitialTargets() { ProjectInstance first = GetSampleProjectInstance(); ProjectInstance second = first.DeepCopy(); Helpers.AssertListsValueEqual(new string[] { "it" }, second.InitialTargets); } /// <summary> /// Cloning project copies toolsversion /// </summary> [Fact] public void CloneToolsVersion() { ProjectInstance first = GetSampleProjectInstance(); ProjectInstance second = first.DeepCopy(); Assert.Equal(first.Toolset, second.Toolset); } /// <summary> /// Cloning project copies toolsversion /// </summary> [Fact] public void CloneStateTranslation() { ProjectInstance first = GetSampleProjectInstance(); first.TranslateEntireState = true; ProjectInstance second = first.DeepCopy(); Assert.True(second.TranslateEntireState); } /// <summary> /// Tests building a simple project and verifying the log looks as expected. /// </summary> [Fact] public void Build() { // Setting the current directory to the MSBuild running location. It *should* be this // already, but if it's not some other test changed it and didn't change it back. If // the directory does not include the reference dlls the compilation will fail. Directory.SetCurrentDirectory(BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory); string projectFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <UsingTask TaskName='Microsoft.Build.Tasks.Message' AssemblyFile='Microsoft.Build.Tasks.Core.dll'/> <ItemGroup> <i Include='i0'/> </ItemGroup> <Target Name='Build'> <Message Text='Building...'/> <Message Text='Completed!'/> </Target> </Project>"; ProjectInstance projectInstance = GetProjectInstance(projectFileContent); List<ILogger> loggers = new List<ILogger>(); MockLogger mockLogger = new MockLogger(_output); loggers.Add(mockLogger); bool success = projectInstance.Build("Build", loggers); Assert.True(success); mockLogger.AssertLogContains(new string[] { "Building...", "Completed!" }); } [Theory] [InlineData( @" <Project> </Project> ")] // Project with one of each direct child(indirect children trees are tested separately) [InlineData( @" <Project InitialTargets=`t1` DefaultTargets=`t2` ToolsVersion=`{0}`> <UsingTask TaskName=`t1` AssemblyFile=`f1`/> <ItemDefinitionGroup> <i> <n>n1</n> </i> </ItemDefinitionGroup> <PropertyGroup> <p1>v1</p1> </PropertyGroup> <ItemGroup> <i Include='i0'/> </ItemGroup> <Target Name='t1'> <t1/> </Target> <Target Name='t2' BeforeTargets=`t1`> <t2/> </Target> <Target Name='t3' AfterTargets=`t2`> <t3/> </Target> </Project> ")] // Project with at least two instances of each direct child. Tests that collections serialize well. [InlineData( @" <Project InitialTargets=`t1` DefaultTargets=`t2` ToolsVersion=`{0}`> <UsingTask TaskName=`t1` AssemblyFile=`f1`/> <UsingTask TaskName=`t2` AssemblyFile=`f2`/> <ItemDefinitionGroup> <i> <n>n1</n> </i> </ItemDefinitionGroup> <ItemDefinitionGroup> <i2> <n2>n2</n2> </i2> </ItemDefinitionGroup> <PropertyGroup> <p1>v1</p1> </PropertyGroup> <PropertyGroup> <p2>v2</p2> </PropertyGroup> <ItemGroup> <i Include='i1'/> </ItemGroup> <ItemGroup> <i2 Include='i2'> <m1 Condition=`1==1`>m1</m1> <m2>m2</m2> </i2> </ItemGroup> <Target Name='t1'> <t1/> </Target> <Target Name='t2' BeforeTargets=`t1`> <t2/> </Target> <Target Name='t3' AfterTargets=`t1`> <t3/> </Target> <Target Name='t4' BeforeTargets=`t1`> <t4/> </Target> <Target Name='t5' AfterTargets=`t1`> <t5/> </Target> </Project> ")] public void ProjectInstanceCanSerializeEntireStateViaTranslator(string projectContents) { projectContents = string.Format(projectContents, MSBuildConstants.CurrentToolsVersion); var original = new ProjectInstance(ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(projectContents))))); original.TranslateEntireState = true; ((ITranslatable) original).Translate(TranslationHelpers.GetWriteTranslator()); var copy = ProjectInstance.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(original, copy, new ProjectInstanceComparer()); } public delegate ProjectInstance ProjectInstanceFactory(string file, ProjectRootElement xml, ProjectCollection collection); public static IEnumerable<object[]> ProjectInstanceHasEvaluationIdTestData() { // from file yield return new ProjectInstanceFactory[] { (f, xml, c) => new ProjectInstance(f, null, null, c) }; // from Project yield return new ProjectInstanceFactory[] { (f, xml, c) => new Project(f, null, null, c).CreateProjectInstance() }; // from DeepCopy yield return new ProjectInstanceFactory[] { (f, xml, c) => new ProjectInstance(f, null, null, c).DeepCopy() }; // from ProjectRootElement yield return new ProjectInstanceFactory[] { (f, xml, c) => new ProjectInstance(xml, null, null, c).DeepCopy() }; // from translated project instance yield return new ProjectInstanceFactory[] { (f, xml, c) => { var pi = new ProjectInstance(f, null, null, c); pi.AddItem("foo", "bar"); pi.TranslateEntireState = true; ((ITranslatable) pi).Translate(TranslationHelpers.GetWriteTranslator()); var copy = ProjectInstance.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); return copy; } }; } [Theory] [MemberData(nameof(ProjectInstanceHasEvaluationIdTestData))] public void ProjectInstanceHasEvaluationId(ProjectInstanceFactory projectInstanceFactory) { using (var env = TestEnvironment.Create()) { var file = env.CreateFile().Path; var projectCollection = env.CreateProjectCollection().Collection; var xml = ProjectRootElement.Create(projectCollection); xml.Save(file); var projectInstance = projectInstanceFactory.Invoke(file, xml, projectCollection); Assert.NotEqual(BuildEventContext.InvalidEvaluationId, projectInstance.EvaluationId); } } [Fact] public void AddTargetAddsNewTarget() { string projectFileContent = @" <Project> <Target Name='a' /> </Project>"; ProjectRootElement rootElement = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent))); ProjectInstance projectInstance = new ProjectInstance(rootElement); ProjectTargetInstance targetInstance = projectInstance.AddTarget("b", "1==1", "inputs", "outputs", "returns", "keepDuplicateOutputs", "dependsOnTargets", "beforeTargets", "afterTargets", true); Assert.Equal(2, projectInstance.Targets.Count); Assert.Equal(targetInstance, projectInstance.Targets["b"]); Assert.Equal("b", targetInstance.Name); Assert.Equal("1==1", targetInstance.Condition); Assert.Equal("inputs", targetInstance.Inputs); Assert.Equal("outputs", targetInstance.Outputs); Assert.Equal("returns", targetInstance.Returns); Assert.Equal("keepDuplicateOutputs", targetInstance.KeepDuplicateOutputs); Assert.Equal("dependsOnTargets", targetInstance.DependsOnTargets); Assert.Equal("beforeTargets", targetInstance.BeforeTargets); Assert.Equal("afterTargets", targetInstance.AfterTargets); Assert.Equal(projectInstance.ProjectFileLocation, targetInstance.Location); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.ConditionLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.InputsLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.OutputsLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.ReturnsLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.KeepDuplicateOutputsLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.DependsOnTargetsLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.BeforeTargetsLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.AfterTargetsLocation); Assert.True(targetInstance.ParentProjectSupportsReturnsAttribute); } [Fact] public void AddTargetThrowsWithExistingTarget() { string projectFileContent = @" <Project> <Target Name='a' /> </Project>"; ProjectRootElement rootElement = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent))); ProjectInstance projectInstance = new ProjectInstance(rootElement); Assert.Throws<InternalErrorException>(() => projectInstance.AddTarget("a", "1==1", "inputs", "outputs", "returns", "keepDuplicateOutputs", "dependsOnTargets", "beforeTargets", "afterTargets", true)); } /// <summary> /// Create a ProjectInstance from provided project content /// </summary> private static ProjectInstance GetProjectInstance(string content) { return GetProjectInstance(content, null); } /// <summary> /// Create a ProjectInstance from provided project content and host services object /// </summary> private static ProjectInstance GetProjectInstance(string content, HostServices hostServices) { return GetProjectInstance(content, hostServices, null, null); } /// <summary> /// Create a ProjectInstance from provided project content and host services object /// </summary> private static ProjectInstance GetProjectInstance(string content, HostServices hostServices, IDictionary<string, string> globalProperties, ProjectCollection projectCollection, string toolsVersion = null) { XmlReader reader = XmlReader.Create(new StringReader(content)); if (globalProperties == null) { // choose some interesting defaults if we weren't explicitly asked to use a set. globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); globalProperties.Add("g1", "v1"); globalProperties.Add("g2", "v2"); } Project project = new Project(reader, globalProperties, toolsVersion ?? ObjectModelHelpers.MSBuildDefaultToolsVersion, projectCollection ?? ProjectCollection.GlobalProjectCollection); ProjectInstance instance = project.CreateProjectInstance(); return instance; } /// <summary> /// Create a ProjectInstance with some items and properties and targets /// </summary> private static ProjectInstance GetSampleProjectInstance() { return GetSampleProjectInstance(null); } /// <summary> /// Create a ProjectInstance with some items and properties and targets /// </summary> private static ProjectInstance GetSampleProjectInstance(HostServices hostServices) { return GetSampleProjectInstance(hostServices, null, null); } /// <summary> /// Create a ProjectInstance with some items and properties and targets /// </summary> private static ProjectInstance GetSampleProjectInstance(HostServices hostServices, IDictionary<string, string> globalProperties, ProjectCollection projectCollection, string toolsVersion = null) { string toolsVersionSubstring = toolsVersion != null ? "ToolsVersion=\"" + toolsVersion + "\" " : String.Empty; string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' InitialTargets='it' DefaultTargets='dt' " + toolsVersionSubstring + @"> <PropertyGroup> <p1>v1</p1> <p2>v2</p2> <p2>$(p2)X$(p)</p2> </PropertyGroup> <ItemGroup> <i Include='i0'/> <i Include='i1'> <m>m1</m> </i> <i Include='$(p1)'/> </ItemGroup> <Target Name='t'> <t1 a='a1' b='b1' ContinueOnError='coe' Condition='c'/> <t2/> </Target> <Target Name='tt'/> </Project> "; ProjectInstance p = GetProjectInstance(content, hostServices, globalProperties, projectCollection, toolsVersion); return p; } /// <summary> /// Creates a toolset with the given tools version if one does not already exist. /// </summary> private static void CreateMockToolsetIfNotExists(string toolsVersion, ProjectCollection projectCollection) { ProjectCollection pc = projectCollection; if (!pc.Toolsets.Any(t => String.Equals(t.ToolsVersion, toolsVersion, StringComparison.OrdinalIgnoreCase))) { Toolset template = pc.Toolsets.First(t => String.Equals(t.ToolsVersion, pc.DefaultToolsVersion, StringComparison.OrdinalIgnoreCase)); var toolset = new Toolset( toolsVersion, template.ToolsPath, template.Properties.ToDictionary(p => p.Key, p => p.Value.EvaluatedValue), pc, null); pc.AddToolset(toolset); } } } }
// 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.IO; using System.Text; using Microsoft.Protocols.TestTools.StackSdk; using Microsoft.Protocols.TestTools.StackSdk.Messages; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs { /// <summary> /// Packets for SmbTrans2GetDfsReferalFinal Response /// </summary> public class SmbTrans2GetDfsReferalFinalResponsePacket : SmbTransaction2FinalResponsePacket { #region Fields private TRANS2_GET_DFS_REFERRAL_Response_Trans2_Data trans2Data; private const ushort referralHeaderSize = 8; private const ushort referralV1FixedSize = 8; private const ushort referralV2FixedSize = 22; #endregion #region Properties /// <summary> /// get or set the Trans2_Data:TRANS2_GET_DFS_REFERRAL_Response_Trans2_Data /// </summary> public TRANS2_GET_DFS_REFERRAL_Response_Trans2_Data Trans2Data { get { return this.trans2Data; } set { this.trans2Data = value; } } #endregion #region Constructor /// <summary> /// Constructor. /// </summary> public SmbTrans2GetDfsReferalFinalResponsePacket() : base() { this.InitDefaultValue(); } /// <summary> /// Constructor: Create a request directly from a buffer. /// </summary> public SmbTrans2GetDfsReferalFinalResponsePacket(byte[] data) : base(data) { } /// <summary> /// Deep copy constructor. /// </summary> public SmbTrans2GetDfsReferalFinalResponsePacket(SmbTrans2GetDfsReferalFinalResponsePacket packet) : base(packet) { this.InitDefaultValue(); this.trans2Data.ReferralResponse = packet.trans2Data.ReferralResponse; } #endregion #region Methods /// <summary> /// Update the offset of paths /// </summary> public void UpdatePathOffset() { DFS_REFERRAL_V2[] referral2List = this.trans2Data.ReferralResponse.ReferralEntries as DFS_REFERRAL_V2[]; if (referral2List != null) { int pathOffset = 0; ushort wordLength = 2; ushort nullLength = 1; for (int i = 0; i < referral2List.Length; i++) { int currentFerralFixedOffset = (referral2List.Length - i) * referralV2FixedSize; referral2List[i].DFSPathOffset = (ushort)(currentFerralFixedOffset + pathOffset); pathOffset += (referral2List[i].DFSPath.Length + nullLength) * wordLength; referral2List[i].DFSAlternatePathOffset = (ushort)(currentFerralFixedOffset + pathOffset); pathOffset += (referral2List[i].DFSAlternatePath.Length + nullLength) * wordLength; referral2List[i].NetworkAddressOffset = (ushort)(currentFerralFixedOffset + pathOffset); pathOffset += (referral2List[i].DFSTargetPath.Length + nullLength) * wordLength; } } } #endregion #region override methods /// <summary> /// to create an instance of the StackPacket class that is identical to the current StackPacket. /// </summary> /// <returns>a new Packet cloned from this.</returns> public override StackPacket Clone() { return new SmbTrans2GetDfsReferalFinalResponsePacket(this); } /// <summary> /// Encode the struct of Trans2Parameters into the byte array in SmbData.Trans2_Parameters /// </summary> protected override void EncodeTrans2Parameters() { } /// <summary> /// Encode the struct of Trans2Data into the byte array in SmbData.Trans2_Data /// </summary> protected override void EncodeTrans2Data() { int totalSize = referralHeaderSize; DFS_REFERRAL_V1[] referral1List = this.trans2Data.ReferralResponse.ReferralEntries as DFS_REFERRAL_V1[]; DFS_REFERRAL_V2[] referral2List = this.trans2Data.ReferralResponse.ReferralEntries as DFS_REFERRAL_V2[]; if (referral1List != null) { for (int i = 0; i < referral1List.Length; i++) { totalSize += referralV1FixedSize + referral1List[i].ShareName.Length; } } else if (referral2List != null) { ushort wordLength = 2; ushort nullLength = 3; for (int i = 0; i < referral2List.Length; i++) { totalSize += referralV2FixedSize + wordLength * (referral2List[i].DFSPath.Length + referral2List[i].DFSAlternatePath.Length + referral2List[i].DFSTargetPath.Length + nullLength); } } else { // Branch for negative testing. } this.smbData.Trans2_Data = new byte[totalSize]; using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data)) { using (Channel channel = new Channel(null, memoryStream)) { channel.BeginWriteGroup(); channel.Write<ushort>(this.trans2Data.ReferralResponse.PathConsumed); channel.Write<ushort>(this.trans2Data.ReferralResponse.NumberOfReferrals); channel.Write<ReferralHeaderFlags>(this.trans2Data.ReferralResponse.ReferralHeaderFlags); if (referral1List != null) { for (int i = 0; i < referral1List.Length; i++) { channel.Write<DFS_REFERRAL_V1>(referral1List[i]); } } else if (referral2List != null) { for (int i = 0; i < referral2List.Length; i++) { channel.Write<ushort>(referral2List[i].VersionNumber); channel.Write<ushort>(referral2List[i].Size); channel.Write<ushort>(referral2List[i].ServerType); channel.Write<ushort>(referral2List[i].ReferralEntryFlags); channel.Write<uint>(referral2List[i].Proximity); channel.Write<uint>(referral2List[i].TimeToLive); channel.Write<ushort>(referral2List[i].DFSPathOffset); channel.Write<ushort>(referral2List[i].DFSAlternatePathOffset); channel.Write<ushort>(referral2List[i].NetworkAddressOffset); } for (int i = 0; i < referral2List.Length; i++) { channel.WriteBytes(Encoding.Unicode.GetBytes(referral2List[i].DFSPath + "\0")); channel.WriteBytes(Encoding.Unicode.GetBytes(referral2List[i].DFSAlternatePath + "\0")); channel.WriteBytes(Encoding.Unicode.GetBytes(referral2List[i].DFSTargetPath + "\0")); } } else { // Branch for negative testing. } channel.EndWriteGroup(); } } } /// <summary> /// to decode the Trans2 parameters: from the general Trans2Parameters to the concrete Trans2 Parameters. /// </summary> protected override void DecodeTrans2Parameters() { } /// <summary> /// to decode the Trans2 data: from the general Trans2Dada to the concrete Trans2 Data. /// </summary> protected override void DecodeTrans2Data() { if (this.smbData.Trans2_Data != null && this.smbData.Trans2_Data.Length > 0) { using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data)) { using (Channel channel = new Channel(null, memoryStream)) { this.trans2Data.ReferralResponse.PathConsumed = channel.Read<ushort>(); this.trans2Data.ReferralResponse.NumberOfReferrals = channel.Read<ushort>(); this.trans2Data.ReferralResponse.ReferralHeaderFlags = channel.Read<ReferralHeaderFlags>(); if (this.trans2Data.ReferralResponse.NumberOfReferrals == 0) { return; } ushort versionNumber = channel.Peek<ushort>(0); switch (versionNumber) { case 0x0001: List<DFS_REFERRAL_V1> referral1List = new List<DFS_REFERRAL_V1>(); for (int i = 0; i < this.trans2Data.ReferralResponse.NumberOfReferrals; i++) { referral1List.Add(channel.Read<DFS_REFERRAL_V1>()); } this.trans2Data.ReferralResponse.ReferralEntries = referral1List.ToArray(); break; case 0x0002: List<DFS_REFERRAL_V2> referral2List = new List<DFS_REFERRAL_V2>(); for (int i = 0; i < this.trans2Data.ReferralResponse.NumberOfReferrals; i++) { DFS_REFERRAL_V2 referral2 = new DFS_REFERRAL_V2(); referral2.VersionNumber = channel.Read<ushort>(); referral2.Size = channel.Read<ushort>(); referral2.ServerType = channel.Read<ushort>(); referral2.ReferralEntryFlags = channel.Read<ushort>(); referral2.Proximity = channel.Read<uint>(); referral2.TimeToLive = channel.Read<uint>(); referral2.DFSPathOffset = channel.Read<ushort>(); referral2.DFSAlternatePathOffset = channel.Read<ushort>(); referral2.NetworkAddressOffset = channel.Read<ushort>(); referral2List.Add(referral2); } int fixedListSize = this.trans2Data.ReferralResponse.NumberOfReferrals * referralV2FixedSize; byte[] pathData = channel.ReadBytes(this.smbData.Trans2_Data.Length - fixedListSize - referralHeaderSize); for (int i = 0; i < referral2List.Count; i++) { int leftCount = referral2List.Count - i; DFS_REFERRAL_V2 referral2 = referral2List[i]; int dfsPathOffset = referral2.DFSPathOffset - leftCount * referralV2FixedSize; int dfsAlternatePathOffset = referral2.DFSAlternatePathOffset - leftCount * referralV2FixedSize; int targetPathOffset = referral2.NetworkAddressOffset - leftCount * referralV2FixedSize; int pathLength = 0; byte wordLength = 2; for (int j = dfsPathOffset; ; j += wordLength) { if (pathData[j] == 0 && pathData[j + 1] == 0) { break; } else { pathLength += wordLength; } } referral2.DFSPath = Encoding.Unicode.GetString(pathData, dfsPathOffset, pathLength); pathLength = 0; for (int j = dfsAlternatePathOffset; ; j += wordLength) { if (pathData[j] == 0 && pathData[j + 1] == 0) { break; } else { pathLength += wordLength; } } referral2.DFSAlternatePath = Encoding.Unicode.GetString(pathData, dfsAlternatePathOffset, pathLength); pathLength = 0; for (int j = targetPathOffset; ; j += wordLength) { if (pathData[j] == 0 && pathData[j + 1] == 0) { break; } else { pathLength += wordLength; } } referral2.DFSTargetPath = Encoding.Unicode.GetString(pathData, targetPathOffset, pathLength); referral2List[i] = referral2; } this.trans2Data.ReferralResponse.ReferralEntries = referral2List.ToArray(); break; } } } } } #endregion #region initialize fields with default value /// <summary> /// init packet, set default field data /// </summary> private void InitDefaultValue() { } #endregion } }
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. Copyright (c) 2011-2012 openxlive.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. ****************************************************************************/ namespace CocosSharp { /// <summary> /// @brief CCShuffleTiles action /// Shuffle the tiles in random order /// </summary> public class CCShuffleTiles : CCTiledGrid3DAction { protected internal const int NoSeedSpecified = -1; protected internal int Seed { get; private set; } #region Constructors /// <summary> /// creates the action with a random seed, the grid size and the duration /// </summary> public CCShuffleTiles (CCGridSize gridSize, float duration, int seed = NoSeedSpecified) : base (duration, gridSize) { } #endregion Constructors protected internal override CCActionState StartAction(CCNode target) { return new CCShuffleTilesState (this, target); } } #region Action state public class CCShuffleTilesState : CCTiledGrid3DActionState { protected int TilesCount { get; private set; } protected CCTile[] Tiles { get; private set; } protected int[] TilesOrder { get; private set; } public CCShuffleTilesState (CCShuffleTiles action, CCNode target) : base (action, target) { CCGridSize gridSize = action.GridSize; TilesCount = gridSize.X * gridSize.Y; int[] shuffledTilesOrder = new int[TilesCount]; int i, j, f = 0; for (i = 0; i < TilesCount; i++) { shuffledTilesOrder [i] = i; } if (action.Seed != CCShuffleTiles.NoSeedSpecified) { CCRandom.Next (action.Seed); } Shuffle (ref shuffledTilesOrder, TilesCount); TilesOrder = shuffledTilesOrder; Tiles = new CCTile[TilesCount]; for (i = 0; i < gridSize.X; ++i) { for (j = 0; j < gridSize.Y; ++j) { Tiles [f] = new CCTile { Position = new CCPoint (i, j), StartPosition = new CCPoint (i, j), Delta = GetDelta (i, j) }; f++; } } } public override void Update (float time) { int i, j, f = 0; for (i = 0; i < GridSize.X; ++i) { for (j = 0; j < GridSize.Y; ++j) { CCTile item = Tiles [f]; item.Position = new CCPoint ((item.Delta.X * time), (item.Delta.Y * time)); PlaceTile (i, j, item); f++; } } } #region Tile Shuffling public void Shuffle (ref int[] pArray, int nLen) { int i; for (i = nLen - 1; i >= 0; i--) { int j = CCRandom.Next () % (i + 1); int v = pArray [i]; pArray [i] = pArray [j]; pArray [j] = v; } } protected CCGridSize GetDelta (CCGridSize pos) { var pos2 = CCPoint.Zero; int idx = pos.X * GridSize.Y + pos.Y; int tileOrder = TilesOrder [idx]; pos2.X = (tileOrder / GridSize.Y); pos2.Y = (tileOrder % GridSize.Y); return new CCGridSize ((int)(pos2.X - pos.X), (int)(pos2.Y - pos.Y)); } protected CCGridSize GetDelta (int x, int y) { var pos2 = CCPoint.Zero; int idx = x * GridSize.Y + y; int tileOrder = TilesOrder [idx]; pos2.X = (tileOrder / GridSize.Y); pos2.Y = (tileOrder % GridSize.Y); return new CCGridSize ((int)(pos2.X - x), (int)(pos2.Y - y)); } protected void PlaceTile (CCGridSize pos, CCTile tile) { CCQuad3 coords = OriginalTile (pos); CCPoint step = Target.Grid.Step; coords.BottomLeft.X += (int)(tile.Position.X * step.X); coords.BottomLeft.Y += (int)(tile.Position.Y * step.Y); coords.BottomRight.X += (int)(tile.Position.X * step.X); coords.BottomRight.Y += (int)(tile.Position.Y * step.Y); coords.TopLeft.X += (int)(tile.Position.X * step.X); coords.TopLeft.Y += (int)(tile.Position.Y * step.Y); coords.TopRight.X += (int)(tile.Position.X * step.X); coords.TopRight.Y += (int)(tile.Position.Y * step.Y); SetTile (pos, ref coords); } protected void PlaceTile (int x, int y, CCTile tile) { CCQuad3 coords = OriginalTile (x, y); CCPoint step = Target.Grid.Step; coords.BottomLeft.X += (int)(tile.Position.X * step.X); coords.BottomLeft.Y += (int)(tile.Position.Y * step.Y); coords.BottomRight.X += (int)(tile.Position.X * step.X); coords.BottomRight.Y += (int)(tile.Position.Y * step.Y); coords.TopLeft.X += (int)(tile.Position.X * step.X); coords.TopLeft.Y += (int)(tile.Position.Y * step.Y); coords.TopRight.X += (int)(tile.Position.X * step.X); coords.TopRight.Y += (int)(tile.Position.Y * step.Y); SetTile (x, y, ref coords); } #endregion Tile Shuffling } #endregion Action state }
// MIT License // // Copyright(c) 2022 ICARUS Consulting GmbH // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using Yaapii.Atoms.Enumerable; #pragma warning disable NoProperties // No Properties #pragma warning disable MaxPublicMethodCount // a public methods count maximum namespace Yaapii.Atoms.Map { /// <summary> /// A map which matches a version. /// It can match the version range, not the exact version. /// This means if you have two krvps inside: 1.0 and 3.0, and your key is 2.0, the version 1.0 is matched. /// </summary> public sealed class VersionMap : MapEnvelope<Version, string> { public VersionMap(bool openEnd, params IKvp<Version, string>[] kvps) : this(new ManyOf<IKvp<Version, string>>(kvps), openEnd) { } public VersionMap(IEnumerable<IKvp<Version, string>> kvps, bool openEnd) : base(() => new VersionMap<string>(kvps, openEnd), false) { } } /// <summary> /// A dictionary which matches a version. /// It matches the version range, not the exact version. /// This means if you have two kvps inside: 1.0 and 3.0, and your key is 2.0, the version 1.0 is matched. /// </summary> /// <typeparam name="Value"></typeparam> public sealed class VersionMap<Value> : IDictionary<Version, Value> { private readonly IDictionary<Version, Value> map; private readonly InvalidOperationException reject = new InvalidOperationException("Not supported, this is only a lookup map for versions."); private readonly bool openEnd; private readonly Func<Version, IEnumerable<Version>, InvalidOperationException> versionNotFound = (version, available) => new InvalidOperationException( $"Cannot find value for version {version.ToString()}, the version must be within: " + new Text.Joined(", ", new Mapped<Version, string>( v => v.ToString(), available ) ).AsString() ); /// <summary> /// A dictionary which matches a version. /// It matches the version range, not the exact version. /// This means if you have two kvps inside: 1.0 and 3.0, and your key is 2.0, the version 1.0 is matched. /// </summary> public VersionMap(params IKvp<Version, Value>[] kvps) : this(false, kvps) { } /// <summary> /// A dictionary which matches a version. /// It matches the version range, not the exact version. /// This means if you have two kvps inside: 1.0 and 3.0, and your key is 2.0, the version 1.0 is matched. /// </summary> public VersionMap(bool openEnd, params IKvp<Version, Value>[] kvps) : this(new ManyOf<IKvp<Version, Value>>(kvps), openEnd) { } /// <summary> /// A dictionary which matches a version. /// It matches the version range, not the exact version. /// This means if you have two kvps inside: 1.0 and 3.0, and your key is 2.0, the version 1.0 is matched. /// </summary> public VersionMap(IEnumerable<IKvp<Version, Value>> kvps, bool openEnd) { this.map = new LazyDict<Version, Value>(kvps); this.openEnd = openEnd; } public Value this[Version key] { get => this.Match(key); set => throw this.reject; } public ICollection<Version> Keys => this.map.Keys; public ICollection<Value> Values => this.map.Values; public int Count => this.map.Count; public bool IsReadOnly => true; public void Add(Version key, Value value) { throw this.reject; } public void Add(KeyValuePair<Version, Value> item) { throw this.reject; } public void Clear() { throw this.reject; } public bool Contains(KeyValuePair<Version, Value> item) { return this.map.Contains(item); } public bool ContainsKey(Version key) { var result = false; try { var value = this.Match(key); result = true; } catch (Exception) { } return result; } public void CopyTo(KeyValuePair<Version, Value>[] array, int arrayIndex) { throw this.reject; } public IEnumerator<KeyValuePair<Version, Value>> GetEnumerator() { return this.map.GetEnumerator(); } public bool Remove(Version key) { throw this.reject; } public bool Remove(KeyValuePair<Version, Value> item) { throw this.reject; } public bool TryGetValue(Version key, out Value value) { var result = false; value = default(Value); try { value = this.Match(key); result = true; } catch (Exception) { } return result; } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } private Value Match(Version candidate) { var match = new Version(0, 0); var matched = false; foreach (var lowerBound in this.map.Keys) { if (candidate >= lowerBound) { match = lowerBound; matched = true; } else if (match < candidate) { break; } } if (matched) { if (this.openEnd || new List<Version>(this.map.Keys).IndexOf(match) < this.map.Keys.Count - 1) { return this.map[match]; } else { throw this.versionNotFound(candidate, this.map.Keys); } } throw this.versionNotFound(candidate, this.map.Keys); } } }
//Use project level define(s) when referencing with Paket. //#define CSX_ENUM_INTERNAL // Uncomment this to set visibility to internal. //#define CSX_ENUM_REM_STD_FUNC // Uncomment this to remove standard functions. //#define CSX_REM_MAYBE_FUNC // Uncomment this to remove dependency to Maybe.cs. //#define CSX_REM_EXTRA_FUNC // Uncomment this to extra functions. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using LinqEnumerable = System.Linq.Enumerable; namespace CSharpx { #if !CSX_ENUM_INTERNAL public #endif static class EnumerableExtensions { #if !CSX_ENUM_REM_STD_FUNC private static IEnumerable<TSource> AssertCountImpl<TSource>(IEnumerable<TSource> source, int count, Func<int, int, Exception> errorSelector) { var collection = source as ICollection<TSource>; // Optimization for collections if (collection != null) { if (collection.Count != count) throw errorSelector(collection.Count.CompareTo(count), count); return source; } return ExpectingCountYieldingImpl(source, count, errorSelector); } private static IEnumerable<TSource> ExpectingCountYieldingImpl<TSource>(IEnumerable<TSource> source, int count, Func<int, int, Exception> errorSelector) { var iterations = 0; foreach (var element in source) { iterations++; if (iterations > count) { throw errorSelector(1, count); } yield return element; } if (iterations != count) { throw errorSelector(-1, count); } } /// <summary> /// Returns the Cartesian product of two sequences by combining each element of the first set with each in the second /// and applying the user=define projection to the pair. /// </summary> public static IEnumerable<TResult> Cartesian<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector) { if (first == null) throw new ArgumentNullException("first"); if (second == null) throw new ArgumentNullException("second"); if (resultSelector == null) throw new ArgumentNullException("resultSelector"); return from item1 in first from item2 in second // TODO buffer to avoid multiple enumerations select resultSelector(item1, item2); } /// <summary> /// Prepends a single value to a sequence. /// </summary> public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<TSource> source, TSource value) { if (source == null) throw new ArgumentNullException("source"); return LinqEnumerable.Concat(LinqEnumerable.Repeat(value, 1), source); } /// <summary> /// Returns a sequence consisting of the head element and the given tail elements. /// </summary> public static IEnumerable<T> Concat<T>(this T head, IEnumerable<T> tail) { if (tail == null) throw new ArgumentNullException("tail"); return tail.Prepend(head); } /// <summary> /// Returns a sequence consisting of the head elements and the given tail element. /// </summary> public static IEnumerable<T> Concat<T>(this IEnumerable<T> head, T tail) { if (head == null) throw new ArgumentNullException("head"); return LinqEnumerable.Concat(head, LinqEnumerable.Repeat(tail, 1)); } /// <summary> /// Excludes <paramref name="count"/> elements from a sequence starting at a given index /// </summary> /// <typeparam name="T">The type of the elements of the sequence</typeparam> public static IEnumerable<T> Exclude<T>(this IEnumerable<T> sequence, int startIndex, int count) { if (sequence == null) throw new ArgumentNullException("sequence"); if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex"); if (count < 0) throw new ArgumentOutOfRangeException("count"); return ExcludeImpl(sequence, startIndex, count); } private static IEnumerable<T> ExcludeImpl<T>(IEnumerable<T> sequence, int startIndex, int count) { var index = -1; var endIndex = startIndex + count; using (var iter = sequence.GetEnumerator()) { // yield the first part of the sequence while (iter.MoveNext() && ++index < startIndex) yield return iter.Current; // skip the next part (up to count items) while (++index < endIndex && iter.MoveNext()) continue; // yield the remainder of the sequence while (iter.MoveNext()) yield return iter.Current; } } /// <summary> /// Returns a sequence of <see cref="KeyValuePair{TKey,TValue}"/> /// where the key is the zero-based index of the value in the source /// sequence. /// </summary> public static IEnumerable<KeyValuePair<int, TSource>> Index<TSource>(this IEnumerable<TSource> source) { return source.Index(0); } /// <summary> /// Returns a sequence of <see cref="KeyValuePair{TKey,TValue}"/> /// where the key is the index of the value in the source sequence. /// An additional parameter specifies the starting index. /// </summary> public static IEnumerable<KeyValuePair<int, TSource>> Index<TSource>(this IEnumerable<TSource> source, int startIndex) { return source.Select((item, index) => new KeyValuePair<int, TSource>(startIndex + index, item)); } /// <summary> /// Returns the result of applying a function to a sequence of /// 1 element. /// </summary> public static TResult Fold<T, TResult>(this IEnumerable<T> source, Func<T, TResult> folder) { return FoldImpl(source, 1, folder, null, null, null); } /// <summary> /// Returns the result of applying a function to a sequence of /// 2 elements. /// </summary> public static TResult Fold<T, TResult>(this IEnumerable<T> source, Func<T, T, TResult> folder) { return FoldImpl(source, 2, null, folder, null, null); } /// <summary> /// Returns the result of applying a function to a sequence of /// 3 elements. /// </summary> public static TResult Fold<T, TResult>(this IEnumerable<T> source, Func<T, T, T, TResult> folder) { return FoldImpl(source, 3, null, null, folder, null); } /// <summary> /// Returns the result of applying a function to a sequence of /// 4 elements. /// </summary> public static TResult Fold<T, TResult>(this IEnumerable<T> source, Func<T, T, T, T, TResult> folder) { return FoldImpl(source, 4, null, null, null, folder); } static TResult FoldImpl<T, TResult>(IEnumerable<T> source, int count, Func<T, TResult> folder1, Func<T, T, TResult> folder2, Func<T, T, T, TResult> folder3, Func<T, T, T, T, TResult> folder4) { if (source == null) throw new ArgumentNullException("source"); if (count == 1 && folder1 == null || count == 2 && folder2 == null || count == 3 && folder3 == null || count == 4 && folder4 == null) { // ReSharper disable NotResolvedInText throw new ArgumentNullException("folder"); // ReSharper restore NotResolvedInText } var elements = new T[count]; foreach (var e in AssertCountImpl(source.Index(), count, OnFolderSourceSizeErrorSelector)) elements[e.Key] = e.Value; switch (count) { case 1: return folder1(elements[0]); case 2: return folder2(elements[0], elements[1]); case 3: return folder3(elements[0], elements[1], elements[2]); case 4: return folder4(elements[0], elements[1], elements[2], elements[3]); default: throw new NotSupportedException(); } } static readonly Func<int, int, Exception> OnFolderSourceSizeErrorSelector = OnFolderSourceSizeError; static Exception OnFolderSourceSizeError(int cmp, int count) { var message = cmp < 0 ? "Sequence contains too few elements when exactly {0} {1} expected." : "Sequence contains too many elements when exactly {0} {1} expected."; return new Exception(string.Format(message, count.ToString("N0"), count == 1 ? "was" : "were")); } /// <summary> /// Immediately executes the given action on each element in the source sequence. /// </summary> /// <typeparam name="T">The type of the elements in the sequence</typeparam> public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) { if (source == null) throw new ArgumentNullException("source"); if (action == null) throw new ArgumentNullException("action"); foreach (var element in source) { action(element); } } /// <summary> /// Returns a sequence resulting from applying a function to each /// element in the source sequence and its /// predecessor, with the exception of the first element which is /// only returned as the predecessor of the second element. /// </summary> public static IEnumerable<TResult> Pairwise<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TSource, TResult> resultSelector) { if (source == null) throw new ArgumentNullException("source"); if (resultSelector == null) throw new ArgumentNullException("resultSelector"); return PairwiseImpl(source, resultSelector); } private static IEnumerable<TResult> PairwiseImpl<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TSource, TResult> resultSelector) { Debug.Assert(source != null); Debug.Assert(resultSelector != null); using (var e = source.GetEnumerator()) { if (!e.MoveNext()) yield break; var previous = e.Current; while (e.MoveNext()) { yield return resultSelector(previous, e.Current); previous = e.Current; } } } /// <summary> /// Creates a delimited string from a sequence of values. The /// delimiter used depends on the current culture of the executing thread. /// </summary> public static string ToDelimitedString<TSource>(this IEnumerable<TSource> source) { return ToDelimitedString(source, null); } /// <summary> /// Creates a delimited string from a sequence of values and /// a given delimiter. /// </summary> public static string ToDelimitedString<TSource>(this IEnumerable<TSource> source, string delimiter) { if (source == null) throw new ArgumentNullException("source"); return ToDelimitedStringImpl(source, delimiter, (sb, e) => sb.Append(e)); } static string ToDelimitedStringImpl<T>(IEnumerable<T> source, string delimiter, Func<StringBuilder, T, StringBuilder> append) { Debug.Assert(source != null); Debug.Assert(append != null); delimiter = delimiter ?? CultureInfo.CurrentCulture.TextInfo.ListSeparator; var sb = new StringBuilder(); var i = 0; foreach (var value in source) { if (i++ > 0) sb.Append(delimiter); append(sb, value); } return sb.ToString(); } #endif #if !CSX_REM_MAYBE_FUNC /// <summary> /// Safe function that returns Just(first element) or None. /// </summary> public static Maybe<T> TryHead<T>(this IEnumerable<T> source) { using (var e = source.GetEnumerator()) { return e.MoveNext() ? Maybe.Just(e.Current) : Maybe.Nothing<T>(); } } /// <summary> /// Turns an empty sequence to Nothing, otherwise Just(sequence). /// </summary> public static Maybe<IEnumerable<T>> ToMaybe<T>(this IEnumerable<T> source) { using (var e = source.GetEnumerator()) { return e.MoveNext() ? Maybe.Just(source) : Maybe.Nothing<IEnumerable<T>>(); } } #endif #if !CSX_REM_EXTRA_FUNC /// <summary> /// Return everything except first element and throws exception if empty. /// </summary> public static IEnumerable<T> Tail<T>(this IEnumerable<T> source) { using (var e = source.GetEnumerator()) { if (e.MoveNext()) while (e.MoveNext()) yield return e.Current; else throw new ArgumentException("Source sequence cannot be empty.", "source"); } } /// <summary> /// Return everything except first element without throwing exception if empty. /// </summary> public static IEnumerable<T> TailNoFail<T>(this IEnumerable<T> source) { using (var e = source.GetEnumerator()) { if (e.MoveNext()) while (e.MoveNext()) yield return e.Current; } } /// <summary> /// Captures current state of a sequence. /// </summary> public static IEnumerable<T> Memorize<T>(this IEnumerable<T> source) { return source.GetType().IsArray ? source : source.ToArray(); } /// <summary> /// Creates an immutable copy of a sequence. /// </summary> public static IEnumerable<T> Materialize<T>(this IEnumerable<T> source) { if (source is MaterializedEnumerable<T> || source.GetType().IsArray) { return source; } return new MaterializedEnumerable<T>(source); } private class MaterializedEnumerable<T> : IEnumerable<T> { private readonly ICollection<T> inner; public MaterializedEnumerable(IEnumerable<T> enumerable) { inner = enumerable as ICollection<T> ?? enumerable.ToArray(); } public IEnumerator<T> GetEnumerator() { return inner.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } #endif } }
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 MusicStoreServices.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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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.ActionDescriptor.ReturnType; 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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [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 RSG.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using Serilog; using Serilog.Events; using System.IO; using RSG.Scene.Query; using Newtonsoft.Json; using RSG.UnityApp.Internal; namespace RSG { /// <summary> /// Singleton application class. Used AppInit to bootstrap in a Unity scene. /// </summary> public interface IApp { /// <summary> /// Get the factory instance. /// </summary> IFactory Factory { get; } /// <summary> /// Global logger. /// </summary> RSG.Utils.ILogger Logger { get; } /// <summary> /// Used to schedule code onto the main thread. /// </summary> IDispatcher Dispatcher { get; } /// <summary> /// Get the global promise timer. /// </summary> IPromiseTimer PromiseTimer { get; } /// <summary> /// Global singleton manager. /// </summary> ISingletonManager SingletonManager { get; } /// <summary> /// The name of the device assigned by the application. /// </summary> void SetDeviceName(string newDeviceName); } /// <summary> /// Singleton application class. Used AppInit to bootstrap in a Unity scene. /// </summary> public class App : IApp { /// <summary> /// Instance ID for the application. Used to differentuate logs from different runs of the app. /// </summary> public static readonly string AppInstanceID = Guid.NewGuid().ToString(); /// <summary> /// Name of the game object automatically added to the scene that handles events on behalf of the app. /// </summary> public static readonly string AppHubObjectName = "_AppHub"; /// <summary> /// Accessor for the singleton app instance. /// </summary> public static IApp Instance { get; private set; } /// <summary> /// The path to where persistant device info is stored. /// </summary> private string DeviceInfoFilePath { get { return Path.Combine(Application.persistentDataPath, "DeviceInfo.json"); } } /// <summary> /// The path to where log configuration is stored. /// </summary> private string LogConfigFilePath { get { #if UNITY_ANDROID return Path.Combine(Application.persistentDataPath, "LogInfo.json"); #else return Path.Combine(Application.dataPath, "LogInfo.json"); #endif } } /// <summary> /// Path where the 'running file' is saved. This is a file that is present when the app is running and /// allows unclean shutdown to be detected. /// </summary> private string AppRunningFilePath { get { return Path.Combine(Application.persistentDataPath, "AppRunning.json"); } } /// <summary> /// Unique identifier that for this device. /// This is generated on first run and then persisted from instance-to-instance of the app. /// </summary> public static Guid DeviceID { get; private set; } /// <summary> /// A name for the device. This name can be assigned by the app, although it defaults to the device ID. /// </summary> public static string DeviceName { get; private set; } /// <summary> /// Initialize the app. Can be called multiple times. /// </summary> public static void Init() { if (Instance != null) { // Already initialised. return; } var app = new App(); Instance = app; app.InitSingletons(); } /// <summary> /// Resolve dependencies on a specific object, first ensuring that the application has been initialized. /// </summary> public static void ResolveDependencies(object obj) { Argument.NotNull(() => obj); Init(); Instance.Factory.ResolveDependencies(obj); } public App() { InitDeviceId(); var reflection = new Reflection(); var logConfig = LoadLogConfig(); var logger = new SerilogLogger(logConfig, reflection); var factory = new Factory("App", logger, reflection); factory.Dep<IApp>(this); factory.Dep<RSG.Utils.ILogger>(logger); var dispatcher = new Dispatcher(logger); this.Dispatcher = dispatcher; factory.Dep<IDispatcher>(dispatcher); factory.Dep<IDispatchQueue>(dispatcher); factory.Dep<ISceneQuery>(new SceneQuery()); factory.Dep<ISceneTraversal>(new SceneTraversal()); this.PromiseTimer = new PromiseTimer(); factory.Dep<IPromiseTimer>(this.PromiseTimer); var factoryLogger = new FactoryLogger(logger, logConfig.FactoryLogPath); this.SingletonManager = InitFactory(factoryLogger, factory, reflection); this.Factory = factory; this.Logger = factory.ResolveDep<RSG.Utils.ILogger>(); InitRunningFile(); } private void InitSingletons() { SingletonManager.InstantiateSingletons(Factory); SingletonManager.Startup(); var taskManager = Factory.ResolveDep<ITaskManager>(); SingletonManager.Singletons.ForType((IUpdatable u) => taskManager.RegisterUpdatable(u)); SingletonManager.Singletons.ForType((IRenderable r) => taskManager.RegisterRenderable(r)); SingletonManager.Singletons.ForType((IEndOfFrameUpdatable u) => taskManager.RegisterEndOfFrameUpdatable(u)); SingletonManager.Singletons.ForType((ILateUpdatable u) => taskManager.RegisterLateUpdatable(u)); var appHub = InitAppHub(); appHub.Shutdown = () => { SingletonManager.Shutdown(); SingletonManager.Singletons.ForType((IUpdatable u) => taskManager.UnregisterUpdatable(u)); SingletonManager.Singletons.ForType((IRenderable r) => taskManager.UnregisterRenderable(r)); SingletonManager.Singletons.ForType((IEndOfFrameUpdatable u) => taskManager.UnregisterEndOfFrameUpdatable(u)); SingletonManager.Singletons.ForType((ILateUpdatable u) => taskManager.UnregisterLateUpdatable(u)); DeleteRunningFile(); }; } /// <summary> /// Used to serialize details of the running app. /// </summary> private class AppRunning { /// <summary> /// The instance of the app that is running. /// </summary> public string AppInstance; /// <summary> /// The date the app started running at. /// </summary> public DateTime StartedAt; } /// <summary> /// Initialise a file that is present while the app is running. /// We use this to detect an unclean shutodwn on the next app instance. /// </summary> private void InitRunningFile() { if (File.Exists(AppRunningFilePath)) { try { var previousAppRunning = JsonConvert.DeserializeObject<AppRunning>(File.ReadAllText(AppRunningFilePath)); Logger.LogError("Unclean shutdown detected from previous application instance {PrevAppInstanceID} which started at {AppStartDate}", previousAppRunning.AppInstance, previousAppRunning.StartedAt); } catch (Exception ex) { Logger.LogError(ex, "Unclean shutdown detected from previous application instance, was unable to read 'running file' from {AppRunningFilePath}", AppRunningFilePath); } } try { File.WriteAllText(AppRunningFilePath, JsonConvert.SerializeObject( new AppRunning() { AppInstance = App.AppInstanceID, StartedAt = DateTime.Now } ) ); } catch (Exception ex) { Logger.LogError(ex, "Failed to save 'running file'."); } } /// <summary> /// Delete the file that is present while the app is running. /// This only happens on clean shutdown. /// </summary> private void DeleteRunningFile() { try { File.Delete(AppRunningFilePath); } catch (Exception ex) { Logger.LogError(ex, "Failed to delete 'running file' at {AppRunningFilePath}", AppRunningFilePath); } } /// <summary> /// Used for serializing persistent app info. /// </summary> private class DeviceInfo { /// <summary> /// Unique ID for the device. /// </summary> public Guid DeviceID; /// <summary> /// A name that can be assigned to the device (defaults to the ID). /// </summary> public string DeviceName; } /// <summary> /// Initialise an ID for the device the app is running. /// This allows each device to be uniquely identified. /// </summary> private void InitDeviceId() { if (LoadDeviceId()) { // Loaded previously saved device id. return; } // No device info was loaded. // Create a new device ID. var deviceID = Guid.NewGuid(); App.DeviceID = deviceID; App.DeviceName = string.Empty; Debug.Log("Allocated device id " + deviceID); SaveDeviceInfoFile(); } /// <summary> /// The name of the device assigned by the application. /// </summary> public void SetDeviceName(string newDeviceName) { Argument.StringNotNullOrEmpty(() => newDeviceName); App.DeviceName = newDeviceName; SaveDeviceInfoFile(); } /// <summary> /// Save the device info file to persistant data. /// </summary> private void SaveDeviceInfoFile() { try { // Serialize device ID, etc, to be remembered at next app instance. File.WriteAllText(DeviceInfoFilePath, JsonConvert.SerializeObject( new DeviceInfo() { DeviceID = App.DeviceID, DeviceName = App.DeviceName } ) ); } catch (Exception ex) { Debug.LogError("Failed to save DeviceInfo file: " + DeviceInfoFilePath); Debug.LogException(ex); } } /// <summary> /// Load device ID from the device info file. /// Returns false if the file doesn't exist or failes to load /// </summary> private bool LoadDeviceId() { // // Load device ID. // if (!File.Exists(DeviceInfoFilePath)) { return false; } Debug.Log("Loading device info file: " + DeviceInfoFilePath); try { var deviceInfo = JsonConvert.DeserializeObject<DeviceInfo>(File.ReadAllText(DeviceInfoFilePath)); App.DeviceID = deviceInfo.DeviceID; App.DeviceName = deviceInfo.DeviceName; return true; } catch (Exception ex) { Debug.LogError("Failed to load DeviceInfo file: " + DeviceInfoFilePath); Debug.LogException(ex); return false; } } /// <summary> /// Load logger configuration from a file. /// </summary> private LogConfig LoadLogConfig() { // // Load log configuration. // if (!File.Exists(LogConfigFilePath)) { return new LogConfig(); } Debug.Log("Loading log configuration file: " + LogConfigFilePath); try { return JsonConvert.DeserializeObject<LogConfig>(File.ReadAllText(LogConfigFilePath)); } catch (Exception ex) { Debug.LogError("Failed to load log configuration file: " + LogConfigFilePath); Debug.LogException(ex); return new LogConfig(); } } /// <summary> /// Helper function to initalize the factory. /// </summary> private static SingletonManager InitFactory(Utils.ILogger logger, Factory factory, IReflection reflection) { //todo: all this code should merge into RSG.Factory. factory.AutoRegisterTypes(); var singletonManager = new SingletonManager(logger, factory); factory.Dep(reflection); factory.AddDependencyProvider(singletonManager); var singletonScanner = new SingletonScanner(reflection, logger, singletonManager); singletonScanner.ScanSingletonTypes(); return singletonManager; } /// <summary> /// Helper function to initalize the app hub. /// </summary> private static AppHub InitAppHub() { var appHubGO = GameObject.Find(AppHubObjectName); if (appHubGO == null) { appHubGO = new GameObject(AppHubObjectName); GameObject.DontDestroyOnLoad(appHubGO); } var appHub = appHubGO.GetComponent<AppHub>(); if (appHub == null) { appHub = appHubGO.AddComponent<AppHub>(); } return appHub; } /// <summary> /// Get the factory instance. /// </summary> public IFactory Factory { get; private set; } /// <summary> /// Global logger. /// </summary> public RSG.Utils.ILogger Logger { get; private set; } /// <summary> /// Used to schedule code onto the main thread. /// </summary> public IDispatcher Dispatcher { get; private set; } /// <summary> /// Get the global promise timer. /// </summary> public IPromiseTimer PromiseTimer { get; private set; } /// <summary> /// Global singleton manager. /// </summary> public ISingletonManager SingletonManager { get; private set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace System.Transactions { internal delegate void FinishVolatileDelegate(InternalEnlistment enlistment); // Base class for all volatile enlistment states internal abstract class VolatileEnlistmentState : EnlistmentState { private static VolatileEnlistmentActive s_volatileEnlistmentActive; private static VolatileEnlistmentPreparing s_volatileEnlistmentPreparing; private static VolatileEnlistmentPrepared s_volatileEnlistmentPrepared; private static VolatileEnlistmentSPC s_volatileEnlistmentSPC; private static VolatileEnlistmentPreparingAborting s_volatileEnlistmentPreparingAborting; private static VolatileEnlistmentAborting s_volatileEnlistmentAborting; private static VolatileEnlistmentCommitting s_volatileEnlistmentCommitting; private static VolatileEnlistmentInDoubt s_volatileEnlistmentInDoubt; private static VolatileEnlistmentEnded s_volatileEnlistmentEnded; private static VolatileEnlistmentDone s_volatileEnlistmentDone; // Object for synchronizing access to the entire class( avoiding lock( typeof( ... )) ) private static object s_classSyncObject; internal static VolatileEnlistmentActive VolatileEnlistmentActive => LazyInitializer.EnsureInitialized(ref s_volatileEnlistmentActive, ref s_classSyncObject, () => new VolatileEnlistmentActive()); protected static VolatileEnlistmentPreparing VolatileEnlistmentPreparing => LazyInitializer.EnsureInitialized(ref s_volatileEnlistmentPreparing, ref s_classSyncObject, () => new VolatileEnlistmentPreparing()); protected static VolatileEnlistmentPrepared VolatileEnlistmentPrepared => LazyInitializer.EnsureInitialized(ref s_volatileEnlistmentPrepared, ref s_classSyncObject, () => new VolatileEnlistmentPrepared()); protected static VolatileEnlistmentSPC VolatileEnlistmentSPC => LazyInitializer.EnsureInitialized(ref s_volatileEnlistmentSPC, ref s_classSyncObject, () => new VolatileEnlistmentSPC()); protected static VolatileEnlistmentPreparingAborting VolatileEnlistmentPreparingAborting => LazyInitializer.EnsureInitialized(ref s_volatileEnlistmentPreparingAborting, ref s_classSyncObject, () => new VolatileEnlistmentPreparingAborting()); protected static VolatileEnlistmentAborting VolatileEnlistmentAborting => LazyInitializer.EnsureInitialized(ref s_volatileEnlistmentAborting, ref s_classSyncObject, () => new VolatileEnlistmentAborting()); protected static VolatileEnlistmentCommitting VolatileEnlistmentCommitting => LazyInitializer.EnsureInitialized(ref s_volatileEnlistmentCommitting, ref s_classSyncObject, () => new VolatileEnlistmentCommitting()); protected static VolatileEnlistmentInDoubt VolatileEnlistmentInDoubt => LazyInitializer.EnsureInitialized(ref s_volatileEnlistmentInDoubt, ref s_classSyncObject, () => new VolatileEnlistmentInDoubt()); protected static VolatileEnlistmentEnded VolatileEnlistmentEnded => LazyInitializer.EnsureInitialized(ref s_volatileEnlistmentEnded, ref s_classSyncObject, () => new VolatileEnlistmentEnded()); protected static VolatileEnlistmentDone VolatileEnlistmentDone => LazyInitializer.EnsureInitialized(ref s_volatileEnlistmentDone, ref s_classSyncObject, () => new VolatileEnlistmentDone()); // Override of get_RecoveryInformation to be more specific with the exception string. internal override byte[] RecoveryInformation(InternalEnlistment enlistment) { throw TransactionException.CreateInvalidOperationException(TraceSourceType.TraceSourceLtm, SR.VolEnlistNoRecoveryInfo, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId); } } // Active state for a volatile enlistment indicates that the enlistment has been created // but no one has begun committing or aborting the transaction. From this state the enlistment // can abort the transaction or call read only to indicate that it does not want to // participate further in the transaction. internal class VolatileEnlistmentActive : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; // Yeah it's active. } #region IEnlistment Related Events internal override void EnlistmentDone(InternalEnlistment enlistment) { // End this enlistment VolatileEnlistmentDone.EnterState(enlistment); // Note another enlistment finished. enlistment.FinishEnlistment(); } #endregion #region State Change Events internal override void ChangeStatePreparing(InternalEnlistment enlistment) { VolatileEnlistmentPreparing.EnterState(enlistment); } internal override void ChangeStateSinglePhaseCommit(InternalEnlistment enlistment) { VolatileEnlistmentSPC.EnterState(enlistment); } #endregion #region Internal Events internal override void InternalAborted(InternalEnlistment enlistment) { // Change the enlistment state to aborting. VolatileEnlistmentAborting.EnterState(enlistment); } #endregion } // Preparing state is the time after prepare has been called but no response has been received. internal class VolatileEnlistmentPreparing : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; Monitor.Exit(enlistment.Transaction); try // Don't hold this lock while calling into the application code. { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.EnlistmentStatus(enlistment, NotificationCall.Prepare); } enlistment.EnlistmentNotification.Prepare(enlistment.PreparingEnlistment); } finally { Monitor.Enter(enlistment.Transaction); } } internal override void EnlistmentDone(InternalEnlistment enlistment) { VolatileEnlistmentDone.EnterState(enlistment); // Process Finished InternalEnlistment enlistment.FinishEnlistment(); } internal override void Prepared(InternalEnlistment enlistment) { // Change the enlistments state to prepared. VolatileEnlistmentPrepared.EnterState(enlistment); // Process Finished InternalEnlistment enlistment.FinishEnlistment(); } // The enlistment says to abort start the abort sequence. internal override void ForceRollback(InternalEnlistment enlistment, Exception e) { // Change enlistment state to aborting VolatileEnlistmentEnded.EnterState(enlistment); // Start the transaction aborting enlistment.Transaction.State.ChangeStateTransactionAborted(enlistment.Transaction, e); // Process Finished InternalEnlistment enlistment.FinishEnlistment(); } internal override void ChangeStatePreparing(InternalEnlistment enlistment) { // If the transaction promotes during phase 0 then the transition to // the promoted phase 0 state for the transaction may cause this // notification to be delivered again. So in this case it should be // ignored. } internal override void InternalAborted(InternalEnlistment enlistment) { VolatileEnlistmentPreparingAborting.EnterState(enlistment); } } // SPC state for a volatile enlistment is the point at which there is exactly 1 enlisment // and it supports SPC. The TM will send a single phase commit to the enlistment and wait // for the response from the TM. internal class VolatileEnlistmentSPC : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { bool spcCommitted = false; // Set the enlistment state enlistment.State = this; // Send Single Phase Commit to the enlistment TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.EnlistmentStatus(enlistment, NotificationCall.SinglePhaseCommit); } Monitor.Exit(enlistment.Transaction); try // Don't hold this lock while calling into the application code. { enlistment.SinglePhaseNotification.SinglePhaseCommit(enlistment.SinglePhaseEnlistment); spcCommitted = true; } finally { if (!spcCommitted) { //If we have an exception thrown in SPC, we don't know the if the enlistment is committed or not //reply indoubt enlistment.SinglePhaseEnlistment.InDoubt(); } Monitor.Enter(enlistment.Transaction); } } internal override void EnlistmentDone(InternalEnlistment enlistment) { VolatileEnlistmentEnded.EnterState(enlistment); enlistment.Transaction.State.ChangeStateTransactionCommitted(enlistment.Transaction); } internal override void Committed(InternalEnlistment enlistment) { VolatileEnlistmentEnded.EnterState(enlistment); enlistment.Transaction.State.ChangeStateTransactionCommitted(enlistment.Transaction); } internal override void Aborted(InternalEnlistment enlistment, Exception e) { VolatileEnlistmentEnded.EnterState(enlistment); enlistment.Transaction.State.ChangeStateTransactionAborted(enlistment.Transaction, e); } internal override void InDoubt(InternalEnlistment enlistment, Exception e) { VolatileEnlistmentEnded.EnterState(enlistment); if (enlistment.Transaction._innerException == null) { enlistment.Transaction._innerException = e; } enlistment.Transaction.State.InDoubtFromEnlistment(enlistment.Transaction); } } // Prepared state for a volatile enlistment is the point at which prepare has been called // and the enlistment has responded prepared. No enlistment operations are valid at this // point. The RM must wait for the TM to take the next action. internal class VolatileEnlistmentPrepared : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; // Wait for Committed } internal override void InternalAborted(InternalEnlistment enlistment) { VolatileEnlistmentAborting.EnterState(enlistment); } internal override void InternalCommitted(InternalEnlistment enlistment) { VolatileEnlistmentCommitting.EnterState(enlistment); } internal override void InternalIndoubt(InternalEnlistment enlistment) { // Change the enlistment state to InDoubt. VolatileEnlistmentInDoubt.EnterState(enlistment); } internal override void ChangeStatePreparing(InternalEnlistment enlistment) { // This would happen in the second pass of a phase 0 wave. } } // Aborting state is when Rollback has been sent to the enlistment. internal class VolatileEnlistmentPreparingAborting : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; } internal override void EnlistmentDone(InternalEnlistment enlistment) { // Move this enlistment to the ended state VolatileEnlistmentEnded.EnterState(enlistment); } internal override void Prepared(InternalEnlistment enlistment) { // The enlistment has respondend so changes it's state to aborting. VolatileEnlistmentAborting.EnterState(enlistment); // Process Finished InternalEnlistment enlistment.FinishEnlistment(); } // The enlistment says to abort start the abort sequence. internal override void ForceRollback(InternalEnlistment enlistment, Exception e) { // Change enlistment state to aborting VolatileEnlistmentEnded.EnterState(enlistment); // Record the exception in the transaction if (enlistment.Transaction._innerException == null) { // Arguably this is the second call to ForceRollback and not the call that // aborted the transaction but just in case. enlistment.Transaction._innerException = e; } // Process Finished InternalEnlistment enlistment.FinishEnlistment(); } internal override void InternalAborted(InternalEnlistment enlistment) { // If this event comes from multiple places just ignore it. Continue // waiting for the enlistment to respond so that we can respond to it. } } // Aborting state is when Rollback has been sent to the enlistment. internal class VolatileEnlistmentAborting : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; Monitor.Exit(enlistment.Transaction); try // Don't hold this lock while calling into the application code. { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.EnlistmentStatus(enlistment, NotificationCall.Rollback); } enlistment.EnlistmentNotification.Rollback(enlistment.SinglePhaseEnlistment); } finally { Monitor.Enter(enlistment.Transaction); } } internal override void ChangeStatePreparing(InternalEnlistment enlistment) { // This enlistment was told to abort before being told to prepare } internal override void EnlistmentDone(InternalEnlistment enlistment) { // Move this enlistment to the ended state VolatileEnlistmentEnded.EnterState(enlistment); } internal override void InternalAborted(InternalEnlistment enlistment) { // Already working on it. } } // Committing state is when Commit has been sent to the enlistment. internal class VolatileEnlistmentCommitting : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; Monitor.Exit(enlistment.Transaction); try // Don't hold this lock while calling into the application code. { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.EnlistmentStatus(enlistment, NotificationCall.Commit); } // Forward the notification to the enlistment enlistment.EnlistmentNotification.Commit(enlistment.Enlistment); } finally { Monitor.Enter(enlistment.Transaction); } } internal override void EnlistmentDone(InternalEnlistment enlistment) { // Move this enlistment to the ended state VolatileEnlistmentEnded.EnterState(enlistment); } } // InDoubt state is for an enlistment that has sent indoubt but has not been responeded to. internal class VolatileEnlistmentInDoubt : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; Monitor.Exit(enlistment.Transaction); try // Don't hold this lock while calling into the application code. { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.EnlistmentStatus(enlistment, NotificationCall.InDoubt); } // Forward the notification to the enlistment enlistment.EnlistmentNotification.InDoubt(enlistment.PreparingEnlistment); } finally { Monitor.Enter(enlistment.Transaction); } } internal override void EnlistmentDone(InternalEnlistment enlistment) { // Move this enlistment to the ended state VolatileEnlistmentEnded.EnterState(enlistment); } } // Ended state is the state that is entered when the transaction has committed, // aborted, or said read only for an enlistment. At this point there are no valid // operations on the enlistment. internal class VolatileEnlistmentEnded : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; // Nothing to do. } internal override void ChangeStatePreparing(InternalEnlistment enlistment) { // This enlistment was told to abort before being told to prepare } internal override void InternalAborted(InternalEnlistment enlistment) { // Ignore this in case the enlistment gets here before // the transaction tells it to do so } internal override void InternalCommitted(InternalEnlistment enlistment) { // Ignore this in case the enlistment gets here before // the transaction tells it to do so } internal override void InternalIndoubt(InternalEnlistment enlistment) { // Ignore this in case the enlistment gets here before // the transaction tells it to do so } internal override void InDoubt(InternalEnlistment enlistment, Exception e) { // Ignore this in case the enlistment gets here before // the transaction tells it to do so } } // At some point either early or late the enlistment responded ReadOnly internal class VolatileEnlistmentDone : VolatileEnlistmentEnded { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; // Nothing to do. } internal override void ChangeStatePreparing(InternalEnlistment enlistment) { enlistment.CheckComplete(); } } }
/* * 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.Data; using System.Reflection; using System.Collections.Generic; using log4net; #if CSharpSqlite using Community.CsharpSqlite.Sqlite; #else using Mono.Data.Sqlite; #endif using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.SQLite { /// <summary> /// An asset storage interface for the SQLite database system /// </summary> public class SQLiteAssetData : AssetDataBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const string SelectAssetSQL = "select * from assets where UUID=:UUID"; private const string SelectAssetMetadataSQL = "select Name, Description, Type, Temporary, asset_flags, UUID, CreatorID from assets limit :start, :count"; private const string DeleteAssetSQL = "delete from assets where UUID=:UUID"; private const string InsertAssetSQL = "insert into assets(UUID, Name, Description, Type, Local, Temporary, asset_flags, CreatorID, Data) values(:UUID, :Name, :Description, :Type, :Local, :Temporary, :Flags, :CreatorID, :Data)"; private const string UpdateAssetSQL = "update assets set Name=:Name, Description=:Description, Type=:Type, Local=:Local, Temporary=:Temporary, asset_flags=:Flags, CreatorID=:CreatorID, Data=:Data where UUID=:UUID"; private const string assetSelect = "select * from assets"; private SqliteConnection m_conn; protected virtual Assembly Assembly { get { return GetType().Assembly; } } override public void Dispose() { if (m_conn != null) { m_conn.Close(); m_conn = null; } } /// <summary> /// <list type="bullet"> /// <item>Initialises AssetData interface</item> /// <item>Loads and initialises a new SQLite connection and maintains it.</item> /// <item>use default URI if connect string is empty.</item> /// </list> /// </summary> /// <param name="dbconnect">connect string</param> override public void Initialise(string dbconnect) { if (Util.IsWindows()) Util.LoadArchSpecificWindowsDll("sqlite3.dll"); if (dbconnect == string.Empty) { dbconnect = "URI=file:Asset.db,version=3"; } m_conn = new SqliteConnection(dbconnect); m_conn.Open(); Migration m = new Migration(m_conn, Assembly, "AssetStore"); m.Update(); return; } /// <summary> /// Fetch Asset /// </summary> /// <param name="uuid">UUID of ... ?</param> /// <returns>Asset base</returns> override public AssetBase GetAsset(UUID uuid) { lock (this) { using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); using (IDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { AssetBase asset = buildAsset(reader); reader.Close(); return asset; } else { reader.Close(); return null; } } } } } /// <summary> /// Create an asset /// </summary> /// <param name="asset">Asset Base</param> override public void StoreAsset(AssetBase asset) { string assetName = asset.Name; if (asset.Name.Length > AssetBase.MAX_ASSET_NAME) { assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME); m_log.WarnFormat( "[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add", asset.Name, asset.ID, asset.Name.Length, assetName.Length); } string assetDescription = asset.Description; if (asset.Description.Length > AssetBase.MAX_ASSET_DESC) { assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC); m_log.WarnFormat( "[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add", asset.Description, asset.ID, asset.Description.Length, assetDescription.Length); } //m_log.Info("[ASSET DB]: Creating Asset " + asset.FullID.ToString()); if (AssetsExist(new[] { asset.FullID })[0]) { //LogAssetLoad(asset); lock (this) { using (SqliteCommand cmd = new SqliteCommand(UpdateAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString())); cmd.Parameters.Add(new SqliteParameter(":Name", assetName)); cmd.Parameters.Add(new SqliteParameter(":Description", assetDescription)); cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type)); cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local)); cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary)); cmd.Parameters.Add(new SqliteParameter(":Flags", asset.Flags)); cmd.Parameters.Add(new SqliteParameter(":CreatorID", asset.Metadata.CreatorID)); cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data)); cmd.ExecuteNonQuery(); } } } else { lock (this) { using (SqliteCommand cmd = new SqliteCommand(InsertAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString())); cmd.Parameters.Add(new SqliteParameter(":Name", assetName)); cmd.Parameters.Add(new SqliteParameter(":Description", assetDescription)); cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type)); cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local)); cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary)); cmd.Parameters.Add(new SqliteParameter(":Flags", asset.Flags)); cmd.Parameters.Add(new SqliteParameter(":CreatorID", asset.Metadata.CreatorID)); cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data)); cmd.ExecuteNonQuery(); } } } } // /// <summary> // /// Some... logging functionnality // /// </summary> // /// <param name="asset"></param> // private static void LogAssetLoad(AssetBase asset) // { // string temporary = asset.Temporary ? "Temporary" : "Stored"; // string local = asset.Local ? "Local" : "Remote"; // // int assetLength = (asset.Data != null) ? asset.Data.Length : 0; // // m_log.Debug("[ASSET DB]: " + // string.Format("Loaded {5} {4} Asset: [{0}][{3}] \"{1}\":{2} ({6} bytes)", // asset.FullID, asset.Name, asset.Description, asset.Type, // temporary, local, assetLength)); // } /// <summary> /// Check if the assets exist in the database. /// </summary> /// <param name="uuids">The assets' IDs</param> /// <returns>For each asset: true if it exists, false otherwise</returns> public override bool[] AssetsExist(UUID[] uuids) { if (uuids.Length == 0) return new bool[0]; HashSet<UUID> exist = new HashSet<UUID>(); string ids = "'" + string.Join("','", uuids) + "'"; string sql = string.Format("select UUID from assets where UUID in ({0})", ids); lock (this) { using (SqliteCommand cmd = new SqliteCommand(sql, m_conn)) { using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { UUID id = new UUID((string)reader["UUID"]); exist.Add(id); } } } } bool[] results = new bool[uuids.Length]; for (int i = 0; i < uuids.Length; i++) results[i] = exist.Contains(uuids[i]); return results; } /// <summary> /// /// </summary> /// <param name="row"></param> /// <returns></returns> private static AssetBase buildAsset(IDataReader row) { // TODO: this doesn't work yet because something more // interesting has to be done to actually get these values // back out. Not enough time to figure it out yet. AssetBase asset = new AssetBase( new UUID((String)row["UUID"]), (String)row["Name"], Convert.ToSByte(row["Type"]), (String)row["CreatorID"] ); asset.Description = (String) row["Description"]; asset.Local = Convert.ToBoolean(row["Local"]); asset.Temporary = Convert.ToBoolean(row["Temporary"]); asset.Flags = (AssetFlags)Convert.ToInt32(row["asset_flags"]); asset.Data = (byte[])row["Data"]; return asset; } private static AssetMetadata buildAssetMetadata(IDataReader row) { AssetMetadata metadata = new AssetMetadata(); metadata.FullID = new UUID((string) row["UUID"]); metadata.Name = (string) row["Name"]; metadata.Description = (string) row["Description"]; metadata.Type = Convert.ToSByte(row["Type"]); metadata.Temporary = Convert.ToBoolean(row["Temporary"]); // Not sure if this is correct. metadata.Flags = (AssetFlags)Convert.ToInt32(row["asset_flags"]); metadata.CreatorID = row["CreatorID"].ToString(); // Current SHA1s are not stored/computed. metadata.SHA1 = new byte[] {}; return metadata; } /// <summary> /// Returns a list of AssetMetadata objects. The list is a subset of /// the entire data set offset by <paramref name="start" /> containing /// <paramref name="count" /> elements. /// </summary> /// <param name="start">The number of results to discard from the total data set.</param> /// <param name="count">The number of rows the returned list should contain.</param> /// <returns>A list of AssetMetadata objects.</returns> public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count) { List<AssetMetadata> retList = new List<AssetMetadata>(count); lock (this) { using (SqliteCommand cmd = new SqliteCommand(SelectAssetMetadataSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":start", start)); cmd.Parameters.Add(new SqliteParameter(":count", count)); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { AssetMetadata metadata = buildAssetMetadata(reader); retList.Add(metadata); } } } } return retList; } /*********************************************************************** * * Database Binding functions * * These will be db specific due to typing, and minor differences * in databases. * **********************************************************************/ #region IPlugin interface /// <summary> /// /// </summary> override public string Version { get { Module module = GetType().Module; // string dllName = module.Assembly.ManifestModule.Name; Version dllVersion = module.Assembly.GetName().Version; return string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, dllVersion.Revision); } } /// <summary> /// Initialise the AssetData interface using default URI /// </summary> override public void Initialise() { Initialise("URI=file:Asset.db,version=3"); } /// <summary> /// Name of this DB provider /// </summary> override public string Name { get { return "SQLite Asset storage engine"; } } // TODO: (AlexRa): one of these is to be removed eventually (?) /// <summary> /// Delete an asset from database /// </summary> /// <param name="uuid"></param> public bool DeleteAsset(UUID uuid) { lock (this) { using (SqliteCommand cmd = new SqliteCommand(DeleteAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); cmd.ExecuteNonQuery(); } } return true; } public override bool Delete(string id) { UUID assetID; if (!UUID.TryParse(id, out assetID)) return false; return DeleteAsset(assetID); } #endregion } }
/* * A custom task that walks a directory tree and creates a WiX fragment containing * components to recreate it in an installer. * * From John Hall <john.hall@xjtag.com>, originally named "PackageTree" and posted on the wix-users mailing list * * John Hatton modified a bit to make it more general and started cleaning it up. * * Places a "".guidsForInstaller.xml" in each directory. THIS SHOULD BE CHECKED INTO VERSION CONTROL. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Xml; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace SIL.BuildTasks.MakeWixForDirTree { public class MakeWixForDirTree : Task, ILogger { static public string kFileNameOfGuidDatabase = ".guidsForInstaller.xml"; #region Private data private string _rootDir; private string _outputFilePath; private string[] _filesAndDirsToExclude = null; private Regex _fileMatchPattern = new Regex(@".*"); private Regex _ignoreFilePattern = new Regex(@"IGNOREME"); private string _installerSourceDirectory; //todo: this should just be a list private Dictionary<string, string> m_exclude = new Dictionary<string, string>(); private bool m_checkOnly = false; private List<string> m_components = new List<string>(); private Dictionary<string, int> m_suffixes = new Dictionary<string, int>(); private DateTime m_refDate = DateTime.MinValue; private bool m_filesChanged = false; private bool _hasLoggedErrors=false; private string _directoryReferenceId; private string _componentGroupId; private bool _giveAllPermissions; private const string XMLNS = "http://schemas.microsoft.com/wix/2006/wi"; #endregion #region Public members [Required] public string RootDirectory { get { return _rootDir; } set { _rootDir = value; } } /// <summary> /// Subfolders and files to exclude. Kinda wonky. Using Ignore makes more sense. /// </summary> public string[] Exclude { get { return _filesAndDirsToExclude; } set { _filesAndDirsToExclude = value; } } /// <summary> /// Allow normal non-administrators to write and delete the files /// </summary> public bool GiveAllPermissions { get { return _giveAllPermissions; } set { _giveAllPermissions = value; } } /* * Regex pattern to match files. Defaults to .* */ public string MatchRegExPattern { get { return _fileMatchPattern.ToString(); } set { _fileMatchPattern = new Regex(value, RegexOptions.IgnoreCase); } } /// <summary> /// Will exclude if either the filename or the full path matches the expression. /// </summary> public string IgnoreRegExPattern { get { return _ignoreFilePattern.ToString(); } set { _ignoreFilePattern = new Regex(value, RegexOptions.IgnoreCase); } } /// <summary> /// Whether to just check that all the metadata is uptodate or not. If this is true then no file is output. /// </summary> public bool CheckOnly { get { return m_checkOnly; } set { m_checkOnly = value; } } /// <summary> /// Directory where the installer source (.wixproj) is located. /// If provided, is used to determine relative path of the components /// </summary> public string InstallerSourceDirectory { get { return _installerSourceDirectory; } set { _installerSourceDirectory = value; } } [Output, Required] public string OutputFilePath { get { return _outputFilePath; } set { _outputFilePath = value; } } public override bool Execute() { if (!Directory.Exists(_rootDir)) { LogError("Directory not found: " + _rootDir); return false; } LogMessage(MessageImportance.High, "Creating Wix fragment for " + _rootDir); //make it an absolute path _outputFilePath = Path.GetFullPath(_outputFilePath); if (!string.IsNullOrEmpty(_installerSourceDirectory)) _installerSourceDirectory = Path.GetFullPath(_installerSourceDirectory); /* hatton removed this... it would leave deleted files referenced in the wxs file if (File.Exists(_outputFilePath)) { DateTime curFileDate = File.GetLastWriteTime(_outputFilePath); m_refDate = curFileDate; // if this assembly has been modified since the existing file was created then // force the output to be updated Assembly thisAssembly = Assembly.GetExecutingAssembly(); DateTime assemblyTime = File.GetLastWriteTime(thisAssembly.Location); if (assemblyTime > curFileDate) m_filesChanged = true; } */ //instead, start afresh every time. if(File.Exists(_outputFilePath)) { File.Delete(_outputFilePath); } SetupExclusions(); try { XmlDocument doc = new XmlDocument(); XmlElement elemWix = doc.CreateElement("Wix", XMLNS); doc.AppendChild(elemWix); XmlElement elemFrag = doc.CreateElement("Fragment", XMLNS); elemWix.AppendChild(elemFrag); XmlElement elemDirRef = doc.CreateElement("DirectoryRef", XMLNS); elemDirRef.SetAttribute("Id", DirectoryReferenceId); elemFrag.AppendChild(elemDirRef); // recurse through the tree add elements ProcessDir(elemDirRef, Path.GetFullPath(_rootDir), DirectoryReferenceId); // write out components into a group XmlElement elemGroup = doc.CreateElement("ComponentGroup", XMLNS); elemGroup.SetAttribute("Id", _componentGroupId); elemFrag.AppendChild(elemGroup); AddComponentRefsToDom(doc, elemGroup); WriteDomToFile(doc); } catch (IOException e) { LogErrorFromException(e); return false; } return !HasLoggedErrors; } /// <summary> /// Though the guid-tracking *should* get stuff uninstalled, sometimes it does. So as an added precaution, delete the files on install and uninstall. /// Note that the *.* here should uninstall even files that were in the previous install but not this one. /// </summary> /// <param name="elemFrag"></param> private void InsertFileDeletionInstruction(XmlElement elemFrag) { //awkwardly, wix only allows this in <component>, not <directory>. Further, the directory deletion equivalent (RemoveFolder) can only delete completely empty folders. var node = elemFrag.OwnerDocument.CreateElement("RemoveFile", XMLNS); node.SetAttribute("Id", "_"+Guid.NewGuid().ToString().Replace("-","")); node.SetAttribute("On", "both");//both = install time and uninstall time "uninstall"); node.SetAttribute("Name", "*.*"); elemFrag.AppendChild(node); } private void WriteDomToFile(XmlDocument doc) { // write the XML out onlystringles have been modified if (!m_checkOnly && m_filesChanged) { var settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = " "; settings.Encoding = Encoding.UTF8; using (var xmlWriter = XmlWriter.Create(_outputFilePath, settings)) { doc.WriteTo(xmlWriter); } } } private void AddComponentRefsToDom(XmlDocument doc, XmlElement elemGroup) { foreach (string c in m_components) { XmlElement elem = doc.CreateElement("ComponentRef", XMLNS); elem.SetAttribute("Id", c); elemGroup.AppendChild(elem); } } private void SetupExclusions() { if (_filesAndDirsToExclude != null) { foreach (string s in _filesAndDirsToExclude) { string key; if (Path.IsPathRooted(s)) key = s.ToLower(); else key = Path.GetFullPath(Path.Combine(_rootDir, s)).ToLower(); m_exclude.Add(key, s); } } } public bool HasLoggedErrors { get { return _hasLoggedErrors; } } /// <summary> /// will show up as: DirectoryRef Id="this property" /// </summary> public string DirectoryReferenceId { get { return _directoryReferenceId; } set { _directoryReferenceId = value; } } public string ComponentGroupId { get { return _componentGroupId; } set { _componentGroupId = value; } } public void LogErrorFromException(Exception e) { _hasLoggedErrors = true; Log.LogErrorFromException(e); } public void LogError(string s) { _hasLoggedErrors = true; Log.LogError(s); } public void LogWarning(string s) { Log.LogWarning(s); } private void ProcessDir(XmlElement parent, string dirPath, string outerDirectoryId) { LogMessage(MessageImportance.Low, "Processing dir {0}", dirPath); XmlDocument doc = parent.OwnerDocument; List<string> files = new List<string>(); IdToGuidDatabase guidDatabase = IdToGuidDatabase.Create(Path.Combine(dirPath, kFileNameOfGuidDatabase), this); ; SetupDirectoryPermissions(dirPath, parent, outerDirectoryId, doc, guidDatabase); // Build a list of the files in this directory removing any that have been exluded foreach (string f in Directory.GetFiles(dirPath)) { if (_fileMatchPattern.IsMatch(f) && !_ignoreFilePattern.IsMatch(f) && !_ignoreFilePattern.IsMatch(Path.GetFileName(f)) && !m_exclude.ContainsKey(f.ToLower()) && !f.Contains(kFileNameOfGuidDatabase) ) files.Add(f); } // Process all files bool isFirst = true; foreach (string path in files) { ProcessFile(parent, path, doc, guidDatabase, isFirst, outerDirectoryId); isFirst = false; } // Recursively process any subdirectories foreach (string d in Directory.GetDirectories(dirPath)) { string shortName = Path.GetFileName(d); if (!m_exclude.ContainsKey(d.ToLower()) && shortName != ".svn" && shortName != "CVS") { string id = GetSafeDirectoryId(d, outerDirectoryId); XmlElement elemDir = doc.CreateElement("Directory", XMLNS); elemDir.SetAttribute("Id", id); elemDir.SetAttribute("Name", shortName); parent.AppendChild(elemDir); ProcessDir(elemDir, d, id); if (elemDir.ChildNodes.Count == 0) parent.RemoveChild(elemDir); } } } private void SetupDirectoryPermissions(string dirPath, XmlElement parent, string parentDirectoryId, XmlDocument doc, IdToGuidDatabase guidDatabase) { if (_giveAllPermissions) { /* Need to add one of these in order to set the permissions on the directory * <Component Id="biatahCacheDir" Guid="492F2725-9DF9-46B1-9ACE-E84E70AFEE99"> <CreateFolder Directory="biatahCacheDir"> <Permission GenericAll="yes" User="Everyone" /> </CreateFolder> </Component> */ string id = GetSafeDirectoryId(string.Empty, parentDirectoryId); XmlElement componentElement = doc.CreateElement("Component", XMLNS); componentElement.SetAttribute("Id", id); componentElement.SetAttribute("Guid", guidDatabase.GetGuid(id, this.CheckOnly)); XmlElement createFolderElement = doc.CreateElement("CreateFolder", XMLNS); createFolderElement.SetAttribute("Directory", id); AddPermissionElement(doc, createFolderElement); componentElement.AppendChild(createFolderElement); parent.AppendChild(componentElement); m_components.Add(id); } } private string GetSafeDirectoryId(string directoryPath, string parentDirectoryId) { string id = parentDirectoryId; //bit of a hack... we don't want our id to have this prefix.dir form fo the top level, //where it is going to be referenced by other wix files, that will just be expecting the id //the msbuild target gave for the id of this directory //I don't have it quite right, though. See the test file, where you get // <Component Id="common.bin.bin" (the last bin is undesirable) if (Path.GetFullPath(_rootDir) != directoryPath) { id+="." + Path.GetFileName(directoryPath); id = id.TrimEnd('.'); //for the case where directoryPath is intentionally empty } id = Regex.Replace(id, @"[^\p{Lu}\p{Ll}\p{Nd}._]", "_"); return id; } private void ProcessFile(XmlElement parent, string path, XmlDocument doc, IdToGuidDatabase guidDatabase, bool isFirst, string directoryId) { string guid; string name = Path.GetFileName(path); string id = directoryId+"."+name; //includ the parent directory id so that files with the same name (e.g. "index.html") found twice in the system will get different ids. const int kMaxLength = 50; //I have so far not found out what the max really is if (id.Length > kMaxLength) { id = id.Substring(id.Length - kMaxLength, kMaxLength); //get the last chunk of it } if (!Char.IsLetter(id[0]) && id[0] != '_')//probably not needed now that we're prepending the parent directory id, accept maybe at the root? id = '_' + id; id = Regex.Replace(id, @"[^\p{Lu}\p{Ll}\p{Nd}._]", "_"); LogMessage(MessageImportance.Normal, "Adding file {0} with id {1}", path, id); string key = id.ToLower(); if (m_suffixes.ContainsKey(key)) { int suffix = m_suffixes[key] + 1; m_suffixes[key] = suffix; id += suffix.ToString(); } else { m_suffixes[key] = 0; } // Create <Component> and <File> for this file XmlElement elemComp = doc.CreateElement("Component", XMLNS); elemComp.SetAttribute("Id", id); guid = guidDatabase.GetGuid(id,this.CheckOnly); if (guid == null) m_filesChanged = true; // this file is new else elemComp.SetAttribute("Guid", guid.ToUpper()); parent.AppendChild(elemComp); XmlElement elemFile = doc.CreateElement("File", XMLNS); elemFile.SetAttribute("Id", id); elemFile.SetAttribute("Name", name); if (isFirst) { elemFile.SetAttribute("KeyPath", "yes"); } string relativePath; if (String.IsNullOrEmpty(_installerSourceDirectory)) relativePath = PathUtil.RelativePathTo(Path.GetDirectoryName(_outputFilePath), path); else relativePath = PathUtil.RelativePathTo(_installerSourceDirectory, path); elemFile.SetAttribute("Source", relativePath); if (GiveAllPermissions) { AddPermissionElement(doc, elemFile); } elemComp.AppendChild(elemFile); InsertFileDeletionInstruction(elemComp); m_components.Add(id); // check whether the file is newer if (File.GetLastWriteTime(path) > m_refDate) m_filesChanged = true; } private void AddPermissionElement(XmlDocument doc, XmlElement elementToAddPermissionTo) { XmlElement persmission = doc.CreateElement("Permission", XMLNS); persmission.SetAttribute("GenericAll", "yes"); persmission.SetAttribute("User", "Everyone"); elementToAddPermissionTo.AppendChild(persmission); } private void LogMessage(string message, params object[] args) { LogMessage(MessageImportance.Normal, message, args); } public void LogMessage(MessageImportance importance, string message) { try { Log.LogMessage(importance.ToString(), message); } catch (InvalidOperationException) { // Swallow exceptions for testing } } private void LogMessage(MessageImportance importance, string message, params object[] args) { try { Log.LogMessage(importance.ToString(), message, args); } catch (InvalidOperationException) { // Swallow exceptions for testing } } private void LogError(string message, params object[] args) { try { Log.LogError(message, args); } catch (InvalidOperationException) { // Swallow exceptions for testing } } #endregion } }
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. using System.Security.Claims; using MartinCostello.LondonTravel.Site.Services.Data; using Microsoft.AspNetCore.Identity; namespace MartinCostello.LondonTravel.Site.Identity; /// <summary> /// A class representing a custom implementation of a user store. This class cannot be inherited. /// </summary> public sealed class UserStore : IUserStore<LondonTravelUser>, IUserEmailStore<LondonTravelUser>, IUserLoginStore<LondonTravelUser>, IUserRoleStore<LondonTravelUser>, IUserSecurityStampStore<LondonTravelUser> { /// <summary> /// The issuer to use for roles. /// </summary> private const string RoleClaimIssuer = "https://londontravel.martincostello.com/"; /// <summary> /// The <see cref="IDocumentService"/> to use. This field is read-only. /// </summary> private readonly IDocumentService _service; /// <summary> /// Initializes a new instance of the <see cref="UserStore"/> class. /// </summary> /// <param name="service">The <see cref="IDocumentService"/> to use.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="service"/> is <see langword="null"/>. /// </exception> public UserStore(IDocumentService service) { ArgumentNullException.ThrowIfNull(service); _service = service; } /// <inheritdoc /> public Task AddLoginAsync(LondonTravelUser user, UserLoginInfo login, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); ArgumentNullException.ThrowIfNull(login); if (user.Logins.Any((p) => p.LoginProvider == login.LoginProvider)) { throw new InvalidOperationException($"Failed to add login for provider '{login.LoginProvider}' for user '{user.Id}' as a login for that provider already exists."); } user.Logins.Add(LondonTravelLoginInfo.FromUserLoginInfo(login)); return Task.CompletedTask; } /// <inheritdoc /> public async Task<IdentityResult> CreateAsync(LondonTravelUser user, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); user.Id = await _service.CreateAsync(user); return IdentityResult.Success; } /// <inheritdoc /> public async Task<IdentityResult> DeleteAsync(LondonTravelUser user, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); if (string.IsNullOrEmpty(user.Id)) { throw new ArgumentException("No user Id specified.", nameof(user)); } bool deleted = await _service.DeleteAsync(user.Id); return deleted ? IdentityResult.Success : ResultForError("UserNotFound", $"User with Id '{user.Id}' does not exist."); } /// <inheritdoc /> public void Dispose() { // Not used } /// <inheritdoc /> public async Task<LondonTravelUser> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(normalizedEmail); var results = await _service.GetAsync((p) => p.EmailNormalized == normalizedEmail, cancellationToken); var result = results.FirstOrDefault(); return result!; } /// <inheritdoc /> public async Task<LondonTravelUser> FindByIdAsync(string userId, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(userId); var user = await _service.GetAsync(userId); return user!; } /// <inheritdoc /> public async Task<LondonTravelUser> FindByLoginAsync(string loginProvider, string providerKey, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(loginProvider); ArgumentNullException.ThrowIfNull(providerKey); var results = await _service.GetAsync( (p) => p.Logins.Contains(new LondonTravelLoginInfo() { LoginProvider = loginProvider, ProviderKey = providerKey, ProviderDisplayName = null }) || p.Logins.Contains(new LondonTravelLoginInfo() { LoginProvider = loginProvider, ProviderKey = providerKey, ProviderDisplayName = loginProvider }), cancellationToken); var result = results.FirstOrDefault(); return result!; } /// <inheritdoc /> public async Task<LondonTravelUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(normalizedUserName); var results = await _service.GetAsync((p) => p.UserNameNormalized == normalizedUserName, cancellationToken); var result = results.FirstOrDefault(); return result!; } /// <inheritdoc /> public Task<string> GetEmailAsync(LondonTravelUser user, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); return Task.FromResult(user.Email!); } /// <inheritdoc /> public Task<bool> GetEmailConfirmedAsync(LondonTravelUser user, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); return Task.FromResult(user.EmailConfirmed); } /// <inheritdoc /> public Task<IList<UserLoginInfo>> GetLoginsAsync(LondonTravelUser user, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); IList<UserLoginInfo> logins = user.Logins .Select((p) => new UserLoginInfo(p.LoginProvider, p.ProviderKey, p.ProviderDisplayName)) .ToList(); return Task.FromResult(logins); } /// <inheritdoc /> public Task<string> GetNormalizedEmailAsync(LondonTravelUser user, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); return Task.FromResult(user.EmailNormalized!); } /// <inheritdoc /> public Task<string> GetNormalizedUserNameAsync(LondonTravelUser user, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); return Task.FromResult(user.UserNameNormalized!); } /// <inheritdoc /> public Task<string> GetSecurityStampAsync(LondonTravelUser user, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); return Task.FromResult(user.SecurityStamp!); } /// <inheritdoc /> public Task<string> GetUserIdAsync(LondonTravelUser user, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); return Task.FromResult(user.Id!); } /// <inheritdoc /> public Task<string> GetUserNameAsync(LondonTravelUser user, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); return Task.FromResult(user.UserName!); } /// <inheritdoc /> public Task RemoveLoginAsync(LondonTravelUser user, string loginProvider, string providerKey, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); ArgumentNullException.ThrowIfNull(loginProvider); ArgumentNullException.ThrowIfNull(providerKey); if (user.Logins != null) { var loginsToRemove = user.Logins .Where((p) => p.LoginProvider == loginProvider) .Where((p) => p.ProviderKey == providerKey) .ToList(); if (loginsToRemove.Count > 0) { foreach (var login in loginsToRemove) { user.Logins.Remove(login); } } } return Task.CompletedTask; } /// <inheritdoc /> public Task SetEmailAsync(LondonTravelUser user, string email, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); user.Email = email; return Task.CompletedTask; } /// <inheritdoc /> public Task SetEmailConfirmedAsync(LondonTravelUser user, bool confirmed, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); user.EmailConfirmed = confirmed; return Task.CompletedTask; } /// <inheritdoc /> public Task SetNormalizedEmailAsync(LondonTravelUser user, string normalizedEmail, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); user.EmailNormalized = normalizedEmail; return Task.CompletedTask; } /// <inheritdoc /> public Task SetNormalizedUserNameAsync(LondonTravelUser user, string normalizedName, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); user.UserNameNormalized = normalizedName; return Task.CompletedTask; } /// <inheritdoc /> public Task SetSecurityStampAsync(LondonTravelUser user, string stamp, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); user.SecurityStamp = stamp; return Task.CompletedTask; } /// <inheritdoc /> public Task SetUserNameAsync(LondonTravelUser user, string userName, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); user.UserName = userName; return Task.CompletedTask; } /// <inheritdoc /> public async Task<IdentityResult> UpdateAsync(LondonTravelUser user, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); if (user.CreatedAt == DateTime.MinValue) { user.CreatedAt = DateTimeOffset.FromUnixTimeSeconds(user.Timestamp).UtcDateTime; } LondonTravelUser? updated = await _service.ReplaceAsync(user, user.ETag); if (updated != null) { user.ETag = updated.ETag; return IdentityResult.Success; } else { return ResultForError("Conflict", "The user could not be updated as the ETag value is out-of-date."); } } /// <inheritdoc /> public Task AddToRoleAsync(LondonTravelUser user, string roleName, CancellationToken cancellationToken) { throw new NotImplementedException(); } /// <inheritdoc /> public Task<IList<string>> GetRolesAsync(LondonTravelUser user, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); IList<string> roles = Array.Empty<string>(); if (user.RoleClaims?.Count > 0) { roles = user.RoleClaims .Where((p) => string.Equals(p.Issuer, RoleClaimIssuer, StringComparison.Ordinal)) .Where((p) => string.Equals(p.ClaimType, ClaimTypes.Role, StringComparison.Ordinal)) .Where((p) => string.Equals(p.ValueType, ClaimValueTypes.String, StringComparison.Ordinal)) .Where((p) => !string.IsNullOrEmpty(p.Value)) .Select((p) => p.Value!) .ToArray(); } return Task.FromResult(roles); } /// <inheritdoc /> public Task<IList<LondonTravelUser>> GetUsersInRoleAsync(string roleName, CancellationToken cancellationToken) { throw new NotImplementedException(); } /// <inheritdoc /> public Task<bool> IsInRoleAsync(LondonTravelUser user, string roleName, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(user); ArgumentNullException.ThrowIfNull(roleName); bool isInRole = false; if (user.RoleClaims?.Count > 0) { isInRole = user.RoleClaims .Where((p) => string.Equals(p.Issuer, RoleClaimIssuer, StringComparison.Ordinal)) .Where((p) => string.Equals(p.ClaimType, ClaimTypes.Role, StringComparison.Ordinal)) .Where((p) => string.Equals(p.ValueType, ClaimValueTypes.String, StringComparison.Ordinal)) .Where((p) => string.Equals(p.Value, roleName, StringComparison.Ordinal)) .Any(); } return Task.FromResult(isInRole); } /// <inheritdoc /> public Task RemoveFromRoleAsync(LondonTravelUser user, string roleName, CancellationToken cancellationToken) { throw new NotImplementedException(); } /// <summary> /// Creates an <see cref="IdentityResult"/> for the specified error. /// </summary> /// <param name="code">The error code.</param> /// <param name="description">The error description.</param> /// <returns> /// The created instance of <see cref="IdentityResult"/>. /// </returns> private static IdentityResult ResultForError(string code, string description) { var error = new IdentityError() { Code = code, Description = description, }; return IdentityResult.Failed(error); } }
// BZip2InputStream.cs // // Copyright (C) 2001 Mike Krueger // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.IO; using ICSharpCode.SharpZipLib.Silverlight.Checksums; namespace ICSharpCode.SharpZipLib.Silverlight.BZip2 { /// <summary> /// An input stream that decompresses files in the BZip2 format /// </summary> public class BZip2InputStream : Stream { #region Constants private const int NO_RAND_PART_A_STATE = 5; private const int NO_RAND_PART_B_STATE = 6; private const int NO_RAND_PART_C_STATE = 7; private const int RAND_PART_A_STATE = 2; private const int RAND_PART_B_STATE = 3; private const int RAND_PART_C_STATE = 4; private const int START_BLOCK_STATE = 1; #endregion #region Constructors /// <summary> /// Construct instance for reading from stream /// </summary> /// <param name="stream">Data source</param> public BZip2InputStream(Stream stream) { // init arrays for (var i = 0; i < BZip2Constants.N_GROUPS; ++i) { limit[i] = new int[BZip2Constants.MAX_ALPHA_SIZE]; baseArray[i] = new int[BZip2Constants.MAX_ALPHA_SIZE]; perm[i] = new int[BZip2Constants.MAX_ALPHA_SIZE]; } BsSetStream(stream); Initialize(); InitBlock(); SetupBlock(); } #endregion /// <summary> /// Get/set flag indicating ownership of underlying stream. /// When the flag is true <see cref="Close"></see> will close the underlying stream also. /// </summary> public bool IsStreamOwner { get { return isStreamOwner; } set { isStreamOwner = value; } } #region Stream Overrides /// <summary> /// Gets a value indicating if the stream supports reading /// </summary> public override bool CanRead { get { return baseStream.CanRead; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> public override bool CanSeek { get { return baseStream.CanSeek; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// This property always returns false /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// Gets the length in bytes of the stream. /// </summary> public override long Length { get { return baseStream.Length; } } /// <summary> /// Gets or sets the streams position. /// Setting the position is not supported and will throw a NotSupportException /// </summary> /// <exception cref="NotSupportedException">Any attempt to set the position</exception> public override long Position { get { return baseStream.Position; } set { throw new NotSupportedException("BZip2InputStream position cannot be set"); } } /// <summary> /// Flushes the stream. /// </summary> public override void Flush() { if (baseStream != null) { baseStream.Flush(); } } /// <summary> /// Set the streams position. This operation is not supported and will throw a NotSupportedException /// </summary> /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param> /// <param name="origin">A value of type <see cref="SeekOrigin"/> indicating the reference point used to obtain the new position.</param> /// <returns>The new position of the stream.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("BZip2InputStream Seek not supported"); } /// <summary> /// Sets the length of this stream to the given value. /// This operation is not supported and will throw a NotSupportedExceptionortedException /// </summary> /// <param name="value">The new length for the stream.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void SetLength(long value) { throw new NotSupportedException("BZip2InputStream SetLength not supported"); } /// <summary> /// Writes a block of bytes to this stream using data from a buffer. /// This operation is not supported and will throw a NotSupportedException /// </summary> /// <param name="buffer">The buffer to source data from.</param> /// <param name="offset">The offset to start obtaining data from.</param> /// <param name="count">The number of bytes of data to write.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException("BZip2InputStream Write not supported"); } /// <summary> /// Writes a byte to the current position in the file stream. /// This operation is not supported and will throw a NotSupportedException /// </summary> /// <param name="value">The value to write.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void WriteByte(byte value) { throw new NotSupportedException("BZip2InputStream WriteByte not supported"); } /// <summary> /// Read a sequence of bytes and advances the read position by one byte. /// </summary> /// <param name="buffer">Array of bytes to store values in</param> /// <param name="offset">Offset in array to begin storing data</param> /// <param name="count">The maximum number of bytes to read</param> /// <returns>The total number of bytes read into the buffer. This might be less /// than the number of bytes requested if that number of bytes are not /// currently available or zero if the end of the stream is reached. /// </returns> public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } for (var i = 0; i < count; ++i) { var rb = ReadByte(); if (rb == -1) { return i; } buffer[offset + i] = (byte) rb; } return count; } /// <summary> /// Closes the stream, releasing any associated resources. /// </summary> public override void Close() { if (IsStreamOwner && (baseStream != null)) { baseStream.Close(); } } /// <summary> /// Read a byte from stream advancing position /// </summary> /// <returns>byte read or -1 on end of stream</returns> public override int ReadByte() { if (streamEnd) { return -1; // ok } var retChar = currentChar; switch (currentState) { case RAND_PART_B_STATE: SetupRandPartB(); break; case RAND_PART_C_STATE: SetupRandPartC(); break; case NO_RAND_PART_B_STATE: SetupNoRandPartB(); break; case NO_RAND_PART_C_STATE: SetupNoRandPartC(); break; case START_BLOCK_STATE: case NO_RAND_PART_A_STATE: case RAND_PART_A_STATE: break; default: break; } return retChar; } #endregion private void MakeMaps() { nInUse = 0; for (var i = 0; i < 256; ++i) { if (inUse[i]) { seqToUnseq[nInUse] = (byte) i; unseqToSeq[i] = (byte) nInUse; nInUse++; } } } private void Initialize() { var magic1 = BsGetUChar(); var magic2 = BsGetUChar(); var magic3 = BsGetUChar(); var magic4 = BsGetUChar(); if (magic1 != 'B' || magic2 != 'Z' || magic3 != 'h' || magic4 < '1' || magic4 > '9') { streamEnd = true; return; } SetDecompressStructureSizes(magic4 - '0'); computedCombinedCRC = 0; } private void InitBlock() { var magic1 = BsGetUChar(); var magic2 = BsGetUChar(); var magic3 = BsGetUChar(); var magic4 = BsGetUChar(); var magic5 = BsGetUChar(); var magic6 = BsGetUChar(); if (magic1 == 0x17 && magic2 == 0x72 && magic3 == 0x45 && magic4 == 0x38 && magic5 == 0x50 && magic6 == 0x90) { Complete(); return; } if (magic1 != 0x31 || magic2 != 0x41 || magic3 != 0x59 || magic4 != 0x26 || magic5 != 0x53 || magic6 != 0x59) { BadBlockHeader(); streamEnd = true; return; } storedBlockCRC = BsGetInt32(); blockRandomised = (BsR(1) == 1); GetAndMoveToFrontDecode(); mCrc.Reset(); currentState = START_BLOCK_STATE; } private void EndBlock() { computedBlockCRC = (int) mCrc.Value; // -- A bad CRC is considered a fatal error. -- if (storedBlockCRC != computedBlockCRC) { CrcError(); } // 1528150659 computedCombinedCRC = ((computedCombinedCRC << 1) & 0xFFFFFFFF) | (computedCombinedCRC >> 31); computedCombinedCRC = computedCombinedCRC ^ (uint) computedBlockCRC; } private void Complete() { storedCombinedCRC = BsGetInt32(); if (storedCombinedCRC != (int) computedCombinedCRC) { CrcError(); } streamEnd = true; } private void BsSetStream(Stream stream) { baseStream = stream; bsLive = 0; bsBuff = 0; } private void FillBuffer() { var thech = 0; try { thech = baseStream.ReadByte(); } catch (Exception) { CompressedStreamEOF(); } if (thech == -1) { CompressedStreamEOF(); } bsBuff = (bsBuff << 8) | (thech & 0xFF); bsLive += 8; } private int BsR(int n) { while (bsLive < n) { FillBuffer(); } var v = (bsBuff >> (bsLive - n)) & ((1 << n) - 1); bsLive -= n; return v; } private char BsGetUChar() { return (char) BsR(8); } private int BsGetint() { var u = BsR(8); u = (u << 8) | BsR(8); u = (u << 8) | BsR(8); u = (u << 8) | BsR(8); return u; } private int BsGetIntVS(int numBits) { return BsR(numBits); } private int BsGetInt32() { return BsGetint(); } private void RecvDecodingTables() { var len = new char[BZip2Constants.N_GROUPS][]; for (var i = 0; i < BZip2Constants.N_GROUPS; ++i) { len[i] = new char[BZip2Constants.MAX_ALPHA_SIZE]; } var inUse16 = new bool[16]; //--- Receive the mapping table --- for (var i = 0; i < 16; i++) { inUse16[i] = (BsR(1) == 1); } for (var i = 0; i < 16; i++) { if (inUse16[i]) { for (var j = 0; j < 16; j++) { inUse[i*16 + j] = (BsR(1) == 1); } } else { for (var j = 0; j < 16; j++) { inUse[i*16 + j] = false; } } } MakeMaps(); var alphaSize = nInUse + 2; //--- Now the selectors --- var nGroups = BsR(3); var nSelectors = BsR(15); for (var i = 0; i < nSelectors; i++) { var j = 0; while (BsR(1) == 1) { j++; } selectorMtf[i] = (byte) j; } //--- Undo the MTF values for the selectors. --- var pos = new byte[BZip2Constants.N_GROUPS]; for (var v = 0; v < nGroups; v++) { pos[v] = (byte) v; } for (var i = 0; i < nSelectors; i++) { int v = selectorMtf[i]; var tmp = pos[v]; while (v > 0) { pos[v] = pos[v - 1]; v--; } pos[0] = tmp; selector[i] = tmp; } //--- Now the coding tables --- for (var t = 0; t < nGroups; t++) { var curr = BsR(5); for (var i = 0; i < alphaSize; i++) { while (BsR(1) == 1) { if (BsR(1) == 0) { curr++; } else { curr--; } } len[t][i] = (char) curr; } } //--- Create the Huffman decoding tables --- for (var t = 0; t < nGroups; t++) { var minLen = 32; var maxLen = 0; for (var i = 0; i < alphaSize; i++) { maxLen = Math.Max(maxLen, len[t][i]); minLen = Math.Min(minLen, len[t][i]); } HbCreateDecodeTables(limit[t], baseArray[t], perm[t], len[t], minLen, maxLen, alphaSize); minLens[t] = minLen; } } private void GetAndMoveToFrontDecode() { var yy = new byte[256]; var limitLast = BZip2Constants.baseBlockSize*blockSize100k; origPtr = BsGetIntVS(24); RecvDecodingTables(); var EOB = nInUse + 1; var groupNo = -1; var groupPos = 0; /*-- Setting up the unzftab entries here is not strictly necessary, but it does save having to do it later in a separate pass, and so saves a block's worth of cache misses. --*/ for (var i = 0; i <= 255; i++) { unzftab[i] = 0; } for (var i = 0; i <= 255; i++) { yy[i] = (byte) i; } last = -1; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.G_SIZE; } groupPos--; int zt = selector[groupNo]; var zn = minLens[zt]; var zvec = BsR(zn); int zj; while (zvec > limit[zt][zn]) { if (zn > 20) { // the longest code throw new BZip2Exception("Bzip data error"); } zn++; while (bsLive < 1) { FillBuffer(); } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; zvec = (zvec << 1) | zj; } if (zvec - baseArray[zt][zn] < 0 || zvec - baseArray[zt][zn] >= BZip2Constants.MAX_ALPHA_SIZE) { throw new BZip2Exception("Bzip data error"); } int nextSym = perm[zt][zvec - baseArray[zt][zn]]; while (true) { if (nextSym == EOB) { break; } if (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB) { var s = -1; var n = 1; do { if (nextSym == BZip2Constants.RUNA) { s += (0 + 1)*n; } else if (nextSym == BZip2Constants.RUNB) { s += (1 + 1)*n; } n <<= 1; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.G_SIZE; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; while (bsLive < 1) { FillBuffer(); } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - baseArray[zt][zn]]; } while (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB); s++; var ch = seqToUnseq[yy[0]]; unzftab[ch] += s; while (s > 0) { last++; ll8[last] = ch; s--; } if (last >= limitLast) { BlockOverrun(); } continue; } last++; if (last >= limitLast) { BlockOverrun(); } var tmp = yy[nextSym - 1]; unzftab[seqToUnseq[tmp]]++; ll8[last] = seqToUnseq[tmp]; for (var j = nextSym - 1; j > 0; --j) { yy[j] = yy[j - 1]; } yy[0] = tmp; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.G_SIZE; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; while (bsLive < 1) { FillBuffer(); } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - baseArray[zt][zn]]; continue; } } private void SetupBlock() { var cftab = new int[257]; cftab[0] = 0; Array.Copy(unzftab, 0, cftab, 1, 256); for (var i = 1; i <= 256; i++) { cftab[i] += cftab[i - 1]; } for (var i = 0; i <= last; i++) { var ch = ll8[i]; tt[cftab[ch]] = i; cftab[ch]++; } tPos = tt[origPtr]; count = 0; i2 = 0; ch2 = 256; /*-- not a char and not EOF --*/ if (blockRandomised) { rNToGo = 0; rTPos = 0; SetupRandPartA(); } else { SetupNoRandPartA(); } } private void SetupRandPartA() { if (i2 <= last) { chPrev = ch2; ch2 = ll8[tPos]; tPos = tt[tPos]; if (rNToGo == 0) { rNToGo = BZip2Constants.rNums[rTPos]; rTPos++; if (rTPos == 512) { rTPos = 0; } } rNToGo--; ch2 ^= ((rNToGo == 1) ? 1 : 0); i2++; currentChar = ch2; currentState = RAND_PART_B_STATE; mCrc.Update(ch2); } else { EndBlock(); InitBlock(); SetupBlock(); } } private void SetupNoRandPartA() { if (i2 <= last) { chPrev = ch2; ch2 = ll8[tPos]; tPos = tt[tPos]; i2++; currentChar = ch2; currentState = NO_RAND_PART_B_STATE; mCrc.Update(ch2); } else { EndBlock(); InitBlock(); SetupBlock(); } } private void SetupRandPartB() { if (ch2 != chPrev) { currentState = RAND_PART_A_STATE; count = 1; SetupRandPartA(); } else { count++; if (count >= 4) { z = ll8[tPos]; tPos = tt[tPos]; if (rNToGo == 0) { rNToGo = BZip2Constants.rNums[rTPos]; rTPos++; if (rTPos == 512) { rTPos = 0; } } rNToGo--; z ^= (byte) ((rNToGo == 1) ? 1 : 0); j2 = 0; currentState = RAND_PART_C_STATE; SetupRandPartC(); } else { currentState = RAND_PART_A_STATE; SetupRandPartA(); } } } private void SetupRandPartC() { if (j2 < z) { currentChar = ch2; mCrc.Update(ch2); j2++; } else { currentState = RAND_PART_A_STATE; i2++; count = 0; SetupRandPartA(); } } private void SetupNoRandPartB() { if (ch2 != chPrev) { currentState = NO_RAND_PART_A_STATE; count = 1; SetupNoRandPartA(); } else { count++; if (count >= 4) { z = ll8[tPos]; tPos = tt[tPos]; currentState = NO_RAND_PART_C_STATE; j2 = 0; SetupNoRandPartC(); } else { currentState = NO_RAND_PART_A_STATE; SetupNoRandPartA(); } } } private void SetupNoRandPartC() { if (j2 < z) { currentChar = ch2; mCrc.Update(ch2); j2++; } else { currentState = NO_RAND_PART_A_STATE; i2++; count = 0; SetupNoRandPartA(); } } private void SetDecompressStructureSizes(int newSize100k) { if (!(0 <= newSize100k && newSize100k <= 9 && 0 <= blockSize100k && blockSize100k <= 9)) { throw new BZip2Exception("Invalid block size"); } blockSize100k = newSize100k; if (newSize100k == 0) { return; } var n = BZip2Constants.baseBlockSize*newSize100k; ll8 = new byte[n]; tt = new int[n]; } private static void CompressedStreamEOF() { throw new EndOfStreamException("BZip2 input stream end of compressed stream"); } private static void BlockOverrun() { throw new BZip2Exception("BZip2 input stream block overrun"); } private static void BadBlockHeader() { throw new BZip2Exception("BZip2 input stream bad block header"); } private static void CrcError() { throw new BZip2Exception("BZip2 input stream crc error"); } private static void HbCreateDecodeTables(int[] limit, int[] baseArray, int[] perm, char[] length, int minLen, int maxLen, int alphaSize) { var pp = 0; for (var i = minLen; i <= maxLen; ++i) { for (var j = 0; j < alphaSize; ++j) { if (length[j] == i) { perm[pp] = j; ++pp; } } } for (var i = 0; i < BZip2Constants.MAX_CODE_LEN; i++) { baseArray[i] = 0; } for (var i = 0; i < alphaSize; i++) { ++baseArray[length[i] + 1]; } for (var i = 1; i < BZip2Constants.MAX_CODE_LEN; i++) { baseArray[i] += baseArray[i - 1]; } for (var i = 0; i < BZip2Constants.MAX_CODE_LEN; i++) { limit[i] = 0; } var vec = 0; for (var i = minLen; i <= maxLen; i++) { vec += (baseArray[i + 1] - baseArray[i]); limit[i] = vec - 1; vec <<= 1; } for (var i = minLen + 1; i <= maxLen; i++) { baseArray[i] = ((limit[i - 1] + 1) << 1) - baseArray[i]; } } #region Instance Fields /*-- index of the last char in the block, so the block size == last + 1. --*/ private readonly int[][] baseArray = new int[BZip2Constants.N_GROUPS][]; private readonly bool[] inUse = new bool[256]; private readonly int[][] limit = new int[BZip2Constants.N_GROUPS][]; private readonly IChecksum mCrc = new StrangeCRC(); private readonly int[] minLens = new int[BZip2Constants.N_GROUPS]; private readonly int[][] perm = new int[BZip2Constants.N_GROUPS][]; private readonly byte[] selector = new byte[BZip2Constants.MAX_SELECTORS]; private readonly byte[] selectorMtf = new byte[BZip2Constants.MAX_SELECTORS]; private readonly byte[] seqToUnseq = new byte[256]; private readonly byte[] unseqToSeq = new byte[256]; /*-- freq table collected to save a pass over the data during decompression. --*/ private readonly int[] unzftab = new int[256]; private Stream baseStream; private bool blockRandomised; private int blockSize100k; private int bsBuff; private int bsLive; private int ch2; private int chPrev; private int computedBlockCRC; private uint computedCombinedCRC; private int count; private int currentChar = -1; private int currentState = START_BLOCK_STATE; private int i2; private bool isStreamOwner = true; private int j2; private int last; private byte[] ll8; private int nInUse; private int origPtr; private int rNToGo; private int rTPos; private int storedBlockCRC, storedCombinedCRC; private bool streamEnd; private int tPos; private int[] tt; private byte z; #endregion } } /* This file was derived from a file containing this license: * * This file is a part of bzip2 and/or libbzip2, a program and * library for lossless, block-sorting data compression. * * Copyright (C) 1996-1998 Julian R Seward. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. The origin of this software must not be misrepresented; you must * not claim that you wrote the original software. If you use this * software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * * 3. Altered source versions must be plainly marked as such, and must * not be misrepresented as being the original software. * * 4. The name of the author may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * Java version ported by Keiron Liddle, Aftex Software <keiron@aftexsw.com> 1999-2001 */
// Copyright 2017 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. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Firebase.Platform; using Firebase.Firestore.Internal; namespace Firebase.Firestore { using SnapshotsInSyncCallbackMap = ListenerRegistrationMap<Action>; using LoadBundleProgressCallbackMap = ListenerRegistrationMap<Action<LoadBundleTaskProgress>>; /// <summary> /// Represents a Cloud Firestore database and is the entry point for all Cloud Firestore /// operations. /// </summary> public sealed class FirebaseFirestore { // This lock and boolean pair are used to ensure that the mapping from Firebase app to Firestore // instance is removed atomically from the C++ instance cache and the C# instance cache. Any // call to a C++ method that removes the mapping from the C++ instance cache must do so while // holding this lock and must then set the boolean flag to false while still holding the lock. // Abiding by this contract ensures that the two caches are kept in sync. private readonly object _isInCppInstanceCacheLock = new object(); private bool _isInCppInstanceCache = true; private readonly ReaderWriterLock _disposeLock = new ReaderWriterLock(); private FirestoreProxy _proxy; private readonly FirebaseFirestoreSettings _settings; private readonly TransactionManager _transactionManager; private static readonly IDictionary<FirebaseApp, FirebaseFirestore> _instanceCache = new Dictionary<FirebaseApp, FirebaseFirestore>(); // We rely on e.g. firestore.Document("a/b").Firestore returning the original Firestore // instance so it's important the constructor remains private and we only create one // FirebaseFirestore instance per FirebaseApp instance. private FirebaseFirestore(FirestoreProxy proxy, FirebaseApp app) { _proxy = Util.NotNull(proxy); App = app; app.AppDisposed += OnAppDisposed; // This call to InitializeConverterCache() exists to make sure that AOT works. Firebase.Firestore.Converters.ConverterCache.InitializeConverterCache(); string dotnetVersion = EnvironmentVersion.GetEnvironmentVersion(); ApiHeaders.SetClientLanguage(String.Format("gl-dotnet/{0}", dotnetVersion)); _settings = new FirebaseFirestoreSettings(proxy); _transactionManager = new TransactionManager(this, proxy); } /// <summary> /// Destroys this object and frees all resources it has acquired. /// </summary> ~FirebaseFirestore() { Dispose(); } void OnAppDisposed(object sender, System.EventArgs eventArgs) { Dispose(); } // TODO(b/201097848) Make `Dispose()` public and implement `IDisposable`. private void Dispose() { _disposeLock.AcquireWriterLock(Int32.MaxValue); try { if (_proxy == null) { return; } snapshotsInSyncCallbacks.ClearCallbacksForOwner(this); loadBundleProgressCallbackMap.ClearCallbacksForOwner(this); DocumentReference.ClearCallbacksForOwner(this); Query.ClearCallbacksForOwner(this); _transactionManager.Dispose(); _settings.Dispose(); App.AppDisposed -= OnAppDisposed; lock (_isInCppInstanceCacheLock) { _proxy.Dispose(); _isInCppInstanceCache = false; RemoveSelfFromInstanceCache(); } _proxy = null; App = null; } finally { _disposeLock.ReleaseWriterLock(); } System.GC.SuppressFinalize(this); } /// <summary> /// Returns the <c>FirebaseApp</c> instance to which this <c>FirebaseFirestore</c> belongs. /// </summary> public FirebaseApp App { get; private set; } /// <summary> /// Gets the instance of <c>FirebaseFirestore</c> for the default <c>FirebaseApp</c>. /// </summary> /// <value>A <c>FirebaseFirestore</c> instance.</value> public static FirebaseFirestore DefaultInstance { get { FirebaseApp app = Util.NotNull(FirebaseApp.DefaultInstance); return GetInstance(app); } } /// <summary> /// Gets an instance of <c>FirebaseFirestore</c> for a specific <c>FirebaseApp</c>. /// </summary> /// <param name="app">The <c>FirebaseApp</c> for which to get a <c>FirebaseFirestore</c> /// instance.</param> /// <returns>A <c>FirebaseFirestore</c> instance.</returns> public static FirebaseFirestore GetInstance(FirebaseApp app) { Preconditions.CheckNotNull(app, nameof(app)); while (true) { FirebaseFirestore firestore; // Acquire the lock on `_instanceCache` to see if the given `FirebaseApp` is in // `_instanceCache`; if it isn't then create the `FirebaseFirestore` instance, put it in the // cache, and return it. lock (_instanceCache) { if (!_instanceCache.TryGetValue(app, out firestore)) { // NOTE: FirestoreProxy.GetInstance() returns an *owning* reference (see the %newobject // directive in firestore.SWIG); therefore, we must make sure that we *never* call // FirestoreProxy.GetInstance() when it would return a proxy for a C++ object that it // previously returned. Otherwise, if it did, then that C++ object would be deleted // twice, causing a crash. FirestoreProxy firestoreProxy = Util.NotNull(FirestoreProxy.GetInstance(app)); firestore = new FirebaseFirestore(firestoreProxy, app); _instanceCache[app] = firestore; return firestore; } } // Acquire the lock on the specific `FirebaseFirestore` instance's `_isInCppInstanceCache` // and check if the mapping is also present in the C++ instance cache. If it is, then go // ahead and return the `FirebaseFirestore` object. If it isn't, then there must have been a // concurrent call to `TerminateAsync` or `Dispose` that removed it from the C++ instance // cache, in which case we just try the whole process over again. That's why this logic is // in "while" loop as opposed to a single "if" statement. lock (firestore._isInCppInstanceCacheLock) { if (firestore._isInCppInstanceCache) { return firestore; } } } } /// <summary> /// The settings of this <c>FirebaseFirestore</c> object. /// </summary> /// <remarks> /// <para>To change the settings used by this <c>FirebaseFirestore</c> instance, simply change /// the values of the properties on this <c>FirebaseFirestoreSettings</c> object.</para> /// <para>Invoking any non-static method on this <c>FirebaseFirestore</c> instance will "lock /// in" the settings. No changes are allowed to be made to the settings once they are locked in. /// Attempting to do so will result in an exception being thrown by the property setter. /// </para> /// </remarks> public FirebaseFirestoreSettings Settings { get { return _settings; } } /// <summary> /// Creates a local <see cref="CollectionReference"/> for the given path, which must include an /// odd number of slash-separated identifiers. This does not perform any remote operations. /// </summary> /// <param name="path">The collection path, e.g. <c>col1/doc1/col2</c>.</param> /// <returns>A collection reference.</returns> public CollectionReference Collection(string path) { Preconditions.CheckNotNullOrEmpty(path, nameof(path)); return WithFirestoreProxy(proxy => new CollectionReference(proxy.Collection(path), this)); } /// <summary> /// Creates a local <see cref="DocumentReference"/> for the given path, which must include an /// even number of slash-separated identifiers. This does not perform any remote operations. /// </summary> /// <param name="path">The document path, e.g. <c>col1/doc1/col2/doc2</c>.</param> /// <returns>A document reference.</returns> public DocumentReference Document(string path) { Preconditions.CheckNotNullOrEmpty(path, nameof(path)); return WithFirestoreProxy(proxy => new DocumentReference(proxy.Document(path), this)); } /// <summary> /// Creates and returns a new <see cref="Query"/> that includes all documents in the /// database that are contained in a collection or subcollection with the /// given collection ID. /// </summary> /// <param name="collectionId">Identifies the collections to query over. /// Every collection or subcollection with this ID as the last segment /// of its path will be included. Must not contain a slash.</param> /// <returns>The created <see cref="Query"/>.</returns> public Query CollectionGroup(string collectionId) { Preconditions.CheckNotNullOrEmpty(collectionId, nameof(collectionId)); return WithFirestoreProxy(proxy => new Query(proxy.CollectionGroup(collectionId), this)); } /// <summary> /// Creates a write batch, which can be used to commit multiple mutations atomically. /// </summary> /// <returns>A write batch for this database.</returns> public WriteBatch StartBatch() { return WithFirestoreProxy(proxy => new WriteBatch(proxy.batch())); } /// <summary> /// Runs a transaction asynchronously, with an asynchronous callback that doesn't return a /// value. The specified callback is executed for a newly-created transaction. /// </summary> /// <remarks> /// <para><c>RunTransactionAsync</c> executes the given callback on the main thread and then /// attempts to commit the changes applied within the transaction. If any document read within /// the transaction has changed, the <paramref name="callback"/> will be retried. If it fails /// to commit after 5 attempts, the transaction will fail.</para> /// /// <para>The maximum number of writes allowed in a single transaction is 500, but note that /// each usage of <see cref="FieldValue.ServerTimestamp"/>, <c>FieldValue.ArrayUnion</c>, /// <c>FieldValue.ArrayRemove</c>, or <c>FieldValue.Increment</c> inside a transaction counts as /// an additional write.</para> /// </remarks> /// <param name="callback">The callback to execute. Must not be <c>null</c>. The callback will /// be invoked on the main thread.</param> /// <returns>A task which completes when the transaction has committed.</returns> public Task RunTransactionAsync(Func<Transaction, Task> callback) { Preconditions.CheckNotNull(callback, nameof(callback)); // Just pass through to the overload where the callback returns a Task<T>. return RunTransactionAsync(transaction => Util.MapResult<object>(callback(transaction), null)); } /// <summary> /// Runs a transaction asynchronously, with an asynchronous callback that returns a value. /// The specified callback is executed for a newly-created transaction. /// </summary> /// <remarks> /// <para><c>RunTransactionAsync</c> executes the given callback on the main thread and then /// attempts to commit the changes applied within the transaction. If any document read within /// the transaction has changed, the <paramref name="callback"/> will be retried. If it fails to /// commit after 5 attempts, the transaction will fail.</para> /// /// <para>The maximum number of writes allowed in a single transaction is 500, but note that /// each usage of <see cref="FieldValue.ServerTimestamp"/>, <c>FieldValue.ArrayUnion</c>, /// <c>FieldValue.ArrayRemove</c>, or <c>FieldValue.Increment</c> inside a transaction counts as /// an additional write.</para> /// </remarks> /// /// <typeparam name="T">The result type of the callback.</typeparam> /// <param name="callback">The callback to execute. Must not be <c>null</c>. The callback will /// be invoked on the main thread.</param> /// <returns>A task which completes when the transaction has committed. The result of the task /// then contains the result of the callback.</returns> public Task<T> RunTransactionAsync<T>(Func<Transaction, Task<T>> callback) { Preconditions.CheckNotNull(callback, nameof(callback)); return WithFirestoreProxy(proxy => _transactionManager.RunTransactionAsync(callback)); } private static SnapshotsInSyncCallbackMap snapshotsInSyncCallbacks = new SnapshotsInSyncCallbackMap(); internal delegate void SnapshotsInSyncDelegate(int callbackId); private static SnapshotsInSyncDelegate snapshotsInSyncHandler = new SnapshotsInSyncDelegate(SnapshotsInSyncHandler); [MonoPInvokeCallback(typeof(SnapshotsInSyncDelegate))] private static void SnapshotsInSyncHandler(int callbackId) { try { Action callback; if (snapshotsInSyncCallbacks.TryGetCallback(callbackId, out callback)) { FirebaseHandler.RunOnMainThread<object>(() => { callback(); return null; }); } } catch (Exception e) { Util.OnPInvokeManagedException(e, nameof(SnapshotsInSyncHandler)); } } /// <summary> /// Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync event indicates /// that all listeners affected by a given change have fired, even if a single /// server-generated change affects multiple listeners. /// </summary> /// <remarks> /// NOTE: The snapshots-in-sync event only indicates that listeners are in sync with each other, /// but does not relate to whether those snapshots are in sync with the server. Use /// SnapshotMetadata in the individual listeners to determine if a snapshot is from the cache or /// the server. /// </remarks> /// <param name="callback">A callback to be called every time all snapshot listeners are in /// sync with each other. The callback will be invoked on the main thread.</param> /// <returns>A registration object that can be used to remove the listener.</returns> public ListenerRegistration ListenForSnapshotsInSync(Action callback) { Preconditions.CheckNotNull(callback, nameof(callback)); var tcs = new TaskCompletionSource<object>(); int uid = -1; ListenerRegistrationProxy listenerProxy = WithFirestoreProxy(proxy => { uid = snapshotsInSyncCallbacks.Register(this, callback); return FirestoreCpp.AddSnapshotsInSyncListener(proxy, uid, snapshotsInSyncHandler); }); return new ListenerRegistration(snapshotsInSyncCallbacks, uid, tcs, listenerProxy); } private static LoadBundleProgressCallbackMap loadBundleProgressCallbackMap = new LoadBundleProgressCallbackMap(); internal delegate void LoadBundleTaskProgressDelegate(int callbackId, IntPtr progress); private static LoadBundleTaskProgressDelegate handler = new LoadBundleTaskProgressDelegate(LoadBundleTaskProgressHandler); [MonoPInvokeCallback(typeof(LoadBundleTaskProgressDelegate))] private static void LoadBundleTaskProgressHandler(int callbackId, IntPtr progressPtr) { try { // Create the proxy object _before_ doing anything else to ensure that the C++ object's // memory does not get leaked (https://github.com/firebase/firebase-unity-sdk/issues/49). var progressProxy = new LoadBundleTaskProgressProxy(progressPtr, /*cMemoryOwn=*/true); Action<LoadBundleTaskProgress> callback; if (loadBundleProgressCallbackMap.TryGetCallback(callbackId, out callback)) { callback(new LoadBundleTaskProgress(progressProxy)); } } catch (Exception e) { Util.OnPInvokeManagedException(e, nameof(LoadBundleTaskProgressHandler)); } } /// <summary> /// Loads a Firestore bundle into the local cache. /// </summary> /// <param name="bundleData">The bundle to be loaded.</param> /// <returns>A task that is completed when the loading is completed. The result of /// the task then contains the final progress of the loading operation. /// </returns> public Task<LoadBundleTaskProgress> LoadBundleAsync(string bundleData) { Preconditions.CheckNotNull(bundleData, nameof(bundleData)); return WithFirestoreProxy( proxy => Util.MapResult(FirestoreCpp.LoadBundleAsync(proxy, bundleData), progressProxy => new LoadBundleTaskProgress(progressProxy))); } /// <summary> /// Loads a Firestore bundle into the local cache, taking an <see cref="System.EventHandler"/> /// to monitor loading progress. /// </summary> /// <param name="bundleData">The bundle to be loaded.</param> /// <param name="progressHandler">A <see cref="System.EventHandler"/> that is notified with /// progress updates, and completion or error updates. The handler will be invoked on the /// main thread.</param> /// <returns>A task that is completed when the loading is completed. The result of the task /// then contains the final progress of the loading operation. /// </returns> public Task<LoadBundleTaskProgress> LoadBundleAsync( string bundleData, System.EventHandler<LoadBundleTaskProgress> progressHandler) { Preconditions.CheckNotNull(bundleData, nameof(bundleData)); Preconditions.CheckNotNull(progressHandler, nameof(progressHandler)); Action<LoadBundleTaskProgress> action = (LoadBundleTaskProgress progress) => { FirebaseHandler.RunOnMainThread<object>(() => { progressHandler(this, progress); return null; }); }; return WithFirestoreProxy(proxy => { int callbackId = loadBundleProgressCallbackMap.Register(this, action); return Util.MapResult(FirestoreCpp.LoadBundleAsync(proxy, bundleData, callbackId, handler), progressProxy => new LoadBundleTaskProgress(progressProxy)); }); } /// <summary> /// Loads a Firestore bundle into the local cache. /// </summary> /// <param name="bundleData">The bundle to be loaded, as a UTF-8 encoded byte array.</param> /// <returns>A task that is completed when the loading is completed. The result of /// the task then contains the final progress of the loading operation. /// </returns> public Task<LoadBundleTaskProgress> LoadBundleAsync(byte[] bundleData) { Preconditions.CheckNotNull(bundleData, nameof(bundleData)); // TODO(b/190626833): Consider expose a C++ interface taking byte array, to avoid encoding // here. return LoadBundleAsync(Encoding.UTF8.GetString(bundleData)); } /// <summary> /// Loads a Firestore bundle into the local cache, taking an <see cref="System.EventHandler"/> /// to monitor loading progress. /// </summary> /// <param name="bundleData">The bundle to be loaded, as a UTF8 encoded byte array.</param> /// <param name="progressHandler">An <see cref="System.EventHandler"/> that is notified with /// progress updates, and completion or error updates. The handler will be invoked on the main /// thread.</param> /// <returns>A task that is completed when the loading is completed. The result of the task /// then contains the final progress of the loading operation. /// </returns> public Task<LoadBundleTaskProgress> LoadBundleAsync( byte[] bundleData, System.EventHandler<LoadBundleTaskProgress> progressHandler) { Preconditions.CheckNotNull(bundleData, nameof(bundleData)); Preconditions.CheckNotNull(progressHandler, nameof(progressHandler)); return LoadBundleAsync(Encoding.UTF8.GetString(bundleData), progressHandler); } /// <summary> /// Reads a Firestore <see cref="Query"/> from the local cache, identified by the given /// name. /// </summary> /// <remarks> /// Named queries are packaged into bundles on the server side (along with the /// resulting documents) and loaded into local cache using <see /// cref="FirebaseFirestore.LoadBundleAsync(string)"/>. Once in the local cache, you can use /// this method to extract a query by name. /// </remarks> /// <param name="queryName">The name of the query to read from saved bundles.</param> /// <returns>A task that is completed with the query associated with the given name. The result /// of the returned task is set to null if no queries can be found. /// </returns> public Task<Query> GetNamedQueryAsync(string queryName) { Preconditions.CheckNotNull(queryName, nameof(queryName)); return WithFirestoreProxy(proxy => { return proxy.NamedQueryAsync(queryName).ContinueWith<Query>((queryProxy) => { if (queryProxy.IsFaulted) { return null; } return new Query(queryProxy.Result, this); }); }); } /// <summary> /// Disables network access for this instance. /// </summary> /// <remarks> /// While the network is disabled, any snapshot listeners or <c>GetSnapshotAsync</c> calls will /// return results from cache, and any write operations will be queued until network usage is /// re-enabled via a call to <see cref="FirebaseFirestore.EnableNetworkAsync"/>. /// </remarks> /// <returns>A task which completes once networking is disabled.</returns> public Task DisableNetworkAsync() { return WithFirestoreProxy(proxy => proxy.DisableNetworkAsync()); } /// <summary> /// Re-enables network usage for this instance after a prior call to /// <see cref="FirebaseFirestore.DisableNetworkAsync"/>. /// </summary> /// <returns>A task which completes once networking is enabled.</returns> public Task EnableNetworkAsync() { return WithFirestoreProxy(proxy => proxy.EnableNetworkAsync()); } /// <summary> /// Waits until all currently pending writes for the active user have been acknowledged by the /// backend. /// </summary> /// /// <remarks> /// The returned Task completes immediately if there are no outstanding writes. Otherwise, the /// Task waits for all previously issued writes (including those written in a previous app /// session), but it does not wait for writes that were added after the method is called. If you /// wish to wait for additional writes, you have to call `WaitForPendingWritesAsync()` again. /// /// Any outstanding `WaitForPendingWritesAsync()` Tasks are cancelled during user changes. /// </remarks> /// /// <returns> A Task which completes when all currently pending writes have been acknowledged /// by the backend.</returns> public Task WaitForPendingWritesAsync() { return WithFirestoreProxy(proxy => proxy.WaitForPendingWritesAsync()); } /// <summary> /// Terminates this <c>FirebaseFirestore</c> instance. /// </summary> /// /// <remarks> /// After calling <c>Terminate()</c>, only the <c>ClearPersistenceAsync()</c> method may be /// used. Calling any other method will result in an error. /// /// To restart after termination, simply create a new instance of <c>FirebaseFirestore</c> with /// <c>GetInstance()</c> or <c>GetInstance(FirebaseApp)</c>. /// /// <c>Terminate()</c> does not cancel any pending writes, and any tasks that are awaiting a /// response from the server will not be resolved. The next time you start this instance, it /// will resume attempting to send these writes to the server. /// /// Note: under normal circumstances, calling <c>Terminate()</c> is not required. This method /// is useful only when you want to force this instance to release all of its resources or in /// combination with <c>ClearPersistenceAsync</c> to ensure that all local state is destroyed /// between test runs. /// </remarks> /// /// <returns> /// A Task which completes when the instance has been successfully terminated. /// </returns> public Task TerminateAsync() { return WithFirestoreProxy(proxy => { lock (_isInCppInstanceCacheLock) { Task terminateTask = proxy.TerminateAsync(); _isInCppInstanceCache = false; RemoveSelfFromInstanceCache(); return terminateTask; } }); } /// <summary> /// Clears the persistent storage. This includes pending writes and cached documents. /// </summary> /// /// <remarks> /// Must be called while the Firestore instance is not started (after the app is shut down or /// when the app is first initialized). On startup, this method must be called before other /// methods (other than getting or setting `FirebaseFirestoreSettings`). If the Firestore /// instance is still running, the task will complete with an error code of /// `FailedPrecondition`. /// /// Note: `ClearPersistenceAsync()` is primarily intended to help write reliable tests that use /// Firestore. It uses the most efficient mechanism possible for dropping existing data but does /// not attempt to securely overwrite or otherwise make cached data unrecoverable. For /// applications that are sensitive to the disclosure of cache data in between user sessions we /// strongly recommend not to enable persistence in the first place. /// </remarks> /// /// <returns>A Task which completes when the clear persistence operation has completed. /// </returns> public Task ClearPersistenceAsync() { return WithFirestoreProxy(proxy => proxy.ClearPersistenceAsync()); } /// <summary> /// Sets the log verbosity of all Firestore instances. /// /// The default verbosity level is /// <see cref="Firebase.LogLevel.Info">Info</see> /// . /// Set to /// <see cref="Firebase.LogLevel.Debug">Debug</see> /// to turn on the diagnostic logging. /// </summary> /// <value>The desired verbosity.</value> public static LogLevel LogLevel { set { // This is thread-safe as far as the underlying one is thread-safe. FirestoreProxy.set_log_level(value); } } /// <summary> /// Ensure that the `FirestoreProxy` has had its settings applied, and then call the given /// `Function` with that `FirestoreProxy` instance, returning whatever it returns. If the /// `FirestoreProxy` has been disposed, then a `FirestoreException` is thrown. /// </summary> private T WithFirestoreProxy<T>(Func<FirestoreProxy, T> func) { _disposeLock.AcquireReaderLock(Int32.MaxValue); try { if (_proxy == null) { throw new InvalidOperationException("Firestore instance has been disposed"); } _settings.EnsureAppliedToFirestoreProxy(); return func(_proxy); } finally { _disposeLock.ReleaseReaderLock(); } } /// <summary> /// Ensure that the `FirestoreProxy` has had its settings applied, and then call the given /// `Action` with that `FirestoreProxy` instance. If the `FirestoreProxy` has been disposed, /// then a `FirestoreException` is thrown. /// </summary> private void WithFirestoreProxy(Action<FirestoreProxy> action) { WithFirestoreProxy<object>(proxy => { action(proxy); return null; }); } /// <summary> /// Removes the mapping from the instance cache for this object. /// </summary> private void RemoveSelfFromInstanceCache() { lock (_instanceCache) { FirebaseFirestore cachedFirestore; if (_instanceCache.TryGetValue(App, out cachedFirestore) && cachedFirestore == this) { _instanceCache.Remove(App); } } } } }
using PublicApiGeneratorTests.Examples; using Xunit; namespace PublicApiGeneratorTests { public class Property_visibility : ApiGeneratorTestsBase { [Fact] public void Should_output_public_property() { AssertPublicApi<ClassWithPublicProperty>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPublicProperty { public ClassWithPublicProperty() { } public string Value { get; set; } } }"); } [Fact] public void Should_output_protected_property() { AssertPublicApi<ClassWithProtectedProperty>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithProtectedProperty { public ClassWithProtectedProperty() { } protected string Value { get; set; } } }"); } [Fact] public void Should_output_protected_internal_property() { AssertPublicApi<ClassWithProtectedInternalProperty>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithProtectedInternalProperty { public ClassWithProtectedInternalProperty() { } protected string Value { get; set; } } }"); } [Fact] public void Should_not_output_private_protected_property() { AssertPublicApi<ClassWithPrivateProtectedProperty>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPrivateProtectedProperty { public ClassWithPrivateProtectedProperty() { } } }"); } [Fact] public void Should_not_output_private_property() { AssertPublicApi<ClassWithPrivateProperty>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPrivateProperty { public ClassWithPrivateProperty() { } } }"); } [Fact] public void Should_not_output_internal_property() { AssertPublicApi<ClassWithInternalProperty>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithInternalProperty { public ClassWithInternalProperty() { } } }"); } [Fact] public void Should_not_output_private_setter_for_public_property() { AssertPublicApi<ClassWithPublicGetterPrivateSetter>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPublicGetterPrivateSetter { public ClassWithPublicGetterPrivateSetter() { } public string Value1 { get; } } }"); } [Fact] public void Should_not_output_internal_setter_for_public_property() { AssertPublicApi<ClassWithPublicGetterInternalSetter>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPublicGetterInternalSetter { public ClassWithPublicGetterInternalSetter() { } public string Value1 { get; } } }"); } [Fact] public void Should_output_protected_setter_for_public_property() { AssertPublicApi<ClassWithPublicGetterProtectedSetter>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPublicGetterProtectedSetter { public ClassWithPublicGetterProtectedSetter() { } public string Value1 { get; set; } } }"); } [Fact(Skip = "Not supported by CodeDOM")] [Trait("TODO", "Property method modifiers not supported by CodeDOM")] public void Should_output_protected_setter_for_public_property_with_correct_modifier() { AssertPublicApi<ClassWithPublicGetterProtectedSetter>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPublicGetterProtectedSetter { public ClassWithPublicGetterProtectedSetter() { } public string Value1 { get; protected set; } } }"); } [Fact] public void Should_output_protected_internal_setter_for_public_property() { AssertPublicApi<ClassWithPublicGetterProtectedInternalSetter>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPublicGetterProtectedInternalSetter { public ClassWithPublicGetterProtectedInternalSetter() { } public string Value1 { get; set; } } }"); } [Fact] public void Should_not_output_private_protected_setter_for_public_property() { AssertPublicApi<ClassWithPublicGetterPrivateProtectedSetter>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPublicGetterPrivateProtectedSetter { public ClassWithPublicGetterPrivateProtectedSetter() { } public string Value1 { get; } } }"); } [Fact(Skip = "Not supported by CodeDOM")] [Trait("TODO", "Property method modifiers not supported by CodeDOM")] public void Should_output_protected_internal_setter_for_public_property_with_correct_modifier() { AssertPublicApi<ClassWithPublicGetterProtectedInternalSetter>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPublicGetterProtectedInternalSetter { public ClassWithPublicGetterProtectedInternalSetter() { } public string Value1 { get; protected internal set; } } }"); } [Fact] public void Should_not_output_private_getter_for_public_property() { AssertPublicApi<ClassWithPrivateGetterPublicSetter>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPrivateGetterPublicSetter { public ClassWithPrivateGetterPublicSetter() { } public string Value1 { set; } } }"); } [Fact] public void Should_not_output_internal_getter_for_public_property() { AssertPublicApi<ClassWithInternalGetterPublicSetter>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithInternalGetterPublicSetter { public ClassWithInternalGetterPublicSetter() { } public string Value1 { set; } } }"); } [Fact] public void Should_output_protected_getter_for_public_property() { // TODO: CodeDOM doesn't support access modifiers on setters or getters // Doesn't really matter for diffing APIs, though AssertPublicApi<ClassWithProtectedGetterPublicSetter>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithProtectedGetterPublicSetter { public ClassWithProtectedGetterPublicSetter() { } public string Value1 { get; set; } } }"); } [Fact(Skip = "Not supported by CodeDOM")] [Trait("TODO", "Property method modifiers not supported by CodeDOM")] public void Should_output_protected_getter_for_public_property_with_correct_modifier() { AssertPublicApi<ClassWithProtectedGetterPublicSetter>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithProtectedGetterPublicSetter { public ClassWithProtectedGetterPublicSetter() { } public string Value1 { protected get; set; } } }"); } [Fact] public void Should_output_protected_internal_getter_for_public_property() { // TODO: CodeDOM doesn't support access modifiers on setters or getters // Doesn't really matter for diffing APIs, though AssertPublicApi<ClassWithProtectedInternalGetterPublicSetter>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithProtectedInternalGetterPublicSetter { public ClassWithProtectedInternalGetterPublicSetter() { } public string Value1 { get; set; } } }"); } [Fact(Skip = "Not supported by CodeDOM")] [Trait("TODO", "Property method modifiers not supported by CodeDOM")] public void Should_output_protected_internal_getter_for_public_property_with_correct_modifier() { AssertPublicApi<ClassWithProtectedInternalGetterPublicSetter>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithProtectedInternalGetterPublicSetter { public ClassWithProtectedInternalGetterPublicSetter() { } public string Value1 { protected get; set; } } }"); } } // ReSharper disable ClassNeverInstantiated.Global // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local // ReSharper disable UnusedAutoPropertyAccessor.Local namespace Examples { public class ClassWithPublicProperty { public string Value { get; set; } } public class ClassWithProtectedProperty { protected string Value { get; set; } } public class ClassWithPrivateProperty { private string Value { get; set; } } public class ClassWithInternalProperty { internal string Value { get; set; } } public class ClassWithProtectedInternalProperty { protected internal string Value { get; set; } } public class ClassWithPrivateProtectedProperty { private protected string Value { get; set; } } public class ClassWithPublicGetterPrivateSetter { public string Value1 { get; private set; } } public class ClassWithPublicGetterInternalSetter { public string Value1 { get; internal set; } } public class ClassWithPublicGetterProtectedSetter { public string Value1 { get; protected set; } } public class ClassWithPublicGetterProtectedInternalSetter { public string Value1 { get; protected internal set; } } public class ClassWithPublicGetterPrivateProtectedSetter { public string Value1 { get; private protected set; } } public class ClassWithPrivateGetterPublicSetter { public string Value1 { private get; set; } } public class ClassWithInternalGetterPublicSetter { public string Value1 { internal get; set; } } public class ClassWithProtectedGetterPublicSetter { public string Value1 { protected get; set; } } public class ClassWithProtectedInternalGetterPublicSetter { public string Value1 { protected internal get; set; } } } // ReSharper restore UnusedAutoPropertyAccessor.Local // ReSharper restore UnusedMember.Local // ReSharper restore UnusedMember.Global // ReSharper restore ClassNeverInstantiated.Global }
// 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.Network { using Azure; using Management; using Rest; using 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> /// RouteFilterRulesOperations operations. /// </summary> internal partial class RouteFilterRulesOperations : IServiceOperations<NetworkManagementClient>, IRouteFilterRulesOperations { /// <summary> /// Initializes a new instance of the RouteFilterRulesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal RouteFilterRulesOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified rule from a route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </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 routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified rule from a route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RouteFilterRule>> GetWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeFilterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName"); } if (ruleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ruleName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeFilterName", routeFilterName); tracingParameters.Add("ruleName", ruleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName)); _url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RouteFilterRule>(); _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<RouteFilterRule>(_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 a route in the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the create or update route filter rule operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<RouteFilterRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<RouteFilterRule> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Updates a route in the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the update route filter rule operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<RouteFilterRule>> UpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<RouteFilterRule> _response = await BeginUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all RouteFilterRules in a route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RouteFilterRule>>> ListByRouteFilterWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeFilterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeFilterName", routeFilterName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByRouteFilter", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RouteFilterRule>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilterRule>>(_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 the specified rule from a route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeFilterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName"); } if (ruleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ruleName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeFilterName", routeFilterName); tracingParameters.Add("ruleName", ruleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName)); _url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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 != 202 && (int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } 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> /// Creates or updates a route in the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the create or update route filter rule operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RouteFilterRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeFilterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName"); } if (ruleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ruleName"); } if (routeFilterRuleParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterRuleParameters"); } if (routeFilterRuleParameters != null) { routeFilterRuleParameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (routeFilterRuleParameters == null) { routeFilterRuleParameters = new RouteFilterRule(); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeFilterName", routeFilterName); tracingParameters.Add("ruleName", ruleName); tracingParameters.Add("routeFilterRuleParameters", routeFilterRuleParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName)); _url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.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(routeFilterRuleParameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routeFilterRuleParameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // 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 != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RouteFilterRule>(); _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<RouteFilterRule>(_responseContent, 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 == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilterRule>(_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> /// Updates a route in the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the update route filter rule operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RouteFilterRule>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeFilterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName"); } if (ruleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ruleName"); } if (routeFilterRuleParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterRuleParameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (routeFilterRuleParameters == null) { routeFilterRuleParameters = new PatchRouteFilterRule(); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeFilterName", routeFilterName); tracingParameters.Add("ruleName", ruleName); tracingParameters.Add("routeFilterRuleParameters", routeFilterRuleParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName)); _url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PATCH"); _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(routeFilterRuleParameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routeFilterRuleParameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RouteFilterRule>(); _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<RouteFilterRule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all RouteFilterRules in a route filter. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RouteFilterRule>>> ListByRouteFilterNextWithHttpMessagesAsync(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, "ListByRouteFilterNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RouteFilterRule>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteFilterRule>>(_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; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using DeOps.Interface.Views; namespace DeOps.Interface { public partial class TextInput : UserControl { // show font strip private bool ShowStrip = true; public bool ShowFontStrip { get { return ShowStrip; } set { ShowStrip = value; if (ShowStrip) FontToolStrip.Show(); else FontToolStrip.Hide(); } } // Default Plain Text bool PlainText; public bool PlainTextMode { get { return PlainText; } set { PlainText = value; FontSeparator.Visible = !value; BoldButton.Visible = !value; ItalicsButton.Visible = !value; UnderlineButton.Visible = !value; FontButton.Visible = !value; ColorsButton.Visible = !value; TextFormat = value ? TextFormat.Plain : TextFormat.RTF; } } // IM Buttons bool _IMButtons; public bool IMButtons { get { return _IMButtons; } set { _IMButtons = value; SendFileButton.Visible = value; BlockButton.Visible = value; } } // read only public bool ReadOnly { get { return InputBox.ReadOnly; } set { InputBox.ReadOnly = value; if (value) // dont auto turn on when input is not read-only ShowFontStrip = false; } } // enter clears private bool _EnterClears = true; public bool EnterClears { get { return _EnterClears; } set { _EnterClears = value; } } // accept tabs public bool AcceptTabs { get { return InputBox.AcceptsTab; } set { InputBox.AcceptsTab = value; } } public TextFormat TextFormat = TextFormat.RTF; public delegate void SendMessageHandler(string message, TextFormat format); public SendMessageHandler SendMessage; public MethodInvoker SendFile; public MethodInvoker IgnoreUser; public MethodInvoker AddBuddy; public TextInput() { InitializeComponent(); GuiUtils.SetupToolstrip(FontToolStrip, new OpusColorTable()); // need to init, so when we get the rtf there is color encoding info in it we can re-assign if need be InputBox.SelectionColor = Color.Black; } private void SmallerButton_Click(object sender, EventArgs e) { Font current = InputBox.SelectionFont; InputBox.SelectionFont = new Font(current.FontFamily, current.Size - 2, current.Style); } private void NormalButton_Click(object sender, EventArgs e) { Font current = InputBox.SelectionFont; InputBox.SelectionFont = new Font(current.FontFamily, 10, current.Style); } private void LargerButton_Click(object sender, EventArgs e) { Font current = InputBox.SelectionFont; InputBox.SelectionFont = new Font(current.FontFamily, current.Size + 2, current.Style); } private void BoldButton_Click(object sender, EventArgs e) { ApplyStyle(FontStyle.Bold, BoldButton.Checked); } private void ItalicsButton_Click(object sender, EventArgs e) { ApplyStyle(FontStyle.Italic, ItalicsButton.Checked); } private void UnderlineButton_Click(object sender, EventArgs e) { ApplyStyle(FontStyle.Underline, UnderlineButton.Checked); } void ApplyStyle(FontStyle style, bool enabled) { FontStyle newStyle = InputBox.SelectionFont.Style; if (enabled) newStyle |= style; else newStyle &= ~style; InputBox.SelectionFont = new Font(InputBox.SelectionFont, newStyle); } private void ColorsButton_Click(object sender, EventArgs e) { ColorDialog dialog = new ColorDialog(); if (dialog.ShowDialog(this) != DialogResult.OK) return; InputBox.SelectionColor = dialog.Color; InputBox.Select(); } private void InputBox_SelectionChanged(object sender, EventArgs e) { if (InputBox.SelectionFont == null) return; BoldButton.Checked = InputBox.SelectionFont.Bold; ItalicsButton.Checked = InputBox.SelectionFont.Italic; UnderlineButton.Checked = InputBox.SelectionFont.Underline; } private void InputBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Return && _EnterClears && !e.Shift) { if (InputBox.Text.Replace("\n", "") != "") { string message = InputBox.Text; if (TextFormat == TextFormat.RTF) { message = InputBox.Rtf; Regex rex = new Regex("\\\\par\\s+", RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); Match m = rex.Match(message); while (m.Success) { message = rex.Replace(message, ""); m = m.NextMatch(); } } BeginInvoke(SendMessage, message, TextFormat); //Panel.SendMessage(); } Font savedFont = InputBox.SelectionFont; Color savedColor = InputBox.SelectionColor; InputBox.Clear(); InputBox.SelectionFont = savedFont; InputBox.SelectionColor = savedColor; e.Handled = true; } } private void FontButton_Click(object sender, EventArgs e) { FontDialog dialog = new FontDialog(); dialog.Font = InputBox.SelectionFont; if (dialog.ShowDialog(this) != DialogResult.OK) return; InputBox.SelectionFont = dialog.Font; InputBox.Select(); } private void BlockButton_Click(object sender, EventArgs e) { BeginInvoke(IgnoreUser); } private void SendFileButton_Click(object sender, EventArgs e) { BeginInvoke(SendFile); } private void PlainTextButton_Click(object sender, EventArgs e) { // clear formatting string text = InputBox.Text; InputBox.Clear(); InputBox.Text = text; PlainTextMode = true; } private void RichTextButton_Click_1(object sender, EventArgs e) { PlainTextMode = false; } private void AddBuddyButton_Click(object sender, EventArgs e) { BeginInvoke(AddBuddy); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Serialization { using System; using System.Reflection; using System.Collections; using System.Diagnostics; using System.Collections.Generic; // These classes define the abstract serialization model, e.g. the rules for WHAT is serialized. // The answer of HOW the values are serialized is answered by a particular reflection importer // by looking for a particular set of custom attributes specific to the serialization format // and building an appropriate set of accessors/mappings. internal class ModelScope { private TypeScope _typeScope; private readonly Dictionary<Type, TypeModel> _models = new Dictionary<Type, TypeModel>(); private readonly Dictionary<Type, TypeModel> _arrayModels = new Dictionary<Type, TypeModel>(); internal ModelScope(TypeScope typeScope) { _typeScope = typeScope; } internal TypeScope TypeScope { get { return _typeScope; } } internal TypeModel GetTypeModel(Type type) { return GetTypeModel(type, true); } internal TypeModel GetTypeModel(Type type, bool directReference) { TypeModel model; if (_models.TryGetValue(type, out model)) return model; TypeDesc typeDesc = _typeScope.GetTypeDesc(type, null, directReference); switch (typeDesc.Kind) { case TypeKind.Enum: model = new EnumModel(type, typeDesc, this); break; case TypeKind.Primitive: model = new PrimitiveModel(type, typeDesc, this); break; case TypeKind.Array: case TypeKind.Collection: case TypeKind.Enumerable: model = new ArrayModel(type, typeDesc, this); break; case TypeKind.Root: case TypeKind.Class: case TypeKind.Struct: model = new StructModel(type, typeDesc, this); break; default: if (!typeDesc.IsSpecial) throw new NotSupportedException(SR.Format(SR.XmlUnsupportedTypeKind, type.FullName)); model = new SpecialModel(type, typeDesc, this); break; } _models.Add(type, model); return model; } internal ArrayModel GetArrayModel(Type type) { TypeModel model; if (!_arrayModels.TryGetValue(type, out model)) { model = GetTypeModel(type); if (!(model is ArrayModel)) { TypeDesc typeDesc = _typeScope.GetArrayTypeDesc(type); model = new ArrayModel(type, typeDesc, this); } _arrayModels.Add(type, model); } return (ArrayModel)model; } } internal abstract class TypeModel { private TypeDesc _typeDesc; private Type _type; private ModelScope _scope; protected TypeModel(Type type, TypeDesc typeDesc, ModelScope scope) { _scope = scope; _type = type; _typeDesc = typeDesc; } internal Type Type { get { return _type; } } internal ModelScope ModelScope { get { return _scope; } } internal TypeDesc TypeDesc { get { return _typeDesc; } } } internal class ArrayModel : TypeModel { internal ArrayModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { } internal TypeModel Element { get { return ModelScope.GetTypeModel(TypeScope.GetArrayElementType(Type, null)); } } } internal class PrimitiveModel : TypeModel { internal PrimitiveModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { } } internal class SpecialModel : TypeModel { internal SpecialModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { } } internal class StructModel : TypeModel { internal StructModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { } internal MemberInfo[] GetMemberInfos() { // we use to return Type.GetMembers() here, the members were returned in a different order: fields first, properties last // Current System.Reflection code returns members in oposite order: properties first, then fields. // This code make sure that returns members in the Everett order. MemberInfo[] members = Type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); MemberInfo[] fieldsAndProps = new MemberInfo[members.Length]; int cMember = 0; // first copy all non-property members over for (int i = 0; i < members.Length; i++) { if (!(members[i] is PropertyInfo)) { fieldsAndProps[cMember++] = members[i]; } } // now copy all property members over for (int i = 0; i < members.Length; i++) { if (members[i] is PropertyInfo) { fieldsAndProps[cMember++] = members[i]; } } return fieldsAndProps; } internal FieldModel GetFieldModel(MemberInfo memberInfo) { FieldModel model = null; if (memberInfo is FieldInfo) model = GetFieldModel((FieldInfo)memberInfo); else if (memberInfo is PropertyInfo) model = GetPropertyModel((PropertyInfo)memberInfo); if (model != null) { if (model.ReadOnly && model.FieldTypeDesc.Kind != TypeKind.Collection && model.FieldTypeDesc.Kind != TypeKind.Enumerable) return null; } return model; } private void CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type type) { if (typeDesc == null) return; if (typeDesc.IsUnsupported) { if (typeDesc.Exception == null) { typeDesc.Exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, typeDesc.FullName)); } throw new InvalidOperationException(SR.Format(SR.XmlSerializerUnsupportedMember, member.DeclaringType.FullName + "." + member.Name, type.FullName), typeDesc.Exception); } CheckSupportedMember(typeDesc.BaseTypeDesc, member, type); CheckSupportedMember(typeDesc.ArrayElementTypeDesc, member, type); } private FieldModel GetFieldModel(FieldInfo fieldInfo) { if (fieldInfo.IsStatic) return null; if (fieldInfo.DeclaringType != Type) return null; TypeDesc typeDesc = ModelScope.TypeScope.GetTypeDesc(fieldInfo.FieldType, fieldInfo, true, false); if (fieldInfo.IsInitOnly && typeDesc.Kind != TypeKind.Collection && typeDesc.Kind != TypeKind.Enumerable) return null; CheckSupportedMember(typeDesc, fieldInfo, fieldInfo.FieldType); return new FieldModel(fieldInfo, fieldInfo.FieldType, typeDesc); } private FieldModel GetPropertyModel(PropertyInfo propertyInfo) { if (propertyInfo.DeclaringType != Type) return null; if (CheckPropertyRead(propertyInfo)) { TypeDesc typeDesc = ModelScope.TypeScope.GetTypeDesc(propertyInfo.PropertyType, propertyInfo, true, false); // Fix for CSDMain 100492, please contact arssrvlt if you need to change this line if (!propertyInfo.CanWrite && typeDesc.Kind != TypeKind.Collection && typeDesc.Kind != TypeKind.Enumerable) return null; CheckSupportedMember(typeDesc, propertyInfo, propertyInfo.PropertyType); return new FieldModel(propertyInfo, propertyInfo.PropertyType, typeDesc); } return null; } //CheckProperty internal static bool CheckPropertyRead(PropertyInfo propertyInfo) { if (!propertyInfo.CanRead) return false; MethodInfo getMethod = propertyInfo.GetMethod; if (getMethod.IsStatic) return false; ParameterInfo[] parameters = getMethod.GetParameters(); if (parameters.Length > 0) return false; return true; } } internal enum SpecifiedAccessor { None, ReadOnly, ReadWrite, } internal class FieldModel { private SpecifiedAccessor _checkSpecified = SpecifiedAccessor.None; private MemberInfo _memberInfo; private MemberInfo _checkSpecifiedMemberInfo; private MethodInfo _checkShouldPersistMethodInfo; private bool _checkShouldPersist; private bool _readOnly = false; private bool _isProperty = false; private Type _fieldType; private string _name; private TypeDesc _fieldTypeDesc; internal FieldModel(string name, Type fieldType, TypeDesc fieldTypeDesc, bool checkSpecified, bool checkShouldPersist) : this(name, fieldType, fieldTypeDesc, checkSpecified, checkShouldPersist, false) { } internal FieldModel(string name, Type fieldType, TypeDesc fieldTypeDesc, bool checkSpecified, bool checkShouldPersist, bool readOnly) { _fieldTypeDesc = fieldTypeDesc; _name = name; _fieldType = fieldType; _checkSpecified = checkSpecified ? SpecifiedAccessor.ReadWrite : SpecifiedAccessor.None; _checkShouldPersist = checkShouldPersist; _readOnly = readOnly; } internal FieldModel(MemberInfo memberInfo, Type fieldType, TypeDesc fieldTypeDesc) { _name = memberInfo.Name; _fieldType = fieldType; _fieldTypeDesc = fieldTypeDesc; _memberInfo = memberInfo; _checkShouldPersistMethodInfo = memberInfo.DeclaringType.GetMethod("ShouldSerialize" + memberInfo.Name, Array.Empty<Type>()); _checkShouldPersist = _checkShouldPersistMethodInfo != null; FieldInfo specifiedField = memberInfo.DeclaringType.GetField(memberInfo.Name + "Specified"); if (specifiedField != null) { if (specifiedField.FieldType != typeof(bool)) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidSpecifiedType, specifiedField.Name, specifiedField.FieldType.FullName, typeof(bool).FullName)); } _checkSpecified = specifiedField.IsInitOnly ? SpecifiedAccessor.ReadOnly : SpecifiedAccessor.ReadWrite; _checkSpecifiedMemberInfo = specifiedField; } else { PropertyInfo specifiedProperty = memberInfo.DeclaringType.GetProperty(memberInfo.Name + "Specified"); if (specifiedProperty != null) { if (StructModel.CheckPropertyRead(specifiedProperty)) { _checkSpecified = specifiedProperty.CanWrite ? SpecifiedAccessor.ReadWrite : SpecifiedAccessor.ReadOnly; _checkSpecifiedMemberInfo = specifiedProperty; } if (_checkSpecified != SpecifiedAccessor.None && specifiedProperty.PropertyType != typeof(bool)) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidSpecifiedType, specifiedProperty.Name, specifiedProperty.PropertyType.FullName, typeof(bool).FullName)); } } } if (memberInfo is PropertyInfo) { _readOnly = !((PropertyInfo)memberInfo).CanWrite; _isProperty = true; } else if (memberInfo is FieldInfo) { _readOnly = ((FieldInfo)memberInfo).IsInitOnly; } } internal string Name { get { return _name; } } internal Type FieldType { get { return _fieldType; } } internal TypeDesc FieldTypeDesc { get { return _fieldTypeDesc; } } internal bool CheckShouldPersist { get { return _checkShouldPersist; } } internal SpecifiedAccessor CheckSpecified { get { return _checkSpecified; } } internal MemberInfo MemberInfo { get { return _memberInfo; } } internal MemberInfo CheckSpecifiedMemberInfo { get { return _checkSpecifiedMemberInfo; } } internal MethodInfo CheckShouldPersistMethodInfo { get { return _checkShouldPersistMethodInfo; } } internal bool ReadOnly { get { return _readOnly; } } internal bool IsProperty { get { return _isProperty; } } } internal class ConstantModel { private FieldInfo _fieldInfo; private long _value; internal ConstantModel(FieldInfo fieldInfo, long value) { _fieldInfo = fieldInfo; _value = value; } internal string Name { get { return _fieldInfo.Name; } } internal long Value { get { return _value; } } internal FieldInfo FieldInfo { get { return _fieldInfo; } } } internal class EnumModel : TypeModel { private ConstantModel[] _constants; internal EnumModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { } internal ConstantModel[] Constants { get { if (_constants == null) { var list = new List<ConstantModel>(); FieldInfo[] fields = Type.GetFields(); for (int i = 0; i < fields.Length; i++) { FieldInfo field = fields[i]; ConstantModel constant = GetConstantModel(field); if (constant != null) list.Add(constant); } _constants = list.ToArray(); } return _constants; } } private ConstantModel GetConstantModel(FieldInfo fieldInfo) { if (fieldInfo.IsSpecialName) return null; return new ConstantModel(fieldInfo, ((IConvertible)fieldInfo.GetValue(null)).ToInt64(null)); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Reflection; using System.Xml; using NHibernate; using NHibernate.Mapping.Attributes; using Configuration=NHibernate.Cfg.Configuration; namespace Csla.NHibernate { /// <summary> /// Class to provide standard factory configuration functions around the NHibernate framework. /// </summary> /// <remarks> /// This class is named so it looks similar to the <c>NHibernate.Cfg</c> namespace. /// </remarks> public class Cfg { #region fields // Declared as static (for singleton pattern) private static Dictionary<string, DatabaseConfiguration> _lookupTable; #endregion #region constructor /// <summary>Direct construction not allowed. Use the factory method.</summary> private Cfg() { } #endregion #region properties private static Dictionary<string, DatabaseConfiguration> LookupTable { get { if (ReferenceEquals(_lookupTable, null)) _lookupTable = new Dictionary<string, DatabaseConfiguration>(); return _lookupTable; } } private DatabaseConfiguration this[string index] { get { CheckKeyIsValid(index); CheckKeyInTable(index); return LookupTable[index]; } } #endregion #region non-public helpers private static void CheckKeyIsValid(string key) { if (String.IsNullOrEmpty(key)) throw new ArgumentException(String.Format("Key '{0}' cannot be null or empty.", key)); } private static void CheckKeyInTable(string key) { if (!LookupTable.ContainsKey(key)) AddNewKey(key); } /// <summary> /// Adds a new key, if it exists in the application configuration file. /// </summary> /// <param name="key">String identifier for the session factory required.</param> /// <exception cref="ConfigurationErrorsException">If the specified session factory key is invalid.</exception> private static void AddNewKey(string key) { // Get the name of the hibernate.cfg.xml file for the required key string factoryCfg = ConfigurationManager.AppSettings[key]; if (String.IsNullOrEmpty(factoryCfg)) throw new ConfigurationErrorsException(String.Format("Key '{0}' cannot be null or empty",key)); // Path it to point to the correct working directory factoryCfg = File.GetNFSConfigFile(factoryCfg); // Now build the required NHibernate database configuration and add it to the lookup table DatabaseConfiguration nhibernateConfig = DatabaseConfiguration.NewDatabaseConfiguration(key); nhibernateConfig.ConnectionString = BuildConnectionString(factoryCfg); nhibernateConfig.SessionFactory = BuildSessionFactory(factoryCfg); LookupTable.Add(key, nhibernateConfig); } private static string BuildConnectionString(string factoryCfg) { string connectionString = null; // Get the connection string from the configuration file using (XmlReader xmlReader = XmlReader.Create(factoryCfg)) { xmlReader.MoveToContent(); // Find the first "property" node if (xmlReader.ReadToFollowing("property")) { bool readRequired; do { string nameAttribute; nameAttribute = xmlReader.GetAttribute("name"); // If we've found the one we need, set the connection string (no more reads needed) if (nameAttribute == "connection.connection_string") { connectionString = xmlReader.ReadString(); readRequired = false; } else { // Get the next "property" node (if one exists) readRequired = xmlReader.ReadToNextSibling("property"); } } while (readRequired); } } return connectionString; } private static ISessionFactory BuildSessionFactory(string factoryCfg) { MemoryStream stream = new MemoryStream(); // where the xml will be written HbmSerializer.Default.Validate = true; // Enable validation (optional) // Set any specific values for the <hibernate-mapping> element here // Set the 'default-access' attribute // This matches our naming convention for member fields HbmSerializer.Default.HbmDefaultAccess = "field.camelcase-underscore"; // Set the 'auto-import' attribute off // This forces NHibernate to use fully qualified class names (i.e. full namespace prefixes) HbmSerializer.Default.HbmAutoImport = false; // Here, we serialize all decorated classes GetNhibernateClasses(stream); stream.Position = 0; // Rewind // TODO: Implement a better method (i.e. configurable) of getting the resulting file out #if DEBUG try { stream.WriteTo(new FileStream(@"ProjectTracker.hbm.xml", FileMode.Create)); } catch (UnauthorizedAccessException e) { //user trying to access the path is probably coming from IIS and it does not have permission to create the file //to catch it and carry on e.ToString(); //prevent r# warning } #endif Configuration configuration = new Configuration();; configuration.Configure(factoryCfg); configuration.AddInputStream(stream); // Use the stream here stream.Close(); // Now use the configuration to build the Session Factory return configuration.BuildSessionFactory(); } private static void GetNhibernateClasses(MemoryStream stream) { XmlTextWriter _xmlTextWriter = null; // Get the list of all assemblies string[] assemblyList; //assemblyList = File.GetNFSAssemblyListInBaseDirectory(true); assemblyList = File.GetFileListInBaseDirectory("ProjectTracker*.dll", true); // Target all classes marked up for NHibernate with the [ClassAttribute] Type targetType = typeof (ClassAttribute); // Iterate thru the assemblies to extract all classes marked up for NHibernate foreach (string assembly in assemblyList) { // Get a list of all the marked up classes (as types) List<Type> typeList = GetClassesWithCustomAttributes(targetType, assembly); // Iterate all types adding them to the serialization foreach (Type classType in typeList) { _xmlTextWriter = HbmSerializer.Default.Serialize(stream, classType, _xmlTextWriter, false); } } // If the reference is null it means nothing was found with markup for NHibernate if (ReferenceEquals(_xmlTextWriter, null)) throw new NullReferenceException("No classes found marked up for NHibernate"); _xmlTextWriter.WriteEndElement(); _xmlTextWriter.WriteEndDocument(); _xmlTextWriter.Flush(); } /// <summary> /// Get a list of classes in an assembly that are marked with a particular custom attribute. /// </summary> /// <param name="targetType">The target custom attribute to search for.</param> /// <param name="assemblyString">The name of the assembly.</param> /// <returns>A <see cref="List{T}"/> of <see cref="Type"/> objects.</returns> private static List<Type> GetClassesWithCustomAttributes(Type targetType, string assemblyString) { // This will hold the types found List<Type> typeList = new List<Type>(); // Load the assembly for reflection purposes only Assembly assembly = Assembly.LoadFrom(assemblyString); // Now get the classes in the assembly try { foreach (Type type in assembly.GetTypes()) { if (type.IsClass) { object[] objArray = type.GetCustomAttributes(targetType, true); if (objArray.Length > 0) typeList.Add(type); } } } catch (ReflectionTypeLoadException ex) { ex.ToString(); } return typeList; } #endregion #region public static methods /// <summary> /// Gets an NHibernate database connection string for the specified key. /// </summary> /// <param name="key">String identifier for the database required.</param> /// <returns>An ADO.NET connection string.</returns> /// <exception cref="ArgumentNullException">If the key is null.</exception> /// <exception cref="ArgumentException">If the key is empty.</exception> /// <exception cref="System.Configuration.ConfigurationErrorsException">If the key is a valid string, but it does not appear in the application configuration file.</exception> /// <exception cref="System.IO.FileNotFoundException">If the required NHibernate configuration file does not exist for the specified key.</exception> public static string GetConnectionString(string key) { Cfg cfg = new Cfg(); DatabaseConfiguration databaseConfiguration = cfg[key]; return databaseConfiguration.ConnectionString; } /// <summary> /// Gets an NHibernate session factory for the specified key. /// </summary> /// <param name="key">String identifier for the database required.</param> /// <returns>An instance object that implements the NHibernate ISessionFactory interface.</returns> /// <exception cref="ArgumentNullException">If the key is null.</exception> /// <exception cref="ArgumentException">If the key is empty.</exception> /// <exception cref="System.Configuration.ConfigurationErrorsException">If the key is a valid string, but it does not appear in the application configuration file.</exception> /// <exception cref="System.IO.FileNotFoundException">If the required NHibernate configuration file does not exist for the specified key.</exception> public static ISessionFactory GetSessionFactory(string key) { Cfg cfg = new Cfg(); DatabaseConfiguration databaseConfiguration = cfg[key]; return databaseConfiguration.SessionFactory; } #endregion } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeFixes; using System.Threading.Tasks; using System.Linq; namespace RefactoringEssentials.CSharp.Diagnostics { [DiagnosticAnalyzer(LanguageNames.CSharp)] [NotPortedYet] public class CS1573ParameterHasNoMatchingParamTagAnalyzer : DiagnosticAnalyzer { internal const string DiagnosticId = "CS1573ParameterHasNoMatchingParamTagAnalyzer"; const string Description = "Parameter has no matching param tag in the XML comment"; const string MessageFormat = ""; const string Category = DiagnosticAnalyzerCategories.CompilerWarnings; static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning, true, "Parameter has no matching param tag in the XML comment"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { //context.RegisterSyntaxNodeAction( // (nodeContext) => { // Diagnostic diagnostic; // if (TryGetDiagnostic (nodeContext, out diagnostic)) { // nodeContext.ReportDiagnostic(diagnostic); // } // }, // new SyntaxKind[] { SyntaxKind.None } //); } static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic) { diagnostic = default(Diagnostic); if (nodeContext.IsFromGeneratedCode()) return false; //var node = nodeContext.Node as ; //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ()); //return true; return false; } // class GatherVisitor : GatherVisitorBase<CS1573ParameterHasNoMatchingParamTagAnalyzer> // { // //readonly List<Comment> storedXmlComment = new List<Comment>(); // public GatherVisitor(SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken) // : base (semanticModel, addDiagnostic, cancellationToken) // { // } //// //// void InvalideXmlComments() //// { //// storedXmlComment.Clear(); //// } //// //// public override void VisitComment(Comment comment) //// { //// base.VisitComment(comment); //// if (comment.CommentType == CommentType.Documentation) //// storedXmlComment.Add(comment); //// } //// //// public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration) //// { //// InvalideXmlComments(); //// base.VisitNamespaceDeclaration(namespaceDeclaration); //// } //// //// public override void VisitUsingDeclaration(UsingDeclaration usingDeclaration) //// { //// InvalideXmlComments(); //// base.VisitUsingDeclaration(usingDeclaration); //// } //// //// public override void VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration) //// { //// InvalideXmlComments(); //// base.VisitUsingAliasDeclaration(usingDeclaration); //// } //// //// public override void VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration) //// { //// InvalideXmlComments(); //// base.VisitExternAliasDeclaration(externAliasDeclaration); //// } //// //// void AddXmlIssue(int line, int col, int length, string str) //// { //// var cmt = storedXmlComment [Math.Max(0, Math.Min(storedXmlComment.Count - 1, line))]; //// //// AddDiagnosticAnalyzer(new CodeIssue(new TextLocation(cmt.StartLocation.Line, cmt.StartLocation.Column + 3 + col), //// new TextLocation(cmt.StartLocation.Line, cmt.StartLocation.Column + 3 + col + length), //// str)); //// } //// //// int SearchAttributeColumn(int x, int line) //// { //// var comment = storedXmlComment [Math.Max(0, Math.Min(storedXmlComment.Count - 1, line))]; //// var idx = comment.Content.IndexOfAny(new char[] { '"', '\'' }, x); //// return idx < 0 ? x : idx + 1; //// } //// //// void CheckXmlDoc(AstNode node) //// { //// ResolveResult resolveResult = ctx.Resolve(node); //// IEntity member = null; //// if (resolveResult is TypeResolveResult) //// member = resolveResult.Type.GetDefinition(); //// if (resolveResult is MemberResolveResult) //// member = ((MemberResolveResult)resolveResult).Member; //// var xml = new StringBuilder(); //// xml.AppendLine("<root>"); //// foreach (var cmt in storedXmlComment) //// xml.AppendLine(cmt.Content); //// xml.AppendLine("</root>"); //// //// List<Tuple<string, int>> parameters = new List<Tuple<string, int>>(); //// //// using (var reader = new XmlTextReader(new StringReader(xml.ToString()))) { //// reader.XmlResolver = null; //// try { //// while (reader.Read()) { //// if (member == null) //// continue; //// if (reader.NodeType == XmlNodeType.Element) { //// switch (reader.Name) { //// case "param": //// reader.MoveToFirstAttribute(); //// var line = reader.LineNumber; //// var name = reader.GetAttribute("name"); //// if (name == null) //// break; //// parameters.Add(Tuple.Create(name, line)); //// break; //// //// } //// } //// } //// } catch (XmlException) { //// } //// //// if (storedXmlComment.Count > 0 && parameters.Count > 0) { //// var pm = member as IParameterizedMember; //// if (pm != null) { //// for (int i = 0; i < pm.Parameters.Count; i++) { //// var p = pm.Parameters [i]; //// if (!parameters.Any(tp => tp.Item1 == p.Name)) { //// AstNode before = i < parameters.Count ? storedXmlComment [parameters [i].Item2 - 2] : null; //// AstNode afterNode = before == null ? storedXmlComment [storedXmlComment.Count - 1] : null; //// AddDiagnosticAnalyzer(new CodeIssue( //// GetParameterHighlightNode(node, i), //// string.Format(ctx.TranslateString("Missing xml documentation for Parameter '{0}'"), p.Name), //// string.Format(ctx.TranslateString("Create xml documentation for Parameter '{0}'"), p.Name), //// script => { //// if (before != null) { //// script.InsertBefore( //// before, //// new Comment(string.Format(" <param name = \"{0}\"></param>", p.Name), CommentType.Documentation) //// ); //// } else { //// script.InsertAfter( //// afterNode, //// new Comment(string.Format(" <param name = \"{0}\"></param>", p.Name), CommentType.Documentation) //// ); //// } //// })); //// } //// } //// //// } //// } //// storedXmlComment.Clear(); //// } //// } //// //// AstNode GetParameterHighlightNode(AstNode node, int i) //// { //// if (node is MethodDeclaration) //// return ((MethodDeclaration)node).Parameters.ElementAt(i).NameToken; //// if (node is ConstructorDeclaration) //// return ((ConstructorDeclaration)node).Parameters.ElementAt(i).NameToken; //// if (node is OperatorDeclaration) //// return ((OperatorDeclaration)node).Parameters.ElementAt(i).NameToken; //// if (node is IndexerDeclaration) //// return ((IndexerDeclaration)node).Parameters.ElementAt(i).NameToken; //// throw new InvalidOperationException("invalid parameterized node:" + node); //// } //// //// protected virtual void VisitXmlChildren(AstNode node) //// { //// AstNode next; //// var child = node.FirstChild; //// while (child != null && (child is Comment || child is PreProcessorDirective || child.Role == Roles.NewLine)) { //// next = child.NextSibling; //// child.AcceptVisitor(this); //// child = next; //// } //// //// CheckXmlDoc(node); //// //// for (; child != null; child = next) { //// // Store next to allow the loop to continue //// // if the visitor removes/replaces child. //// next = child.NextSibling; //// child.AcceptVisitor(this); //// } //// InvalideXmlComments(); //// } //// //// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) //// { //// VisitXmlChildren(typeDeclaration); //// } //// //// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration) //// { //// VisitXmlChildren(methodDeclaration); //// } //// //// public override void VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration) //// { //// VisitXmlChildren(delegateDeclaration); //// } //// //// public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration) //// { //// VisitXmlChildren(constructorDeclaration); //// } //// //// public override void VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration) //// { //// VisitXmlChildren(eventDeclaration); //// } //// //// public override void VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration) //// { //// VisitXmlChildren(destructorDeclaration); //// } //// //// public override void VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration) //// { //// VisitXmlChildren(enumMemberDeclaration); //// } //// //// public override void VisitEventDeclaration(EventDeclaration eventDeclaration) //// { //// VisitXmlChildren(eventDeclaration); //// } //// //// public override void VisitFieldDeclaration(FieldDeclaration fieldDeclaration) //// { //// VisitXmlChildren(fieldDeclaration); //// } //// //// public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration) //// { //// VisitXmlChildren(indexerDeclaration); //// } //// //// public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration) //// { //// VisitXmlChildren(propertyDeclaration); //// } //// //// public override void VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration) //// { //// VisitXmlChildren(operatorDeclaration); //// } // } } [ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared] public class CS1573ParameterHasNoMatchingParamTagFixProvider : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(CS1573ParameterHasNoMatchingParamTagAnalyzer.DiagnosticId); } } public override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } public async override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var span = context.Span; var diagnostics = context.Diagnostics; var root = await document.GetSyntaxRootAsync(cancellationToken); var diagnostic = diagnostics.First(); var node = root.FindNode(context.Span); //if (!node.IsKind(SyntaxKind.BaseList)) // continue; var newRoot = root.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia); context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, diagnostic.GetMessage(), document.WithSyntaxRoot(newRoot)), diagnostic); } } }
// // HttpListener.cs // Copied from System.Net.HttpListener.cs // // Author: // Gonzalo Paniagua Javier (gonzalo@novell.com) // sta (sta.blockhead@gmail.com) // // Copyright (c) 2005 Novell, Inc. (http://www.novell.com) // Copyright (c) 2012-2013 sta.blockhead // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using System.Threading; // TODO: logging namespace WebSocketSharp.Net { /// <summary> /// Provides a simple, programmatically controlled HTTP listener. /// </summary> public sealed class HttpListener : IDisposable { #region Private Fields AuthenticationSchemes auth_schemes; AuthenticationSchemeSelector auth_selector; string cert_folder_path; Dictionary<HttpConnection, HttpConnection> connections; List<HttpListenerContext> ctx_queue; X509Certificate2 default_cert; bool disposed; bool ignore_write_exceptions; bool listening; HttpListenerPrefixCollection prefixes; string realm; Dictionary<HttpListenerContext, HttpListenerContext> registry; bool unsafe_ntlm_auth; List<ListenerAsyncResult> wait_queue; #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="HttpListener"/> class. /// </summary> public HttpListener () { prefixes = new HttpListenerPrefixCollection (this); registry = new Dictionary<HttpListenerContext, HttpListenerContext> (); connections = new Dictionary<HttpConnection, HttpConnection> (); ctx_queue = new List<HttpListenerContext> (); wait_queue = new List<ListenerAsyncResult> (); auth_schemes = AuthenticationSchemes.Anonymous; } #endregion #region Public Properties /// <summary> /// Gets or sets the scheme used to authenticate the clients. /// </summary> /// <value> /// One of the <see cref="AuthenticationSchemes"/> values that indicates the scheme used to /// authenticate the clients. The default value is <see cref="AuthenticationSchemes.Anonymous"/>. /// </value> /// <exception cref="ObjectDisposedException"> /// This object has been closed. /// </exception> public AuthenticationSchemes AuthenticationSchemes { // TODO: Digest, NTLM and Negotiate require ControlPrincipal get { CheckDisposed (); return auth_schemes; } set { CheckDisposed (); auth_schemes = value; } } /// <summary> /// Gets or sets the delegate called to determine the scheme used to authenticate clients. /// </summary> /// <value> /// A <see cref="AuthenticationSchemeSelector"/> delegate that invokes the method(s) used to select /// an authentication scheme. The default value is <see langword="null"/>. /// </value> /// <exception cref="ObjectDisposedException"> /// This object has been closed. /// </exception> public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate { get { CheckDisposed (); return auth_selector; } set { CheckDisposed (); auth_selector = value; } } /// <summary> /// Gets or sets the path to the folder stored the certificate files used to authenticate /// the server on the secure connection. /// </summary> /// <remarks> /// This property represents the path to the folder stored the certificate files associated with /// the port number of each added URI prefix. A set of the certificate files is a pair of the /// <c>'port number'.cer</c> (DER) and <c>'port number'.key</c> (DER, RSA Private Key). /// </remarks> /// <value> /// A <see cref="string"/> that contains the path to the certificate folder. The default value is /// the result of <c>Environment.GetFolderPath</c> (<see cref="Environment.SpecialFolder.ApplicationData"/>). /// </value> /// <exception cref="ObjectDisposedException"> /// This object has been closed. /// </exception> public string CertificateFolderPath { get { CheckDisposed (); if (cert_folder_path.IsNullOrEmpty ()) cert_folder_path = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData); return cert_folder_path; } set { CheckDisposed (); cert_folder_path = value; } } /// <summary> /// Gets or sets the default certificate used to authenticate the server on the secure connection. /// </summary> /// <value> /// A <see cref="X509Certificate2"/> used to authenticate the server if the certificate associated with /// the port number of each added URI prefix is not found in the <see cref="CertificateFolderPath"/>. /// </value> /// <exception cref="ObjectDisposedException"> /// This object has been closed. /// </exception> public X509Certificate2 DefaultCertificate { get { CheckDisposed (); return default_cert; } set { CheckDisposed (); default_cert = value; } } /// <summary> /// Gets or sets a value indicating whether the <see cref="HttpListener"/> returns exceptions /// that occur when sending the response to the client. /// </summary> /// <value> /// <c>true</c> if does not return exceptions that occur when sending the response to the client; /// otherwise, <c>false</c>. The default value is <c>false</c>. /// </value> /// <exception cref="ObjectDisposedException"> /// This object has been closed. /// </exception> public bool IgnoreWriteExceptions { get { CheckDisposed (); return ignore_write_exceptions; } set { CheckDisposed (); ignore_write_exceptions = value; } } /// <summary> /// Gets a value indicating whether the <see cref="HttpListener"/> has been started. /// </summary> /// <value> /// <c>true</c> if the <see cref="HttpListener"/> has been started; otherwise, <c>false</c>. /// </value> public bool IsListening { get { return listening; } } /// <summary> /// Gets a value indicating whether the <see cref="HttpListener"/> can be used with the current operating system. /// </summary> /// <value> /// <c>true</c>. /// </value> public static bool IsSupported { get { return true; } } /// <summary> /// Gets the URI prefixes handled by the <see cref="HttpListener"/>. /// </summary> /// <value> /// A <see cref="HttpListenerPrefixCollection"/> that contains the URI prefixes. /// </value> /// <exception cref="ObjectDisposedException"> /// This object has been closed. /// </exception> public HttpListenerPrefixCollection Prefixes { get { CheckDisposed (); return prefixes; } } /// <summary> /// Gets or sets the name of the realm associated with the <see cref="HttpListener"/>. /// </summary> /// <value> /// A <see cref="string"/> that contains the name of the realm. /// </value> /// <exception cref="ObjectDisposedException"> /// This object has been closed. /// </exception> public string Realm { // TODO: Use this get { CheckDisposed (); return realm; } set { CheckDisposed (); realm = value; } } /// <summary> /// Gets or sets a value indicating whether, when NTLM authentication is used, /// the authentication information of first request is used to authenticate /// additional requests on the same connection. /// </summary> /// <value> /// <c>true</c> if the authentication information of first request is used; /// otherwise, <c>false</c>. The default value is <c>false</c>. /// </value> /// <exception cref="ObjectDisposedException"> /// This object has been closed. /// </exception> public bool UnsafeConnectionNtlmAuthentication { // TODO: Support for NTLM needs some loving. get { CheckDisposed (); return unsafe_ntlm_auth; } set { CheckDisposed (); unsafe_ntlm_auth = value; } } #endregion #region Private Methods void Cleanup (bool force) { lock (((ICollection)registry).SyncRoot) { if (!force) SendServiceUnavailable (); CleanupContextRegistry (); CleanupConnections (); CleanupWaitQueue (); } } void CleanupConnections () { lock (((ICollection)connections).SyncRoot) { if (connections.Count == 0) return; // Need to copy this since closing will call RemoveConnection ICollection keys = connections.Keys; var conns = new HttpConnection [keys.Count]; keys.CopyTo (conns, 0); connections.Clear (); for (int i = conns.Length - 1; i >= 0; i--) conns [i].Close (true); } } void CleanupContextRegistry () { lock (((ICollection)registry).SyncRoot) { if (registry.Count == 0) return; // Need to copy this since closing will call UnregisterContext ICollection keys = registry.Keys; var all = new HttpListenerContext [keys.Count]; keys.CopyTo (all, 0); registry.Clear (); for (int i = all.Length - 1; i >= 0; i--) all [i].Connection.Close (true); } } void CleanupWaitQueue () { lock (((ICollection)wait_queue).SyncRoot) { if (wait_queue.Count == 0) return; var exc = new ObjectDisposedException (GetType ().ToString ()); foreach (var ares in wait_queue) { ares.Complete (exc); } wait_queue.Clear (); } } void Close (bool force) { EndPointManager.RemoveListener (this); Cleanup (force); } // Must be called with a lock on ctx_queue HttpListenerContext GetContextFromQueue () { if (ctx_queue.Count == 0) return null; var context = ctx_queue [0]; ctx_queue.RemoveAt (0); return context; } void SendServiceUnavailable () { lock (((ICollection)ctx_queue).SyncRoot) { if (ctx_queue.Count == 0) return; var ctxs = ctx_queue.ToArray (); ctx_queue.Clear (); foreach (var ctx in ctxs) { var res = ctx.Response; res.StatusCode = (int)HttpStatusCode.ServiceUnavailable; res.Close(); } } } #endregion #region Internal Methods internal void AddConnection (HttpConnection cnc) { connections [cnc] = cnc; } internal void CheckDisposed () { if (disposed) throw new ObjectDisposedException (GetType ().ToString ()); } internal void RegisterContext (HttpListenerContext context) { lock (((ICollection)registry).SyncRoot) registry [context] = context; ListenerAsyncResult ares = null; lock (((ICollection)wait_queue).SyncRoot) { if (wait_queue.Count == 0) { lock (((ICollection)ctx_queue).SyncRoot) ctx_queue.Add (context); } else { ares = wait_queue [0]; wait_queue.RemoveAt (0); } } if (ares != null) ares.Complete (context); } internal void RemoveConnection (HttpConnection cnc) { connections.Remove (cnc); } internal AuthenticationSchemes SelectAuthenticationScheme (HttpListenerContext context) { if (AuthenticationSchemeSelectorDelegate != null) return AuthenticationSchemeSelectorDelegate (context.Request); else return auth_schemes; } internal void UnregisterContext (HttpListenerContext context) { lock (((ICollection)registry).SyncRoot) registry.Remove (context); lock (((ICollection)ctx_queue).SyncRoot) { int idx = ctx_queue.IndexOf (context); if (idx >= 0) ctx_queue.RemoveAt (idx); } } #endregion #region Public Methods /// <summary> /// Shuts down the <see cref="HttpListener"/> immediately. /// </summary> public void Abort () { if (disposed) return; Close (true); disposed = true; } /// <summary> /// Begins getting an incoming request information asynchronously. /// </summary> /// <remarks> /// This asynchronous operation must be completed by calling the <see cref="EndGetContext"/> method. /// Typically, the method is invoked by the <paramref name="callback"/> delegate. /// </remarks> /// <returns> /// An <see cref="IAsyncResult"/> that contains the status of the asynchronous operation. /// </returns> /// <param name="callback"> /// An <see cref="AsyncCallback"/> delegate that references the method(s) /// called when the asynchronous operation completes. /// </param> /// <param name="state"> /// An <see cref="object"/> that contains a user defined object to pass to the <paramref name="callback"/> delegate. /// </param> /// <exception cref="ObjectDisposedException"> /// This object has been closed. /// </exception> /// <exception cref="InvalidOperationException"> /// The <see cref="HttpListener"/> has not been started or is stopped currently. /// </exception> public IAsyncResult BeginGetContext (AsyncCallback callback, Object state) { CheckDisposed (); if (!listening) throw new InvalidOperationException ("Please, call Start before using this method."); ListenerAsyncResult ares = new ListenerAsyncResult (callback, state); // lock wait_queue early to avoid race conditions lock (((ICollection)wait_queue).SyncRoot) { lock (((ICollection)ctx_queue).SyncRoot) { HttpListenerContext ctx = GetContextFromQueue (); if (ctx != null) { ares.Complete (ctx, true); return ares; } } wait_queue.Add (ares); } return ares; } /// <summary> /// Shuts down the <see cref="HttpListener"/>. /// </summary> public void Close () { if (disposed) return; Close (false); disposed = true; } /// <summary> /// Ends an asynchronous operation to get an incoming request information. /// </summary> /// <remarks> /// This method completes an asynchronous operation started by calling the <see cref="BeginGetContext"/> method. /// </remarks> /// <returns> /// A <see cref="HttpListenerContext"/> that contains a client's request information. /// </returns> /// <param name="asyncResult"> /// An <see cref="IAsyncResult"/> obtained by calling the <see cref="BeginGetContext"/> method. /// </param> /// <exception cref="ObjectDisposedException"> /// This object has been closed. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="asyncResult"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="asyncResult"/> was not obtained by calling the <see cref="BeginGetContext"/> method. /// </exception> /// <exception cref="InvalidOperationException"> /// The EndGetContext method was already called for the specified <paramref name="asyncResult"/>. /// </exception> public HttpListenerContext EndGetContext (IAsyncResult asyncResult) { CheckDisposed (); if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); ListenerAsyncResult ares = asyncResult as ListenerAsyncResult; if (ares == null) throw new ArgumentException ("Wrong IAsyncResult.", "asyncResult"); if (ares.EndCalled) throw new InvalidOperationException ("Cannot reuse this IAsyncResult."); ares.EndCalled = true; if (!ares.IsCompleted) ares.AsyncWaitHandle.WaitOne (); lock (((ICollection)wait_queue).SyncRoot) { int idx = wait_queue.IndexOf (ares); if (idx >= 0) wait_queue.RemoveAt (idx); } HttpListenerContext context = ares.GetContext (); context.ParseAuthentication (SelectAuthenticationScheme (context)); return context; // This will throw on error. } /// <summary> /// Gets an incoming request information. /// </summary> /// <remarks> /// This method waits for an incoming request and returns the request information /// when received the request. /// </remarks> /// <returns> /// A <see cref="HttpListenerContext"/> that contains a client's request information. /// </returns> /// <exception cref="InvalidOperationException"> /// <para> /// The <see cref="HttpListener"/> does not have any URI prefixes to listen on. /// </para> /// <para> /// -or- /// </para> /// <para> /// The <see cref="HttpListener"/> has not been started or is stopped currently. /// </para> /// </exception> /// <exception cref="ObjectDisposedException"> /// This object has been closed. /// </exception> public HttpListenerContext GetContext () { // The prefixes are not checked when using the async interface!? if (prefixes.Count == 0) throw new InvalidOperationException ("Please, call AddPrefix before using this method."); ListenerAsyncResult ares = (ListenerAsyncResult) BeginGetContext (null, null); ares.InGet = true; return EndGetContext (ares); } /// <summary> /// Starts to receive incoming requests. /// </summary> /// <exception cref="ObjectDisposedException"> /// This object has been closed. /// </exception> public void Start () { CheckDisposed (); if (listening) return; EndPointManager.AddListener (this); listening = true; } /// <summary> /// Stops receiving incoming requests. /// </summary> /// <exception cref="ObjectDisposedException"> /// This object has been closed. /// </exception> public void Stop () { CheckDisposed (); if (!listening) return; listening = false; EndPointManager.RemoveListener (this); SendServiceUnavailable (); } #endregion #region Explicit Interface Implementation /// <summary> /// Releases all resource used by the <see cref="HttpListener"/>. /// </summary> void IDisposable.Dispose () { if (disposed) return; Close (true); // TODO: Should we force here or not? disposed = true; } #endregion } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Composition; using System.Drawing; using System.Windows.Forms; using DotSpatial.Controls.Header; namespace DotSpatial.Controls { /// <summary> /// A pre-configured status strip with a thread safe Progress function. /// </summary> [ToolboxBitmap(typeof(SpatialStatusStrip), "SpatialStatusStrip.ico")] [PartNotDiscoverable] // Do not allow discover this class by MEF public partial class SpatialStatusStrip : StatusStrip, IStatusControl { #region Fields private readonly Dictionary<StatusPanel, PanelGuiElements> _panels = new Dictionary<StatusPanel, PanelGuiElements>(); #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="SpatialStatusStrip"/> class which has a built in, thread safe Progress handler. /// </summary> public SpatialStatusStrip() { InitializeComponent(); } #endregion #region Properties /// <summary> /// Gets or sets the progress bar. By default, the first ToolStripProgressBar that is added to the tool strip. /// </summary> /// <value> /// The progress bar. /// </value> [Description("Gets or sets the progress bar. By default, the first ToolStripProgressBar that is added to the tool strip.")] public ToolStripProgressBar ProgressBar { get; set; } /// <summary> /// Gets or sets the progress label. By default, the first ToolStripStatusLabel that is added to the tool strip. /// </summary> /// <value> /// The progress label. /// </value> [Description("Gets or sets the progress label. By default, the first ToolStripStatusLabel that is added to the tool strip.")] public ToolStripStatusLabel ProgressLabel { get; set; } #endregion #region Methods /// <inheritdoc /> public void Add(StatusPanel panel) { if (panel == null) throw new ArgumentNullException(nameof(panel)); ToolStripProgressBar pb = null; var psp = panel as ProgressStatusPanel; if (psp != null) { pb = new ToolStripProgressBar { Name = GetKeyName<ToolStripProgressBar>(panel.Key), Width = 100, Alignment = ToolStripItemAlignment.Left }; Items.Add(pb); } var sl = new ToolStripStatusLabel { Name = GetKeyName<ToolStripStatusLabel>(panel.Key), Text = panel.Caption, Spring = panel.Width == 0, TextAlign = ContentAlignment.MiddleLeft }; Items.Add(sl); _panels.Add(panel, new PanelGuiElements { Caption = sl, Progress = pb }); panel.PropertyChanged += PanelOnPropertyChanged; } /// <summary> /// This method is thread safe so that people calling this method don't cause a cross-thread violation /// by updating the progress indicator from a different thread. /// </summary> /// <param name="percent">The integer percent from 0 to 100.</param> /// <param name="message">A message including the percent information if wanted.</param> public void Progress(int percent, string message) { if (InvokeRequired) { BeginInvoke((Action<int, string>)UpdateProgress, percent, message); } else { UpdateProgress(percent, message); } } /// <summary> /// Resets the progress. This method is thread safe so that people calling this method don't cause a cross-thread violation /// by updating the progress indicator from a different thread. /// </summary> public void Reset() { Progress(0, string.Empty); } /// <inheritdoc /> public void Remove(StatusPanel panel) { if (panel == null) throw new ArgumentNullException(nameof(panel)); panel.PropertyChanged -= PanelOnPropertyChanged; PanelGuiElements panelDesc; if (!_panels.TryGetValue(panel, out panelDesc)) return; if (panelDesc.Caption != null) Items.Remove(panelDesc.Caption); if (panelDesc.Progress != null) Items.Remove(panelDesc.Progress); } /// <summary> /// Raises the <see cref="E:System.Windows.Forms.ToolStrip.ItemAdded"/> event. /// </summary> /// <param name="e">A <see cref="T:System.Windows.Forms.ToolStripItemEventArgs"/> that contains the event data.</param> protected override void OnItemAdded(ToolStripItemEventArgs e) { base.OnItemAdded(e); if (ProgressBar == null) { var pb = e.Item as ToolStripProgressBar; if (pb != null) { ProgressBar = pb; } } if (ProgressLabel == null) { var sl = e.Item as ToolStripStatusLabel; if (sl != null) { ProgressLabel = sl; } } } /// <inheritdoc /> protected override void OnItemRemoved(ToolStripItemEventArgs e) { base.OnItemRemoved(e); if (ProgressBar == e.Item) ProgressBar = null; if (ProgressLabel == e.Item) ProgressLabel = null; } private static string GetKeyName<T>(string key) { return typeof(T).Name + key; } private void PanelOnPropertyChanged(object sender, PropertyChangedEventArgs e) { var panel = (StatusPanel)sender; if (InvokeRequired) { BeginInvoke((Action<StatusPanel, string>)UpdatePanelGuiProps, panel, e.PropertyName); } else { UpdatePanelGuiProps(panel, e.PropertyName); } } private void UpdatePanelGuiProps(StatusPanel sender, string propertyName) { PanelGuiElements panelDesc; if (!_panels.TryGetValue(sender, out panelDesc)) return; switch (propertyName) { case "Caption": if (panelDesc.Caption != null) { panelDesc.Caption.Text = sender.Caption; } break; case "Percent": if (panelDesc.Progress != null && sender is ProgressStatusPanel) { panelDesc.Progress.Value = ((ProgressStatusPanel)sender).Percent; } break; } Refresh(); } private void UpdateProgress(int percent, string message) { if (ProgressBar != null) ProgressBar.Value = percent; if (ProgressLabel != null) ProgressLabel.Text = message; Refresh(); } #endregion #region Classes /// <summary> /// PanelGuiElements. /// </summary> internal class PanelGuiElements { #region Properties /// <summary> /// Gets or sets the caption. /// </summary> public ToolStripStatusLabel Caption { get; set; } /// <summary> /// Gets or sets the progress bar. /// </summary> public ToolStripProgressBar Progress { get; set; } #endregion } #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.IO; using System.Runtime.InteropServices; using System.Security; using System.Diagnostics; using Microsoft.Win32.SafeHandles; namespace System.Net.WebSockets { internal static class WebSocketProtocolComponent { private static readonly string s_dummyWebsocketKeyBase64 = Convert.ToBase64String(new byte[16]); private static readonly SafeLibraryHandle s_webSocketDllHandle; private static readonly string s_supportedVersion; private static readonly Interop.WebSocket.HttpHeader[] s_initialClientRequestHeaders = new Interop.WebSocket.HttpHeader[] { new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.Connection, NameLength = (uint)HttpKnownHeaderNames.Connection.Length, Value = HttpKnownHeaderNames.Upgrade, ValueLength = (uint)HttpKnownHeaderNames.Upgrade.Length }, new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.Upgrade, NameLength = (uint)HttpKnownHeaderNames.Upgrade.Length, Value = HttpWebSocket.WebSocketUpgradeToken, ValueLength = (uint)HttpWebSocket.WebSocketUpgradeToken.Length } }; private static readonly Interop.WebSocket.HttpHeader[] s_ServerFakeRequestHeaders; internal enum Action { NoAction = 0, SendToNetwork = 1, IndicateSendComplete = 2, ReceiveFromNetwork = 3, IndicateReceiveComplete = 4, } internal enum BufferType : uint { None = 0x00000000, UTF8Message = 0x80000000, UTF8Fragment = 0x80000001, BinaryMessage = 0x80000002, BinaryFragment = 0x80000003, Close = 0x80000004, PingPong = 0x80000005, UnsolicitedPong = 0x80000006 } internal enum PropertyType { ReceiveBufferSize = 0, SendBufferSize = 1, DisableMasking = 2, AllocatedBuffer = 3, DisableUtf8Verification = 4, KeepAliveInterval = 5, } internal enum ActionQueue { Send = 1, Receive = 2, } static WebSocketProtocolComponent() { s_webSocketDllHandle = Interop.Kernel32.LoadLibraryExW(Interop.Libraries.WebSocket, IntPtr.Zero, 0); if (!s_webSocketDllHandle.IsInvalid) { s_supportedVersion = GetSupportedVersion(); s_ServerFakeRequestHeaders = new Interop.WebSocket.HttpHeader[] { new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.Connection, NameLength = (uint)HttpKnownHeaderNames.Connection.Length, Value = HttpKnownHeaderNames.Upgrade, ValueLength = (uint)HttpKnownHeaderNames.Upgrade.Length }, new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.Upgrade, NameLength = (uint)HttpKnownHeaderNames.Upgrade.Length, Value = HttpWebSocket.WebSocketUpgradeToken, ValueLength = (uint)HttpWebSocket.WebSocketUpgradeToken.Length }, new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.Host, NameLength = (uint)HttpKnownHeaderNames.Host.Length, Value = string.Empty, ValueLength = 0 }, new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.SecWebSocketVersion, NameLength = (uint)HttpKnownHeaderNames.SecWebSocketVersion.Length, Value = s_supportedVersion, ValueLength = (uint)s_supportedVersion.Length }, new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.SecWebSocketKey, NameLength = (uint)HttpKnownHeaderNames.SecWebSocketKey.Length, Value = s_dummyWebsocketKeyBase64, ValueLength = (uint)s_dummyWebsocketKeyBase64.Length } }; } } internal static string SupportedVersion { get { if (s_webSocketDllHandle.IsInvalid) { HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } return s_supportedVersion; } } internal static bool IsSupported { get { return !s_webSocketDllHandle.IsInvalid; } } internal static string GetSupportedVersion() { if (s_webSocketDllHandle.IsInvalid) { HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } SafeWebSocketHandle webSocketHandle = null; try { int errorCode = Interop.WebSocket.WebSocketCreateClientHandle(null, 0, out webSocketHandle); ThrowOnError(errorCode); if (webSocketHandle == null || webSocketHandle.IsInvalid) { HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } IntPtr additionalHeadersPtr; uint additionalHeaderCount; errorCode = Interop.WebSocket.WebSocketBeginClientHandshake(webSocketHandle, IntPtr.Zero, 0, IntPtr.Zero, 0, s_initialClientRequestHeaders, (uint)s_initialClientRequestHeaders.Length, out additionalHeadersPtr, out additionalHeaderCount); ThrowOnError(errorCode); Interop.WebSocket.HttpHeader[] additionalHeaders = MarshalHttpHeaders(additionalHeadersPtr, (int)additionalHeaderCount); string version = null; foreach (Interop.WebSocket.HttpHeader header in additionalHeaders) { if (string.Compare(header.Name, HttpKnownHeaderNames.SecWebSocketVersion, StringComparison.OrdinalIgnoreCase) == 0) { version = header.Value; break; } } Debug.Assert(version != null, "'version' MUST NOT be NULL."); return version; } finally { if (webSocketHandle != null) { webSocketHandle.Dispose(); } } } internal static void WebSocketCreateServerHandle(Interop.WebSocket.Property[] properties, int propertyCount, out SafeWebSocketHandle webSocketHandle) { Debug.Assert(propertyCount >= 0, "'propertyCount' MUST NOT be negative."); Debug.Assert((properties == null && propertyCount == 0) || (properties != null && propertyCount == properties.Length), "'propertyCount' MUST MATCH 'properties.Length'."); if (s_webSocketDllHandle.IsInvalid) { HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } int errorCode = Interop.WebSocket.WebSocketCreateServerHandle(properties, (uint)propertyCount, out webSocketHandle); ThrowOnError(errorCode); if (webSocketHandle == null || webSocketHandle.IsInvalid) { HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } IntPtr responseHeadersPtr; uint responseHeaderCount; // Currently the WSPC doesn't allow to initiate a data session // without also being involved in the http handshake // There is no information whatsoever, which is needed by the // WSPC for parsing WebSocket frames from the HTTP handshake // In the managed implementation the HTTP header handling // will be done using the managed HTTP stack and we will // just fake an HTTP handshake for the WSPC calling // WebSocketBeginServerHandshake and WebSocketEndServerHandshake // with statically defined dummy headers. errorCode = Interop.WebSocket.WebSocketBeginServerHandshake(webSocketHandle, IntPtr.Zero, IntPtr.Zero, 0, s_ServerFakeRequestHeaders, (uint)s_ServerFakeRequestHeaders.Length, out responseHeadersPtr, out responseHeaderCount); ThrowOnError(errorCode); Interop.WebSocket.HttpHeader[] responseHeaders = MarshalHttpHeaders(responseHeadersPtr, (int)responseHeaderCount); errorCode = Interop.WebSocket.WebSocketEndServerHandshake(webSocketHandle); ThrowOnError(errorCode); Debug.Assert(webSocketHandle != null, "'webSocketHandle' MUST NOT be NULL at this point."); } internal static void WebSocketAbortHandle(SafeHandle webSocketHandle) { Debug.Assert(webSocketHandle != null && !webSocketHandle.IsInvalid, "'webSocketHandle' MUST NOT be NULL or INVALID."); Interop.WebSocket.WebSocketAbortHandle(webSocketHandle); DrainActionQueue(webSocketHandle, ActionQueue.Send); DrainActionQueue(webSocketHandle, ActionQueue.Receive); } internal static void WebSocketDeleteHandle(IntPtr webSocketPtr) { Debug.Assert(webSocketPtr != IntPtr.Zero, "'webSocketPtr' MUST NOT be IntPtr.Zero."); Interop.WebSocket.WebSocketDeleteHandle(webSocketPtr); } internal static void WebSocketSend(WebSocketBase webSocket, BufferType bufferType, Interop.WebSocket.Buffer buffer) { Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL or INVALID."); Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); ThrowIfSessionHandleClosed(webSocket); int errorCode; try { errorCode = Interop.WebSocket.WebSocketSend_Raw(webSocket.SessionHandle, bufferType, ref buffer, IntPtr.Zero); } catch (ObjectDisposedException innerException) { throw ConvertObjectDisposedException(webSocket, innerException); } ThrowOnError(errorCode); } internal static void WebSocketSendWithoutBody(WebSocketBase webSocket, BufferType bufferType) { Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL or INVALID."); Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); ThrowIfSessionHandleClosed(webSocket); int errorCode; try { errorCode = Interop.WebSocket.WebSocketSendWithoutBody_Raw(webSocket.SessionHandle, bufferType, IntPtr.Zero, IntPtr.Zero); } catch (ObjectDisposedException innerException) { throw ConvertObjectDisposedException(webSocket, innerException); } ThrowOnError(errorCode); } internal static void WebSocketReceive(WebSocketBase webSocket) { Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL or INVALID."); Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); ThrowIfSessionHandleClosed(webSocket); int errorCode; try { errorCode = Interop.WebSocket.WebSocketReceive(webSocket.SessionHandle, IntPtr.Zero, IntPtr.Zero); } catch (ObjectDisposedException innerException) { throw ConvertObjectDisposedException(webSocket, innerException); } ThrowOnError(errorCode); } internal static void WebSocketGetAction(WebSocketBase webSocket, ActionQueue actionQueue, Interop.WebSocket.Buffer[] dataBuffers, ref uint dataBufferCount, out Action action, out BufferType bufferType, out IntPtr actionContext) { Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL or INVALID."); Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); Debug.Assert(dataBufferCount >= 0, "'dataBufferCount' MUST NOT be negative."); Debug.Assert((dataBuffers == null && dataBufferCount == 0) || (dataBuffers != null && dataBufferCount == dataBuffers.Length), "'dataBufferCount' MUST MATCH 'dataBuffers.Length'."); action = Action.NoAction; bufferType = BufferType.None; actionContext = IntPtr.Zero; IntPtr dummy; ThrowIfSessionHandleClosed(webSocket); int errorCode; try { errorCode = Interop.WebSocket.WebSocketGetAction(webSocket.SessionHandle, actionQueue, dataBuffers, ref dataBufferCount, out action, out bufferType, out dummy, out actionContext); } catch (ObjectDisposedException innerException) { throw ConvertObjectDisposedException(webSocket, innerException); } ThrowOnError(errorCode); webSocket.ValidateNativeBuffers(action, bufferType, dataBuffers, dataBufferCount); Debug.Assert(dataBufferCount >= 0); Debug.Assert((dataBufferCount == 0 && dataBuffers == null) || (dataBufferCount <= dataBuffers.Length)); } internal static void WebSocketCompleteAction(WebSocketBase webSocket, IntPtr actionContext, int bytesTransferred) { Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL or INVALID."); Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); Debug.Assert(actionContext != IntPtr.Zero, "'actionContext' MUST NOT be IntPtr.Zero."); Debug.Assert(bytesTransferred >= 0, "'bytesTransferred' MUST NOT be negative."); if (webSocket.SessionHandle.IsClosed) { return; } try { Interop.WebSocket.WebSocketCompleteAction(webSocket.SessionHandle, actionContext, (uint)bytesTransferred); } catch (ObjectDisposedException) { } } private static void DrainActionQueue(SafeHandle webSocketHandle, ActionQueue actionQueue) { Debug.Assert(webSocketHandle != null && !webSocketHandle.IsInvalid, "'webSocketHandle' MUST NOT be NULL or INVALID."); IntPtr actionContext; IntPtr dummy; Action action; BufferType bufferType; while (true) { Interop.WebSocket.Buffer[] dataBuffers = new Interop.WebSocket.Buffer[1]; uint dataBufferCount = 1; int errorCode = Interop.WebSocket.WebSocketGetAction(webSocketHandle, actionQueue, dataBuffers, ref dataBufferCount, out action, out bufferType, out dummy, out actionContext); if (!Succeeded(errorCode)) { Debug.Assert(errorCode == 0, "'errorCode' MUST be 0."); return; } if (action == Action.NoAction) { return; } Interop.WebSocket.WebSocketCompleteAction(webSocketHandle, actionContext, 0); } } private static void MarshalAndVerifyHttpHeader(IntPtr httpHeaderPtr, ref Interop.WebSocket.HttpHeader httpHeader) { Debug.Assert(httpHeaderPtr != IntPtr.Zero, "'currentHttpHeaderPtr' MUST NOT be IntPtr.Zero."); IntPtr httpHeaderNamePtr = Marshal.ReadIntPtr(httpHeaderPtr); IntPtr lengthPtr = IntPtr.Add(httpHeaderPtr, IntPtr.Size); int length = Marshal.ReadInt32(lengthPtr); Debug.Assert(length >= 0, "'length' MUST NOT be negative."); if (httpHeaderNamePtr != IntPtr.Zero) { httpHeader.Name = Marshal.PtrToStringAnsi(httpHeaderNamePtr, length); } if ((httpHeader.Name == null && length != 0) || (httpHeader.Name != null && length != httpHeader.Name.Length)) { Debug.Assert(false, "The length of 'httpHeader.Name' MUST MATCH 'length'."); throw new AccessViolationException(); } // structure of Interop.WebSocket.HttpHeader: // Name = string* // NameLength = uint* // Value = string* // ValueLength = uint* // NOTE - All fields in the object are pointers to the actual value, hence the use of // n * IntPtr.Size to get to the correct place in the object. int valueOffset = 2 * IntPtr.Size; int lengthOffset = 3 * IntPtr.Size; IntPtr httpHeaderValuePtr = Marshal.ReadIntPtr(IntPtr.Add(httpHeaderPtr, valueOffset)); lengthPtr = IntPtr.Add(httpHeaderPtr, lengthOffset); length = Marshal.ReadInt32(lengthPtr); httpHeader.Value = Marshal.PtrToStringAnsi(httpHeaderValuePtr, (int)length); if ((httpHeader.Value == null && length != 0) || (httpHeader.Value != null && length != httpHeader.Value.Length)) { Debug.Assert(false, "The length of 'httpHeader.Value' MUST MATCH 'length'."); throw new AccessViolationException(); } } private static Interop.WebSocket.HttpHeader[] MarshalHttpHeaders(IntPtr nativeHeadersPtr, int nativeHeaderCount) { Debug.Assert(nativeHeaderCount >= 0, "'nativeHeaderCount' MUST NOT be negative."); Debug.Assert(nativeHeadersPtr != IntPtr.Zero || nativeHeaderCount == 0, "'nativeHeaderCount' MUST be 0."); Interop.WebSocket.HttpHeader[] httpHeaders = new Interop.WebSocket.HttpHeader[nativeHeaderCount]; // structure of Interop.WebSocket.HttpHeader: // Name = string* // NameLength = uint* // Value = string* // ValueLength = uint* // NOTE - All fields in the object are pointers to the actual value, hence the use of // 4 * IntPtr.Size to get to the next header. int httpHeaderStructSize = 4 * IntPtr.Size; for (int i = 0; i < nativeHeaderCount; i++) { int offset = httpHeaderStructSize * i; IntPtr currentHttpHeaderPtr = IntPtr.Add(nativeHeadersPtr, offset); MarshalAndVerifyHttpHeader(currentHttpHeaderPtr, ref httpHeaders[i]); } Debug.Assert(httpHeaders != null); Debug.Assert(httpHeaders.Length == nativeHeaderCount); return httpHeaders; } public static bool Succeeded(int hr) { return (hr >= 0); } private static void ThrowOnError(int errorCode) { if (Succeeded(errorCode)) { return; } throw new WebSocketException(errorCode); } private static void ThrowIfSessionHandleClosed(WebSocketBase webSocket) { if (webSocket.SessionHandle.IsClosed) { throw new WebSocketException(WebSocketError.InvalidState, SR.Format(SR.net_WebSockets_InvalidState_ClosedOrAborted, webSocket.GetType().FullName, webSocket.State)); } } private static WebSocketException ConvertObjectDisposedException(WebSocketBase webSocket, ObjectDisposedException innerException) { return new WebSocketException(WebSocketError.InvalidState, SR.Format(SR.net_WebSockets_InvalidState_ClosedOrAborted, webSocket.GetType().FullName, webSocket.State), innerException); } } }
// 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.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.ProjectManagement; namespace Microsoft.CodeAnalysis.GenerateType { internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax> { private class GenerateTypeCodeAction : CodeAction { private readonly bool _intoNamespace; private readonly bool _inNewFile; private readonly TService _service; private readonly Document _document; private readonly State _state; private readonly string _equivalenceKey; public GenerateTypeCodeAction( TService service, Document document, State state, bool intoNamespace, bool inNewFile) { _service = service; _document = document; _state = state; _intoNamespace = intoNamespace; _inNewFile = inNewFile; _equivalenceKey = Title; } private static string FormatDisplayText( State state, bool inNewFile, bool isNested) { var finalName = GetTypeName(state); if (inNewFile) { return string.Format(FeaturesResources.Generate_0_1_in_new_file, state.IsStruct ? "struct" : state.IsInterface ? "interface" : "class", state.Name); } else { return string.Format(isNested ? FeaturesResources.Generate_nested_0_1 : FeaturesResources.Generate_0_1, state.IsStruct ? "struct" : state.IsInterface ? "interface" : "class", state.Name); } } protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken) { var semanticDocument = await SemanticDocument.CreateAsync(_document, cancellationToken).ConfigureAwait(false); var editor = new Editor(_service, semanticDocument, _state, _intoNamespace, _inNewFile, cancellationToken: cancellationToken); return await editor.GetOperationsAsync().ConfigureAwait(false); } public override string Title { get { if (_intoNamespace) { var namespaceToGenerateIn = string.IsNullOrEmpty(_state.NamespaceToGenerateInOpt) ? FeaturesResources.Global_Namespace : _state.NamespaceToGenerateInOpt; return FormatDisplayText(_state, _inNewFile, isNested: false); } else { return FormatDisplayText(_state, inNewFile: false, isNested: true); } } } public override string EquivalenceKey { get { return _equivalenceKey; } } } private class GenerateTypeCodeActionWithOption : CodeActionWithOptions { private readonly TService _service; private readonly Document _document; private readonly State _state; internal GenerateTypeCodeActionWithOption(TService service, Document document, State state) { _service = service; _document = document; _state = state; } public override string Title { get { return FeaturesResources.Generate_new_type; } } public override string EquivalenceKey { get { return _state.Name; } } public override object GetOptions(CancellationToken cancellationToken) { var generateTypeOptionsService = _document.Project.Solution.Workspace.Services.GetService<IGenerateTypeOptionsService>(); var notificationService = _document.Project.Solution.Workspace.Services.GetService<INotificationService>(); var projectManagementService = _document.Project.Solution.Workspace.Services.GetService<IProjectManagementService>(); var syntaxFactsService = _document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var typeKindValue = GetTypeKindOption(_state); var isPublicOnlyAccessibility = IsPublicOnlyAccessibility(_state, _document.Project); return generateTypeOptionsService.GetGenerateTypeOptions( _state.Name, new GenerateTypeDialogOptions(isPublicOnlyAccessibility, typeKindValue, _state.IsAttribute), _document, notificationService, projectManagementService, syntaxFactsService); } private bool IsPublicOnlyAccessibility(State state, Project project) { return _service.IsPublicOnlyAccessibility(state.NameOrMemberAccessExpression, project) || _service.IsPublicOnlyAccessibility(state.SimpleName, project); } private TypeKindOptions GetTypeKindOption(State state) { var gotPreassignedTypeOptions = GetPredefinedTypeKindOption(state, out var typeKindValue); if (!gotPreassignedTypeOptions) { typeKindValue = state.IsSimpleNameGeneric ? TypeKindOptionsHelper.RemoveOptions(typeKindValue, TypeKindOptions.GenericInCompatibleTypes) : typeKindValue; typeKindValue = state.IsMembersWithModule ? TypeKindOptionsHelper.AddOption(typeKindValue, TypeKindOptions.Module) : typeKindValue; typeKindValue = state.IsInterfaceOrEnumNotAllowedInTypeContext ? TypeKindOptionsHelper.RemoveOptions(typeKindValue, TypeKindOptions.Interface, TypeKindOptions.Enum) : typeKindValue; typeKindValue = state.IsDelegateAllowed ? typeKindValue : TypeKindOptionsHelper.RemoveOptions(typeKindValue, TypeKindOptions.Delegate); typeKindValue = state.IsEnumNotAllowed ? TypeKindOptionsHelper.RemoveOptions(typeKindValue, TypeKindOptions.Enum) : typeKindValue; } return typeKindValue; } private bool GetPredefinedTypeKindOption(State state, out TypeKindOptions typeKindValueFinal) { if (state.IsAttribute) { typeKindValueFinal = TypeKindOptions.Attribute; return true; } TypeKindOptions typeKindValue = TypeKindOptions.None; if (_service.TryGetBaseList(state.NameOrMemberAccessExpression, out typeKindValue) || _service.TryGetBaseList(state.SimpleName, out typeKindValue)) { typeKindValueFinal = typeKindValue; return true; } if (state.IsClassInterfaceTypes) { typeKindValueFinal = TypeKindOptions.BaseList; return true; } if (state.IsDelegateOnly) { typeKindValueFinal = TypeKindOptions.Delegate; return true; } if (state.IsTypeGeneratedIntoNamespaceFromMemberAccess) { typeKindValueFinal = state.IsSimpleNameGeneric ? TypeKindOptionsHelper.RemoveOptions(TypeKindOptions.MemberAccessWithNamespace, TypeKindOptions.GenericInCompatibleTypes) : TypeKindOptions.MemberAccessWithNamespace; typeKindValueFinal = state.IsEnumNotAllowed ? TypeKindOptionsHelper.RemoveOptions(typeKindValueFinal, TypeKindOptions.Enum) : typeKindValueFinal; return true; } typeKindValueFinal = TypeKindOptions.AllOptions; return false; } protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken) { IEnumerable<CodeActionOperation> operations = null; var generateTypeOptions = options as GenerateTypeOptionsResult; if (generateTypeOptions != null && !generateTypeOptions.IsCancelled) { var semanticDocument = await SemanticDocument.CreateAsync(_document, cancellationToken).ConfigureAwait(false); var editor = new Editor(_service, semanticDocument, _state, true, generateTypeOptions, cancellationToken); operations = await editor.GetOperationsAsync().ConfigureAwait(false); } return operations; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.IDictionary.Keys /// </summary> public class IDictionaryKeys { private int c_MINI_STRING_LENGTH = 1; private int c_MAX_STRING_LENGTH = 20; public static int Main(string[] args) { IDictionaryKeys testObj = new IDictionaryKeys(); TestLibrary.TestFramework.BeginTestCase("Testing for Property: System.Collections.Generic.IDictionary.Keys"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Using Dictionary<TKey,TValue> which implemented the Keys property in IDictionay<TKey,TValue> and TKey is int..."; const string c_TEST_ID = "P001"; Dictionary<int, int> dictionary = new Dictionary<int, int>(); int key = TestLibrary.Generator.GetInt32(-55); int value = TestLibrary.Generator.GetInt32(-55); dictionary.Add(key, value); key = key + 1; dictionary.Add(key,value); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ICollection<int> keys = ((IDictionary<int, int>)dictionary).Keys; if (keys.Count != 2) { string errorDesc = "( the count of IDictionary<int, int>.Keys 2 as expected: Actual(" + keys.Count + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } if (!keys.Contains(key)) { string errorDesc = key + "should exist in (IDictionary<int, int>.Keys"; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Using Dictionary<TKey,TValue> which implemented the Keys property in IDictionay<TKey,TValue> and TKey is String..."; const string c_TEST_ID = "P002"; Dictionary<String, String> dictionary = new Dictionary<String, String>(); String key = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); String value = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); dictionary.Add(key, value); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ICollection<String> keys = ((IDictionary<String, String>)dictionary).Keys; if (keys.Count != 1) { string errorDesc = "( the count of IDictionary<int, int>.Keys 1 as expected: Actual(" + keys.Count + ")"; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } if (!keys.Contains(key)) { string errorDesc = key + "should exist in (IDictionary<String, String>.Keys"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: Using Dictionary<TKey,TValue> which implemented the Keys property in IDictionay<TKey,TValue> and TKey is customer class..."; const string c_TEST_ID = "P003"; Dictionary<MyClass, int> dictionary = new Dictionary<MyClass, int>(); MyClass key = new MyClass(); int value = TestLibrary.Generator.GetInt32(-55); dictionary.Add(key, value); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ICollection<MyClass> keys = ((IDictionary<MyClass, int>)dictionary).Keys; if (keys.Count != 1) { string errorDesc = "( the count of IDictionary<int, int>.Keys 1 as expected: Actual(" + keys.Count + ")"; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } if (!keys.Contains(key)) { string errorDesc = "MyClass object should exist in (IDictionary<String, String>.Keys"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("009", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: Using Dictionary<TKey,TValue> which implemented the Keys property in IDictionay<TKey,TValue> and Keys is empty..."; const string c_TEST_ID = "P004"; Dictionary<int, int> dictionary = new Dictionary<int, int>(); int key = TestLibrary.Generator.GetInt32(-55); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ICollection<int> keys = ((IDictionary<int, int>)dictionary).Keys; if (keys.Count != 0) { string errorDesc = "( the count of IDictionary<int, int>.Keys 0 as expected: Actual(" + keys.Count + ")"; TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } if (keys.Contains(key)) { string errorDesc = key + "should not exist in (IDictionary<int, int>.Keys"; TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region Help Class public class MyClass { } #endregion }
namespace T5Suite2 { partial class frmFreeTuneSettings { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton(); this.simpleButton2 = new DevExpress.XtraEditors.SimpleButton(); this.groupControl1 = new DevExpress.XtraEditors.GroupControl(); this.spinEdit4 = new DevExpress.XtraEditors.SpinEdit(); this.labelControl8 = new DevExpress.XtraEditors.LabelControl(); this.spinEdit3 = new DevExpress.XtraEditors.SpinEdit(); this.labelControl7 = new DevExpress.XtraEditors.LabelControl(); this.labelControl6 = new DevExpress.XtraEditors.LabelControl(); this.comboBoxEdit4 = new DevExpress.XtraEditors.ComboBoxEdit(); this.labelControl5 = new DevExpress.XtraEditors.LabelControl(); this.spinEdit2 = new DevExpress.XtraEditors.SpinEdit(); this.radioGroup1 = new DevExpress.XtraEditors.RadioGroup(); this.labelControl4 = new DevExpress.XtraEditors.LabelControl(); this.spinEdit1 = new DevExpress.XtraEditors.SpinEdit(); this.labelControl3 = new DevExpress.XtraEditors.LabelControl(); this.comboBoxEdit3 = new DevExpress.XtraEditors.ComboBoxEdit(); this.labelControl2 = new DevExpress.XtraEditors.LabelControl(); this.comboBoxEdit2 = new DevExpress.XtraEditors.ComboBoxEdit(); this.labelControl1 = new DevExpress.XtraEditors.LabelControl(); this.comboBoxEdit1 = new DevExpress.XtraEditors.ComboBoxEdit(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.groupControl1)).BeginInit(); this.groupControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit4.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit3.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit4.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit2.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.radioGroup1.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit1.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit3.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit2.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit1.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // simpleButton1 // this.simpleButton1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.simpleButton1.Location = new System.Drawing.Point(512, 429); this.simpleButton1.Name = "simpleButton1"; this.simpleButton1.Size = new System.Drawing.Size(75, 23); this.simpleButton1.TabIndex = 0; this.simpleButton1.Text = "Tune!"; this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click); // // simpleButton2 // this.simpleButton2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.simpleButton2.Location = new System.Drawing.Point(431, 429); this.simpleButton2.Name = "simpleButton2"; this.simpleButton2.Size = new System.Drawing.Size(75, 23); this.simpleButton2.TabIndex = 1; this.simpleButton2.Text = "Cancel"; this.simpleButton2.Click += new System.EventHandler(this.simpleButton2_Click); // // groupControl1 // this.groupControl1.Controls.Add(this.spinEdit4); this.groupControl1.Controls.Add(this.labelControl8); this.groupControl1.Controls.Add(this.spinEdit3); this.groupControl1.Controls.Add(this.labelControl7); this.groupControl1.Controls.Add(this.labelControl6); this.groupControl1.Controls.Add(this.comboBoxEdit4); this.groupControl1.Controls.Add(this.labelControl5); this.groupControl1.Controls.Add(this.spinEdit2); this.groupControl1.Controls.Add(this.radioGroup1); this.groupControl1.Controls.Add(this.labelControl4); this.groupControl1.Controls.Add(this.spinEdit1); this.groupControl1.Controls.Add(this.labelControl3); this.groupControl1.Controls.Add(this.comboBoxEdit3); this.groupControl1.Controls.Add(this.labelControl2); this.groupControl1.Controls.Add(this.comboBoxEdit2); this.groupControl1.Controls.Add(this.labelControl1); this.groupControl1.Controls.Add(this.comboBoxEdit1); this.groupControl1.Location = new System.Drawing.Point(15, 13); this.groupControl1.Name = "groupControl1"; this.groupControl1.Size = new System.Drawing.Size(572, 271); this.groupControl1.TabIndex = 2; this.groupControl1.Text = "Tune settings"; // // spinEdit4 // this.spinEdit4.EditValue = new decimal(new int[] { 12000, 0, 0, 0}); this.spinEdit4.Location = new System.Drawing.Point(124, 159); this.spinEdit4.Name = "spinEdit4"; this.spinEdit4.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.spinEdit4.Properties.Increment = new decimal(new int[] { 25, 0, 0, 0}); this.spinEdit4.Properties.IsFloatValue = false; this.spinEdit4.Properties.Mask.EditMask = "N00"; this.spinEdit4.Properties.MaxValue = new decimal(new int[] { 20000, 0, 0, 0}); this.spinEdit4.Properties.MinValue = new decimal(new int[] { 1000, 0, 0, 0}); this.spinEdit4.Size = new System.Drawing.Size(426, 20); this.spinEdit4.TabIndex = 17; // // labelControl8 // this.labelControl8.Location = new System.Drawing.Point(24, 164); this.labelControl8.Name = "labelControl8"; this.labelControl8.Size = new System.Drawing.Size(75, 13); this.labelControl8.TabIndex = 16; this.labelControl8.Text = "Knock time (ms)"; // // spinEdit3 // this.spinEdit3.EditValue = new decimal(new int[] { 6500, 0, 0, 0}); this.spinEdit3.Location = new System.Drawing.Point(124, 133); this.spinEdit3.Name = "spinEdit3"; this.spinEdit3.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.spinEdit3.Properties.Increment = new decimal(new int[] { 25, 0, 0, 0}); this.spinEdit3.Properties.IsFloatValue = false; this.spinEdit3.Properties.Mask.EditMask = "N00"; this.spinEdit3.Properties.MaxValue = new decimal(new int[] { 8500, 0, 0, 0}); this.spinEdit3.Properties.MinValue = new decimal(new int[] { 6000, 0, 0, 0}); this.spinEdit3.Size = new System.Drawing.Size(426, 20); this.spinEdit3.TabIndex = 15; // // labelControl7 // this.labelControl7.Location = new System.Drawing.Point(24, 138); this.labelControl7.Name = "labelControl7"; this.labelControl7.Size = new System.Drawing.Size(52, 13); this.labelControl7.TabIndex = 14; this.labelControl7.Text = "RPM limiter"; // // labelControl6 // this.labelControl6.Location = new System.Drawing.Point(24, 112); this.labelControl6.Name = "labelControl6"; this.labelControl6.Size = new System.Drawing.Size(44, 13); this.labelControl6.TabIndex = 12; this.labelControl6.Text = "BCV type"; // // comboBoxEdit4 // this.comboBoxEdit4.EditValue = "Trionic 5 valve"; this.comboBoxEdit4.Location = new System.Drawing.Point(124, 107); this.comboBoxEdit4.Name = "comboBoxEdit4"; this.comboBoxEdit4.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.comboBoxEdit4.Properties.Items.AddRange(new object[] { "Trionic 5 valve", "Trionic 7 valve"}); this.comboBoxEdit4.Size = new System.Drawing.Size(426, 20); this.comboBoxEdit4.TabIndex = 11; // // labelControl5 // this.labelControl5.Location = new System.Drawing.Point(180, 232); this.labelControl5.Name = "labelControl5"; this.labelControl5.Size = new System.Drawing.Size(80, 13); this.labelControl5.TabIndex = 10; this.labelControl5.Text = "Peak boost (bar)"; // // spinEdit2 // this.spinEdit2.EditValue = new decimal(new int[] { 140, 0, 0, 131072}); this.spinEdit2.Location = new System.Drawing.Point(281, 225); this.spinEdit2.Name = "spinEdit2"; this.spinEdit2.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.spinEdit2.Properties.DisplayFormat.FormatString = "F2"; this.spinEdit2.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom; this.spinEdit2.Properties.EditFormat.FormatString = "F2"; this.spinEdit2.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.Custom; this.spinEdit2.Properties.Increment = new decimal(new int[] { 5, 0, 0, 131072}); this.spinEdit2.Properties.MaxValue = new decimal(new int[] { 22, 0, 0, 65536}); this.spinEdit2.Size = new System.Drawing.Size(269, 20); this.spinEdit2.TabIndex = 9; // // radioGroup1 // this.radioGroup1.Location = new System.Drawing.Point(23, 190); this.radioGroup1.Name = "radioGroup1"; this.radioGroup1.Properties.Items.AddRange(new DevExpress.XtraEditors.Controls.RadioGroupItem[] { new DevExpress.XtraEditors.Controls.RadioGroupItem(0, "Tune based on torque"), new DevExpress.XtraEditors.Controls.RadioGroupItem(1, "Tune based on boost")}); this.radioGroup1.Size = new System.Drawing.Size(151, 67); this.radioGroup1.TabIndex = 8; this.radioGroup1.EditValueChanged += new System.EventHandler(this.radioGroup1_EditValueChanged); // // labelControl4 // this.labelControl4.Location = new System.Drawing.Point(180, 206); this.labelControl4.Name = "labelControl4"; this.labelControl4.Size = new System.Drawing.Size(84, 13); this.labelControl4.TabIndex = 7; this.labelControl4.Text = "Peak torque (Nm)"; // // spinEdit1 // this.spinEdit1.EditValue = new decimal(new int[] { 400, 0, 0, 0}); this.spinEdit1.Location = new System.Drawing.Point(281, 199); this.spinEdit1.Name = "spinEdit1"; this.spinEdit1.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.spinEdit1.Properties.Increment = new decimal(new int[] { 25, 0, 0, 0}); this.spinEdit1.Properties.IsFloatValue = false; this.spinEdit1.Properties.Mask.EditMask = "N00"; this.spinEdit1.Properties.MaxValue = new decimal(new int[] { 650, 0, 0, 0}); this.spinEdit1.Properties.MinValue = new decimal(new int[] { 100, 0, 0, 0}); this.spinEdit1.Size = new System.Drawing.Size(269, 20); this.spinEdit1.TabIndex = 6; this.spinEdit1.ValueChanged += new System.EventHandler(this.spinEdit1_ValueChanged); // // labelControl3 // this.labelControl3.Location = new System.Drawing.Point(24, 86); this.labelControl3.Name = "labelControl3"; this.labelControl3.Size = new System.Drawing.Size(53, 13); this.labelControl3.TabIndex = 5; this.labelControl3.Text = "Turbo type"; // // comboBoxEdit3 // this.comboBoxEdit3.EditValue = "Stock"; this.comboBoxEdit3.Location = new System.Drawing.Point(124, 81); this.comboBoxEdit3.Name = "comboBoxEdit3"; this.comboBoxEdit3.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.comboBoxEdit3.Properties.Items.AddRange(new object[] { "Stock", "MHI TD04HL-15T", "MHI TD04HL-19T", "Garrett GT28BB", "Garrett GT28RS", "Garrett GT3071R", "Holset HX35w", "Holset HX40w"}); this.comboBoxEdit3.Size = new System.Drawing.Size(426, 20); this.comboBoxEdit3.TabIndex = 4; this.comboBoxEdit3.SelectedIndexChanged += new System.EventHandler(this.comboBoxEdit3_SelectedIndexChanged); // // labelControl2 // this.labelControl2.Location = new System.Drawing.Point(24, 60); this.labelControl2.Name = "labelControl2"; this.labelControl2.Size = new System.Drawing.Size(63, 13); this.labelControl2.TabIndex = 3; this.labelControl2.Text = "Injector type"; // // comboBoxEdit2 // this.comboBoxEdit2.EditValue = "Stock injectors"; this.comboBoxEdit2.Location = new System.Drawing.Point(124, 55); this.comboBoxEdit2.Name = "comboBoxEdit2"; this.comboBoxEdit2.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.comboBoxEdit2.Properties.Items.AddRange(new object[] { "Stock injectors", "Green giants", "Siemens deka 630cc (60lb/h)", "Siemens deka 875cc (80lb/h)", "Siemens 1000cc/min"}); this.comboBoxEdit2.Size = new System.Drawing.Size(426, 20); this.comboBoxEdit2.TabIndex = 2; this.comboBoxEdit2.SelectedIndexChanged += new System.EventHandler(this.comboBoxEdit2_SelectedIndexChanged); // // labelControl1 // this.labelControl1.Location = new System.Drawing.Point(24, 34); this.labelControl1.Name = "labelControl1"; this.labelControl1.Size = new System.Drawing.Size(77, 13); this.labelControl1.TabIndex = 1; this.labelControl1.Text = "Mapsensor type"; // // comboBoxEdit1 // this.comboBoxEdit1.EditValue = "Stock mapsensor (2.5 bar)"; this.comboBoxEdit1.Location = new System.Drawing.Point(124, 29); this.comboBoxEdit1.Name = "comboBoxEdit1"; this.comboBoxEdit1.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.comboBoxEdit1.Properties.Items.AddRange(new object[] { "Stock mapsensor (2.5 bar)", "3.0 bar mapsensor", "3.5 bar mapsensor", "4.0 bar mapsensor", "5.0 bar mapsensor"}); this.comboBoxEdit1.Size = new System.Drawing.Size(426, 20); this.comboBoxEdit1.TabIndex = 0; this.comboBoxEdit1.SelectedIndexChanged += new System.EventHandler(this.comboBoxEdit1_SelectedIndexChanged); // // pictureBox1 // this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.pictureBox1.Location = new System.Drawing.Point(15, 290); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(186, 159); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pictureBox1.TabIndex = 3; this.pictureBox1.TabStop = false; // // frmFreeTuneSettings // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(599, 464); this.ControlBox = false; this.Controls.Add(this.pictureBox1); this.Controls.Add(this.groupControl1); this.Controls.Add(this.simpleButton2); this.Controls.Add(this.simpleButton1); this.Name = "frmFreeTuneSettings"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Free tuning parameters"; this.Shown += new System.EventHandler(this.frmFreeTuneSettings_Shown); ((System.ComponentModel.ISupportInitialize)(this.groupControl1)).EndInit(); this.groupControl1.ResumeLayout(false); this.groupControl1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit4.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit3.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit4.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit2.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.radioGroup1.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit1.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit3.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit2.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit1.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraEditors.SimpleButton simpleButton1; private DevExpress.XtraEditors.SimpleButton simpleButton2; private DevExpress.XtraEditors.GroupControl groupControl1; private DevExpress.XtraEditors.LabelControl labelControl4; private DevExpress.XtraEditors.SpinEdit spinEdit1; private DevExpress.XtraEditors.LabelControl labelControl3; private DevExpress.XtraEditors.ComboBoxEdit comboBoxEdit3; private DevExpress.XtraEditors.LabelControl labelControl2; private DevExpress.XtraEditors.ComboBoxEdit comboBoxEdit2; private DevExpress.XtraEditors.LabelControl labelControl1; private DevExpress.XtraEditors.ComboBoxEdit comboBoxEdit1; private DevExpress.XtraEditors.LabelControl labelControl5; private DevExpress.XtraEditors.SpinEdit spinEdit2; private DevExpress.XtraEditors.RadioGroup radioGroup1; private System.Windows.Forms.PictureBox pictureBox1; private DevExpress.XtraEditors.LabelControl labelControl6; private DevExpress.XtraEditors.ComboBoxEdit comboBoxEdit4; private DevExpress.XtraEditors.SpinEdit spinEdit3; private DevExpress.XtraEditors.LabelControl labelControl7; private DevExpress.XtraEditors.SpinEdit spinEdit4; private DevExpress.XtraEditors.LabelControl labelControl8; } }
using DevExpress.Internal; using DevExpress.Mvvm.Native; using DevExpress.Mvvm.UI.Interactivity; using DevExpress.Mvvm.UI.Native; using DevExpress.Utils; using NUnit.Framework; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shell; using System.Reflection; namespace DevExpress.Mvvm.UI.Tests { public static class ApplicationJumpListServiceTestsImageSourceHelper { public static void RegisterPackScheme() { new System.Windows.Documents.FlowDocument(); } public static ImageSource GetImageSource(Uri uri) { if(uri == null) return null; try { #if SILVERLIGHT return new BitmapImage(uri); #else return BitmapFrame.Create(uri); #endif } catch { return null; } } public static ImageSource GetImageSource(Stream stream) { if(stream == null) return null; try { #if SILVERLIGHT BitmapImage bi = new BitmapImage(); bi.SetSource(stream); return bi; #else return BitmapFrame.Create(stream); #endif } catch { return null; } } } [TestFixture] public class ApplicationJumpListServiceTests : BaseWpfFixture { TestJumpActionsManager jumpActionsManager; TestNativeJumpList nativeJumpList; IApplicationJumpListService applicationJumpListService; protected override void SetUpCore() { base.SetUpCore(); ApplicationJumpListServiceTestsImageSourceHelper.RegisterPackScheme(); NativeResourceManager.CompanyNameOverride = "DevExpress Tests"; NativeResourceManager.ProductNameOverride = "DevExpress.Xpf.Core Tests"; NativeResourceManager.VersionOverride = AssemblyInfo.Version; nativeJumpList = new TestNativeJumpList(); jumpActionsManager = new TestJumpActionsManager(); applicationJumpListService = new TestApplicationJumpListService(nativeJumpList, jumpActionsManager); Assert.IsNotNull(applicationJumpListService); applicationJumpListService.Items.Clear(); } protected override void TearDownCore() { string resourcesFolder = NativeResourceManager.ExpandVariables(NativeResourceManager.ResourcesFolder); if(Directory.Exists(resourcesFolder)) Directory.Delete(resourcesFolder, true); NativeResourceManager.ProductNameOverride = null; NativeResourceManager.CompanyNameOverride = null; NativeResourceManager.VersionOverride = null; base.TearDownCore(); } [Test] public void FillJumpListInXaml_AttachToWindow_ShowWindow_CheckApplied() { applicationJumpListService.Items.Add(new ApplicationJumpPathInfo() { Path = "1.txt" }); Interaction.GetBehaviors(Window).Add((ServiceBase)applicationJumpListService); EnqueueShowWindow(); Assert.IsTrue(Window.IsLoaded); AssertHelper.AssertEnumerablesAreEqual(new JumpItem[] { new JumpPath() { Path = "1.txt" } }, nativeJumpList.AppliedList.JumpItems, true, false); } [Test] public void ShowFrequentCategory_ShowRecentCategory() { applicationJumpListService.ShowFrequentCategory = true; applicationJumpListService.ShowRecentCategory = true; applicationJumpListService.Apply(); Assert.AreEqual(true, nativeJumpList.AppliedList.ShowFrequentCategory); Assert.AreEqual(true, nativeJumpList.AppliedList.ShowRecentCategory); } [Test] public void AddToRecentCategory() { applicationJumpListService.AddToRecentCategory("1"); AssertHelper.AssertEnumerablesAreEqual(new string[] { "1" }, nativeJumpList.RecentCategory); } [Test] public void AddJumpPath_CheckRejectedItemsListIsEmpty() { applicationJumpListService.Items.Add("4"); AssertHelper.AssertEnumerablesAreEqual(new RejectedApplicationJumpItem[] { }, applicationJumpListService.Apply()); } [Test] public void AddJumpPath() { applicationJumpListService.Items.Add("1"); applicationJumpListService.Items.Add("category", "2"); applicationJumpListService.Apply(); AssertHelper.AssertEnumerablesAreEqual( new JumpItem[] { new JumpPath() { Path = "1" }, new JumpPath() { Path = "2", CustomCategory = "category" } }, nativeJumpList.AppliedList.JumpItems, true, false ); } [Test] public void ClearJumpPath() { applicationJumpListService.Items.Add("1"); applicationJumpListService.Items.Add("category", "2"); applicationJumpListService.Items.Clear(); applicationJumpListService.Apply(); AssertHelper.AssertEnumerablesAreEqual(new JumpItem[] { }, nativeJumpList.AppliedList.JumpItems, true, false); } [Test] public void ReplaceJumpPath() { applicationJumpListService.Items.Add("1"); applicationJumpListService.Items.Add("category", "2"); applicationJumpListService.Items.Add("category5", "3"); applicationJumpListService.Items[1] = applicationJumpListService.Items[0]; applicationJumpListService.Apply(); AssertHelper.AssertEnumerablesAreEqual( new JumpItem[] { new JumpPath() { Path = "1" }, new JumpPath() { Path = "1" }, new JumpPath() { Path = "3", CustomCategory = "category5" }, }, nativeJumpList.AppliedList.JumpItems, true, false ); } [Test] public void RemoveJumpPath() { applicationJumpListService.Items.Add("1"); applicationJumpListService.Items.Add("category", "2"); applicationJumpListService.Items.Add("category5", "3"); applicationJumpListService.Items.RemoveAt(1); applicationJumpListService.Apply(); AssertHelper.AssertEnumerablesAreEqual( new JumpItem[] { new JumpPath() { Path = "1" }, new JumpPath() { Path = "3", CustomCategory = "category5" }, }, nativeJumpList.AppliedList.JumpItems, true, false ); } [Test] public void AddApplicationJumpTask_CheckProperties() { Action action = () => { }; applicationJumpListService.Items.Add("category", "1", null, "desc", action); applicationJumpListService.Items.Add(new ApplicationJumpTaskInfo() { Title = "2", IconResourcePath = "D:\\1.ico", IconResourceIndex = 3 }); applicationJumpListService.Apply(); AssertHelper.AssertEnumerablesAreEqual( new JumpItem[] { new JumpTask() { Title = "1", IconResourcePath = null, Description = "desc", CustomCategory = "category" }, new JumpTask() { Title = "2", IconResourcePath = "D:\\1.ico", IconResourceIndex = 3 } }, nativeJumpList.AppliedList.JumpItems, true, false ); } [Test] public void AddApplicationJumpTask() { Action action = () => { }; ApplicationJumpTaskInfo jumpTask = applicationJumpListService.Items.Add("category", "1", null, "desc", action); applicationJumpListService.Apply(); AssertHelper.AssertEnumerablesAreEqual( new ApplicationJumpTaskInfo[] { jumpTask }, jumpActionsManager.RegisteredActions, true ); } [Test] public void AddApplicationJumpTaskWithoutAction_AssignAction_CheckActionRegistered() { ApplicationJumpTaskInfo jumpTask = new ApplicationJumpTaskInfo() { Title = "1" }; applicationJumpListService.Items.Add(jumpTask); applicationJumpListService.Apply(); jumpTask.Action = () => { }; AssertHelper.AssertEnumerablesAreEqual( new ApplicationJumpTaskInfo[] { jumpTask }, jumpActionsManager.RegisteredActions, true ); } [Test] public void AddApplicationJumpTaskWithIcon_CheckIconJumpTaskIconResourcePath() { ImageSource icon = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource( AssemblyHelper.GetResourceUri(typeof(ApplicationJumpListServiceTests).Assembly, "Services/ApplicationJumpListService/demoicon.ico")); ApplicationJumpTaskInfo applicationJumpTask = applicationJumpListService.Items.Add("title", icon, () => { }); applicationJumpListService.Apply(); ApplicationJumpTaskWrap jumpTask = (ApplicationJumpTaskWrap)nativeJumpList.AppliedList.JumpItems.Single(); Assert.IsNotNull(jumpTask.IconResourcePath); byte[] expectedIcon = StreamHelper.CopyAllBytes( AssemblyHelper.GetResourceStream(typeof(ApplicationJumpListServiceTests).Assembly, "Services/ApplicationJumpListService/demoicon.ico", true)); byte[] actualIcon = File.ReadAllBytes(jumpTask.IconResourcePath); AssertHelper.AssertEnumerablesAreEqual(expectedIcon, actualIcon); } [Test] public void RejectedReasons() { ImageSource invalidIcon = new BitmapImage() { UriSource = AssemblyHelper.GetResourceUri(typeof(ApplicationJumpListServiceTests).Assembly, "INVALID") }; ImageSource icon = ApplicationJumpListServiceTestsImageSourceHelper.GetImageSource( AssemblyHelper.GetResourceUri(typeof(ApplicationJumpListServiceTests).Assembly, "Services/ApplicationJumpListService/demoicon.ico")); applicationJumpListService.Items.Add("a:None"); applicationJumpListService.Items.Add("b:InvalidItem"); applicationJumpListService.Items.Add("c:NoRegisteredHandler"); applicationJumpListService.Items.Add("d:RemovedByUser"); AssertHelper.AssertThrows<ArgumentException>(() => { applicationJumpListService.Items.Add("e", invalidIcon, () => { }, "e"); }, e => { Assert.AreEqual("icon", e.ParamName); Assert.IsTrue(e.InnerException is ApplicationJumpTaskInvalidIconException); }); AssertHelper.AssertThrows<ApplicationJumpTaskBothIconAndIconResourcePathSpecifiedException>(() => { applicationJumpListService.Items.Add(new ApplicationJumpTaskInfo() { Title = "g", Icon = icon, IconResourcePath = "C:\\1.ico", Action = () => { }, CommandId = "g" }); }); IEnumerable<RejectedApplicationJumpItem> rejection = applicationJumpListService.Apply(); AssertHelper.AssertEnumerablesAreEqual(new JumpItemRejectionReason[] { JumpItemRejectionReason.None, JumpItemRejectionReason.InvalidItem, JumpItemRejectionReason.NoRegisteredHandler, JumpItemRejectionReason.RemovedByUser, }, rejection.Select(r => r.Reason)); } [Test] public void AddApplicationJumpTaskTwice() { applicationJumpListService.Items.Add("category", "1", null, "desc", () => { }); AssertHelper.AssertThrows<InvalidOperationException>(() => { applicationJumpListService.Items.Add("category", "1", null, "desc", () => { }); }); applicationJumpListService.Items.Add("another category", "1", null, "desc", () => { }); IEnumerable<RejectedApplicationJumpItem> rejection = applicationJumpListService.Apply(); AssertHelper.AssertEnumerablesAreEqual(new JumpItemRejectionReason[] { }, rejection.Select(r => r.Reason)); } [Test] public void AddApplicationJumpTaskWithNullTitleAndNullCategory() { applicationJumpListService.Items.Add(null, null, null, "desc", () => { }); IEnumerable<RejectedApplicationJumpItem> rejection = applicationJumpListService.Apply(); Assert.IsFalse(rejection.Any()); } [Test] public void JumpListCanBeConstructedFromXaml() { Assert.IsNotNull(typeof(ApplicationJumpListService).GetConstructor(new Type[] { })); Type itemsCollectionType = typeof(ApplicationJumpListService).GetProperty("Items").PropertyType; Assert.IsTrue(itemsCollectionType.GetInterfaces().Contains(typeof(IList))); Type[] itemTypes = itemsCollectionType.GetMethods().Where(m => m.Name == "Add").Select(m => m.GetParameters().SingleOrDefault()).Where(x => x != null).Select(p => p.ParameterType).ToArray(); AssertHelper.AssertSetsAreEqual(new Type[] { typeof(ApplicationJumpItem) }, itemTypes); } [Test] public void AddPath_CastListToObjectArray() { ApplicationJumpPathInfo jumpPathInfo = applicationJumpListService.Items.Add("1"); object[] a = applicationJumpListService.Items.Cast<object>().ToArray(); Assert.AreEqual(1, a.Length); Assert.AreEqual(jumpPathInfo, a[0]); IEnumerable items = applicationJumpListService.Items; object[] b = items.Cast<object>().ToArray(); Assert.AreEqual(1, b.Length); Assert.AreEqual(jumpPathInfo, b[0]); object[] c = ((ApplicationJumpListService)applicationJumpListService).Items.Cast<object>().ToArray(); Assert.AreEqual(1, c.Length); ApplicationJumpPath jumpPath = (ApplicationJumpPath)c[0]; Assert.AreEqual(jumpPathInfo, ApplicationJumpItem.GetItemInfo(jumpPath)); Assert.AreEqual(jumpPath, ApplicationJumpItem.GetItem(jumpPathInfo)); } [Test] public void SeveralJumpList() { IApplicationJumpListService jumpList_2 = new TestApplicationJumpListService(nativeJumpList, jumpActionsManager); Assert.IsFalse(jumpList_2.ShowFrequentCategory); Assert.IsFalse(jumpList_2.ShowRecentCategory); applicationJumpListService.ShowFrequentCategory = true; applicationJumpListService.ShowRecentCategory = true; applicationJumpListService.Items.Add("1"); applicationJumpListService.Apply(); AssertHelper.AssertEnumerablesAreEqual(new ApplicationJumpItemInfo[] { new ApplicationJumpPathInfo() { Path = "1" } }, jumpList_2.Items, true); Assert.IsTrue(jumpList_2.ShowFrequentCategory); Assert.IsTrue(jumpList_2.ShowRecentCategory); } [Test] public void TryChangeTitleAfterAddingToList() { ApplicationJumpTaskInfo task = applicationJumpListService.Items.Add("title", null, () => { }); AssertHelper.AssertThrows<InvalidOperationException>(() => task.Title = "new title"); } [Test] public void TryRegisterTwoSimilarTasks_SetCommandIdManual_Register() { ApplicationJumpTaskInfo task = applicationJumpListService.Items.Add("title", null, () => { }).Clone(); AssertHelper.AssertThrows<ApplicationJumpTaskDuplicateCommandIdException>(() => applicationJumpListService.Items.Add(task)); task.CommandId = "xxx"; applicationJumpListService.Items.Add(task); } [Test] public void ReplaceTaskByTaskWithSimilarCommand() { ApplicationJumpTaskInfo task = applicationJumpListService.Items.Add("title", null, () => { }, "xxx").Clone(); task.Title = "another"; applicationJumpListService.Items[0] = task; } [Test] public void AddOrReplace() { ApplicationJumpTaskInfo task = applicationJumpListService.Items.Add("title", null, () => { }); task = task.Clone(); Assert.IsFalse(applicationJumpListService.Items.AddOrReplace(task)); Assert.AreEqual(1, applicationJumpListService.Items.Count); task = task.Clone(); task.Title = "new title"; Assert.IsTrue(applicationJumpListService.Items.AddOrReplace(task)); Assert.AreEqual(2, applicationJumpListService.Items.Count); } } public class TestNativeJumpList : NativeJumpList { public TestNativeJumpList() : base(ApplicationJumpItemWrapper.GetJumpItemCommandId) { AppliedList = new JumpList(); RecentCategory = new List<string>(); } public JumpList AppliedList { get; private set; } public List<string> RecentCategory { get; private set; } protected override IEnumerable<Tuple<JumpItem, JumpItemRejectionReason>> ApplyOverride(JumpList list) { AppliedList.ShowFrequentCategory = list.ShowFrequentCategory; AppliedList.ShowRecentCategory = list.ShowRecentCategory; AppliedList.JumpItems.Clear(); AppliedList.JumpItems.AddRange(list.JumpItems); List<Tuple<JumpItem, JumpItemRejectionReason>> rejection = new List<Tuple<JumpItem, JumpItemRejectionReason>>(); foreach(JumpItem item in list.JumpItems) { string title = (item as JumpPath).Return(p => p.Path, () => ((JumpTask)item).Title) ?? string.Empty; title.Split(':') .Skip(1).SingleOrDefault() .Do(s => rejection.Add(new Tuple<JumpItem, JumpItemRejectionReason>(item, (JumpItemRejectionReason)Enum.Parse(typeof(JumpItemRejectionReason), s)))); } foreach(JumpItem item in rejection.Select(r => r.Item1)) list.JumpItems.Remove(item); return rejection; } protected override void AddToRecentCategoryOverride(string path) { RecentCategory.Add(path); } } public class TestJumpActionsManager : IJumpActionsManager { List<ApplicationJumpTaskInfo> registeredActions = new List<ApplicationJumpTaskInfo>(); bool updating = false; public List<ApplicationJumpTaskInfo> RegisteredActions { get { return registeredActions; } } public void BeginUpdate() { if(updating) throw new InvalidOperationException(); updating = true; } public void EndUpdate() { updating = false; } public void RegisterAction(IJumpAction jumpAction, string commandLineArgumentPrefix, Func<string> launcherPath) { if(!updating) throw new InvalidOperationException(); Assert.IsNotNull(commandLineArgumentPrefix); Assert.IsNotNull(launcherPath); Assert.IsTrue(File.Exists(launcherPath())); Assert.IsNotNull(jumpAction.CommandId); ApplicationJumpTaskWrap applicationJumpTaskWrap = (ApplicationJumpTaskWrap)jumpAction; RegisteredActions.Add(applicationJumpTaskWrap.ApplicationJumpTask); } } public class TestApplicationJumpListService : ApplicationJumpListService { public TestApplicationJumpListService(INativeJumpList nativeJumpList, IJumpActionsManager jumpActionsManager) : base(nativeJumpList, jumpActionsManager) { } } }
using System; using System.Configuration; using System.Collections.Generic; using System.Net; using System.Web; using EmergeTk; using EmergeTk.Model; using ServiceStack.Client; using ServiceStack.Redis; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using ProtobufSerializer; using System.IO; using System.Data; using System.Text; using System.Xml; using System.Reflection; using System.Text.RegularExpressions; namespace EmergeTk.Model { public class RedisReadWritePair { public String ReadServer { get; set; } public String WriteServer { get; set; } } public class HashCachePoolConfiguration : List<RedisReadWritePair> { protected static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(HashCachePoolConfiguration)); public void ConstructFromFile(String xmlFile) { //log.DebugFormat("Constructing HashCachePoolConfiguration object from file {0}", xmlFile); XmlDocument doc = new XmlDocument(); if (!File.Exists(xmlFile)) throw new Exception(String.Format("Configuration file {0} for HashCachePool does not exist!", xmlFile)); //log.DebugFormat("Configuring HashCachePool from config file found at {0}", xmlFile); doc.Load(xmlFile); this.ConstructFromXmlDoc(doc); } public void ConstructFromXmlDoc(XmlDocument doc) { XmlNodeList shardNodes = doc.SelectNodes("hashPoolConfig/shard"); foreach (XmlNode shardNode in shardNodes) { RedisReadWritePair readWritePair = new RedisReadWritePair(); readWritePair.ReadServer = shardNode.SelectSingleNode("reads").InnerText; readWritePair.WriteServer = shardNode.SelectSingleNode("writes").InnerText; this.Add(readWritePair); //log.DebugFormat("Found shard with readServer = {0}, writeServer = {1}", readWritePair.ReadServer, readWritePair.WriteServer); } } public HashCachePoolConfiguration(String pathToXmlFile) { ConstructFromFile(pathToXmlFile); } public HashCachePoolConfiguration() { } } public class HashCachePool { protected static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(HashCachePool)); private List<PooledRedisClientManager> redisPools = new List<PooledRedisClientManager>(); public void Configure(HashCachePoolConfiguration config) { foreach (RedisReadWritePair pair in config) { redisPools.Add(new PooledRedisClientManager(new List<String> { pair.WriteServer }, new List<String> { pair.ReadServer })); } } public IRedisClient GetReadClient(String key) { return GetShard(key).GetReadOnlyClient(); } public IRedisClient GetWriteClient(String key) { return GetShard(key).GetClient(); } private PooledRedisClientManager GetShard(String key) { int hash = Math.Abs(key.GetHashCode()); int index = hash % redisPools.Count; return redisPools[index]; } public void FlushAll() { foreach (PooledRedisClientManager redisPool in redisPools) { redisPool.FlushAll(); } } } public class LocalCache { protected static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(LocalCache)); private Dictionary<RecordDefinition, AbstractRecord> localRecords = new Dictionary<RecordDefinition, AbstractRecord>(); Dictionary<string, RecordDefinition> localRecordKeyMap = new Dictionary<string, RecordDefinition>(); // the syntax for child property list key expressions is: // fullname:rowid:propertyName // e.g. "FiveToOne.Gallery.Rmx.Playlist:12345:Creatives" protected static Regex rgxProperty = new Regex(@"(?<recordDefSuffix>[\w\.]+:\d+):(?<property>\w+)", RegexOptions.Compiled); [NonSerialized] ReaderWriterLockSlim dictionaryLock = new ReaderWriterLockSlim (); public ReaderWriterLockSlim DictionaryLock { get { return dictionaryLock; } } public void PutLocal(string key, AbstractRecord value) { this.DictionaryLock.EnterWriteLock (); try { key = PrepareKey(key); localRecordKeyMap[key] = value.Definition; if (localRecords.ContainsKey (value.Definition) && !object.ReferenceEquals (value, localRecords[value.Definition])) { //expire the old guy. localRecords[value.Definition].MarkAsStale (); } localRecords[value.Definition] = value; } finally { this.DictionaryLock.ExitWriteLock (); } } static public string PrepareKey(string key) { //return HttpUtility.UrlEncode( key ).ToLower(); return key.Replace(" ", "-").ToLower(); } public AbstractRecord GetLocalRecord(RecordDefinition rd) { //using (new ReadLock(this.DictionaryLock)) this.DictionaryLock.EnterReadLock (); try { if (localRecords.ContainsKey (rd)) { var rec = localRecords[rd]; if (rec != null && !rec.IsStale) return rec; } return null; } finally { this.DictionaryLock.ExitReadLock (); } } public AbstractRecord GetLocalRecord(string key) { key = PrepareKey(key); this.DictionaryLock.EnterReadLock (); try { if (localRecordKeyMap.ContainsKey(key)) { RecordDefinition rd = localRecordKeyMap[key]; if (localRecords.ContainsKey (rd)) { var rec = localRecords[rd]; if (rec != null && !rec.IsStale) return rec; } } } finally { this.DictionaryLock.ExitReadLock (); } return null; } public AbstractRecord GetLocalRecordFromPreparedKey(string keyPrepared) { this.DictionaryLock.EnterReadLock (); try { if (localRecordKeyMap.ContainsKey(keyPrepared)) { RecordDefinition rd = localRecordKeyMap[keyPrepared]; if (localRecords.ContainsKey (rd)) { var rec = localRecords[rd]; if (rec != null && !rec.IsStale) return rec; } } } finally { this.DictionaryLock.ExitReadLock (); } return null; } public void Remove(RecordDefinition def) { this.DictionaryLock.EnterWriteLock (); try { if (localRecords.ContainsKey (def)) { localRecords[def].MarkAsStale(); localRecords.Remove(def); } } finally { this.DictionaryLock.ExitWriteLock (); } } public void ClearFromLocalCache(string key) { if (key == null) { log.Error("Null key attempted to clear from cache.", System.Environment.StackTrace); return; } Match m = rgxProperty.Match(key); if (m.Success) { String propertyName = m.Groups["property"].Value; String recordDefString = "Record:" + m.Groups["recordDefSuffix"].Value; AbstractRecord record = GetLocalRecord(RecordDefinition.FromString(recordDefString)); if (record != null) { this.DictionaryLock.EnterWriteLock (); try { record.UnsetProperty(propertyName, false); } finally { this.DictionaryLock.ExitWriteLock (); } } } else { key = LocalCache.PrepareKey(key); //log.Debug("clearing from cache " + key); this.DictionaryLock.EnterWriteLock (); try { if (localRecordKeyMap.ContainsKey(key)) { RemoveRecordByDefinition(localRecordKeyMap[key]); localRecordKeyMap.Remove(key); } else if (key.StartsWith("record:")) { RemoveRecordByDefinition(RecordDefinition.FromString(key)); } } finally { this.DictionaryLock.ExitWriteLock (); } } } // N.B. - do NOT call this function without being in a WriteLock. private void RemoveRecordByDefinition(RecordDefinition rd) { if (localRecords.ContainsKey(rd)) { AbstractRecord r = localRecords[rd]; if (null != r) r.MarkAsStale(); localRecords.Remove(rd); } } public bool ContainsLocalRecord(RecordDefinition rd) { this.DictionaryLock.EnterReadLock (); try { return localRecords.ContainsKey(rd); } finally { this.DictionaryLock.ExitReadLock (); } } public void Flush() { this.DictionaryLock.EnterWriteLock (); try { localRecordKeyMap.Clear(); localRecords.Clear(); } finally { this.DictionaryLock.ExitWriteLock (); } } } public class RedisCacheClient : ICacheProvider { protected static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(RedisCacheClient)); static public HashCachePool hashCachePool = new HashCachePool(); LocalCache localCache = new LocalCache(); #region ICacheProvider implementation public AbstractRecord GetLocalRecord(string key) { return localCache.GetLocalRecord(key); } public AbstractRecord GetLocalRecord (RecordDefinition rd) { return localCache.GetLocalRecord (rd); } public void PutLocal(string key, AbstractRecord value) { localCache.PutLocal(key, value); } public bool Set (string key, AbstractRecord value) { StopWatch watch = new StopWatch("RedisCacheClient.Set_AbstractRecord", this.GetType().Name); watch.Start(); key = LocalCache.PrepareKey(key); localCache.PutLocal(key, value); watch.Stop(); if (value is ICacheLocalOnly) return true; if (value == null) throw new ArgumentException("Unable to index AbstractRecord: " + value); //log.Debug("Setting key for abstractrecord", key, value.OriginalValues ); //log.DebugFormat ("Setting record : {0}, {1}", key, value); MemoryStream s = new MemoryStream(100); ProtoSerializer.Serialize(value, s); try { using (IRedisClient rc = hashCachePool.GetWriteClient(key)) { rc.Set<byte[]>(key, s.ToArray()); } watch.Stop(); return true; } catch (Exception ex) { log.ErrorFormat("Set error. key={0}. Exception={1}", key, ex); } return false; } public bool Set (string key, object value) { StopWatch watch = new StopWatch("RedisCacheClient.Set_Object", this.GetType().Name); watch.Start(); key = LocalCache.PrepareKey(key); try { if (null != value) { MemoryStream s = new MemoryStream(100); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(s, value); using (IRedisClient rc = hashCachePool.GetWriteClient(key)) { rc.Set<byte[]>(key, s.ToArray()); } } watch.Stop(); return true; } catch (Exception ex) { log.ErrorFormat("Set error. key={0}. Exception={1}", key, ex); } return false; } public bool Set(string key, string value) { StopWatch watch = new StopWatch("RedisCacheClient.Set_String", this.GetType().Name); watch.Start(); key = LocalCache.PrepareKey(key); //log.Debug("Setting key for string", key, value); try { if (null != value) { using (IRedisClient rc = hashCachePool.GetWriteClient(key)) { rc.Set<string>(key, value); } } watch.Stop(); return true; } catch (Exception ex) { log.ErrorFormat("Set error. key={0}. Exception={1}", key, ex); } return false; } private static byte[] nullByte = { 0 }; public void AppendStringList(string key, string value) { try { //log.Debug("Appending StringList key ", key); key = LocalCache.PrepareKey(key); using (IRedisClient rc = hashCachePool.GetWriteClient(key)) { rc.AddItemToList(key, value); } } catch (Exception ex) { log.ErrorFormat("AppendStringList error. key={0}. Exception={1}", key, ex); } } public string[] GetStringList(string key) { string[] items = null; try { //log.Debug("GetStringList key ", key); key = LocalCache.PrepareKey(key); List<string> listItems = null; using (IRedisClient rc = hashCachePool.GetReadClient(key)) { listItems = rc.GetAllItemsFromList(key); } if (listItems != null && listItems.Count > 0) { items = listItems.ToArray(); } } catch (Exception ex) { log.ErrorFormat("GetStringList error. key={0}. Exception={1}", key, ex); } return items; } public T GetRecord<T>(string key) where T : AbstractRecord, new() { key = LocalCache.PrepareKey(key); AbstractRecord record = localCache.GetLocalRecordFromPreparedKey(key); if (null != record || typeof(T).GetInterface("ICacheLocalOnly") != null) return record as T; object o = null; try { //log.Debug("GetRecord<T> key ", key); using (IRedisClient rc = hashCachePool.GetReadClient(key)) { o = rc.Get<byte[]>(key); } } catch (Exception ex) { log.ErrorFormat("GetRecord error. key={0}. Exception={1}", key, ex); } if (o == null) return null; if (!(o is byte[])) { log.Error("Expecting value to be byte[] but got " + o); throw new Exception("Expecting value to be byte[]"); } byte[] bytes = (byte[])o; MemoryStream s = new MemoryStream(bytes); T t = ProtoSerializer.Deserialize<T>(s); localCache.PutLocal(key, t); return t; } public AbstractRecord GetRecord(Type t, string key) { key = LocalCache.PrepareKey(key); AbstractRecord record = localCache.GetLocalRecordFromPreparedKey(key); if (null != record || t.GetInterface("IRedisLocalOnly") != null) return record; object o = null; try { //log.Debug("GetRecord key ", key); using (IRedisClient rc = hashCachePool.GetReadClient(key)) { o = rc.Get<byte[]>(key); } } catch (Exception ex) { log.ErrorFormat("GetRecord error. key={0}. Exception={1}", key, ex); } if (o == null) return null; if (!(o is byte[])) { log.Error("Expecting value to be byte[] but got " + o); throw new Exception("Expecting value to be byte[]"); } byte[] bytes = (byte[])o; MemoryStream s = new MemoryStream(bytes); AbstractRecord r = ProtoSerializer.Deserialize(t, s); localCache.PutLocal(key, r); return r; } public object GetObject (string key) { //log.DebugFormat("key '{0}' in local cache? " + localCache.ContainsKey(key), key ); key = LocalCache.PrepareKey(key); StopWatch watch = new StopWatch("RedisCacheClient.Get", this.GetType().Name); watch.Start(); object o = null; try { //log.Debug("GetObject key ", key); byte[] bytes = null; using (IRedisClient rc = hashCachePool.GetReadClient(key)) { bytes = rc.Get<byte[]>(key); } if (null != bytes && bytes.Length > 0) { MemoryStream s = new MemoryStream(bytes); BinaryFormatter bf = new BinaryFormatter(); o = bf.Deserialize(s); } } catch (System.NullReferenceException) { return null; } catch (System.Runtime.Serialization.SerializationException) { return null; } catch (Exception ex) { log.ErrorFormat("GetObject error. key={0}. Exception={1}", key, ex); } finally { watch.Stop(); } //log.Debug("Getting key", key, o ); return o; } public string GetString(string key) { key = LocalCache.PrepareKey(key); string o = null; try { //log.Debug("GetString key ", key); using (IRedisClient rc = hashCachePool.GetReadClient(key)) { o = rc.Get<string>(key); } } catch (Exception ex) { log.ErrorFormat("GetString error. key={0}. Exception={1}", key, ex); } return o; } public object[] GetList(params string[] keys) { StopWatch watch = new StopWatch("RedisCacheClient.GetList", this.GetType().Name); watch.Start(); List<object> listObjects = new List<object>(); for (int i = 0; i < keys.Length; i++) { //keys[i] = prepareKey(keys[i]); listObjects.Add(GetObject(keys[i])); } return listObjects.ToArray(); #if false // (Don Mar.13,2011) How can we re-write this function to take advantage of the RedisClient.GetByIds() functionality // while still preserving usage of hashed pool? Perhaps we segregate the keys by hash client cluster, // make the calls, then rejoin the results? Is that cheaper then calling GetObject() over and over? // probably. However, no one is calling this function currently; it's just here because it's a member // of ICacheProvider. Talk to Ben, and see if we can remove this member. try { IList<object> values = null; using (IRedisClient rc = redisPool.GetClient()) { values = rc.GetByIds<object>(keys); } watch.Stop(); return values != null ? values.ToArray() : null; } catch (Exception ex) { log.Error("GetList error.", ex); return null; } #endif } public void Remove(string originalKey) { var key = LocalCache.PrepareKey(originalKey); StopWatch watch = new StopWatch("RedisCacheClient.Remove", this.GetType().Name); watch.Start(); try { using (IRedisClient rc = hashCachePool.GetWriteClient(key)) { rc.Remove(key); } } catch (Exception ex) { log.ErrorFormat("Remove error. key={0}. Exception={1}", key, ex); return; } //now send out the expiration notice SetExpirationEvent(originalKey); //done. watch.Stop(); } private List<string> localKeys = new List<string> (); private object localKeyLock = new object (); private void SetExpirationEvent (string key) { try { //log.Debug("SetExpirationEvent for key: " + key); using (IRedisClient rc = hashCachePool.GetWriteClient("EXPIRE_KEY")) { lock (localKeyLock) { localKeys.Add (key); } rc.PublishMessage ("EXPIRE_KEY", key); } } catch (Exception ex) { log.ErrorFormat("SetExpirationEvent error. key={0}. Exception={1}", key, ex); } } public void Remove(AbstractRecord record) { log.Debug ("Removing ", record); localCache.Remove(record.Definition); if (! (record is ICacheLocalOnly)) RemoveRemote (record); } private void RemoveRemote (AbstractRecord record) { try { String key = record.CreateStandardCacheKey(); using (IRedisClient rc = hashCachePool.GetWriteClient(key)) { rc.Remove(key); } } catch (Exception ex) { log.ErrorFormat("Remove error. key={0}. Exception={1}", record.CreateStandardCacheKey(), ex); } record.InvalidateCache(); SetExpirationEvent(record.Definition.ToString()); } //This function needs to ensure that no stale references to the record exist anywhere in the cache service. public void Update (AbstractRecord record) { var oldrec = localCache.GetLocalRecord (record.Definition); var equals = object.ReferenceEquals (record, oldrec); //log.Debug ("Updating ", record, oldrec, equals); //when updating, if the copy in the local cache is ref equal to the current record being udpated, do not remove it, or mark it as stale. if (! equals) { localCache.Remove(record.Definition); localCache.PutLocal (record.CreateStandardCacheKey (), record); } if (! (record is ICacheLocalOnly)) RemoveRemote (record); } public void FlushAll() { try { //TODO: need to send flush event out through system. localCache.Flush(); hashCachePool.FlushAll(); } catch (Exception ex) { log.ErrorFormat("FlushAll error. Exception={0}", ex); } } #endregion public RedisCacheClient() { Initialize(true); } public RedisCacheClient(bool startExpirationThread) { Initialize(startExpirationThread); } static RedisCacheClient() { String redisConfig = ConfigurationManager.AppSettings["RedisConfig"]; if (String.IsNullOrEmpty(redisConfig)) throw new Exception("no RedisConfig key in App.Config, cannot continue"); log.InfoFormat("INITIALIZING CACHE CLIENT: Configuring HashedPoolManager from config at {0} ", redisConfig); hashCachePool.Configure(new HashCachePoolConfiguration(redisConfig)); } public void Initialize(bool startExpirationThread) { //log.DebugFormat("RedisCacheClient ctor called with startExpirationThread = {0}", startExpirationThread ? "true" : "false"); try { if (startExpirationThread) { log.Info("Starting background thread to check for Cache Expiration Events"); ThreadStart job = new ThreadStart(CheckForExpirationEvents); Thread thread = new Thread(job); thread.Start(); } } catch (Exception e) { log.Error("RedisCacheClient Initialize:", e); } } /// <summary> /// Try to use redis' pub/sub feature for this. /// </summary> void CheckForExpirationEvents() { try { var rc = hashCachePool.GetWriteClient("EXPIRE_KEY"); var subscription = rc.CreateSubscription (); subscription.OnMessage += (channel, message) => { switch (channel) { case "EXPIRE_KEY": bool keyIsNotLocal = true; lock (localKeyLock) { if (localKeys.Contains (message)) { localKeys.Remove (message); keyIsNotLocal = false; } } if (keyIsNotLocal) localCache.ClearFromLocalCache(message); break; } }; subscription.SubscribeToChannels ("EXPIRE_KEY"); } catch (Exception e) { log.Error ("Error checking for expiration events.", e); } } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Gallio.Common.Collections; using Gallio.Runtime.Extensibility; using Gallio.Runtime.FileTypes; using MbUnit.Framework; using Rhino.Mocks; namespace Gallio.Tests.Runtime.FileTypes { [TestsOn(typeof(FileTypeManager))] public class FileTypeManagerTest { [Test] public void Constructor_WhenHandlesArrayIsNull_Throws() { Assert.Throws<ArgumentNullException>(() => new FileTypeManager(null)); } [Test] public void Constructor_WhenHandlesArrayContainsNull_Throws() { Assert.Throws<ArgumentNullException>(() => new FileTypeManager( new ComponentHandle<IFileTypeRecognizer, FileTypeRecognizerTraits>[] { null })); } [Test] public void Constructor_WhenHandlesArrayContainsDoublyDefinedType_Throws() { var handles = CreateRecognizerHandles( new RecognizerInfo { Traits = new FileTypeRecognizerTraits("TypeA", "A") }, new RecognizerInfo { Traits = new FileTypeRecognizerTraits("TypeA", "Duplicate") }); var ex = Assert.Throws<InvalidOperationException>(() => new FileTypeManager(handles)); Assert.AreEqual("There appear to be multiple file types registered with id 'TypeA'.", ex.Message); } [Test] public void Constructor_WhenHandlesArrayContainsReferenceToUnknownSuperType_Throws() { var handles = CreateRecognizerHandles( new RecognizerInfo { Traits = new FileTypeRecognizerTraits("TypeA", "A") { SuperTypeId = "TypeB" } }); var ex = Assert.Throws<InvalidOperationException>(() => new FileTypeManager(handles)); Assert.AreEqual("File type 'TypeA' refers to super type 'TypeB' but the super type is not registered.", ex.Message); } [Test] public void Constructor_WhenHandlesArrayContainsCircularReferenceToSuperType_Throws() { var handles = CreateRecognizerHandles( new RecognizerInfo { Traits = new FileTypeRecognizerTraits("TypeA", "A") { SuperTypeId = "TypeB" } }, new RecognizerInfo { Traits = new FileTypeRecognizerTraits("TypeB", "B") { SuperTypeId = "TypeA" } }); var ex = Assert.Throws<InvalidOperationException>(() => new FileTypeManager(handles)); Assert.AreEqual("File type 'TypeB' contains a circular reference to super type 'TypeA'.", ex.Message); } [Test] public void UnknownFileType_ReturnsAFileTypeCalledUnknown() { var handles = CreateRecognizerHandles(); var fileTypeManager = new FileTypeManager(handles); FileType fileType = fileTypeManager.UnknownFileType; Assert.Multiple(() => { Assert.AreEqual("Unknown", fileType.Id); Assert.AreEqual("File of unknown type.", fileType.Description); Assert.IsNull(fileType.SuperType); }); } [Test] public void GetFileTypeById_WhenIdIsNull_Throws() { var handles = CreateRecognizerHandles(); var fileTypeManager = new FileTypeManager(handles); Assert.Throws<ArgumentNullException>(() => fileTypeManager.GetFileTypeById(null)); } [Test] public void GetFileTypeById_WhenIdIsTheUnknownFileTypeId_ReturnsUnknownFileType() { var handles = CreateRecognizerHandles(); var fileTypeManager = new FileTypeManager(handles); FileType fileType = fileTypeManager.GetFileTypeById("Unknown"); Assert.AreSame(fileTypeManager.UnknownFileType, fileType); } [Test] public void GetFileTypeById_WhenIdIsKnown_ReturnsFileType() { var handles = CreateRecognizerHandles( new RecognizerInfo { Traits = new FileTypeRecognizerTraits("Type", "A file type.") }); var fileTypeManager = new FileTypeManager(handles); FileType fileType = fileTypeManager.GetFileTypeById("Type"); Assert.AreEqual("Type", fileType.Id); Assert.AreEqual("A file type.", fileType.Description); } [Test] public void GetFileTypeById_WhenIdIsNotKnown_ReturnsNull() { var handles = CreateRecognizerHandles(); var fileTypeManager = new FileTypeManager(handles); Assert.IsNull(fileTypeManager.GetFileTypeById("Type")); } [Test] public void GetFileTypes_ReturnsListOfAllFileTypesIncludingUnknown() { var handles = CreateRecognizerHandles( new RecognizerInfo { Traits = new FileTypeRecognizerTraits("TypeA", "A") }, new RecognizerInfo { Traits = new FileTypeRecognizerTraits("TypeB", "B") { SuperTypeId = "TypeC" } }, new RecognizerInfo { Traits = new FileTypeRecognizerTraits("TypeC", "C") { SuperTypeId = "TypeD" } }, new RecognizerInfo { Traits = new FileTypeRecognizerTraits("TypeD", "D") }); var fileTypeManager = new FileTypeManager(handles); var expectedFileTypes = new FileType[5]; expectedFileTypes[0] = new FileType("TypeA", "A", null); expectedFileTypes[3] = new FileType("TypeD", "D", null); expectedFileTypes[2] = new FileType("TypeC", "C", expectedFileTypes[3]); expectedFileTypes[1] = new FileType("TypeB", "B", expectedFileTypes[2]); expectedFileTypes[4] = fileTypeManager.UnknownFileType; IList<FileType> actualFileTypes = fileTypeManager.GetFileTypes(); Assert.Over.KeyedPairs( expectedFileTypes.ToDictionary(x => x.Id), actualFileTypes.ToDictionary(x => x.Id), (x, y) => AssertEx.That(() => AreEquivalent(x, y))); } [Test] public void IdentifyFileType_FileInfo_WhenFileInfoIsNull_Throws() { var handles = CreateRecognizerHandles(); var fileTypeManager = new FileTypeManager(handles); Assert.Throws<ArgumentNullException>(() => fileTypeManager.IdentifyFileType((FileInfo)null)); } [Test] public void IdentifyFileType_FileInspector_WhenFileInspectorIsNull_Throws() { var handles = CreateRecognizerHandles(); var fileTypeManager = new FileTypeManager(handles); Assert.Throws<ArgumentNullException>(() => fileTypeManager.IdentifyFileType((IFileInspector)null)); } [Test] public void IdentifyFileType_FileInfoWithCandidates_WhenFileInfoIsNull_Throws() { var handles = CreateRecognizerHandles(); var fileTypeManager = new FileTypeManager(handles); Assert.Throws<ArgumentNullException>(() => fileTypeManager.IdentifyFileType((FileInfo)null, new FileType[0])); } [Test] public void IdentifyFileType_FileInspectorWithCandidates_WhenFileInspectorIsNull_Throws() { var handles = CreateRecognizerHandles(); var fileTypeManager = new FileTypeManager(handles); Assert.Throws<ArgumentNullException>(() => fileTypeManager.IdentifyFileType((IFileInspector)null, new FileType[0])); } [Test] public void IdentifyFileType_FileInfoWithCandidates_WhenCandidatesIsNull_Throws() { var handles = CreateRecognizerHandles(); var fileTypeManager = new FileTypeManager(handles); Assert.Throws<ArgumentNullException>(() => fileTypeManager.IdentifyFileType(new FileInfo(@"C:\"), null)); } [Test] public void IdentifyFileType_FileInspectorWithCandidates_WhenCandidatesIsNull_Throws() { var handles = CreateRecognizerHandles(); var fileTypeManager = new FileTypeManager(handles); Assert.Throws<ArgumentNullException>(() => fileTypeManager.IdentifyFileType(MockRepository.GenerateStub<IFileInspector>(), null)); } [Test] [Row(null, null, true, true, Description = "No filename regex, no contents regex, recognizer returns true.")] [Row(null, null, false, false, Description = "No filename regex, no contents regex, recognizer returns false.")] [Row(".*.txt", null, true, true, Description = "Matched filename regex, no contents regex, recognizer returns true.")] [Row(".*.txt", null, false, false, Description = "Matched filename regex, no contents regex, recognizer returns false.")] [Row(".*.TxT", null, true, true, Description = "Matched filename regex (case-insensitive), no contents regex, recognizer returns true.")] [Row(".*.TxT", null, false, false, Description = "Matched filename regex (case-insensitive), no contents regex, recognizer returns false.")] [Row(".*.dll", null, true, false, Description = "Unmatched filename regex, no contents regex, recognizer returns true.")] [Row(".*.dll", null, false, false, Description = "Unmatched filename regex, no contents regex, recognizer returns false.")] [Row(null, "contents", true, true, Description = "No filename regex, matched contents regex, recognizer returns true.")] [Row(null, "contents", false, false, Description = "No filename regex, matched contents regex, recognizer returns false.")] [Row(null, "ConTents", true, true, Description = "No filename regex (case-insensitive), matched contents regex, recognizer returns true.")] [Row(null, "ConTents", false, false, Description = "No filename regex (case-insensitive), matched contents regex, recognizer returns false.")] [Row(null, "different", true, false, Description = "No filename regex, unmatched contents regex, recognizer returns true.")] [Row(null, "different", false, false, Description = "No filename regex, unmatched contents regex, recognizer returns false.")] public void IdentifyFileType_FileInspector_WhenMatchCriteriaAreVaried_ReturnsTypeIfMatchedOrUnknownOtherwise(string fileNameRegex, string contentsRegex, bool recognizerResult, bool expectedMatch) { var inspector = new FakeFileInspector() { FileInfo = new FileInfo(@"C:\file.txt"), Contents = "contents" }; var recognizer = MockRepository.GenerateStub<IFileTypeRecognizer>(); recognizer.Stub(x => x.IsRecognizedFile(inspector)).Return(recognizerResult); var handles = CreateRecognizerHandles( new RecognizerInfo { Traits = new FileTypeRecognizerTraits("TypeA", "A") { FileNameRegex = fileNameRegex, ContentsRegex = contentsRegex }, Recognizer = recognizer }); var fileTypeManager = new FileTypeManager(handles); FileType fileType = fileTypeManager.IdentifyFileType(inspector); Assert.AreEqual(expectedMatch ? "TypeA" : "Unknown", fileType.Id); } [Test] [Row(true, true, false)] [Row(true, false, false)] [Row(false, true, true)] [Row(false, false, false)] public void IdentifyFileType_FileInspector_WhenFileInfoNotAvailable_ReturnsTypeOnlyIfNoFilenameCriteriaAndRecognizerMatches( bool filenameCriteria, bool recognizerResult, bool expectedMatch) { var inspector = new FakeFileInspector(); var recognizer = MockRepository.GenerateStub<IFileTypeRecognizer>(); recognizer.Stub(x => x.IsRecognizedFile(inspector)).Return(recognizerResult); var handles = CreateRecognizerHandles( new RecognizerInfo { Traits = new FileTypeRecognizerTraits("TypeA", "A") { FileNameRegex = filenameCriteria ? ".*" : null }, Recognizer = recognizer }); var fileTypeManager = new FileTypeManager(handles); FileType fileType = fileTypeManager.IdentifyFileType(inspector); Assert.AreEqual(expectedMatch ? "TypeA" : "Unknown", fileType.Id); } [Test] [Row(true, true, false)] [Row(true, false, false)] [Row(false, true, true)] [Row(false, false, false)] public void IdentifyFileType_FileInspector_WhenContentsNotAvailable_ReturnsTypeOnlyIfNoContentCriteriaAndRecognizerMatches( bool contentCriteria, bool recognizerResult, bool expectedMatch) { var inspector = new FakeFileInspector(); var recognizer = MockRepository.GenerateStub<IFileTypeRecognizer>(); recognizer.Stub(x => x.IsRecognizedFile(inspector)).Return(recognizerResult); var handles = CreateRecognizerHandles( new RecognizerInfo { Traits = new FileTypeRecognizerTraits("TypeA", "A") { ContentsRegex = contentCriteria ? ".*" : null }, Recognizer = recognizer }); var fileTypeManager = new FileTypeManager(handles); FileType fileType = fileTypeManager.IdentifyFileType(inspector); Assert.AreEqual(expectedMatch ? "TypeA" : "Unknown", fileType.Id); } [Test] [Row(true, true, true, true, "SubType", Description = "Supertype included, subtype included, supertype matched, subtype matched, should match subtype.")] [Row(true, true, true, false, "SuperType", Description = "Supertype included, subtype included, supertype matched, subtype unmatched, should match supertype.")] [Row(true, true, false, true, "Unknown", Description = "Supertype included, subtype included, supertype unmatched, subtype matched, should match unknown.")] [Row(false, true, true, true, "SubType", Description = "Supertype excluded, subtype included, supertype matched, subtype matched, should match subtype.")] [Row(true, false, true, true, "SuperType", Description = "Supertype included, subtype excluded, supertype matched, subtype matched, should match supertype.")] [Row(false, true, true, false, "Unknown", Description = "Supertype excluded, subtype included, supertype matched, subtype unmatched, should match unknown.")] [Row(false, false, true, true, "Unknown", Description = "Supertype excluded, subtype excluded, supertype matched, subtype matched, should match unknown.")] public void IdentifyFileType_FileInspectorWithCandidates_WhenMatchCriteriaAndCandidatesAreVaried_ReturnsTypeIfMatchedOrUnknownOtherwise( bool includeSupertypeAsCandidate, bool includeSubtypeAsCandidate, bool superRecognizerResult, bool subRecognizerResult, string expectedMatchType) { var inspector = new FakeFileInspector() { FileInfo = new FileInfo(@"C:\file.txt"), Contents = "contents" }; var superRecognizer = MockRepository.GenerateStub<IFileTypeRecognizer>(); superRecognizer.Stub(x => x.IsRecognizedFile(inspector)).Return(superRecognizerResult); var subRecognizer = MockRepository.GenerateStub<IFileTypeRecognizer>(); subRecognizer.Stub(x => x.IsRecognizedFile(inspector)).Return(subRecognizerResult); var handles = CreateRecognizerHandles( new RecognizerInfo { Traits = new FileTypeRecognizerTraits("SuperType", "Super"), Recognizer = superRecognizer }, new RecognizerInfo { Traits = new FileTypeRecognizerTraits("SubType", "Sub") { SuperTypeId = "SuperType" }, Recognizer = subRecognizer }); var fileTypeManager = new FileTypeManager(handles); var candidates = new List<FileType>(); if (includeSupertypeAsCandidate) candidates.Add(fileTypeManager.GetFileTypeById("SuperType")); if (includeSubtypeAsCandidate) candidates.Add(fileTypeManager.GetFileTypeById("SubType")); FileType fileType = fileTypeManager.IdentifyFileType(inspector, candidates); Assert.AreEqual(expectedMatchType, fileType.Id); } private static bool AreEquivalent(FileType left, FileType right) { if (left == null && right == null) return true; if (left == null || right == null) return false; return left.Id == right.Id && left.Description == right.Description && AreEquivalent(left.SuperType, right.SuperType); } private sealed class RecognizerInfo { public IFileTypeRecognizer Recognizer; public FileTypeRecognizerTraits Traits; } private static ComponentHandle<IFileTypeRecognizer, FileTypeRecognizerTraits>[] CreateRecognizerHandles( params RecognizerInfo[] recognizerInfos) { return GenericCollectionUtils.ConvertAllToArray(recognizerInfos, recognizerInfo => ComponentHandle.CreateStub("component", recognizerInfo.Recognizer ?? MockRepository.GenerateStub<IFileTypeRecognizer>(), recognizerInfo.Traits ?? new FileTypeRecognizerTraits("Dummy", "Dummy"))); } private class FakeFileInspector : IFileInspector { public FileInfo FileInfo { get; set; } public Stream Stream { get; set; } public string Contents { get; set; } public bool TryGetFileInfo(out FileInfo fileInfo) { fileInfo = FileInfo; return fileInfo != null; } public bool TryGetContents(out string contents) { contents = Contents; return contents != null; } public bool TryGetStream(out Stream stream) { stream = Stream; return stream != null; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos.Settings.Master.Pokemon.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Settings.Master.Pokemon { /// <summary>Holder for reflection information generated from POGOProtos.Settings.Master.Pokemon.proto</summary> public static partial class POGOProtosSettingsMasterPokemonReflection { #region Descriptor /// <summary>File descriptor for POGOProtos.Settings.Master.Pokemon.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static POGOProtosSettingsMasterPokemonReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CihQT0dPUHJvdG9zLlNldHRpbmdzLk1hc3Rlci5Qb2tlbW9uLnByb3RvEiJQ", "T0dPUHJvdG9zLlNldHRpbmdzLk1hc3Rlci5Qb2tlbW9uGhZQT0dPUHJvdG9z", "LkVudW1zLnByb3RvIpcBChBDYW1lcmFBdHRyaWJ1dGVzEhUKDWRpc2tfcmFk", "aXVzX20YASABKAISGQoRY3lsaW5kZXJfcmFkaXVzX20YAiABKAISGQoRY3ls", "aW5kZXJfaGVpZ2h0X20YAyABKAISGQoRY3lsaW5kZXJfZ3JvdW5kX20YBCAB", "KAISGwoTc2hvdWxkZXJfbW9kZV9zY2FsZRgFIAEoAiKmAgoTRW5jb3VudGVy", "QXR0cmlidXRlcxIZChFiYXNlX2NhcHR1cmVfcmF0ZRgBIAEoAhIWCg5iYXNl", "X2ZsZWVfcmF0ZRgCIAEoAhIaChJjb2xsaXNpb25fcmFkaXVzX20YAyABKAIS", "GgoSY29sbGlzaW9uX2hlaWdodF9tGAQgASgCEh8KF2NvbGxpc2lvbl9oZWFk", "X3JhZGl1c19tGAUgASgCEjwKDW1vdmVtZW50X3R5cGUYBiABKA4yJS5QT0dP", "UHJvdG9zLkVudW1zLlBva2Vtb25Nb3ZlbWVudFR5cGUSGAoQbW92ZW1lbnRf", "dGltZXJfcxgHIAEoAhITCgtqdW1wX3RpbWVfcxgIIAEoAhIWCg5hdHRhY2tf", "dGltZXJfcxgJIAEoAiJuCg9TdGF0c0F0dHJpYnV0ZXMSFAoMYmFzZV9zdGFt", "aW5hGAEgASgFEhMKC2Jhc2VfYXR0YWNrGAIgASgFEhQKDGJhc2VfZGVmZW5z", "ZRgDIAEoBRIaChJkb2RnZV9lbmVyZ3lfZGVsdGEYCCABKAVQAGIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Enums.POGOProtosEnumsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.Master.Pokemon.CameraAttributes), global::POGOProtos.Settings.Master.Pokemon.CameraAttributes.Parser, new[]{ "DiskRadiusM", "CylinderRadiusM", "CylinderHeightM", "CylinderGroundM", "ShoulderModeScale" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.Master.Pokemon.EncounterAttributes), global::POGOProtos.Settings.Master.Pokemon.EncounterAttributes.Parser, new[]{ "BaseCaptureRate", "BaseFleeRate", "CollisionRadiusM", "CollisionHeightM", "CollisionHeadRadiusM", "MovementType", "MovementTimerS", "JumpTimeS", "AttackTimerS" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.Master.Pokemon.StatsAttributes), global::POGOProtos.Settings.Master.Pokemon.StatsAttributes.Parser, new[]{ "BaseStamina", "BaseAttack", "BaseDefense", "DodgeEnergyDelta" }, null, null, null) })); } #endregion } #region Messages public sealed partial class CameraAttributes : pb::IMessage<CameraAttributes> { private static readonly pb::MessageParser<CameraAttributes> _parser = new pb::MessageParser<CameraAttributes>(() => new CameraAttributes()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CameraAttributes> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Settings.Master.Pokemon.POGOProtosSettingsMasterPokemonReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CameraAttributes() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CameraAttributes(CameraAttributes other) : this() { diskRadiusM_ = other.diskRadiusM_; cylinderRadiusM_ = other.cylinderRadiusM_; cylinderHeightM_ = other.cylinderHeightM_; cylinderGroundM_ = other.cylinderGroundM_; shoulderModeScale_ = other.shoulderModeScale_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CameraAttributes Clone() { return new CameraAttributes(this); } /// <summary>Field number for the "disk_radius_m" field.</summary> public const int DiskRadiusMFieldNumber = 1; private float diskRadiusM_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float DiskRadiusM { get { return diskRadiusM_; } set { diskRadiusM_ = value; } } /// <summary>Field number for the "cylinder_radius_m" field.</summary> public const int CylinderRadiusMFieldNumber = 2; private float cylinderRadiusM_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float CylinderRadiusM { get { return cylinderRadiusM_; } set { cylinderRadiusM_ = value; } } /// <summary>Field number for the "cylinder_height_m" field.</summary> public const int CylinderHeightMFieldNumber = 3; private float cylinderHeightM_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float CylinderHeightM { get { return cylinderHeightM_; } set { cylinderHeightM_ = value; } } /// <summary>Field number for the "cylinder_ground_m" field.</summary> public const int CylinderGroundMFieldNumber = 4; private float cylinderGroundM_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float CylinderGroundM { get { return cylinderGroundM_; } set { cylinderGroundM_ = value; } } /// <summary>Field number for the "shoulder_mode_scale" field.</summary> public const int ShoulderModeScaleFieldNumber = 5; private float shoulderModeScale_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float ShoulderModeScale { get { return shoulderModeScale_; } set { shoulderModeScale_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CameraAttributes); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CameraAttributes other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (DiskRadiusM != other.DiskRadiusM) return false; if (CylinderRadiusM != other.CylinderRadiusM) return false; if (CylinderHeightM != other.CylinderHeightM) return false; if (CylinderGroundM != other.CylinderGroundM) return false; if (ShoulderModeScale != other.ShoulderModeScale) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (DiskRadiusM != 0F) hash ^= DiskRadiusM.GetHashCode(); if (CylinderRadiusM != 0F) hash ^= CylinderRadiusM.GetHashCode(); if (CylinderHeightM != 0F) hash ^= CylinderHeightM.GetHashCode(); if (CylinderGroundM != 0F) hash ^= CylinderGroundM.GetHashCode(); if (ShoulderModeScale != 0F) hash ^= ShoulderModeScale.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (DiskRadiusM != 0F) { output.WriteRawTag(13); output.WriteFloat(DiskRadiusM); } if (CylinderRadiusM != 0F) { output.WriteRawTag(21); output.WriteFloat(CylinderRadiusM); } if (CylinderHeightM != 0F) { output.WriteRawTag(29); output.WriteFloat(CylinderHeightM); } if (CylinderGroundM != 0F) { output.WriteRawTag(37); output.WriteFloat(CylinderGroundM); } if (ShoulderModeScale != 0F) { output.WriteRawTag(45); output.WriteFloat(ShoulderModeScale); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (DiskRadiusM != 0F) { size += 1 + 4; } if (CylinderRadiusM != 0F) { size += 1 + 4; } if (CylinderHeightM != 0F) { size += 1 + 4; } if (CylinderGroundM != 0F) { size += 1 + 4; } if (ShoulderModeScale != 0F) { size += 1 + 4; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CameraAttributes other) { if (other == null) { return; } if (other.DiskRadiusM != 0F) { DiskRadiusM = other.DiskRadiusM; } if (other.CylinderRadiusM != 0F) { CylinderRadiusM = other.CylinderRadiusM; } if (other.CylinderHeightM != 0F) { CylinderHeightM = other.CylinderHeightM; } if (other.CylinderGroundM != 0F) { CylinderGroundM = other.CylinderGroundM; } if (other.ShoulderModeScale != 0F) { ShoulderModeScale = other.ShoulderModeScale; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 13: { DiskRadiusM = input.ReadFloat(); break; } case 21: { CylinderRadiusM = input.ReadFloat(); break; } case 29: { CylinderHeightM = input.ReadFloat(); break; } case 37: { CylinderGroundM = input.ReadFloat(); break; } case 45: { ShoulderModeScale = input.ReadFloat(); break; } } } } } public sealed partial class EncounterAttributes : pb::IMessage<EncounterAttributes> { private static readonly pb::MessageParser<EncounterAttributes> _parser = new pb::MessageParser<EncounterAttributes>(() => new EncounterAttributes()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<EncounterAttributes> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Settings.Master.Pokemon.POGOProtosSettingsMasterPokemonReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EncounterAttributes() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EncounterAttributes(EncounterAttributes other) : this() { baseCaptureRate_ = other.baseCaptureRate_; baseFleeRate_ = other.baseFleeRate_; collisionRadiusM_ = other.collisionRadiusM_; collisionHeightM_ = other.collisionHeightM_; collisionHeadRadiusM_ = other.collisionHeadRadiusM_; movementType_ = other.movementType_; movementTimerS_ = other.movementTimerS_; jumpTimeS_ = other.jumpTimeS_; attackTimerS_ = other.attackTimerS_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EncounterAttributes Clone() { return new EncounterAttributes(this); } /// <summary>Field number for the "base_capture_rate" field.</summary> public const int BaseCaptureRateFieldNumber = 1; private float baseCaptureRate_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float BaseCaptureRate { get { return baseCaptureRate_; } set { baseCaptureRate_ = value; } } /// <summary>Field number for the "base_flee_rate" field.</summary> public const int BaseFleeRateFieldNumber = 2; private float baseFleeRate_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float BaseFleeRate { get { return baseFleeRate_; } set { baseFleeRate_ = value; } } /// <summary>Field number for the "collision_radius_m" field.</summary> public const int CollisionRadiusMFieldNumber = 3; private float collisionRadiusM_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float CollisionRadiusM { get { return collisionRadiusM_; } set { collisionRadiusM_ = value; } } /// <summary>Field number for the "collision_height_m" field.</summary> public const int CollisionHeightMFieldNumber = 4; private float collisionHeightM_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float CollisionHeightM { get { return collisionHeightM_; } set { collisionHeightM_ = value; } } /// <summary>Field number for the "collision_head_radius_m" field.</summary> public const int CollisionHeadRadiusMFieldNumber = 5; private float collisionHeadRadiusM_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float CollisionHeadRadiusM { get { return collisionHeadRadiusM_; } set { collisionHeadRadiusM_ = value; } } /// <summary>Field number for the "movement_type" field.</summary> public const int MovementTypeFieldNumber = 6; private global::POGOProtos.Enums.PokemonMovementType movementType_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Enums.PokemonMovementType MovementType { get { return movementType_; } set { movementType_ = value; } } /// <summary>Field number for the "movement_timer_s" field.</summary> public const int MovementTimerSFieldNumber = 7; private float movementTimerS_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float MovementTimerS { get { return movementTimerS_; } set { movementTimerS_ = value; } } /// <summary>Field number for the "jump_time_s" field.</summary> public const int JumpTimeSFieldNumber = 8; private float jumpTimeS_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float JumpTimeS { get { return jumpTimeS_; } set { jumpTimeS_ = value; } } /// <summary>Field number for the "attack_timer_s" field.</summary> public const int AttackTimerSFieldNumber = 9; private float attackTimerS_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float AttackTimerS { get { return attackTimerS_; } set { attackTimerS_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as EncounterAttributes); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(EncounterAttributes other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (BaseCaptureRate != other.BaseCaptureRate) return false; if (BaseFleeRate != other.BaseFleeRate) return false; if (CollisionRadiusM != other.CollisionRadiusM) return false; if (CollisionHeightM != other.CollisionHeightM) return false; if (CollisionHeadRadiusM != other.CollisionHeadRadiusM) return false; if (MovementType != other.MovementType) return false; if (MovementTimerS != other.MovementTimerS) return false; if (JumpTimeS != other.JumpTimeS) return false; if (AttackTimerS != other.AttackTimerS) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (BaseCaptureRate != 0F) hash ^= BaseCaptureRate.GetHashCode(); if (BaseFleeRate != 0F) hash ^= BaseFleeRate.GetHashCode(); if (CollisionRadiusM != 0F) hash ^= CollisionRadiusM.GetHashCode(); if (CollisionHeightM != 0F) hash ^= CollisionHeightM.GetHashCode(); if (CollisionHeadRadiusM != 0F) hash ^= CollisionHeadRadiusM.GetHashCode(); if (MovementType != 0) hash ^= MovementType.GetHashCode(); if (MovementTimerS != 0F) hash ^= MovementTimerS.GetHashCode(); if (JumpTimeS != 0F) hash ^= JumpTimeS.GetHashCode(); if (AttackTimerS != 0F) hash ^= AttackTimerS.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (BaseCaptureRate != 0F) { output.WriteRawTag(13); output.WriteFloat(BaseCaptureRate); } if (BaseFleeRate != 0F) { output.WriteRawTag(21); output.WriteFloat(BaseFleeRate); } if (CollisionRadiusM != 0F) { output.WriteRawTag(29); output.WriteFloat(CollisionRadiusM); } if (CollisionHeightM != 0F) { output.WriteRawTag(37); output.WriteFloat(CollisionHeightM); } if (CollisionHeadRadiusM != 0F) { output.WriteRawTag(45); output.WriteFloat(CollisionHeadRadiusM); } if (MovementType != 0) { output.WriteRawTag(48); output.WriteEnum((int) MovementType); } if (MovementTimerS != 0F) { output.WriteRawTag(61); output.WriteFloat(MovementTimerS); } if (JumpTimeS != 0F) { output.WriteRawTag(69); output.WriteFloat(JumpTimeS); } if (AttackTimerS != 0F) { output.WriteRawTag(77); output.WriteFloat(AttackTimerS); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (BaseCaptureRate != 0F) { size += 1 + 4; } if (BaseFleeRate != 0F) { size += 1 + 4; } if (CollisionRadiusM != 0F) { size += 1 + 4; } if (CollisionHeightM != 0F) { size += 1 + 4; } if (CollisionHeadRadiusM != 0F) { size += 1 + 4; } if (MovementType != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) MovementType); } if (MovementTimerS != 0F) { size += 1 + 4; } if (JumpTimeS != 0F) { size += 1 + 4; } if (AttackTimerS != 0F) { size += 1 + 4; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(EncounterAttributes other) { if (other == null) { return; } if (other.BaseCaptureRate != 0F) { BaseCaptureRate = other.BaseCaptureRate; } if (other.BaseFleeRate != 0F) { BaseFleeRate = other.BaseFleeRate; } if (other.CollisionRadiusM != 0F) { CollisionRadiusM = other.CollisionRadiusM; } if (other.CollisionHeightM != 0F) { CollisionHeightM = other.CollisionHeightM; } if (other.CollisionHeadRadiusM != 0F) { CollisionHeadRadiusM = other.CollisionHeadRadiusM; } if (other.MovementType != 0) { MovementType = other.MovementType; } if (other.MovementTimerS != 0F) { MovementTimerS = other.MovementTimerS; } if (other.JumpTimeS != 0F) { JumpTimeS = other.JumpTimeS; } if (other.AttackTimerS != 0F) { AttackTimerS = other.AttackTimerS; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 13: { BaseCaptureRate = input.ReadFloat(); break; } case 21: { BaseFleeRate = input.ReadFloat(); break; } case 29: { CollisionRadiusM = input.ReadFloat(); break; } case 37: { CollisionHeightM = input.ReadFloat(); break; } case 45: { CollisionHeadRadiusM = input.ReadFloat(); break; } case 48: { movementType_ = (global::POGOProtos.Enums.PokemonMovementType) input.ReadEnum(); break; } case 61: { MovementTimerS = input.ReadFloat(); break; } case 69: { JumpTimeS = input.ReadFloat(); break; } case 77: { AttackTimerS = input.ReadFloat(); break; } } } } } public sealed partial class StatsAttributes : pb::IMessage<StatsAttributes> { private static readonly pb::MessageParser<StatsAttributes> _parser = new pb::MessageParser<StatsAttributes>(() => new StatsAttributes()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<StatsAttributes> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Settings.Master.Pokemon.POGOProtosSettingsMasterPokemonReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public StatsAttributes() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public StatsAttributes(StatsAttributes other) : this() { baseStamina_ = other.baseStamina_; baseAttack_ = other.baseAttack_; baseDefense_ = other.baseDefense_; dodgeEnergyDelta_ = other.dodgeEnergyDelta_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public StatsAttributes Clone() { return new StatsAttributes(this); } /// <summary>Field number for the "base_stamina" field.</summary> public const int BaseStaminaFieldNumber = 1; private int baseStamina_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int BaseStamina { get { return baseStamina_; } set { baseStamina_ = value; } } /// <summary>Field number for the "base_attack" field.</summary> public const int BaseAttackFieldNumber = 2; private int baseAttack_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int BaseAttack { get { return baseAttack_; } set { baseAttack_ = value; } } /// <summary>Field number for the "base_defense" field.</summary> public const int BaseDefenseFieldNumber = 3; private int baseDefense_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int BaseDefense { get { return baseDefense_; } set { baseDefense_ = value; } } /// <summary>Field number for the "dodge_energy_delta" field.</summary> public const int DodgeEnergyDeltaFieldNumber = 8; private int dodgeEnergyDelta_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int DodgeEnergyDelta { get { return dodgeEnergyDelta_; } set { dodgeEnergyDelta_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as StatsAttributes); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(StatsAttributes other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (BaseStamina != other.BaseStamina) return false; if (BaseAttack != other.BaseAttack) return false; if (BaseDefense != other.BaseDefense) return false; if (DodgeEnergyDelta != other.DodgeEnergyDelta) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (BaseStamina != 0) hash ^= BaseStamina.GetHashCode(); if (BaseAttack != 0) hash ^= BaseAttack.GetHashCode(); if (BaseDefense != 0) hash ^= BaseDefense.GetHashCode(); if (DodgeEnergyDelta != 0) hash ^= DodgeEnergyDelta.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (BaseStamina != 0) { output.WriteRawTag(8); output.WriteInt32(BaseStamina); } if (BaseAttack != 0) { output.WriteRawTag(16); output.WriteInt32(BaseAttack); } if (BaseDefense != 0) { output.WriteRawTag(24); output.WriteInt32(BaseDefense); } if (DodgeEnergyDelta != 0) { output.WriteRawTag(64); output.WriteInt32(DodgeEnergyDelta); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (BaseStamina != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(BaseStamina); } if (BaseAttack != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(BaseAttack); } if (BaseDefense != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(BaseDefense); } if (DodgeEnergyDelta != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(DodgeEnergyDelta); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(StatsAttributes other) { if (other == null) { return; } if (other.BaseStamina != 0) { BaseStamina = other.BaseStamina; } if (other.BaseAttack != 0) { BaseAttack = other.BaseAttack; } if (other.BaseDefense != 0) { BaseDefense = other.BaseDefense; } if (other.DodgeEnergyDelta != 0) { DodgeEnergyDelta = other.DodgeEnergyDelta; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { BaseStamina = input.ReadInt32(); break; } case 16: { BaseAttack = input.ReadInt32(); break; } case 24: { BaseDefense = input.ReadInt32(); break; } case 64: { DodgeEnergyDelta = input.ReadInt32(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.IO; using System.Text; using SteamKit2; namespace SteamLB { class Program { static SteamClient steamClient; static CallbackManager manager; static SteamUser steamUser; static SteamUserStats steamUserStats; static bool isRunning; static bool loggedIn; static string user, pass; static int batchSize = 10000; static void Main(string[] args) { if (args.Length < 4) { Console.WriteLine("usage: SteamLB.exe <username> <password> <appid> <leaderboardListFile>"); return; } Run(args); steamClient.Disconnect(); } static void Run(string[] args) { user = args[0]; pass = args[1]; steamClient = new SteamClient(System.Net.Sockets.ProtocolType.Tcp); manager = new CallbackManager(steamClient); steamUser = steamClient.GetHandler<SteamUser>(); steamUserStats = steamClient.GetHandler<SteamUserStats>(); manager.Subscribe<SteamClient.ConnectedCallback>(OnConnected); manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected); manager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn); manager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff); isRunning = true; Console.WriteLine("Connecting to Steam..."); loggedIn = false; SteamDirectory.Initialize().Wait(); steamClient.Connect(); while (!loggedIn) { manager.RunWaitCallbacks(TimeSpan.FromSeconds(1)); if (!isRunning) { return; } } uint appid = Convert.ToUInt32(args[2]); string lbListFile = args[3]; foreach (string lbname in File.ReadLines(lbListFile)) { if (!String.IsNullOrEmpty(lbname) && isRunning) { DownloadLeaderboard(appid, lbname); } } } static EResult DownloadLeaderboard(uint appid, string lbname) { Console.WriteLine($"Locating leaderboard {lbname} for appID {appid}..."); var findLeaderboardJob = steamUserStats.FindLeaderboard(appid, lbname); while (findLeaderboardJob.GetAwaiter().IsCompleted) { manager.RunWaitCallbacks(TimeSpan.FromSeconds(1)); if (!isRunning) { return EResult.Fail; } } var leaderboardResult = findLeaderboardJob.GetAwaiter().GetResult(); if (leaderboardResult.Result != EResult.OK) { Console.Error.WriteLine($"Failed to locate leaderboard {lbname} for appID {appid}! Error code: {leaderboardResult.Result.ToString()}"); return leaderboardResult.Result; } if (leaderboardResult.ID == 0) { Console.Error.WriteLine($"Failed to locate leaderboard {lbname} for appID {appid}! ID returned was 0"); return EResult.Fail; } var firstEntry = 1; var lastEntry = leaderboardResult.EntryCount; var downloadEntryCount = lastEntry - firstEntry + 1; Console.WriteLine($"Found leaderboard {lbname}."); Console.WriteLine($"Preparing to download {downloadEntryCount} entries..."); var outputFilename = $"{leaderboardResult.ID}.csv"; using (var outputWriter = new StreamWriter(File.Open(outputFilename, FileMode.Create))) { outputWriter.WriteLine(lbname); for (int i = 0; i < downloadEntryCount / batchSize; ++i) { DownloadLeaderboardRange(appid, leaderboardResult.ID, i * batchSize + firstEntry, firstEntry + (i + 1) * batchSize - 1, downloadEntryCount, outputWriter); } if (downloadEntryCount % batchSize != 0) { DownloadLeaderboardRange(appid, leaderboardResult.ID, (downloadEntryCount / batchSize) * batchSize + firstEntry, lastEntry, downloadEntryCount, outputWriter); } Console.WriteLine($"Done! Results for {lbname} written to {outputFilename}"); } return EResult.OK; } static EResult DownloadLeaderboardRange(uint appid, int lbid, int first, int last, int totalCount, StreamWriter outputWriter) { Console.WriteLine($"Downloading entries {first} to {last}... [{(first * 100) / totalCount}%]"); var queryLeaderboardEntriesJob = steamUserStats.GetLeaderboardEntries(appid, lbid, first, last, ELeaderboardDataRequest.Global); while (queryLeaderboardEntriesJob.GetAwaiter().IsCompleted) { manager.RunWaitCallbacks(TimeSpan.FromSeconds(1)); if (!isRunning) { return EResult.Fail; } } var result = queryLeaderboardEntriesJob.GetAwaiter().GetResult(); if (result.Result == EResult.OK) { foreach (var entry in result.Entries) { var line = new StringBuilder(); line.Append(entry.SteamID.ConvertToUInt64()); line.Append(','); line.Append(entry.GlobalRank); line.Append(','); line.Append(entry.Score); line.Append(','); line.Append(entry.UGCId.Value); foreach (var detail in entry.Details) { line.Append(','); line.Append(detail); } outputWriter.WriteLine(line); } } else { Console.Error.WriteLine($"Failed to download leaderboard section! Error code: {result.Result.ToString()}"); } return result.Result; } static void OnConnected(SteamClient.ConnectedCallback callback) { if (callback.Result != EResult.OK) { Console.WriteLine("Unable to connect to Steam: {0}", callback.Result); isRunning = false; return; } Console.WriteLine("Connected to Steam! Logging in '{0}'...", user); steamUser.LogOn(new SteamUser.LogOnDetails { Username = user, Password = pass, }); } static void OnDisconnected(SteamClient.DisconnectedCallback callback) { Console.WriteLine("Disconnected from Steam"); isRunning = false; } static void OnLoggedOn(SteamUser.LoggedOnCallback callback) { if (callback.Result != EResult.OK) { if (callback.Result == EResult.AccountLogonDenied) { Console.WriteLine("Unable to logon to Steam: This account is SteamGuard protected."); isRunning = false; return; } Console.WriteLine($"Unable to logon to Steam: {callback.Result.ToString()} / {callback.ExtendedResult}"); isRunning = false; return; } Console.WriteLine("Successfully logged on!"); loggedIn = true; } static void OnLoggedOff(SteamUser.LoggedOffCallback callback) { Console.WriteLine("Logged off of Steam: {callback.Result.ToString()}"); } } }
using System; using System.Collections.Generic; using Bridge.Html5; using Engine.Interfaces; using Direction = Engine.Interfaces.Direction; namespace Engine.Web { public class WebScreen : IScreen { public HTMLDivElement Element { get; set; } public WebScreen(WebScreenManager webScreenManager) { ScreenManager = webScreenManager; WebLayouts = new List<WebLayout>(); Element = (HTMLDivElement)Document.CreateElement("div"); } public void Destroy() { var divElement = Element; Document.Body.RemoveChild(divElement); foreach (WebLayout layout in Layouts) { var el = layout.Element; while (el.FirstChild != null) { el.RemoveChild(el.FirstChild); } } foreach (var layout in Layouts) { layout.LayoutView.Destroy(); } } public BaseLayout CreateLayout(int width, int height) { var xnaLayout = new WebLayout(this, width, height); WebLayouts.Add(xnaLayout); Element.AppendChild(xnaLayout.Element); return xnaLayout; } protected List<WebLayout> WebLayouts { get; set; } public IEnumerable<BaseLayout> Layouts { get { return WebLayouts; } } public bool OneLayoutAtATime { get; set; } public IScreenManager ScreenManager { get; set; } public WebLayout CurrentLayout { get { foreach (var xnaLayout in WebLayouts) { if (xnaLayout.Active) { return xnaLayout; } } return null; } } public void Init() { Document.Body.InsertBefore(Element, (((WebScreenManager)ScreenManager).Renderer).ClickManager); foreach (var layout in Layouts) { layout.LayoutView.InitLayoutView(); } } public void Draw(TimeSpan elapsedGameTime) { if (OneLayoutAtATime) { CurrentLayout.LayoutView.Render(elapsedGameTime); } else { foreach (var xnaLayout in WebLayouts) { xnaLayout.LayoutView.Render(elapsedGameTime); } } } public void Tick(TimeSpan elapsedGameTime) { if (OneLayoutAtATime) { CurrentLayout.LayoutView.TickLayoutView(elapsedGameTime); foreach (var xnaLayout in WebLayouts) { if (xnaLayout.AlwaysTick && CurrentLayout != xnaLayout) xnaLayout.LayoutView.TickLayoutView(elapsedGameTime); } } else { foreach (var xnaLayout in WebLayouts) { xnaLayout.LayoutView.TickLayoutView(elapsedGameTime); } } } public Size GetLayoutSize() { if (OneLayoutAtATime) { return new Size(CurrentLayout.Width, CurrentLayout.Height); } else { Size size = new Size(); foreach (var layout in Layouts) { var rectangle = layout.LayoutPosition.Location; if (size.Width < rectangle.X + rectangle.Width) { size.Width = rectangle.X + rectangle.Width; } if (size.Height < rectangle.Y + rectangle.Height) { size.Height = rectangle.Y + rectangle.Height; } } return size; } } public bool HasLayout(Direction direction) { if (OneLayoutAtATime) { switch (direction) { case Direction.Left: if (CurrentLayout.LayoutPosition.Left != null) return true; break; case Direction.Right: if (CurrentLayout.LayoutPosition.Right != null) return true; break; case Direction.Up: if (CurrentLayout.LayoutPosition.Top != null) return true; break; case Direction.Down: if (CurrentLayout.LayoutPosition.Bottom != null) return true; break; default: throw new ArgumentOutOfRangeException("direction"); } } return false; } public void ChangeLayout(Direction direction) { if (OneLayoutAtATime) { switch (direction) { case Direction.Left: if (CurrentLayout.LayoutPosition.Left != null) ChangeLayout(CurrentLayout.LayoutPosition.Left); break; case Direction.Right: if (CurrentLayout.LayoutPosition.Right != null) ChangeLayout(CurrentLayout.LayoutPosition.Right); break; case Direction.Up: if (CurrentLayout.LayoutPosition.Top != null) ChangeLayout(CurrentLayout.LayoutPosition.Top); break; case Direction.Down: if (CurrentLayout.LayoutPosition.Bottom != null) ChangeLayout(CurrentLayout.LayoutPosition.Bottom); break; default: throw new ArgumentOutOfRangeException("direction"); } } } public void ChangeLayout(BaseLayout changeTo) { changeTo.Active = true; } public void TouchEvent(TouchType touchType, int x, int y) { if (OneLayoutAtATime) { CurrentLayout.LayoutView.TouchManager.ProcessTouchEvent(touchType, x, y); } else { foreach (var xnaLayout in WebLayouts) { var rectangle = xnaLayout.LayoutPosition.Location; if (rectangle.Contains(new Point(x, y))) { xnaLayout.LayoutView.TouchManager.ProcessTouchEvent(touchType, x - rectangle.X, y - rectangle.Y); } } } } } }
// 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. // -------------------------------------------------------------------------------------- // // A class that provides a simple, lightweight implementation of lazy initialization, // obviating the need for a developer to implement a custom, thread-safe lazy initialization // solution. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #pragma warning disable 0420 using System.Diagnostics; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Threading; namespace System { internal enum LazyState { NoneViaConstructor = 0, NoneViaFactory = 1, NoneException = 2, PublicationOnlyViaConstructor = 3, PublicationOnlyViaFactory = 4, PublicationOnlyWait = 5, PublicationOnlyException = 6, ExecutionAndPublicationViaConstructor = 7, ExecutionAndPublicationViaFactory = 8, ExecutionAndPublicationException = 9, } /// <summary> /// LazyHelper serves multiples purposes /// - minimizing code size of Lazy&lt;T&gt; by implementing as much of the code that is not generic /// this reduces generic code bloat, making faster class initialization /// - contains singleton objects that are used to handle threading primitives for PublicationOnly mode /// - allows for instantiation for ExecutionAndPublication so as to create an object for locking on /// - holds exception information. /// </summary> internal class LazyHelper { internal readonly static LazyHelper NoneViaConstructor = new LazyHelper(LazyState.NoneViaConstructor); internal readonly static LazyHelper NoneViaFactory = new LazyHelper(LazyState.NoneViaFactory); internal readonly static LazyHelper PublicationOnlyViaConstructor = new LazyHelper(LazyState.PublicationOnlyViaConstructor); internal readonly static LazyHelper PublicationOnlyViaFactory = new LazyHelper(LazyState.PublicationOnlyViaFactory); internal readonly static LazyHelper PublicationOnlyWaitForOtherThreadToPublish = new LazyHelper(LazyState.PublicationOnlyWait); internal LazyState State { get; } private readonly ExceptionDispatchInfo _exceptionDispatch; /// <summary> /// Constructor that defines the state /// </summary> internal LazyHelper(LazyState state) { State = state; } /// <summary> /// Constructor used for exceptions /// </summary> internal LazyHelper(LazyThreadSafetyMode mode, Exception exception) { switch(mode) { case LazyThreadSafetyMode.ExecutionAndPublication: State = LazyState.ExecutionAndPublicationException; break; case LazyThreadSafetyMode.None: State = LazyState.NoneException; break; case LazyThreadSafetyMode.PublicationOnly: State = LazyState.PublicationOnlyException; break; default: Debug.Assert(false, "internal constructor, this should never occur"); break; } _exceptionDispatch = ExceptionDispatchInfo.Capture(exception); } internal void ThrowException() { Debug.Assert(_exceptionDispatch != null, "execution path is invalid"); _exceptionDispatch.Throw(); } private LazyThreadSafetyMode GetMode() { switch (State) { case LazyState.NoneViaConstructor: case LazyState.NoneViaFactory: case LazyState.NoneException: return LazyThreadSafetyMode.None; case LazyState.PublicationOnlyViaConstructor: case LazyState.PublicationOnlyViaFactory: case LazyState.PublicationOnlyWait: case LazyState.PublicationOnlyException: return LazyThreadSafetyMode.PublicationOnly; case LazyState.ExecutionAndPublicationViaConstructor: case LazyState.ExecutionAndPublicationViaFactory: case LazyState.ExecutionAndPublicationException: return LazyThreadSafetyMode.ExecutionAndPublication; default: Debug.Assert(false, "Invalid logic; State should always have a valid value"); return default(LazyThreadSafetyMode); } } internal static LazyThreadSafetyMode? GetMode(LazyHelper state) { if (state == null) return null; // we don't know the mode anymore return state.GetMode(); } internal static bool GetIsValueFaulted(LazyHelper state) => state?._exceptionDispatch != null; internal static LazyHelper Create(LazyThreadSafetyMode mode, bool useDefaultConstructor) { switch (mode) { case LazyThreadSafetyMode.None: return useDefaultConstructor ? NoneViaConstructor : NoneViaFactory; case LazyThreadSafetyMode.PublicationOnly: return useDefaultConstructor ? PublicationOnlyViaConstructor : PublicationOnlyViaFactory; case LazyThreadSafetyMode.ExecutionAndPublication: // we need to create an object for ExecutionAndPublication because we use Monitor-based locking var state = useDefaultConstructor ? LazyState.ExecutionAndPublicationViaConstructor : LazyState.ExecutionAndPublicationViaFactory; return new LazyHelper(state); default: throw new ArgumentOutOfRangeException(nameof(mode), SR.Lazy_ctor_ModeInvalid); } } internal static object CreateViaDefaultConstructor(Type type) { try { return Activator.CreateInstance(type); } catch (MissingMethodException) { throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT); } } internal static LazyThreadSafetyMode GetModeFromIsThreadSafe(bool isThreadSafe) { return isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None; } } /// <summary> /// Provides support for lazy initialization. /// </summary> /// <typeparam name="T">Specifies the type of element being lazily initialized.</typeparam> /// <remarks> /// <para> /// By default, all public and protected members of <see cref="Lazy{T}"/> are thread-safe and may be used /// concurrently from multiple threads. These thread-safety guarantees may be removed optionally and per instance /// using parameters to the type's constructors. /// </para> /// </remarks> [DebuggerTypeProxy(typeof(System_LazyDebugView<>))] [DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")] public class Lazy<T> { private static T CreateViaDefaultConstructor() { return (T)LazyHelper.CreateViaDefaultConstructor(typeof(T)); } // _state, a volatile reference, is set to null after m_value has been set [NonSerialized] private volatile LazyHelper _state; // we ensure that _factory when finished is set to null to allow garbage collector to clean up // any referenced items [NonSerialized] private Func<T> _factory; // _value eventually stores the lazily created value. It is valid when _state = null. private T m_value; // Do not rename (binary serialization) /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that /// uses <typeparamref name="T"/>'s default constructor for lazy initialization. /// </summary> /// <remarks> /// An instance created with this constructor may be used concurrently from multiple threads. /// </remarks> public Lazy() : this(null, LazyThreadSafetyMode.ExecutionAndPublication, useDefaultConstructor:true) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that /// uses a pre-initialized specified value. /// </summary> /// <remarks> /// An instance created with this constructor should be usable by multiple threads // concurrently. /// </remarks> public Lazy(T value) { m_value = value; } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that uses a /// specified initialization function. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is /// needed. /// </param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <remarks> /// An instance created with this constructor may be used concurrently from multiple threads. /// </remarks> public Lazy(Func<T> valueFactory) : this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication, useDefaultConstructor:false) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> /// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode. /// </summary> /// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time. /// </param> public Lazy(bool isThreadSafe) : this(null, LazyHelper.GetModeFromIsThreadSafe(isThreadSafe), useDefaultConstructor:true) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> /// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode. /// </summary> /// <param name="mode">The lazy thread-safety mode</param> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid valuee</exception> public Lazy(LazyThreadSafetyMode mode) : this(null, mode, useDefaultConstructor:true) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class /// that uses a specified initialization function and a specified thread-safety mode. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed. /// </param> /// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time. /// </param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is /// a null reference (Nothing in Visual Basic).</exception> public Lazy(Func<T> valueFactory, bool isThreadSafe) : this(valueFactory, LazyHelper.GetModeFromIsThreadSafe(isThreadSafe), useDefaultConstructor:false) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class /// that uses a specified initialization function and a specified thread-safety mode. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed. /// </param> /// <param name="mode">The lazy thread-safety mode.</param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is /// a null reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid value.</exception> public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode) : this(valueFactory, mode, useDefaultConstructor:false) { } private Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode, bool useDefaultConstructor) { if (valueFactory == null && !useDefaultConstructor) throw new ArgumentNullException(nameof(valueFactory)); _factory = valueFactory; _state = LazyHelper.Create(mode, useDefaultConstructor); } private void ViaConstructor() { m_value = CreateViaDefaultConstructor(); _state = null; // volatile write, must occur after setting _value } private void ViaFactory(LazyThreadSafetyMode mode) { try { Func<T> factory = _factory; if (factory == null) throw new InvalidOperationException(SR.Lazy_Value_RecursiveCallsToValue); _factory = null; m_value = factory(); _state = null; // volatile write, must occur after setting _value } catch (Exception exception) { _state = new LazyHelper(mode, exception); throw; } } private void ExecutionAndPublication(LazyHelper executionAndPublication, bool useDefaultConstructor) { lock (executionAndPublication) { // it's possible for multiple calls to have piled up behind the lock, so we need to check // to see if the ExecutionAndPublication object is still the current implementation. if (ReferenceEquals(_state, executionAndPublication)) { if (useDefaultConstructor) { ViaConstructor(); } else { ViaFactory(LazyThreadSafetyMode.ExecutionAndPublication); } } } } private void PublicationOnly(LazyHelper publicationOnly, T possibleValue) { LazyHelper previous = Interlocked.CompareExchange(ref _state, LazyHelper.PublicationOnlyWaitForOtherThreadToPublish, publicationOnly); if (previous == publicationOnly) { _factory = null; m_value = possibleValue; _state = null; // volatile write, must occur after setting _value } } private void PublicationOnlyViaConstructor(LazyHelper initializer) { PublicationOnly(initializer, CreateViaDefaultConstructor()); } private void PublicationOnlyViaFactory(LazyHelper initializer) { Func<T> factory = _factory; if (factory == null) { PublicationOnlyWaitForOtherThreadToPublish(); } else { PublicationOnly(initializer, factory()); } } private void PublicationOnlyWaitForOtherThreadToPublish() { var spinWait = new SpinWait(); while (!ReferenceEquals(_state, null)) { // We get here when PublicationOnly temporarily sets _state to LazyHelper.PublicationOnlyWaitForOtherThreadToPublish. // This temporary state should be quickly followed by _state being set to null. spinWait.SpinOnce(); } } private T CreateValue() { // we have to create a copy of state here, and use the copy exclusively from here on in // so as to ensure thread safety. var state = _state; if (state != null) { switch (state.State) { case LazyState.NoneViaConstructor: ViaConstructor(); break; case LazyState.NoneViaFactory: ViaFactory(LazyThreadSafetyMode.None); break; case LazyState.PublicationOnlyViaConstructor: PublicationOnlyViaConstructor(state); break; case LazyState.PublicationOnlyViaFactory: PublicationOnlyViaFactory(state); break; case LazyState.PublicationOnlyWait: PublicationOnlyWaitForOtherThreadToPublish(); break; case LazyState.ExecutionAndPublicationViaConstructor: ExecutionAndPublication(state, useDefaultConstructor:true); break; case LazyState.ExecutionAndPublicationViaFactory: ExecutionAndPublication(state, useDefaultConstructor:false); break; default: state.ThrowException(); break; } } return Value; } /// <summary>Forces initialization during serialization.</summary> /// <param name="context">The StreamingContext for the serialization operation.</param> [OnSerializing] private void OnSerializing(StreamingContext context) { // Force initialization T dummy = Value; } /// <summary>Creates and returns a string representation of this instance.</summary> /// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see /// cref="Value"/>.</returns> /// <exception cref="T:System.NullReferenceException"> /// The <see cref="Value"/> is null. /// </exception> public override string ToString() { return IsValueCreated ? Value.ToString() : SR.Lazy_ToString_ValueNotCreated; } /// <summary>Gets the value of the Lazy&lt;T&gt; for debugging display purposes.</summary> internal T ValueForDebugDisplay { get { if (!IsValueCreated) { return default(T); } return m_value; } } /// <summary> /// Gets a value indicating whether this instance may be used concurrently from multiple threads. /// </summary> internal LazyThreadSafetyMode? Mode => LazyHelper.GetMode(_state); /// <summary> /// Gets whether the value creation is faulted or not /// </summary> internal bool IsValueFaulted => LazyHelper.GetIsValueFaulted(_state); /// <summary>Gets a value indicating whether the <see cref="T:System.Lazy{T}"/> has been initialized. /// </summary> /// <value>true if the <see cref="T:System.Lazy{T}"/> instance has been initialized; /// otherwise, false.</value> /// <remarks> /// The initialization of a <see cref="T:System.Lazy{T}"/> instance may result in either /// a value being produced or an exception being thrown. If an exception goes unhandled during initialization, /// <see cref="IsValueCreated"/> will return false. /// </remarks> public bool IsValueCreated => _state == null; /// <summary>Gets the lazily initialized value of the current <see /// cref="T:System.Threading.Lazy{T}"/>.</summary> /// <value>The lazily initialized value of the current <see /// cref="T:System.Threading.Lazy{T}"/>.</value> /// <exception cref="T:System.MissingMemberException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor /// of the type being lazily initialized, and that type does not have a public, parameterless constructor. /// </exception> /// <exception cref="T:System.MemberAccessException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor /// of the type being lazily initialized, and permissions to access the constructor were missing. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was constructed with the <see cref="T:System.Threading.LazyThreadSafetyMode.ExecutionAndPublication"/> or /// <see cref="T:System.Threading.LazyThreadSafetyMode.None"/> and the initialization function attempted to access <see cref="Value"/> on this instance. /// </exception> /// <remarks> /// If <see cref="IsValueCreated"/> is false, accessing <see cref="Value"/> will force initialization. /// Please <see cref="System.Threading.LazyThreadSafetyMode"> for more information on how <see cref="T:System.Threading.Lazy{T}"/> will behave if an exception is thrown /// from initialization delegate. /// </remarks> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Value => _state == null ? m_value : CreateValue(); } /// <summary>A debugger view of the Lazy&lt;T&gt; to surface additional debugging properties and /// to ensure that the Lazy&lt;T&gt; does not become initialized if it was not already.</summary> internal sealed class System_LazyDebugView<T> { //The Lazy object being viewed. private readonly Lazy<T> _lazy; /// <summary>Constructs a new debugger view object for the provided Lazy object.</summary> /// <param name="lazy">A Lazy object to browse in the debugger.</param> public System_LazyDebugView(Lazy<T> lazy) { _lazy = lazy; } /// <summary>Returns whether the Lazy object is initialized or not.</summary> public bool IsValueCreated { get { return _lazy.IsValueCreated; } } /// <summary>Returns the value of the Lazy object.</summary> public T Value { get { return _lazy.ValueForDebugDisplay; } } /// <summary>Returns the execution mode of the Lazy object</summary> public LazyThreadSafetyMode? Mode { get { return _lazy.Mode; } } /// <summary>Returns the execution mode of the Lazy object</summary> public bool IsValueFaulted { get { return _lazy.IsValueFaulted; } } } }
//----------------------------------------------------------------------------- // <copyright file="JsonReader.cs" company="Dropbox Inc"> // Copyright (c) Dropbox Inc. All rights reserved. // </copyright> //----------------------------------------------------------------------------- namespace Dropbox.Api.Stone { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using Newtonsoft.Json; /// <summary> /// Parse and read from json string. /// </summary> internal sealed class JsonReader : IJsonReader { /// <summary> /// The json text reader. /// </summary> private readonly JsonTextReader reader; /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class. /// </summary> /// <param name="reader">The json text reader.</param> private JsonReader(JsonTextReader reader) { this.reader = reader; this.reader.Read(); } /// <summary> /// Gets a value indicating whether current token is start object. /// </summary> bool IJsonReader.IsStartObject { get { return this.reader.TokenType == JsonToken.StartObject; } } /// <summary> /// Gets a value indicating whether current token is end object. /// </summary> bool IJsonReader.IsEndObject { get { return this.reader.TokenType == JsonToken.EndObject; } } /// <summary> /// Gets a value indicating whether current token is start array. /// </summary> bool IJsonReader.IsStartArray { get { return this.reader.TokenType == JsonToken.StartArray; } } /// <summary> /// Gets a value indicating whether current token is end array. /// </summary> bool IJsonReader.IsEndArray { get { return this.reader.TokenType == JsonToken.EndArray; } } /// <summary> /// Gets a value indicating whether current token is property name. /// </summary> bool IJsonReader.IsPropertyName { get { return this.reader.TokenType == JsonToken.PropertyName; } } /// <summary> /// Gets a value indicating whether current token is null. /// </summary> bool IJsonReader.IsNull { get { return this.reader.TokenType == JsonToken.Null; } } /// <summary> /// Read specific type form given json. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <param name="json">The json.</param> /// <param name="decoder">The decoder.</param> /// <returns>The decoded object.</returns> public static T Read<T>(string json, IDecoder<T> decoder) { var reader = new JsonReader(new JsonTextReader(new StringReader(json)) { DateParseHandling = DateParseHandling.None, }); return decoder.Decode(reader); } /// <summary> /// Read one token. /// </summary> /// <returns>If read succeeded.</returns> bool IJsonReader.Read() { return this.reader.Read(); } /// <summary> /// Skip current token. /// </summary> void IJsonReader.Skip() { this.reader.Skip(); this.reader.Read(); } /// <summary> /// Read value as Int32. /// </summary> /// <returns>The value.</returns> int IJsonReader.ReadInt32() { return Convert.ToInt32(this.ReadValue<long>()); } /// <summary> /// Read value as Int64. /// </summary> /// <returns>The value.</returns> long IJsonReader.ReadInt64() { return this.ReadValue<long>(); } /// <summary> /// Read value as UInt32. /// </summary> /// <returns>The value.</returns> uint IJsonReader.ReadUInt32() { return Convert.ToUInt32(this.ReadValue<long>()); } /// <summary> /// Read value as UInt64. /// </summary> /// <returns>The value.</returns> ulong IJsonReader.ReadUInt64() { return Convert.ToUInt64(this.ReadValue<long>()); } /// <summary> /// Read value as double. /// </summary> /// <returns>The value.</returns> double IJsonReader.ReadDouble() { return this.ReadValue<double>(); } /// <summary> /// Read value as float. /// </summary> /// <returns>The value.</returns> float IJsonReader.ReadSingle() { return Convert.ToSingle(this.ReadValue<double>()); } /// <summary> /// Read value as DateTime. /// </summary> /// <returns>The value.</returns> DateTime IJsonReader.ReadDateTime() { return this.ReadValue<DateTime>(); } /// <summary> /// Read value as boolean. /// </summary> /// <returns>The value.</returns> bool IJsonReader.ReadBoolean() { return this.ReadValue<bool>(); } /// <summary> /// Read value as bytes. /// </summary> /// <returns>The value.</returns> byte[] IJsonReader.ReadBytes() { return this.ReadValue<byte[]>(); } /// <summary> /// Read value as string. /// </summary> /// <returns>The value.</returns> string IJsonReader.ReadString() { return this.ReadValue<string>(); } /// <summary> /// Read next token as specific value type. /// </summary> /// <typeparam name="T">The type of the value. The type will be used as explicit cast.</typeparam> /// <returns>The value.</returns> private T ReadValue<T>() { try { var value = (T)this.reader.Value; this.reader.Read(); return value; } catch (InvalidCastException) { throw new InvalidCastException(string.Format( CultureInfo.InvariantCulture, "Value '{0}' is not valid {1} type", this.reader.Value, typeof(T))); } } } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonViewInspector.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // Custom inspector for the PhotonView component. // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- using System; using UnityEditor; using UnityEngine; using Rotorz.ReorderableList.Internal; [CustomEditor(typeof (PhotonView))] public class PhotonViewInspector : Editor { private PhotonView m_Target; public override void OnInspectorGUI() { m_Target = (PhotonView) this.target; bool isProjectPrefab = EditorUtility.IsPersistent(m_Target.gameObject); if (m_Target.ObservedComponents == null) { m_Target.ObservedComponents = new System.Collections.Generic.List<Component>(); } if (m_Target.ObservedComponents.Count == 0) { m_Target.ObservedComponents.Add(null); } EditorGUILayout.BeginHorizontal(); // Owner if (isProjectPrefab) { EditorGUILayout.LabelField("Owner:", "Set at runtime"); } else if (m_Target.isSceneView) { EditorGUILayout.LabelField("Owner", "Scene"); } else { PhotonPlayer owner = m_Target.owner; string ownerInfo = (owner != null) ? owner.name : "<no PhotonPlayer found>"; if (string.IsNullOrEmpty(ownerInfo)) { ownerInfo = "<no playername set>"; } EditorGUILayout.LabelField("Owner", "[" + m_Target.ownerId + "] " + ownerInfo); } // ownership requests EditorGUI.BeginDisabledGroup(Application.isPlaying); m_Target.ownershipTransfer = (OwnershipOption) EditorGUILayout.EnumPopup(m_Target.ownershipTransfer, GUILayout.Width(100)); EditorGUI.EndDisabledGroup(); EditorGUILayout.EndHorizontal(); // View ID if (isProjectPrefab) { EditorGUILayout.LabelField("View ID", "Set at runtime"); } else if (EditorApplication.isPlaying) { EditorGUILayout.LabelField("View ID", m_Target.viewID.ToString()); } else { int idValue = EditorGUILayout.IntField("View ID [1.." + (PhotonNetwork.MAX_VIEW_IDS - 1) + "]", m_Target.viewID); m_Target.viewID = idValue; } // Locally Controlled if (EditorApplication.isPlaying) { string masterClientHint = PhotonNetwork.isMasterClient ? "(master)" : ""; EditorGUILayout.Toggle("Controlled locally: " + masterClientHint, m_Target.isMine); } //DrawOldObservedItem(); this.ConvertOldObservedItemToObservedList(); // ViewSynchronization (reliability) if (m_Target.synchronization == ViewSynchronization.Off) { GUI.color = Color.grey; } EditorGUILayout.PropertyField(serializedObject.FindProperty("synchronization"), new GUIContent("Observe option:")); if (m_Target.synchronization != ViewSynchronization.Off && m_Target.ObservedComponents.FindAll(item => item != null).Count == 0) { GUILayout.BeginVertical(GUI.skin.box); GUILayout.Label("Warning", EditorStyles.boldLabel); GUILayout.Label("Setting the synchronization option only makes sense if you observe something."); GUILayout.EndVertical(); } /*ViewSynchronization vsValue = (ViewSynchronization)EditorGUILayout.EnumPopup("Observe option:", m_Target.synchronization); if (vsValue != m_Target.synchronization) { m_Target.synchronization = vsValue; if (m_Target.synchronization != ViewSynchronization.Off && m_Target.observed == null) { EditorUtility.DisplayDialog("Warning", "Setting the synchronization option only makes sense if you observe something.", "OK, I will fix it."); } }*/ DrawSpecificTypeSerializationOptions(); GUI.color = Color.white; DrawObservedComponentsList(); // Cleanup: save and fix look if (GUI.changed) { EditorUtility.SetDirty(m_Target); PhotonViewHandler.HierarchyChange(); // TODO: check if needed } GUI.color = Color.white; EditorGUIUtility.LookLikeControls(); } private void DrawSpecificTypeSerializationOptions() { if (m_Target.ObservedComponents.FindAll(item => item != null && item.GetType() == typeof(Transform)).Count > 0 || (m_Target.observed != null && m_Target.observed.GetType() == typeof(Transform))) { m_Target.onSerializeTransformOption = (OnSerializeTransform) EditorGUILayout.EnumPopup("Transform Serialization:", m_Target.onSerializeTransformOption); } else if (m_Target.ObservedComponents.FindAll(item => item != null && item.GetType() == typeof(Rigidbody)).Count > 0 || (m_Target.observed != null && m_Target.observed.GetType() == typeof(Rigidbody)) || m_Target.ObservedComponents.FindAll(item => item != null && item.GetType() == typeof(Rigidbody2D)).Count > 0 || (m_Target.observed != null && m_Target.observed.GetType() == typeof(Rigidbody2D))) { m_Target.onSerializeRigidBodyOption = (OnSerializeRigidBody) EditorGUILayout.EnumPopup("Rigidbody Serialization:", m_Target.onSerializeRigidBodyOption); } } private void DrawSpecificTypeOptions() { if (m_Target.observed != null) { Type type = m_Target.observed.GetType(); if (type == typeof (Transform)) { m_Target.onSerializeTransformOption = (OnSerializeTransform) EditorGUILayout.EnumPopup("Serialization:", m_Target.onSerializeTransformOption); } else if (type == typeof (Rigidbody)) { m_Target.onSerializeRigidBodyOption = (OnSerializeRigidBody) EditorGUILayout.EnumPopup("Serialization:", m_Target.onSerializeRigidBodyOption); } } } private void ConvertOldObservedItemToObservedList() { if (Application.isPlaying) { return; } if (m_Target.observed != null) { if (m_Target.ObservedComponents.Contains(m_Target.observed) == false) { bool wasAdded = false; for (int i = 0; i < m_Target.ObservedComponents.Count; ++i) { if (m_Target.ObservedComponents[i] == null) { m_Target.ObservedComponents[i] = m_Target.observed; wasAdded = true; } } if (wasAdded == false) { m_Target.ObservedComponents.Add(m_Target.observed); } } m_Target.observed = null; EditorUtility.SetDirty(m_Target); } } private void DrawOldObservedItem() { EditorGUILayout.BeginHorizontal(); // Using a lower version then 3.4? Remove the TRUE in the next line to fix an compile error string typeOfObserved = string.Empty; if (m_Target.observed != null) { int firstBracketPos = m_Target.observed.ToString().LastIndexOf('('); if (firstBracketPos > 0) { typeOfObserved = m_Target.observed.ToString().Substring(firstBracketPos); } } Component componenValue = (Component) EditorGUILayout.ObjectField("Observe: " + typeOfObserved, m_Target.observed, typeof (Component), true); if (m_Target.observed != componenValue) { if (m_Target.observed == null) { m_Target.synchronization = ViewSynchronization.UnreliableOnChange; // if we didn't observe anything yet. use unreliable on change as default } if (componenValue == null) { m_Target.synchronization = ViewSynchronization.Off; } m_Target.observed = componenValue; } EditorGUILayout.EndHorizontal(); } private int GetObservedComponentsCount() { int count = 0; for (int i = 0; i < m_Target.ObservedComponents.Count; ++i) { if (m_Target.ObservedComponents[i] != null) { count++; } } return count; } private void DrawObservedComponentsList() { GUILayout.Space(5); SerializedProperty listProperty = serializedObject.FindProperty("ObservedComponents"); if (listProperty == null) { return; } float containerElementHeight = 22; float containerHeight = listProperty.arraySize*containerElementHeight; bool isOpen = PhotonGUI.ContainerHeaderFoldout("Observed Components (" + GetObservedComponentsCount() + ")", serializedObject.FindProperty("ObservedComponentsFoldoutOpen").boolValue); serializedObject.FindProperty("ObservedComponentsFoldoutOpen").boolValue = isOpen; if (isOpen == false) { containerHeight = 0; } //Texture2D statsIcon = AssetDatabase.LoadAssetAtPath( "Assets/Photon Unity Networking/Editor/PhotonNetwork/PhotonViewStats.png", typeof( Texture2D ) ) as Texture2D; Rect containerRect = PhotonGUI.ContainerBody(containerHeight); bool wasObservedComponentsEmpty = m_Target.ObservedComponents.FindAll(item => item != null).Count == 0; if (isOpen == true) { for (int i = 0; i < listProperty.arraySize; ++i) { Rect elementRect = new Rect(containerRect.xMin, containerRect.yMin + containerElementHeight*i, containerRect.width, containerElementHeight); { Rect texturePosition = new Rect(elementRect.xMin + 6, elementRect.yMin + elementRect.height/2f - 1, 9, 5); ReorderableListResources.DrawTexture(texturePosition, ReorderableListResources.texGrabHandle); Rect propertyPosition = new Rect(elementRect.xMin + 20, elementRect.yMin + 3, elementRect.width - 45, 16); EditorGUI.PropertyField(propertyPosition, listProperty.GetArrayElementAtIndex(i), new GUIContent()); //Debug.Log( listProperty.GetArrayElementAtIndex( i ).objectReferenceValue.GetType() ); //Rect statsPosition = new Rect( propertyPosition.xMax + 7, propertyPosition.yMin, statsIcon.width, statsIcon.height ); //ReorderableListResources.DrawTexture( statsPosition, statsIcon ); Rect removeButtonRect = new Rect(elementRect.xMax - PhotonGUI.DefaultRemoveButtonStyle.fixedWidth, elementRect.yMin + 2, PhotonGUI.DefaultRemoveButtonStyle.fixedWidth, PhotonGUI.DefaultRemoveButtonStyle.fixedHeight); GUI.enabled = listProperty.arraySize > 1; if (GUI.Button(removeButtonRect, new GUIContent(ReorderableListResources.texRemoveButton), PhotonGUI.DefaultRemoveButtonStyle)) { listProperty.DeleteArrayElementAtIndex(i); } GUI.enabled = true; if (i < listProperty.arraySize - 1) { texturePosition = new Rect(elementRect.xMin + 2, elementRect.yMax, elementRect.width - 4, 1); PhotonGUI.DrawSplitter(texturePosition); } } } } if (PhotonGUI.AddButton()) { listProperty.InsertArrayElementAtIndex(Mathf.Max(0, listProperty.arraySize - 1)); } serializedObject.ApplyModifiedProperties(); bool isObservedComponentsEmpty = m_Target.ObservedComponents.FindAll(item => item != null).Count == 0; if (wasObservedComponentsEmpty == true && isObservedComponentsEmpty == false && m_Target.synchronization == ViewSynchronization.Off) { m_Target.synchronization = ViewSynchronization.UnreliableOnChange; EditorUtility.SetDirty(m_Target); serializedObject.Update(); } if (wasObservedComponentsEmpty == false && isObservedComponentsEmpty == true) { m_Target.synchronization = ViewSynchronization.Off; EditorUtility.SetDirty(m_Target); serializedObject.Update(); } } private static GameObject GetPrefabParent(GameObject mp) { #if UNITY_2_6_1 || UNITY_2_6 || UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 // Unity 3.4 and older use EditorUtility return (EditorUtility.GetPrefabParent(mp) as GameObject); #else // Unity 3.5 uses PrefabUtility return PrefabUtility.GetPrefabParent(mp) as GameObject; #endif } }
/* Matali Physics Demo Copyright (c) 2013 KOMIRES Sp. z o. o. */ using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Drawing; using System.Drawing.Imaging; using OpenTK; using OpenTK.Audio; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Input; using Komires.MataliPhysics; namespace MataliPhysicsDemo { /// <summary> /// This is the main type for your game /// </summary> public class Demo : GameWindow { DemoMouseState mouseState; DemoKeyboardState keyboardState; string infoDrawFPSName; string infoPhysicsFPSName; string infoPhysicsObjectsName; string infoConstraintsName; string infoContactPointsName; string infoMenuName; Color whiteColor; public Color4 ClearLightColor; public Vector3 ClearScreenColor; StringBuilder infoDrawFPSNameBuilder; StringBuilder infoPhysicsFPSNameBuilder; StringBuilder infoPhysicsObjectsNameBuilder; StringBuilder infoConstraintsNameBuilder; StringBuilder infoContactPointsNameBuilder; int infoDrawFPSNameLength; int infoPhysicsFPSNameLength; int infoPhysicsObjectsNameLength; int infoConstraintsNameLength; int infoContactPointsNameLength; public DemoFont DemoFont; public DemoFont3D DemoFont3D; public int SceneFrameBuffer; public int SceneDepthBuffer; public int LightFrameBuffer; public int ScreenFrameBuffer; public int ColorTexture; public int SpecularTexture; public int NormalTexture; public int DepthTexture; public int LightTexture; public int ScreenTexture; public int WindowWidth; public int WindowHeight; public bool EnableVertexBuffer; public bool EnableMipmapExtension; public bool EnableCubeMapExtension; public bool EnableWireframe; public int SceneIndex; // Declare physics engine public PhysicsEngine Engine; // Declare scene object public IDemoScene Scene; // Declare menu object public MenuScene MenuScene; // Declare list of scene objects public List<IDemoScene> Scenes; // Declare dictionary of meshes public Dictionary<string, DemoMesh> Meshes; // Declare dictionary of textures public Dictionary<string, DemoTexture> Textures; // Declare dictionary of menu descriptions public Dictionary<string, List<string>> Descriptions; // Declare dictionary of sound samples public Dictionary<string, DemoSoundSample> SoundSamples; // Declare dictionary of sound groups public Dictionary<string, DemoSoundGroup> SoundGroups; // Declare queue of sounds public DemoSoundQueue SoundQueue; AudioContext Audio; public bool EnableMenu; public Vector3 CursorLightDirection; DemoKeyboardState oldKeyboardState; public Demo() : base(1280, 720, GraphicsMode.Default, "Matali Physics Demo (OpenTK)") { SetWindowSize(1280, 720); Icon = Properties.Resources.MataliPhysicsDemo; Mouse.ButtonUp += Mouse_ButtonUp; Mouse.ButtonDown += Mouse_ButtonDown; Mouse.Move += Mouse_Move; Mouse.WheelChanged += Mouse_WheelChanged; Keyboard.KeyUp += Keyboard_KeyUp; Keyboard.KeyDown += Keyboard_KeyDown; infoDrawFPSName = "Draw FPS: "; infoPhysicsFPSName = "Physics FPS: "; infoPhysicsObjectsName = "Physics objects: "; infoConstraintsName = "Constraints: "; infoContactPointsName = "Contact points: "; infoMenuName = "M: Menu"; whiteColor = Color.White; ClearLightColor = new Color4(0, 0, 0, 0); ClearScreenColor = new Vector3(Color.CornflowerBlue.R / 255.0f, Color.CornflowerBlue.G / 255.0f, Color.CornflowerBlue.B / 255.0f); infoDrawFPSNameBuilder = new StringBuilder(infoDrawFPSName); infoPhysicsFPSNameBuilder = new StringBuilder(infoPhysicsFPSName); infoPhysicsObjectsNameBuilder = new StringBuilder(infoPhysicsObjectsName); infoConstraintsNameBuilder = new StringBuilder(infoConstraintsName); infoContactPointsNameBuilder = new StringBuilder(infoContactPointsName); infoDrawFPSNameLength = infoDrawFPSNameBuilder.Length; infoPhysicsFPSNameLength = infoPhysicsFPSNameBuilder.Length; infoPhysicsObjectsNameLength = infoPhysicsObjectsNameBuilder.Length; infoConstraintsNameLength = infoConstraintsNameBuilder.Length; infoContactPointsNameLength = infoContactPointsNameBuilder.Length; DemoFont = null; DemoFont3D = null; WindowWidth = 1280; WindowHeight = 720; EnableVertexBuffer = false; EnableMipmapExtension = false; EnableCubeMapExtension = false; // Create a new physics engine Engine = new PhysicsEngine("Engine"); Scene = null; // Create a new menu object MenuScene = new MenuScene(this, "Menu", 1, null); // Create a new list of scene objects Scenes = new List<IDemoScene>(); // Create a new dictionary of meshes Meshes = new Dictionary<string, DemoMesh>(); // Create a new dictionary of textures Textures = new Dictionary<string, DemoTexture>(); // Create a new dictionary of menu descriptions Descriptions = new Dictionary<string, List<string>>(); // Create a new dictionary of sound samples SoundSamples = new Dictionary<string, DemoSoundSample>(); // Create a new dictionary of sound groups SoundGroups = new Dictionary<string, DemoSoundGroup>(); // Create a new queue of sounds SoundQueue = new DemoSoundQueue(50); try { Audio = new AudioContext(); } catch (System.TypeInitializationException e) { } SoundQueue.CreateSources(100); EnableMenu = false; CursorLightDirection = new Vector3(0.0f, 0.0f, 1.0f); oldKeyboardState = GetKeyboardState(); } void Mouse_ButtonUp(object sender, MouseButtonEventArgs e) { mouseState.Set(e.Button, false); } void Mouse_ButtonDown(object sender, MouseButtonEventArgs e) { mouseState.Set(e.Button, true); } void Mouse_Move(object sender, MouseMoveEventArgs e) { mouseState.Set(e.X, e.Y); } void Mouse_WheelChanged(object sender, MouseWheelEventArgs e) { mouseState.Set(e.Value); } void Keyboard_KeyUp(object sender, KeyboardKeyEventArgs e) { keyboardState.Set(e.Key, false); } void Keyboard_KeyDown(object sender, KeyboardKeyEventArgs e) { keyboardState.Set(e.Key, true); } public DemoMouseState GetMouseState() { return mouseState; } public DemoKeyboardState GetKeyboardState() { return keyboardState; } public void SetWindowSize(int width, int height) { if ((Width != width) || (Height != height)) { Width = width; Height = height; Context.Update(WindowInfo); GL.Viewport(0, 0, Width, Height); } } public void CreateResources() { GL.Enable(EnableCap.Texture2D); GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest); GL.GenTextures(1, out ColorTexture); GL.BindTexture(TextureTarget.Texture2D, ColorTexture); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, Width, Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); GL.BindTexture(TextureTarget.Texture2D, 0); GL.GenTextures(1, out SpecularTexture); GL.BindTexture(TextureTarget.Texture2D, SpecularTexture); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, Width, Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); GL.BindTexture(TextureTarget.Texture2D, 0); GL.GenTextures(1, out NormalTexture); GL.BindTexture(TextureTarget.Texture2D, NormalTexture); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, Width, Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); GL.BindTexture(TextureTarget.Texture2D, 0); GL.GenTextures(1, out DepthTexture); GL.BindTexture(TextureTarget.Texture2D, DepthTexture); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, Width, Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); GL.BindTexture(TextureTarget.Texture2D, 0); GL.GenTextures(1, out LightTexture); GL.BindTexture(TextureTarget.Texture2D, LightTexture); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, Width, Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); GL.BindTexture(TextureTarget.Texture2D, 0); GL.GenTextures(1, out ScreenTexture); GL.BindTexture(TextureTarget.Texture2D, ScreenTexture); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, Width, Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); GL.BindTexture(TextureTarget.Texture2D, 0); GL.GenFramebuffers(1, out SceneFrameBuffer); GL.BindFramebuffer(FramebufferTarget.Framebuffer, SceneFrameBuffer); GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, ColorTexture, 0); GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment1, TextureTarget.Texture2D, SpecularTexture, 0); GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment2, TextureTarget.Texture2D, NormalTexture, 0); GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment3, TextureTarget.Texture2D, DepthTexture, 0); GL.GenRenderbuffers(1, out SceneDepthBuffer); GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, SceneDepthBuffer); GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, RenderbufferStorage.DepthComponent24, Width, Height); GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment, RenderbufferTarget.Renderbuffer, SceneDepthBuffer); GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); GL.GenFramebuffers(1, out LightFrameBuffer); GL.BindFramebuffer(FramebufferTarget.Framebuffer, LightFrameBuffer); GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, LightTexture, 0); GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); GL.GenFramebuffers(1, out ScreenFrameBuffer); GL.BindFramebuffer(FramebufferTarget.Framebuffer, ScreenFrameBuffer); GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, ScreenTexture, 0); GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); } public void DisposeResources() { if (ColorTexture != 0) { GL.DeleteTextures(1, ref ColorTexture); ColorTexture = 0; } if (SpecularTexture != 0) { GL.DeleteTextures(1, ref SpecularTexture); SpecularTexture = 0; } if (NormalTexture != 0) { GL.DeleteTextures(1, ref NormalTexture); NormalTexture = 0; } if (DepthTexture != 0) { GL.DeleteTextures(1, ref DepthTexture); DepthTexture = 0; } if (LightTexture != 0) { GL.DeleteTextures(1, ref LightTexture); LightTexture = 0; } if (ScreenTexture != 0) { GL.DeleteTextures(1, ref ScreenTexture); ScreenTexture = 0; } if (SceneDepthBuffer != 0) { GL.DeleteRenderbuffers(1, ref SceneDepthBuffer); SceneDepthBuffer = 0; } if (SceneFrameBuffer != 0) { GL.DeleteFramebuffers(1, ref SceneFrameBuffer); SceneFrameBuffer = 0; } if (LightFrameBuffer != 0) { GL.DeleteFramebuffers(1, ref LightFrameBuffer); LightFrameBuffer = 0; } if (ScreenFrameBuffer != 0) { GL.DeleteFramebuffers(1, ref ScreenFrameBuffer); ScreenFrameBuffer = 0; } } /// <summary> /// Called when the user resizes the window. /// </summary> protected override void OnResize(EventArgs e) { Context.Update(WindowInfo); if (Width > 0) WindowWidth = Width; if (Height > 0) WindowHeight = Height; GL.Viewport(0, 0, Width, Height); DemoFont.Resize(); DisposeResources(); for (int i = 0; i < Scenes.Count; i++) Scenes[i].DisposeResources(); MenuScene.DisposeResources(); CreateResources(); for (int i = 0; i < Scenes.Count; i++) Scenes[i].CreateResources(); MenuScene.CreateResources(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void OnLoad(EventArgs e) { string version = GL.GetString(StringName.Version); int versionNumber = int.Parse(version[0].ToString()) * 10 + int.Parse(version[2].ToString()); if (versionNumber < 14) { Console.WriteLine("OpenGL version: " + version + "\nYou need at least OpenGL 1.4 to run this program."); this.Exit(); return; } if (versionNumber >= 15) EnableVertexBuffer = true; string extensions = GL.GetString(StringName.Extensions); if (extensions.Contains("GL_SGIS_generate_mipmap")) EnableMipmapExtension = true; if (extensions.Contains("GL_EXT_texture_cube_map")) EnableCubeMapExtension = true; CreateResources(); GL.Enable(EnableCap.DepthTest); GL.Enable(EnableCap.CullFace); GL.ShadeModel(ShadingModel.Smooth); GL.Disable(EnableCap.Dither); GL.Disable(EnableCap.Lighting); string soundPath = "Sounds"; SoundSamples.Add("Field", new DemoSoundSample(this, soundPath, ".wav")); SoundSamples.Add("Footsteps", new DemoSoundSample(this, soundPath, ".wav")); SoundSamples.Add("Hit1", new DemoSoundSample(this, soundPath, ".wav")); SoundSamples.Add("Hit2", new DemoSoundSample(this, soundPath, ".wav")); SoundSamples.Add("Roll", new DemoSoundSample(this, soundPath, ".wav")); SoundSamples.Add("Slide", new DemoSoundSample(this, soundPath, ".wav")); SoundGroups.Add("Default", new DemoSoundGroup(this, 4, SoundSamples["Hit1"], SoundSamples["Roll"], SoundSamples["Slide"], null)); SoundGroups.Add("Field", new DemoSoundGroup(this, 4, SoundSamples["Hit2"], SoundSamples["Roll"], SoundSamples["Slide"], SoundSamples["Field"])); SoundGroups.Add("Footsteps", new DemoSoundGroup(this, 4, null, null, SoundSamples["Footsteps"], null)); SoundGroups.Add("Hit", new DemoSoundGroup(this, 10, SoundSamples["Hit1"], null, null, null)); SoundGroups.Add("Glass", new DemoSoundGroup(this, 4, SoundSamples["Hit2"], SoundSamples["Roll"], SoundSamples["Slide"], null)); SoundGroups.Add("Roll", new DemoSoundGroup(this, 4, null, SoundSamples["Roll"], SoundSamples["Roll"], null)); SoundGroups.Add("RollSlide", new DemoSoundGroup(this, 4, null, SoundSamples["Roll"], SoundSamples["Slide"], null)); string materialPath = "Materials"; Textures.Add("Default", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Iron", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Brass", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Rubber", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Plastic1", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Plastic2", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Wood1", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Wood2", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Paint1", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Paint2", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Ground", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Blue", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Yellow", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Green", new DemoTexture(this, materialPath, ".jpg", true)); Textures.Add("Leaf", new DemoTexture(this, materialPath, ".jpg", true)); string skycubePath = "Skycubes"; Textures.Add("SkyXZ", new DemoTexture(this, skycubePath, ".jpg", true)); Textures.Add("SkyPosY", new DemoTexture(this, skycubePath, ".jpg", true)); Textures.Add("SkyNegY", new DemoTexture(this, skycubePath, ".jpg", true)); string fontPath = "Fonts"; Textures.Add("DefaultFont", new DemoTexture(this, fontPath, ".png", false)); string terrainPath = "Terrains"; Textures.Add("DefaultHeights", new DemoTexture(this, terrainPath, ".png", false)); Textures.Add("DefaultFrictions", new DemoTexture(this, terrainPath, ".png", false)); Textures.Add("DefaultRestitutions", new DemoTexture(this, terrainPath, ".png", false)); string menuPath = "Menus"; string menuScreensPath = null; menuPath = Path.Combine(menuPath, "Default"); menuScreensPath = Path.Combine(menuPath, "Screens"); Textures.Add("DefaultShapes", new DemoTexture(this, menuScreensPath, ".jpg", true)); Textures.Add("UserShapes", new DemoTexture(this, menuScreensPath, ".jpg", true)); Textures.Add("Stacks", new DemoTexture(this, menuScreensPath, ".jpg", true)); Textures.Add("Ragdolls", new DemoTexture(this, menuScreensPath, ".jpg", true)); Textures.Add("Bridges", new DemoTexture(this, menuScreensPath, ".jpg", true)); Textures.Add("Building", new DemoTexture(this, menuScreensPath, ".jpg", true)); Textures.Add("AI", new DemoTexture(this, menuScreensPath, ".jpg", true)); Textures.Add("Helicopters", new DemoTexture(this, menuScreensPath, ".jpg", true)); Textures.Add("Buildings", new DemoTexture(this, menuScreensPath, ".jpg", true)); Textures.Add("TerrainWithWater", new DemoTexture(this, menuScreensPath, ".jpg", true)); Textures.Add("Animation", new DemoTexture(this, menuScreensPath, ".jpg", true)); Textures.Add("Cloth", new DemoTexture(this, menuScreensPath, ".jpg", true)); Textures.Add("Meshes", new DemoTexture(this, menuScreensPath, ".jpg", true)); string path = null; string directoryPath = null; string changeDirectorySeparator = ".."; directoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, changeDirectorySeparator); directoryPath = Path.Combine(directoryPath, changeDirectorySeparator); directoryPath = Path.Combine(directoryPath, changeDirectorySeparator); directoryPath = Path.Combine(directoryPath, changeDirectorySeparator); directoryPath = Path.Combine(directoryPath, changeDirectorySeparator); directoryPath = Path.Combine(directoryPath, changeDirectorySeparator); directoryPath = Path.Combine(directoryPath, "Data"); directoryPath = Path.GetFullPath(directoryPath); Dictionary<string, DemoSoundSample>.Enumerator position1 = SoundSamples.GetEnumerator(); while (position1.MoveNext()) { DemoSoundSample soundSample = position1.Current.Value; string soundName = position1.Current.Key + soundSample.FileExt; path = directoryPath; if (soundSample.FileDirectory != null) path = Path.Combine(path, soundSample.FileDirectory); path = Path.Combine(path, soundName); if (File.Exists(path)) { soundSample.Set(File.OpenRead(path)); } else { Console.WriteLine("File " + path + " could not be found."); this.Exit(); return; } } Dictionary<string, DemoTexture>.Enumerator position2 = Textures.GetEnumerator(); while (position2.MoveNext()) { DemoTexture texture = position2.Current.Value; string textureName = position2.Current.Key + texture.FileExt; path = directoryPath; if (texture.FileDirectory != null) path = Path.Combine(path, texture.FileDirectory); path = Path.Combine(path, textureName); if (File.Exists(path)) { texture.Create(new Bitmap(path)); } else { Console.WriteLine("File " + path + " could not be found."); this.Exit(); return; } } Textures.Add("Sky", new DemoTexture(this, Textures["SkyXZ"].Bitmap, Textures["SkyPosY"].Bitmap, Textures["SkyNegY"].Bitmap, true)); DemoFont = new DemoFont(this, "DefaultFont", 150); DemoFont3D = new DemoFont3D(this, "DefaultFont", 150); // Create a new lists of menu descriptions Descriptions.Add("DefaultShapes", new List<string>() { "Scene:", "Default shapes", null, null, "Input:", "+, -: Toggle scene", "R: Reset scene", "W, S, D, A: Player control", "Mouse right button: Camera control", "J, K: Sun position control", "B, C, V, I, G, N: Show bounding boxes, contact points, sleeping objects, impact factors,", "lights, wireframe objects", "Mouse move: Cursor control", "Mouse middle buton, ctrl: Shoot", "Mouse move + mouse left button: Grab objects", "Mouse wheel + mouse left button: Move objects to and from player", "P: Print screen to file" }); Descriptions.Add("UserShapes", new List<string>() { "Scene:", "User shapes, transparent objects, force fields, switches,", "triangle meshes", null, "Input:", "+, -: Toggle scene", "R: Reset scene", "W, S, D, A: Player control", "Mouse right button: Camera control", "J, K: Sun position control", "B, C, V, I, G, N: Show bounding boxes, contact points, sleeping objects, impact factors,", "lights, wireframe objects", "Mouse move: Cursor control", "Mouse middle buton, ctrl: Shoot", "Mouse move + mouse left button: Grab objects", "Mouse wheel + mouse left button: Move objects to and from player", "P: Print screen to file" }); Descriptions.Add("Stacks", new List<string>() { "Scene:", "Stacking (Jenga, Pyramid, Wall)", null, null, "Input:", "+, -: Toggle scene", "R: Reset scene", "W, S, D, A: Player control", "Mouse right button: Camera control", "J, K: Sun position control", "B, C, V, I, G, N: Show bounding boxes, contact points, sleeping objects, impact factors, ", "lights, wireframe objects", "Mouse move: Cursor control", "Mouse middle buton, ctrl: Shoot", "Mouse move + mouse left button: Grab objects", "Mouse wheel + mouse left button: Move objects to and from player", "P: Print screen to file" }); Descriptions.Add("Ragdolls", new List<string>() { "Scene:", "Ragdolls", null, null, "Input:", "+, -: Toggle scene", "R: Reset scene", "W, S, D, A: Player control", "Mouse right button: Camera control", "J, K, Tab: Sun position control, Toggle camera", "B, C, V, I, G, N: Show bounding boxes, contact points, sleeping objects, impact factors,", "lights, wireframe objects", "Mouse move: Cursor control", "Mouse middle buton, ctrl: Shoot", "Mouse move + mouse left button: Grab objects", "Mouse wheel + mouse left button: Move objects to and from player", "P: Print screen to file" }); Descriptions.Add("Bridges", new List<string>() { "Scene:", "Bridges, vehicle, ragdoll", null, null, "Input:", "+, -: Toggle scene", "R: Reset scene", "W, S, D, A: Player control", "Mouse right button: Camera control", "J, K: Sun position control", "Arrows up, down, right, left: Vehicle remote control", "B, C, V, I, G, N: Show bounding boxes, contact points, sleeping objects, impact factors,", "lights, wireframe objects", "Mouse move: Cursor control", "Mouse middle buton, ctrl: Shoot", "Mouse move + mouse left button: Grab objects", "Mouse wheel + mouse left button: Move objects to and from player", "P: Print screen to file" }); Descriptions.Add("Building", new List<string>() { "Scene:", "Building, vehicle, ragdoll, plant, particles", null, null, "Input:", "+, -: Toggle scene", "R: Reset scene", "W, S, D, A, Space: Player control", "Mouse right button: Camera control", "J, K, Tab: Sun position control, Toggle camera mode", "Arrows up, down, right, left: Vehicle remote control", "Space + Collision with switch: Switch to driver seat", "B, C, V, I, G, N: Show bounding boxes, contact points, sleeping objects, impact factors,", "lights, wireframe objects", "Mouse move: Cursor control", "Mouse middle buton, ctrl: Shoot", "Mouse move + mouse left button: Grab objects", "Mouse wheel + mouse left button: Move objects to and from player", "P: Print screen to file" }); Descriptions.Add("AI", new List<string>() { "Scene:", "Simple physical AI", null, null, "Input:", "+, -: Toggle scene", "R: Reset scene", "W, S, D, A, Space: Player control", "Mouse right button: Camera control", "J, K, Tab: Sun position control, Toggle camera mode", "Arrows up, down, right, left, PgUp/Down, F: Vehicle remote control, vehicle shoot", "B, C, V, I, G, N: Show bounding boxes, contact points, sleeping objects, impact factors,", "lights, wireframe objects", "Mouse move: Cursor control", "Mouse middle buton, ctrl: Shoot", "Mouse move + mouse left button: Grab objects", "Mouse wheel + mouse left button: Move objects to and from player", "P: Print screen to file" }); Descriptions.Add("Helicopters", new List<string>() { "Scene:", "Physical waypoints, vehicles in the air", null, null, "Input:", "+, -: Toggle scene", "R: Reset scene", "W, S, D, A, Space: Player control", "Mouse right button: Camera control", "J, K, Tab: Sun position control, Toggle camera mode", "Collision with switch: Run vehicle", "B, C, V, I, G, N: Show bounding boxes, contact points, sleeping objects, impact factors,", "lights, wireframe objects", "Mouse move: Cursor control", "Mouse middle buton, ctrl: Shoot", "Mouse move + mouse left button: Grab objects", "Mouse wheel + mouse left button: Move objects to and from player", "P: Print screen to file" }); Descriptions.Add("Buildings", new List<string>() { "Scene:", "Buildings, bridge", null, null, "Input:", "+, -: Toggle scene", "R: Reset scene", "W, S, D, A, Space: Player control", "Mouse right button: Camera control", "J, K, Tab: Sun position control, Toggle camera mode", "B, C, V, I, G, N: Show bounding boxes, contact points, sleeping objects, impact factors,", "lights, wireframe objects", "Mouse move: Cursor control", "Mouse middle buton, ctrl: Shoot", "Mouse move + mouse left button: Grab objects", "Mouse wheel + mouse left button: Move objects to and from player", "P: Print screen to file" }); Descriptions.Add("TerrainWithWater", new List<string>() { "Scene:", "Terrain, water, vehicles", null, null, "Input:", "+, -: Toggle scene", "R: Reset scene", "W, S, D, A, Space: Player control", "Mouse right button: Camera control", "J, K, Tab: Sun position control, Toggle camera mode", "Arrows up, down, right, left: Vehicle remote control", "Space + Collision with switch: Switch to driver seat", "B, C, V, I, G, N: Show bounding boxes, contact points, sleeping objects, impact factors,", "lights, wireframe objects", "Mouse move: Cursor control", "Mouse middle buton, ctrl: Shoot", "Mouse move + mouse left button: Grab objects", "Mouse wheel + mouse left button: Move objects to and from player", "P: Print screen to file" }); Descriptions.Add("Animation", new List<string>() { "Scene:", "Physical animation", null, null, "Input:", "+, -: Toggle scene", "R: Reset scene", "W, S, D, A, Space: Player control", "Mouse right button: Camera control", "J, K, Tab: Sun position control, Toggle camera mode", "B, C, V, I, G, N: Show bounding boxes, contact points, sleeping objects, impact factors,", "lights, wireframe objects", "Mouse move: Cursor control", "Mouse middle buton, ctrl: Shoot", "Mouse move + mouse left button: Grab objects", "Mouse wheel + mouse left button: Move objects to and from player", "P: Print screen to file" }); Descriptions.Add("Cloth", new List<string>() { "Scene:", "Point cloth", null, null, "Input:", "+, -: Toggle scene", "R: Reset scene", "W, S, D, A, Space: Player control", "Mouse right button: Camera control", "J, K, Tab: Sun position control, Toggle camera mode", "Collision with switch: Run machine", "B, C, V, I, G, N: Show bounding boxes, contact points, sleeping objects, impact factors,", "lights, wireframe objects", "Mouse move: Cursor control", "Mouse middle buton, ctrl: Shoot", "Mouse move + mouse left button: Grab objects", "Mouse wheel + mouse left button: Move objects to and from player", "P: Print screen to file" }); Descriptions.Add("Meshes", new List<string>() { "Scene:", "Triangle meshes", null, null, "Input:", "+, -: Toggle scene", "R: Reset scene", "W, S, D, A, Space: Player control", "Mouse right button: Camera control", "J, K, Tab: Sun position control, Toggle camera mode", "B, C, V, I, G, N: Show bounding boxes, contact points, sleeping objects, impact factors,", "lights, wireframe objects", "Mouse move: Cursor control", "Mouse middle buton, ctrl: Shoot", "Mouse move + mouse left button: Grab objects", "Mouse wheel + mouse left button: Move objects to and from player", "P: Print screen to file" }); // Create a new scene objects Scenes.Add(new DefaultShapesScene(this, "DefaultShapes", 1, "Default shapes")); Scenes.Add(new UserShapesScene(this, "UserShapes", 1, "User shapes, transparent objects, force fields, switches, triangle meshes")); Scenes.Add(new StacksScene(this, "Stacks", 1, "Stacking (Jenga, Pyramid, Wall)")); Scenes.Add(new RagdollsScene(this, "Ragdolls", 1, "Ragdolls")); Scenes.Add(new BridgesScene(this, "Bridges", 1, "Bridges, vehicle, ragdoll")); Scenes.Add(new BuildingScene(this, "Building", 1, "Building, vehicle, ragdoll, plant, particles")); Scenes.Add(new AIScene(this, "AI", 1, "Simple physical AI")); Scenes.Add(new HelicoptersScene(this, "Helicopters", 1, "Physical waypoints, vehicles in the air")); Scenes.Add(new BuildingsScene(this, "Buildings", 1, "Buildings, bridge")); Scenes.Add(new TerrainWithWaterScene(this, "TerrainWithWater", 1, "Terrain, water, vehicles")); Scenes.Add(new AnimationScene(this, "Animation", 1, "Physical animation")); Scenes.Add(new ClothScene(this, "Cloth", 1, "Point cloth")); Scenes.Add(new MeshesScene(this, "Meshes", 1, "Triangle meshes")); //Scenes.Add(new SimpleScene(this, "Simple", 1, "Simple scene")); // Create a new physics scene for the menu object MenuScene.Create(); MenuScene.Refresh(0.0); // Create a new physics scene for the scene object SceneIndex = 0; Scene = Scenes[SceneIndex]; Scene.Create(); Scene.Refresh(0.0); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void OnUnload(EventArgs e) { Meshes.Clear(); Scenes.Clear(); Textures.Clear(); Engine.Exit(); } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> protected override void OnUpdateFrame(FrameEventArgs e) { } protected void OnUpdateFrame(double time) { DemoKeyboardState keyboardState = GetKeyboardState(); if (keyboardState[Key.Escape]) this.Exit(); if (keyboardState[Key.M] && !oldKeyboardState[Key.M]) { EnableMenu = !EnableMenu; if (EnableMenu) { MenuScene.Create(); MenuScene.Refresh(0.0); } } if (keyboardState[Key.R] && !oldKeyboardState[Key.R]) { ClearAllSounds(); Scene.Remove(); Scene.Create(); Scene.Refresh(0.0); } if (keyboardState[Key.P] && !oldKeyboardState[Key.P]) { int screenCount = 1; while (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Screen" + screenCount.ToString("d3") + ".bmp")) screenCount++; Bitmap texture = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); BitmapData data = texture.LockBits(new Rectangle(0, 0, texture.Width, texture.Height), ImageLockMode.WriteOnly, texture.PixelFormat); GL.ReadPixels(0, 0, texture.Width, texture.Height, OpenTK.Graphics.OpenGL.PixelFormat.Bgr, PixelType.UnsignedByte, data.Scan0); texture.UnlockBits(data); texture.RotateFlip(RotateFlipType.RotateNoneFlipY); texture.Save(AppDomain.CurrentDomain.BaseDirectory + "Screen" + screenCount.ToString("d3") + ".bmp", ImageFormat.Bmp); } if (keyboardState[Key.Plus] && !oldKeyboardState[Key.Plus]) { ClearAllSounds(); SceneIndex = (SceneIndex + 1) % Scenes.Count; Scene = Scenes[SceneIndex]; Scene.Create(); Scene.Refresh(0.0); } if (keyboardState[Key.Minus] && !oldKeyboardState[Key.Minus]) { ClearAllSounds(); SceneIndex = (SceneIndex - 1) < 0 ? Scenes.Count - 1 : SceneIndex - 1; Scene = Scenes[SceneIndex]; Scene.Create(); Scene.Refresh(0.0); } oldKeyboardState = keyboardState; // Simulate with the synchronization bool isSimulateSynchronized = Scene.PhysicsScene.IsSimulateSynchronized(time); if (EnableMenu && isSimulateSynchronized) { int oldSceneIndex = SceneIndex; MenuScene.PhysicsScene.Simulate(time); if (SceneIndex != oldSceneIndex) { ClearAllSounds(); Scene = Scenes[SceneIndex]; Scene.Create(); Scene.Refresh(0.0); } } Scene.PhysicsScene.SimulateWithSynchronization(time); UpdateSoundQueue(); } /// <summary> /// This is called when the game should draw itself. /// </summary> protected override void OnRenderFrame(FrameEventArgs e) { double time = e.Time; OnUpdateFrame(time); // Draw with the synchronization bool isDrawSynchronized = Scene.PhysicsScene.IsDrawSynchronized(time); if (isDrawSynchronized) GL.Clear(ClearBufferMask.DepthBufferBit); Scene.PhysicsScene.DrawWithSynchronization(time); if (EnableMenu && isDrawSynchronized) { GL.Clear(ClearBufferMask.DepthBufferBit); MenuScene.PhysicsScene.Draw(time); } if (isDrawSynchronized) SwapBuffers(); } public void DrawInfo(DrawMethodArgs args) { PhysicsScene scene = Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex); int offsetX = 0; int offsetY = 0; int physicsObjectCount = scene.TotalPhysicsObjectCount; int constraintCount = scene.TotalConstraintCount; int contactPointCount = scene.TotalContactPointCount; if (EnableMenu) { physicsObjectCount += MenuScene.PhysicsScene.TotalPhysicsObjectCount; constraintCount += MenuScene.PhysicsScene.TotalConstraintCount; contactPointCount += MenuScene.PhysicsScene.TotalContactPointCount; } infoDrawFPSNameBuilder.Remove(infoDrawFPSNameLength, infoDrawFPSNameBuilder.Length - infoDrawFPSNameLength); infoDrawFPSNameBuilder.Append((int)(scene.DrawFPS + 0.5f)); infoPhysicsFPSNameBuilder.Remove(infoPhysicsFPSNameLength, infoPhysicsFPSNameBuilder.Length - infoPhysicsFPSNameLength); infoPhysicsFPSNameBuilder.Append((int)(scene.SimulationFPS + 0.5f)); infoPhysicsObjectsNameBuilder.Remove(infoPhysicsObjectsNameLength, infoPhysicsObjectsNameBuilder.Length - infoPhysicsObjectsNameLength); infoPhysicsObjectsNameBuilder.Append(physicsObjectCount); infoConstraintsNameBuilder.Remove(infoConstraintsNameLength, infoConstraintsNameBuilder.Length - infoConstraintsNameLength); infoConstraintsNameBuilder.Append(constraintCount); infoContactPointsNameBuilder.Remove(infoContactPointsNameLength, infoContactPointsNameBuilder.Length - infoContactPointsNameLength); infoContactPointsNameBuilder.Append(contactPointCount); GL.CullFace(CullFaceMode.Back); DemoFont.Begin(); DemoFont.Draw(offsetX + 15, offsetY + 15, 1.0f, 1.0f, Scene.SceneInfo, whiteColor); DemoFont.Draw(offsetX + 15, offsetY + 30, 1.0f, 1.0f, infoDrawFPSNameBuilder.ToString(), whiteColor); DemoFont.Draw(offsetX + 15, offsetY + 45, 1.0f, 1.0f, infoPhysicsFPSNameBuilder.ToString(), whiteColor); DemoFont.Draw(offsetX + 15, offsetY + 60, 1.0f, 1.0f, infoPhysicsObjectsNameBuilder.ToString(), whiteColor); DemoFont.Draw(offsetX + 15, offsetY + 75, 1.0f, 1.0f, infoConstraintsNameBuilder.ToString(), whiteColor); DemoFont.Draw(offsetX + 15, offsetY + 90, 1.0f, 1.0f, infoContactPointsNameBuilder.ToString(), whiteColor); DemoFont.Draw(offsetX + 15, offsetY + 105, 1.0f, 1.0f, infoMenuName, whiteColor); DemoFont.End(); } public void UpdateSoundQueue() { DemoSound sound; while (SoundQueue.SoundCount > 0) { sound = SoundQueue.DequeueSound(); sound.Start(); } } public void ClearAllSounds() { SoundQueue.Clear(); Dictionary<string, DemoSoundGroup>.Enumerator position = SoundGroups.GetEnumerator(); while (position.MoveNext()) position.Current.Value.ClearAllSounds(); } public static void CreateSharedShapes(Demo demo, PhysicsScene scene) { ShapePrimitive shapePrimitive = null; Shape shape = null; shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("Point"); shapePrimitive.CreatePoint(0.0f, 0.0f, 0.0f); shape = scene.Factory.ShapeManager.Create("Point"); shape.Set(shapePrimitive, Matrix4.Identity, 0.1f); shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("Edge"); shapePrimitive.CreateEdge(-Vector3.UnitY, Vector3.UnitY); shape = scene.Factory.ShapeManager.Create("Edge"); shape.Set(shapePrimitive, Matrix4.Identity, 0.1f); shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("Box"); shapePrimitive.CreateBox(1.0f); shape = scene.Factory.ShapeManager.Create("Box"); shape.Set(shapePrimitive, Matrix4.Identity, 0.0f); shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("CylinderY"); shapePrimitive.CreateCylinderY(2.0f, 1.0f); shape = scene.Factory.ShapeManager.Create("CylinderY"); shape.Set(shapePrimitive, Matrix4.Identity, 0.0f); shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("Sphere"); shapePrimitive.CreateSphere(1.0f); shape = scene.Factory.ShapeManager.Create("Sphere"); shape.Set(shapePrimitive, Matrix4.Identity, 0.0f); // Declare and initialize the displacement vector of geometric center // with negated value returned by GetCenterTranslation function // after use TranslateToCenter function in TriangleMesh class for hemisphere Vector3 centerTranslation = new Vector3(0.0f, -0.03638184f, -0.4571095f); shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("HemisphereZ"); shapePrimitive.CreateHemisphereZ(1.0f); shape = scene.Factory.ShapeManager.Create("HemisphereZ"); shape.Set(shapePrimitive, Matrix4.CreateTranslation(centerTranslation), 0.0f); shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("ConeY"); shapePrimitive.CreateConeY(2.0f, 1.0f); shape = scene.Factory.ShapeManager.Create("ConeY"); shape.Set(shapePrimitive, Matrix4.Identity, 0.0f); shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("ConeZ"); shapePrimitive.CreateConeZ(2.0f, 1.0f); shape = scene.Factory.ShapeManager.Create("ConeZ"); shape.Set(shapePrimitive, Matrix4.Identity, 0.0f); shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("CapsuleY"); shapePrimitive.CreateCapsuleY(2.0f, 1.0f); shape = scene.Factory.ShapeManager.Create("CapsuleY"); shape.Set(shapePrimitive, Matrix4.Identity, 0.0f); TriangleMesh triangleMesh = null; triangleMesh = scene.Factory.TriangleMeshManager.Create("Point"); triangleMesh.CreateSphere(5, 10, 1.0f); if (!demo.Meshes.ContainsKey("Point")) demo.Meshes.Add("Point", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, true, true, true, false, true, CullFaceMode.Back, false, false)); triangleMesh = scene.Factory.TriangleMeshManager.Create("Edge"); triangleMesh.CreateCylinderY(1, 10, 2.2f, 1.0f); if (!demo.Meshes.ContainsKey("Edge")) demo.Meshes.Add("Edge", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, true, true, true, false, true, CullFaceMode.Back, false, false)); triangleMesh = scene.Factory.TriangleMeshManager.Create("Box"); triangleMesh.CreateBox(1.0f); if (!demo.Meshes.ContainsKey("Box")) demo.Meshes.Add("Box", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, true, true, true, false, false, CullFaceMode.Back, false, false)); triangleMesh = scene.Factory.TriangleMeshManager.Create("CylinderY"); triangleMesh.CreateCylinderY(1, 15, 2.0f, 1.0f); if (!demo.Meshes.ContainsKey("CylinderY")) demo.Meshes.Add("CylinderY", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, true, true, true, false, true, CullFaceMode.Back, false, false)); triangleMesh = scene.Factory.TriangleMeshManager.Create("Sphere"); triangleMesh.CreateSphere(10, 15, 1.0f); if (!demo.Meshes.ContainsKey("Sphere")) demo.Meshes.Add("Sphere", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, true, true, true, false, true, CullFaceMode.Back, false, false)); triangleMesh = scene.Factory.TriangleMeshManager.Create("HemisphereZ"); triangleMesh.CreateHemisphereZ(5, 15, 1.0f); triangleMesh.TranslateToCenter(); if (!demo.Meshes.ContainsKey("HemisphereZ")) demo.Meshes.Add("HemisphereZ", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, true, true, true, false, true, CullFaceMode.Back, false, false)); triangleMesh = scene.Factory.TriangleMeshManager.Create("ConeY"); triangleMesh.CreateConeY(1, 15, 2.0f, 1.0f); if (!demo.Meshes.ContainsKey("ConeY")) demo.Meshes.Add("ConeY", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, true, true, true, false, true, CullFaceMode.Back, false, false)); triangleMesh = scene.Factory.TriangleMeshManager.Create("ConeZ"); triangleMesh.CreateConeZ(1, 15, 2.0f, 1.0f); if (!demo.Meshes.ContainsKey("ConeZ")) demo.Meshes.Add("ConeZ", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, true, true, true, false, true, CullFaceMode.Back, false, false)); triangleMesh = scene.Factory.TriangleMeshManager.Create("CapsuleY"); triangleMesh.CreateCapsuleY(10, 15, 2.0f, 1.0f); if (!demo.Meshes.ContainsKey("CapsuleY")) demo.Meshes.Add("CapsuleY", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, true, true, true, false, true, CullFaceMode.Back, false, false)); triangleMesh = scene.Factory.TriangleMeshManager.Create("Sky"); triangleMesh.CreateSphere(10, 10, 1.0f); if (!demo.Meshes.ContainsKey("Sky")) demo.Meshes.Add("Sky", new DemoMesh(demo, triangleMesh, demo.Textures["Sky"], Vector2.One, true, true, true, false, true, CullFaceMode.Front, false, false)); Vector3 point1, point2, point3; point1 = new Vector3(-1.0f, -1.0f, 0.0f); point2 = new Vector3(-1.0f, 1.0f, 0.0f); point3 = new Vector3(1.0f, 1.0f, 0.0f); triangleMesh = scene.Factory.TriangleMeshManager.Create("Triangle1"); triangleMesh.CreateTriangle(point1, point2, point3); if (!demo.Meshes.ContainsKey("Triangle1")) demo.Meshes.Add("Triangle1", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, false, false, true, false, true, CullFaceMode.FrontAndBack, false, false)); shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("Triangle1"); shapePrimitive.CreateTriangle(point1, point2, point3); shape = scene.Factory.ShapeManager.Create("Triangle1"); shape.Set(shapePrimitive, Matrix4.Identity, 0.01f); point1 = new Vector3(1.0f, 1.0f, 0.0f); point2 = new Vector3(1.0f, -1.0f, 0.0f); point3 = new Vector3(-1.0f, -1.0f, 0.0f); triangleMesh = scene.Factory.TriangleMeshManager.Create("Triangle2"); triangleMesh.CreateTriangle(point1, point2, point3); if (!demo.Meshes.ContainsKey("Triangle2")) demo.Meshes.Add("Triangle2", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, false, false, true, false, true, CullFaceMode.FrontAndBack, false, false)); shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("Triangle2"); shapePrimitive.CreateTriangle(point1, point2, point3); shape = scene.Factory.ShapeManager.Create("Triangle2"); shape.Set(shapePrimitive, Matrix4.Identity, 0.01f); triangleMesh = scene.Factory.TriangleMeshManager.Create("Quad"); float[] positionsX = { -1.0f, -1.0f, 1.0f, 1.0f }; float[] positionsY = { -1.0f, 1.0f, 1.0f, -1.0f }; triangleMesh.CreateWall(Vector3.Zero, Vector3.UnitZ, positionsX, positionsY); if (!demo.Meshes.ContainsKey("Quad")) demo.Meshes.Add("Quad", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, false, false, true, false, true, CullFaceMode.FrontAndBack, false, false)); } } }
// <copyright file="MurmurHash3.cs" company="Sedat Kapanoglu"> // Copyright (c) 2015-2021 Sedat Kapanoglu // MIT License (see LICENSE file for details) // </copyright> using System; using System.IO; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace HashDepot { /// <summary> /// x86 flavors of MurmurHash3 algorithms. /// </summary> public static class MurmurHash3 { /// <summary> /// Calculate 32-bit MurmurHash3 hash value. /// </summary> /// <param name="buffer">Input buffer.</param> /// <param name="seed">Seed value.</param> /// <returns>Hash value.</returns> public static uint Hash32(byte[] buffer, uint seed) { return Hash32(buffer.AsSpan(), seed); } /// <summary> /// Calculate 32-bit MurmurHash3 hash value using x86 version of the algorithm. /// </summary> /// <param name="stream">Input stream.</param> /// <param name="seed">Seed value.</param> /// <returns>Hash value.</returns> public static unsafe uint Hash32(Stream stream, uint seed) { const int uintSize = sizeof(uint); const uint final1 = 0x85ebca6b; const uint final2 = 0xc2b2ae35; const uint n = 0xe6546b64; const uint m = 5; uint hash = seed; var buffer = new byte[uintSize]; uint length = 0; int bytesRead; while ((bytesRead = stream.Read(buffer, 0, uintSize)) == uintSize) { uint k = BitConverter.ToUInt32(buffer, 0); round32(ref k, ref hash); hash = Bits.RotateLeft(hash, 13); hash *= m; hash += n; length += (uint)bytesRead; } // process remaning bytes if (bytesRead > 0) { fixed (byte* bufPtr = buffer) { uint remaining = Bits.PartialBytesToUInt32(bufPtr, bytesRead); round32(ref remaining, ref hash); } length += (uint)bytesRead; } hash ^= length; // finalization mix hash ^= hash >> 16; hash *= final1; hash ^= hash >> 13; hash *= final2; hash ^= hash >> 16; return hash; } /// <summary> /// Calculate 32-bit MurmurHash3 hash value using x86 version of the algorithm. /// </summary> /// <param name="stream">Input stream.</param> /// <param name="seed">Seed value.</param> /// <returns>A <see cref="Task"/> representing the asynchronous hash operation.</returns> public static async Task<uint> Hash32Async(Stream stream, uint seed) { const int uintSize = sizeof(uint); const uint final1 = 0x85ebca6b; const uint final2 = 0xc2b2ae35; const uint n = 0xe6546b64; const uint m = 5; uint hash = seed; var buffer = new byte[uintSize]; uint length = 0; int bytesRead; while ((bytesRead = await stream.ReadAsync(buffer.AsMemory()).ConfigureAwait(false)) == uintSize) { uint k = BitConverter.ToUInt32(buffer, 0); round32(ref k, ref hash); hash = Bits.RotateLeft(hash, 13); hash *= m; hash += n; length += (uint)bytesRead; } // process remaning bytes if (bytesRead > 0) { uint remaining = Bits.PartialBytesToUInt32(buffer, bytesRead); round32(ref remaining, ref hash); length += (uint)bytesRead; } hash ^= length; // finalization mix hash ^= hash >> 16; hash *= final1; hash ^= hash >> 13; hash *= final2; hash ^= hash >> 16; return hash; } /// <summary> /// Calculate 32-bit MurmurHash3 hash value. /// </summary> /// <param name="buffer">Input buffer.</param> /// <param name="seed">Seed value.</param> /// <returns>Hash value.</returns> public static unsafe uint Hash32(ReadOnlySpan<byte> buffer, uint seed) { const int uintSize = sizeof(uint); const uint final1 = 0x85ebca6b; const uint final2 = 0xc2b2ae35; const uint n = 0xe6546b64; const uint m = 5; uint hash = seed; int length = buffer.Length; int numUInts = Math.DivRem(length, uintSize, out int leftBytes); fixed (byte* bufPtr = buffer) { uint* pInput = (uint*)bufPtr; for (uint* pEnd = pInput + numUInts; pInput != pEnd; pInput++) { uint k = *pInput; round32(ref k, ref hash); hash = Bits.RotateLeft(hash, 13); hash *= m; hash += n; } if (leftBytes > 0) { uint remaining = Bits.PartialBytesToUInt32((byte*)pInput, leftBytes); round32(ref remaining, ref hash); } } hash ^= (uint)length; // finalization mix hash ^= hash >> 16; hash *= final1; hash ^= hash >> 13; hash *= final2; hash ^= hash >> 16; return hash; } /// <summary> /// Calculate 128-bit MurmurHash3 hash value using 64-bit version of the algorithm. /// </summary> /// <param name="stream">Input stream.</param> /// <param name="seed">Seed value.</param> /// <returns>128-bit hash value in a Span.</returns> public static unsafe byte[] Hash128(Stream stream, uint seed) { const int ulongSize = sizeof(ulong); const int blockSize = ulongSize * 2; const ulong c1 = 0x87c37b91114253d5UL; const ulong c2 = 0x4cf5ad432745937fUL; ulong h1 = seed; ulong h2 = seed; var buffer = new byte[blockSize]; int length = 0; fixed (byte* bufPtr = buffer) { int readBytes; while ((readBytes = stream.Read(buffer, 0, blockSize)) == blockSize) { ulong ik1 = BitConverter.ToUInt64(buffer, 0); ulong ik2 = BitConverter.ToUInt64(buffer, ulongSize); round128(ref ik1, ref h1, c1, c2, h2, 31, 27, 0x52dce729U); round128(ref ik2, ref h2, c2, c1, h1, 33, 31, 0x38495ab5U); length += blockSize; } ulong k1; ulong k2; if (readBytes > ulongSize) { k2 = Bits.PartialBytesToUInt64(bufPtr + ulongSize, readBytes - ulongSize); tailRound128(ref k2, ref h2, c2, c1, 33); length += readBytes - ulongSize; readBytes = ulongSize; } if (readBytes > 0) { k1 = Bits.PartialBytesToUInt64(bufPtr, readBytes); tailRound128(ref k1, ref h1, c1, c2, 31); length += readBytes; } } h1 ^= (ulong)length; h2 ^= (ulong)length; h1 += h2; h2 += h1; fmix64(ref h1); fmix64(ref h2); h1 += h2; h2 += h1; var result = new byte[16]; fixed (byte* outputPtr = result) { ulong* pOutput = (ulong*)outputPtr; pOutput[0] = h1; pOutput[1] = h2; } return result; } /// <summary> /// Calculate 128-bit MurmurHash3 hash value using x64 version of the algorithm. /// </summary> /// <param name="buffer">Input buffer.</param> /// <param name="seed">Seed value.</param> /// <returns>128-bit hash value as a Span of bytes.</returns> public static unsafe byte[] Hash128(ReadOnlySpan<byte> buffer, uint seed) { const int blockSize = 16; const ulong c1 = 0x87c37b91114253d5UL; const ulong c2 = 0x4cf5ad432745937fUL; ulong h1 = seed; ulong h2 = seed; int length = buffer.Length; int blockLen = Math.DivRem(length, blockSize, out int leftBytes); fixed (byte* bufPtr = buffer) { ulong* pItem = (ulong*)bufPtr; ulong* pEnd = (ulong*)bufPtr + (blockLen * 2); while (pItem != pEnd) { ulong ik1 = *pItem++; ulong ik2 = *pItem++; round128(ref ik1, ref h1, c1, c2, h2, 31, 27, 0x52dce729U); round128(ref ik2, ref h2, c2, c1, h1, 33, 31, 0x38495ab5U); } byte* pTail = (byte*)pItem; ulong k1; ulong k2; if (leftBytes > 8) { k2 = Bits.PartialBytesToUInt64(pTail + sizeof(ulong), leftBytes - sizeof(ulong)); tailRound128(ref k2, ref h2, c2, c1, 33); leftBytes = 8; } if (leftBytes > 0) { k1 = Bits.PartialBytesToUInt64(pTail, leftBytes); tailRound128(ref k1, ref h1, c1, c2, 31); } h1 ^= (ulong)length; h2 ^= (ulong)length; h1 += h2; h2 += h1; fmix64(ref h1); fmix64(ref h2); h1 += h2; h2 += h1; var result = new byte[16]; fixed (byte* outputPtr = result) { ulong* pOutput = (ulong*)outputPtr; pOutput[0] = h1; pOutput[1] = h2; } return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void round32(ref uint value, ref uint hash) { const uint c1 = 0xcc9e2d51; const uint c2 = 0x1b873593; value *= c1; value = Bits.RotateLeft(value, 15); value *= c2; hash ^= value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void round128( ref ulong k, ref ulong h, ulong c1, ulong c2, ulong hn, int krot, int hrot, uint x) { k *= c1; k = Bits.RotateLeft(k, krot); k *= c2; h ^= k; h = Bits.RotateLeft(h, hrot); h += hn; h = (h * 5) + x; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void fmix64(ref ulong h) { h ^= h >> 33; h *= 0xff51afd7ed558ccdUL; h ^= h >> 33; h *= 0xc4ceb9fe1a85ec53UL; h ^= h >> 33; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void tailRound128(ref ulong k, ref ulong h, ulong c1, ulong c2, int rot) { k *= c1; k = Bits.RotateLeft(k, rot); k *= c2; h ^= k; } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Mapping; using ArcGIS.Desktop.Mapping.Events; using ArcGIS.Desktop.Framework.Dialogs; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Core.Data; using ArcGIS.Core.Data.UtilityNetwork; using ArcGIS.Desktop.Core; using ArcGIS.Desktop.Core.Geoprocessing; using System.Windows.Input; using UtilityNetworkSamples; namespace CategoriesUsage { /// <summary> /// Represents the ComboBox /// </summary> internal class CategoriesComboBox : ComboBox { /// <summary> /// The selected utility network-based layer in the TOC /// </summary> private Layer myLayer; /// <summary> /// Categories Combo Box constructor /// </summary> public CategoriesComboBox() { Enabled = false; // Subscribe to the table of contents selection changed event. // This allows us to populate the combo box based on the selected layer TOCSelectionChangedEvent.Subscribe(UpdateCategoryList); } /// <summary> /// This method makes sure /// 1. The Mapview is Active /// 2. There is at least one layer selected /// 3. That layer is either /// a. A utility network layer /// b. A feature layer whose feature class belongs to a utility network /// c. A subtype group layer whose feature class belongs to a utility network /// /// If all of these hold true, we populate the combo box with the list of categories that are registered with this utility network /// </summary> private async void UpdateCategoryList(MapViewEventArgs mapViewEventArgs) { Clear(); // Verify that the map view is active and at least one layer is selected if (MapView.Active == null || mapViewEventArgs.MapView.GetSelectedLayers().Count < 1) { Enabled = false; return; } // Verify that we have the correct kind of layer Layer selectedLayer = mapViewEventArgs.MapView.GetSelectedLayers()[0]; if (!(selectedLayer is UtilityNetworkLayer) && !(selectedLayer is FeatureLayer) && !(selectedLayer is SubtypeGroupLayer)) { Enabled = false; return; } // Switch to the MCT to access the geodatabase await QueuedTask.Run(() => { // Get the utility network from the layer. // It's possible that the layer is a FeatureLayer or SubtypeGroupLayer that doesn't refer to a utility network at all. using (UtilityNetwork utilityNetwork = UtilityNetworkUtils.GetUtilityNetworkFromLayer(selectedLayer)) { if (utilityNetwork == null) { Enabled = false; return; } // Enable the combo box and clear out its contents Enabled = true; // Fill the combo box with all of the categories in the utility network using (UtilityNetworkDefinition utilityNetworkDefinition = utilityNetwork.GetDefinition()) { IReadOnlyList<string> categories = utilityNetworkDefinition.GetAvailableCategories(); foreach (string category in categories) { Add(new ComboBoxItem(category)); } } } }); // Store the layer if (Enabled) { myLayer = selectedLayer; } } /// <summary> /// The on comboBox selection change event. This creates a new table that lists the assignments for the specified category. This table is added to the map, selected in the TOC, and opened. /// </summary> /// <param name="item">The newly selected combo box item</param> protected override async void OnSelectionChange(ComboBoxItem item) { if (item == null) return; if (string.IsNullOrEmpty(item.Text)) return; if (myLayer == null) return; //Construct the name of our table for the category assignment report //Remove spaces and colons because these are not valid table names string baseCategoryReportTableName = "CategoryAssignments_" + item.Text; string categoryReportTableName = baseCategoryReportTableName.Replace(" ", "_"); categoryReportTableName = categoryReportTableName.Replace(":", "_"); bool needToCreateTable = true; bool needToAddStandaloneTable = true; // Switch to the MCT to access the geodatabase await QueuedTask.Run(() => { // Check if the table exists using (Geodatabase projectWorkspace = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(Project.Current.DefaultGeodatabasePath)))) { try { using (Table categoryReportTable = projectWorkspace.OpenDataset<Table>(categoryReportTableName)) { // Table exists, we do not need to create it... needToCreateTable = false; // .. but we should delete the existing contents categoryReportTable.DeleteRows(new QueryFilter()); // Check to see if a Standalone table exists in the map bool standaloneTableFound = false; ReadOnlyObservableCollection<StandaloneTable> initialStandaloneTables = MapView.Active.Map.StandaloneTables; foreach (StandaloneTable standaloneTable in initialStandaloneTables) { if (standaloneTable.Name == categoryReportTableName) standaloneTableFound = true; } // Since there is already a StandaloneTable that references our category table in the map, we don't need to add it needToAddStandaloneTable = !standaloneTableFound; } } catch { //Table doesn't exist. Not an error, but we will have to create it } } }); // Create the category report table if (needToCreateTable) { // Create table IReadOnlyList<string> createParams = Geoprocessing.MakeValueArray(new object[] { Project.Current.DefaultGeodatabasePath, categoryReportTableName, null, null }); IGPResult result = await Geoprocessing.ExecuteToolAsync("management.CreateTable", createParams); if (result.IsFailed) { MessageBox.Show("Unable to create category assignment table in project workspace", "Category Assignments"); return; } // Add field for feature class alias IReadOnlyList<string> addFieldParams = Geoprocessing.MakeValueArray(new object[] { categoryReportTableName, "FeatureClassAlias", "TEXT", null, null, 32, "Table", "NULLABLE", "NON_REQUIRED", null }); result = await Geoprocessing.ExecuteToolAsync("management.AddField", addFieldParams); if (result.IsFailed) { MessageBox.Show("Unable to modify schema of category assignment table in project workspace", "Category Assignments"); return; } // Add field for Asset Group name addFieldParams = Geoprocessing.MakeValueArray(new object[] { categoryReportTableName, "AssetGroupName", "TEXT", null, null, 256, "Asset Group Name", "NULLABLE", "NON_REQUIRED", null }); result = await Geoprocessing.ExecuteToolAsync("management.AddField", addFieldParams); if (result.IsFailed) { MessageBox.Show("Unable to modify schema of category assignment table in project workspace", "Category Assignments"); return; } // Add field for Asset Type name addFieldParams = Geoprocessing.MakeValueArray(new object[] { categoryReportTableName, "AssetTypeName", "TEXT", null, null, 256, "Asset Type Name", "NULLABLE", "NON_REQUIRED", null }); result = await Geoprocessing.ExecuteToolAsync("management.AddField", addFieldParams); if (result.IsFailed) { MessageBox.Show("Unable to modify schema of category assignment table in project workspace", "Category Assignments"); return; } needToAddStandaloneTable = false; //creating a table automatically adds it to the map } // Populate table // Again, we need to switch to the MCT to execute geodatabase and utility network code await QueuedTask.Run(() => { using (Geodatabase projectWorkspace = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(Project.Current.DefaultGeodatabasePath)))) using (Table categoryReportTable = projectWorkspace.OpenDataset<Table>(categoryReportTableName)) using (UtilityNetwork utilityNetwork = UtilityNetworkSamples.UtilityNetworkUtils.GetUtilityNetworkFromLayer(myLayer)) using (UtilityNetworkDefinition utilityNetworkDefinition = utilityNetwork.GetDefinition()) { IReadOnlyList<NetworkSource> networkSources = utilityNetworkDefinition.GetNetworkSources(); // Step through each NetworkSource foreach (NetworkSource networkSource in networkSources) { IReadOnlyList<AssetGroup> assetGroups = networkSource.GetAssetGroups(); // Step through each AssetGroup foreach (AssetGroup assetGroup in assetGroups) { IReadOnlyList<AssetType> assetTypes = assetGroup.GetAssetTypes(); // Step through each AssetType foreach (AssetType assetType in assetTypes) { // Check to see if this AssetType is assigned the Category we are looking for IReadOnlyList<string> assignedCategoryList = assetType.CategoryList; foreach (string assignedCategory in assignedCategoryList) { if (assignedCategory == item.Text) { // Our Category is assigned to this AssetType. Create a row to store in the category report table using (Table networkSourceTable = utilityNetwork.GetTable(networkSource)) using (TableDefinition networkSourceTableDefinition = networkSourceTable.GetDefinition()) using (RowBuffer rowBuffer = categoryReportTable.CreateRowBuffer()) { rowBuffer["FeatureClassAlias"] = networkSourceTableDefinition.GetAliasName(); rowBuffer["AssetGroupName"] = assetGroup.Name; rowBuffer["AssetTypeName"] = assetType.Name; categoryReportTable.CreateRow(rowBuffer).Dispose(); } } } } } } // If necessary, add our category report table to the map as a standalone table if (needToAddStandaloneTable) { IStandaloneTableFactory tableFactory = StandaloneTableFactory.Instance; tableFactory.CreateStandaloneTable(categoryReportTable, MapView.Active.Map); } } }); // Open category report stand alone table into a window ReadOnlyObservableCollection<StandaloneTable> standaloneTables = MapView.Active.Map.StandaloneTables; foreach (StandaloneTable standaloneTable in standaloneTables) { if (standaloneTable.Name == categoryReportTableName) FrameworkApplication.Panes.OpenTablePane(standaloneTable, TableViewMode.eAllRecords); } } } }
// // mTouch-PDFReader library // PageView.cs // // Copyright (c) 2012-2014 AlexanderMac(amatsibarov@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // 'Software'), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Drawing; using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using mTouchPDFReader.Library.Managers; using mTouchPDFReader.Library.Data.Enums; namespace mTouchPDFReader.Library.Views.Core { public class PageView : UIScrollView { #region Data private const float ContentViewPadding = 5.0f; private const int ThumbContentSize = 500; private readonly PageContentView _pageContentView; // TODO: private readonly ThumbView _thumbView; private readonly UIView _pageContentContainerView; private float _zoomScaleStep; public int PageNumber { get { return _pageContentView.PageNumber; } set { _pageContentView.PageNumber = value; } } public bool NeedUpdateZoomAndOffset { get; set; } public AutoScaleModes AutoScaleMode { get; set; } #endregion #region Logic public PageView(RectangleF frame, AutoScaleModes autoScaleMode, int pageNumber) : base(frame) { ScrollsToTop = false; DelaysContentTouches = false; ShowsVerticalScrollIndicator = false; ShowsHorizontalScrollIndicator = false; ContentMode = UIViewContentMode.Redraw; AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; UserInteractionEnabled = true; AutosizesSubviews = false; BackgroundColor = UIColor.Clear; ViewForZoomingInScrollView = delegate(UIScrollView sender) { return _pageContentContainerView; }; AutoScaleMode = autoScaleMode; NeedUpdateZoomAndOffset = true; _pageContentView = new PageContentView(PageContentView.GetPageViewSize(pageNumber), pageNumber); _pageContentContainerView = new UIView(_pageContentView.Bounds); _pageContentContainerView.AutosizesSubviews = false; _pageContentContainerView.UserInteractionEnabled = false; _pageContentContainerView.ContentMode = UIViewContentMode.Redraw; _pageContentContainerView.AutoresizingMask = UIViewAutoresizing.None; _pageContentContainerView.Layer.CornerRadius = 5; _pageContentContainerView.Layer.ShadowOffset = new SizeF(2.0f, 2.0f); _pageContentContainerView.Layer.ShadowRadius = 4.0f; _pageContentContainerView.Layer.ShadowOpacity = 1.0f; _pageContentContainerView.Layer.ShadowPath = UIBezierPath.FromRect(_pageContentContainerView.Bounds).CGPath; _pageContentContainerView.BackgroundColor = UIColor.White; // TODO: _ThumbView = new ThumbView(_PageContentView.Bounds, ThumbContentSize, pageNumber); // TODO: _PageContentContainerView.AddSubview(_ThumbView); _pageContentContainerView.AddSubview(_pageContentView); AddSubview(_pageContentContainerView); ContentSize = _pageContentView.Bounds.Size; ContentOffset = new PointF((0.0f - ContentViewPadding), (0.0f - ContentViewPadding)); ContentInset = new UIEdgeInsets(ContentViewPadding, ContentViewPadding, ContentViewPadding, ContentViewPadding); ContentSize = _pageContentContainerView.Bounds.Size; } public override void LayoutSubviews() { base.LayoutSubviews(); if (NeedUpdateZoomAndOffset) { updateMinimumMaximumZoom(); resetZoom(); resetScrollOffset(); NeedUpdateZoomAndOffset = false; } alignPageContentView(); } public override void TouchesBegan(NSSet touches, UIEvent evt) { base.TouchesBegan(touches, evt); if (MgrAccessor.SettingsMgr.Settings.AllowZoomByDoubleTouch) { var touch = touches.AnyObject as UITouch; if (touch.TapCount == 2) { ZoomIncrement(); } } } private void alignPageContentView() { SizeF boundsSize = Bounds.Size; RectangleF viewFrame = _pageContentContainerView.Frame; if (viewFrame.Size.Width < boundsSize.Width) { viewFrame.X = (boundsSize.Width - viewFrame.Size.Width) / 2.0f + ContentOffset.X; } else { viewFrame.X = 0.0f; } if (viewFrame.Size.Height < boundsSize.Height) { viewFrame.Y = (boundsSize.Height - viewFrame.Size.Height) / 2.0f + ContentOffset.Y; } else { viewFrame.Y = 0.0f; } _pageContentContainerView.Frame = viewFrame; } private float getZoomScaleThatFits(SizeF target, SizeF source) { float wScale = target.Width / source.Width; float hScale = target.Height / source.Height; var factor = AutoScaleMode == AutoScaleModes.AutoWidth ? (wScale < hScale ? hScale : wScale) : (wScale < hScale ? wScale : hScale); return factor; } private void updateMinimumMaximumZoom() { RectangleF targetRect = RectangleFExtensions.Inset(Bounds, ContentViewPadding, ContentViewPadding); float zoomScale = getZoomScaleThatFits(targetRect.Size, _pageContentView.Bounds.Size); MinimumZoomScale = zoomScale; MaximumZoomScale = zoomScale * MgrAccessor.SettingsMgr.Settings.ZoomScaleLevels; _zoomScaleStep = (MaximumZoomScale - MinimumZoomScale) / MgrAccessor.SettingsMgr.Settings.ZoomScaleLevels; } private void resetScrollOffset() { SetContentOffset(new PointF(0.0f, 0.0f), false); } private void resetZoom() { ZoomScale = MinimumZoomScale; } public void ZoomDecrement() { float zoomScale = ZoomScale; if (zoomScale > MinimumZoomScale) { zoomScale -= _zoomScaleStep; if (zoomScale < MinimumZoomScale) { zoomScale = MinimumZoomScale; } SetZoomScale(zoomScale, true); } } public void ZoomIncrement() { float zoomScale = ZoomScale; if (zoomScale < MaximumZoomScale) { zoomScale += _zoomScaleStep; if (zoomScale > MaximumZoomScale) { zoomScale = MaximumZoomScale; } SetZoomScale(zoomScale, true); } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation.GoToDefinition; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.GeneratedCodeRecognition; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices { [Export(typeof(VisualStudioWorkspace))] [Export(typeof(VisualStudioWorkspaceImpl))] internal class RoslynVisualStudioWorkspace : VisualStudioWorkspaceImpl { private readonly IEnumerable<Lazy<INavigableItemsPresenter>> _navigableItemsPresenters; private readonly IEnumerable<Lazy<IReferencedSymbolsPresenter>> _referencedSymbolsPresenters; [ImportingConstructor] private RoslynVisualStudioWorkspace( SVsServiceProvider serviceProvider, SaveEventsService saveEventsService, [ImportMany] IEnumerable<Lazy<INavigableItemsPresenter>> navigableItemsPresenters, [ImportMany] IEnumerable<Lazy<IReferencedSymbolsPresenter>> referencedSymbolsPresenters) : base( serviceProvider, backgroundWork: WorkspaceBackgroundWork.ParseAndCompile) { PrimaryWorkspace.Register(this); InitializeStandardVisualStudioWorkspace(serviceProvider, saveEventsService); _navigableItemsPresenters = navigableItemsPresenters; _referencedSymbolsPresenters = referencedSymbolsPresenters; } public override EnvDTE.FileCodeModel GetFileCodeModel(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } var project = ProjectTracker.GetProject(documentId.ProjectId); if (project == null) { throw new ArgumentException(ServicesVSResources.DocumentIdNotFromWorkspace, "documentId"); } var document = project.GetDocumentOrAdditionalDocument(documentId); if (document == null) { throw new ArgumentException(ServicesVSResources.DocumentIdNotFromWorkspace, "documentId"); } var provider = project as IProjectCodeModelProvider; if (provider != null) { var projectCodeModel = provider.ProjectCodeModel; if (projectCodeModel.CanCreateFileCodeModelThroughProject(document.FilePath)) { return (EnvDTE.FileCodeModel)projectCodeModel.CreateFileCodeModelThroughProject(document.FilePath); } } return null; } internal override bool RenameFileCodeModelInstance(DocumentId documentId, string newFilePath) { if (documentId == null) { return false; } var project = ProjectTracker.GetProject(documentId.ProjectId); if (project == null) { return false; } var document = project.GetDocumentOrAdditionalDocument(documentId); if (document == null) { return false; } var codeModelProvider = project as IProjectCodeModelProvider; if (codeModelProvider == null) { return false; } var codeModelCache = codeModelProvider.ProjectCodeModel.GetCodeModelCache(); if (codeModelCache == null) { return false; } codeModelCache.OnSourceFileRenaming(document.FilePath, newFilePath); return true; } internal override IInvisibleEditor OpenInvisibleEditor(DocumentId documentId) { var hostDocument = GetHostDocument(documentId); return OpenInvisibleEditor(hostDocument); } internal override IInvisibleEditor OpenInvisibleEditor(IVisualStudioHostDocument hostDocument) { // We need to ensure the file is saved, only if a global undo transaction is open var globalUndoService = this.Services.GetService<IGlobalUndoService>(); bool needsSave = globalUndoService.IsGlobalTransactionOpen(this); bool needsUndoDisabled = needsSave && this.Services.GetService<IGeneratedCodeRecognitionService>().IsGeneratedCode(this.CurrentSolution.GetDocument(hostDocument.Id)); return new InvisibleEditor(ServiceProvider, hostDocument.FilePath, needsSave, needsUndoDisabled); } private static bool TryResolveSymbol(ISymbol symbol, Project project, CancellationToken cancellationToken, out ISymbol resolvedSymbol, out Project resolvedProject) { resolvedSymbol = null; resolvedProject = null; var currentProject = project.Solution.Workspace.CurrentSolution.GetProject(project.Id); if (currentProject == null) { return false; } var originalCompilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var symbolId = SymbolKey.Create(symbol, originalCompilation, cancellationToken); var currentCompilation = currentProject.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var symbolInfo = symbolId.Resolve(currentCompilation, cancellationToken: cancellationToken); if (symbolInfo.Symbol == null) { return false; } resolvedSymbol = symbolInfo.Symbol; resolvedProject = currentProject; return true; } public override bool TryGoToDefinition(ISymbol symbol, Project project, CancellationToken cancellationToken) { if (!_navigableItemsPresenters.Any()) { return false; } ISymbol searchSymbol; Project searchProject; if (!TryResolveSymbol(symbol, project, cancellationToken, out searchSymbol, out searchProject)) { return false; } return GoToDefinitionHelpers.TryGoToDefinition( searchSymbol, searchProject, _navigableItemsPresenters, containingTypeSymbol: null, throwOnHiddenDefinition: false, cancellationToken: cancellationToken); } public override bool TryFindAllReferences(ISymbol symbol, Project project, CancellationToken cancellationToken) { if (!_referencedSymbolsPresenters.Any()) { return false; } ISymbol searchSymbol; Project searchProject; if (!TryResolveSymbol(symbol, project, cancellationToken, out searchSymbol, out searchProject)) { return false; } var searchSolution = searchProject.Solution; var result = SymbolFinder .FindReferencesAsync(searchSymbol, searchSolution, cancellationToken) .WaitAndGetResult(cancellationToken).ToList(); if (result != null) { DisplayReferencedSymbols(searchSolution, result); return true; } return false; } public override void DisplayReferencedSymbols(Solution solution, IEnumerable<ReferencedSymbol> referencedSymbols) { foreach (var presenter in _referencedSymbolsPresenters) { presenter.Value.DisplayResult(solution, referencedSymbols); } } internal override object GetBrowseObject(SymbolListItem symbolListItem) { var compilation = symbolListItem.GetCompilation(this); if (compilation == null) { return null; } var symbol = symbolListItem.ResolveSymbol(compilation); var sourceLocation = symbol.Locations.Where(l => l.IsInSource).FirstOrDefault(); if (sourceLocation == null) { return null; } var projectId = symbolListItem.ProjectId; if (projectId == null) { return null; } var project = this.CurrentSolution.GetProject(projectId); if (project == null) { return null; } var codeModelService = project.LanguageServices.GetService<ICodeModelService>(); if (codeModelService == null) { return null; } var tree = sourceLocation.SourceTree; var document = project.GetDocument(tree); var vsFileCodeModel = this.GetFileCodeModel(document.Id); var fileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(vsFileCodeModel); if (fileCodeModel != null) { var syntaxNode = tree.GetRoot().FindNode(sourceLocation.SourceSpan); while (syntaxNode != null) { if (!codeModelService.TryGetNodeKey(syntaxNode).IsEmpty) { break; } syntaxNode = syntaxNode.Parent; } if (syntaxNode != null) { var codeElement = fileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(syntaxNode); if (codeElement != null) { return codeElement; } } } return null; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace RestfullService.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; using System.Linq; using System.Threading.Tasks; using OmniSharp.Models; using Xunit; namespace OmniSharp.Tests { public class HighlightFacts { [Fact] public async Task HighlightSingleLine() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new OmnisharpController(workspace, new FakeOmniSharpOptions()); var regions = await controller.Highlight(new HighlightRequest() { FileName = "a.cs", Lines = new[] { 4 } }); AssertSyntax(regions.Highlights, code, 3, Token("class", "keyword"), Token("C1", "class name"), Token("{", "punctuation"), Token("int", "keyword"), Token("n", "identifier"), Token("=", "operator"), Token("true", "keyword"), Token(";", "punctuation"), Token("}", "punctuation")); } [Fact] public async Task HighlightEntireFile() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new OmnisharpController(workspace, new FakeOmniSharpOptions()); var regions = await controller.Highlight(new HighlightRequest() { FileName = "a.cs" }); AssertSyntax(regions.Highlights, code, 0, Token("namespace", "keyword"), Token("N1", "identifier"), Token("{", "punctuation"), Token("class", "keyword"), Token("C1", "class name"), Token("{", "punctuation"), Token("int", "keyword"), Token("n", "identifier"), Token("=", "operator"), Token("true", "keyword"), Token(";", "punctuation"), Token("}", "punctuation"), Token("}", "punctuation")); } [Fact] public async Task HighlightStringInterpolation() { var code = @" class C1 { string s = $""{5}""; } "; var workspace = TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new OmnisharpController(workspace, new FakeOmniSharpOptions()); var regions = await controller.Highlight(new HighlightRequest() { FileName = "a.cs" }); AssertSyntax(regions.Highlights, code, 0, Token("class", "keyword"), Token("C1", "class name"), Token("{", "punctuation"), Token("string", "keyword"), Token("s", "identifier"), Token("=", "operator"), Token("$\"", "string"), Token("{", "punctuation"), Token("5", "number"), Token("}", "punctuation"), Token("\"", "string"), Token(";", "punctuation"), Token("}", "punctuation")); } private void AssertSyntax(IEnumerable<HighlightSpan> regions, string code, int startLine, params TokenSpec[] expected) { var arr = regions.ToArray(); var lineNo = startLine; var lastIndex = 0; var lines = Microsoft.CodeAnalysis.Text.SourceText.From(code).Lines; for (var i = 0; i < arr.Length; i++) { var tokenSpec = expected[i]; var region = arr[i]; string line; int start, end; do { line = lines[lineNo].ToString(); start = line.IndexOf(tokenSpec.Text, lastIndex); if (start == -1) { if(++lineNo >= lines.Count) { throw new Exception($"Could not find token {tokenSpec.Text} in the code"); } lastIndex = 0; } } while (start == -1); end = start + tokenSpec.Text.Length; lastIndex = end; Assert.Equal(tokenSpec.Kind, region.Kind); Assert.Equal(lineNo, region.StartLine - 1); Assert.Equal(lineNo, region.EndLine - 1); Assert.Equal(start, region.StartColumn - 1); Assert.Equal(end, region.EndColumn - 1); } Assert.Equal(expected.Length, arr.Length); } [Fact] public async Task HighlightExcludesUnwantedKeywords() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new OmnisharpController(workspace, new FakeOmniSharpOptions()); var regions = await controller.Highlight(new HighlightRequest() { FileName = "a.cs", ExcludeClassifications = new [] { HighlightClassification.Keyword } }); Assert.DoesNotContain(regions.Highlights, x => x.Kind == "keyword"); } [Fact] public async Task HighlightExcludesUnwantedPunctuation() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new OmnisharpController(workspace, new FakeOmniSharpOptions()); var regions = await controller.Highlight(new HighlightRequest() { FileName = "a.cs", ExcludeClassifications = new [] { HighlightClassification.Punctuation } }); Assert.DoesNotContain(regions.Highlights, x => x.Kind == "punctuation"); } [Fact] public async Task HighlightExcludesUnwantedOperators() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new OmnisharpController(workspace, new FakeOmniSharpOptions()); var regions = await controller.Highlight(new HighlightRequest() { FileName = "a.cs", ExcludeClassifications = new [] { HighlightClassification.Operator } }); Assert.DoesNotContain(regions.Highlights, x => x.Kind == "operator"); } [Fact] public async Task HighlightExcludesUnwantedIdentifiers() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new OmnisharpController(workspace, new FakeOmniSharpOptions()); var regions = await controller.Highlight(new HighlightRequest() { FileName = "a.cs", ExcludeClassifications = new [] { HighlightClassification.Identifier } }); Assert.DoesNotContain(regions.Highlights, x => x.Kind == "identifier"); } [Fact] public async Task HighlightExcludesUnwantedNames() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new OmnisharpController(workspace, new FakeOmniSharpOptions()); var regions = await controller.Highlight(new HighlightRequest() { FileName = "a.cs", ExcludeClassifications = new [] { HighlightClassification.Name } }); Assert.DoesNotContain(regions.Highlights, x => x.Kind.EndsWith(" name")); } private TokenSpec Token(string text, string kind) { return new TokenSpec(kind, text); } private class TokenSpec { public string Text { get; } public string Kind { get; } public TokenSpec(string kind, string text) { Kind = kind; Text = text; } } } }
using ClosedXML.Excel; using NUnit.Framework; using System; using System.Globalization; using System.Threading; namespace ClosedXML_Tests.Excel.CalcEngine { [TestFixture] public class InformationTests { [OneTimeSetUp] public void SetCultureInfo() { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); } #region IsBlank Tests [Test] public void IsBlank_MultipleAllEmpty_true() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); var actual = ws.Evaluate("=IsBlank(A1:A3)"); Assert.AreEqual(true, actual); } } [Test] public void IsBlank_MultipleAllFill_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "1"; ws.Cell("A2").Value = "1"; ws.Cell("A3").Value = "1"; var actual = ws.Evaluate("=IsBlank(A1:A3)"); Assert.AreEqual(false, actual); } } [Test] public void IsBlank_MultipleMixedFill_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "1"; ws.Cell("A3").Value = "1"; var actual = ws.Evaluate("=IsBlank(A1:A3)"); Assert.AreEqual(false, actual); } } [Test] public void IsBlank_Single_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = " "; var actual = ws.Evaluate("=IsBlank(A1)"); Assert.AreEqual(false, actual); } } [Test] public void IsBlank_Single_true() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); var actual = ws.Evaluate("=IsBlank(A1)"); Assert.AreEqual(true, actual); } } #endregion IsBlank Tests #region IsEven Tests [Test] public void IsEven_Single_False() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = 1; ws.Cell("A2").Value = 1.2; ws.Cell("A3").Value = 3; var actual = ws.Evaluate("=IsEven(A1)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsEven(A2)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsEven(A3)"); Assert.AreEqual(false, actual); } } [Test] public void IsEven_Single_True() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = 4; ws.Cell("A2").Value = 0.2; ws.Cell("A3").Value = 12.2; var actual = ws.Evaluate("=IsEven(A1)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsEven(A2)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsEven(A3)"); Assert.AreEqual(true, actual); } } #endregion IsEven Tests #region IsLogical Tests [Test] public void IsLogical_Simpe_False() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = 123; var actual = ws.Evaluate("=IsLogical(A1)"); Assert.AreEqual(false, actual); } } [Test] public void IsLogical_Simple_True() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = true; var actual = ws.Evaluate("=IsLogical(A1)"); Assert.AreEqual(true, actual); } } #endregion IsLogical Tests #region IsNotText Tests [Test] public void IsNotText_Simple_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "asd"; var actual = ws.Evaluate("=IsNonText(A1)"); Assert.AreEqual(false, actual); } } [Test] public void IsNotText_Simple_true() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "123"; //Double Value ws.Cell("A2").Value = DateTime.Now; //Date Value ws.Cell("A3").Value = "12,235.5"; //Comma Formatting ws.Cell("A4").Value = "$12,235.5"; //Currency Value ws.Cell("A5").Value = true; //Bool Value ws.Cell("A6").Value = "12%"; //Percentage Value var actual = ws.Evaluate("=IsNonText(A1)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNonText(A2)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNonText(A3)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNonText(A4)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNonText(A5)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNonText(A6)"); Assert.AreEqual(true, actual); } } #endregion IsNotText Tests #region IsNumber Tests [Test] public void IsNumber_Simple_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "asd"; //String Value ws.Cell("A2").Value = true; //Bool Value var actual = ws.Evaluate("=IsNumber(A1)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsNumber(A2)"); Assert.AreEqual(false, actual); } } [Test] public void IsNumber_Simple_true() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "123"; //Double Value ws.Cell("A2").Value = DateTime.Now; //Date Value ws.Cell("A3").Value = "12,235.5"; //Coma Formatting ws.Cell("A4").Value = "$12,235.5"; //Currency Value ws.Cell("A5").Value = "12%"; //Percentage Value var actual = ws.Evaluate("=IsNumber(A1)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNumber(A2)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNumber(A3)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNumber(A4)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsNumber(A5)"); Assert.AreEqual(true, actual); } } #endregion IsNumber Tests #region IsOdd Test [Test] public void IsOdd_Simple_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = 4; ws.Cell("A2").Value = 0.2; ws.Cell("A3").Value = 12.2; var actual = ws.Evaluate("=IsOdd(A1)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsOdd(A2)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsOdd(A3)"); Assert.AreEqual(false, actual); } } [Test] public void IsOdd_Simple_true() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = 1; ws.Cell("A2").Value = 1.2; ws.Cell("A3").Value = 3; var actual = ws.Evaluate("=IsOdd(A1)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsOdd(A2)"); Assert.AreEqual(true, actual); actual = ws.Evaluate("=IsOdd(A3)"); Assert.AreEqual(true, actual); } } #endregion IsOdd Test #region IsText Tests [Test] public void IsText_Simple_false() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "123"; //Double Value ws.Cell("A2").Value = DateTime.Now; //Date Value ws.Cell("A3").Value = "12,235.5"; //Comma Formatting ws.Cell("A4").Value = "$12,235.5"; //Currency Value ws.Cell("A5").Value = true; //Bool Value ws.Cell("A6").Value = "12%"; //Percentage Value var actual = ws.Evaluate("=IsText(A1)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsText(A2)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsText(A3)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsText(A4)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsText(A5)"); Assert.AreEqual(false, actual); actual = ws.Evaluate("=IsText(A6)"); Assert.AreEqual(false, actual); } } [Test] public void IsText_Simple_true() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "asd"; var actual = ws.Evaluate("=IsText(A1)"); Assert.AreEqual(true, actual); } } #endregion IsText Tests #region N Tests [Test] public void N_Date_SerialNumber() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); var testedDate = DateTime.Now; ws.Cell("A1").Value = testedDate; var actual = ws.Evaluate("=N(A1)"); Assert.AreEqual(testedDate.ToOADate(), actual); } } [Test] public void N_False_Zero() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = false; var actual = ws.Evaluate("=N(A1)"); Assert.AreEqual(0, actual); } } [Test] public void N_Number_Number() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); var testedValue = 123; ws.Cell("A1").Value = testedValue; var actual = ws.Evaluate("=N(A1)"); Assert.AreEqual(testedValue, actual); } } [Test] public void N_String_Zero() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = "asd"; var actual = ws.Evaluate("=N(A1)"); Assert.AreEqual(0, actual); } } [Test] public void N_True_One() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet"); ws.Cell("A1").Value = true; var actual = ws.Evaluate("=N(A1)"); Assert.AreEqual(1, actual); } } #endregion N Tests } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Text.RegularExpressions; namespace Cassandra { /// <summary> /// A date without a time-zone in the ISO-8601 calendar system. /// LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day. /// This class is implemented to match the Date representation CQL string literals. /// </summary> public class LocalDate: IComparable<LocalDate>, IEquatable<LocalDate> { /// <summary> /// Day number relatively to the year based on the month index /// </summary> private static readonly int[] DaysToMonth = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; private static readonly int[] DaysToMonthLeap = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}; // unix epoch is represented by the number 2 ^ 31 private const long DateCenter = 2147483648L; private const long DaysFromYear0ToUnixEpoch = 719528L; // ReSharper disable once InconsistentNaming private const long DaysFromYear0March1stToUnixEpoch = LocalDate.DaysFromYear0ToUnixEpoch - 60L; private static readonly Regex RegexInteger = new Regex("^-?\\d+$", RegexOptions.Compiled); private const string BadFormatMessage = "LocalDate must be provided in the yyyy-mm-dd format or in days since epoch"; /// <summary> /// An unsigned integer representing days with epoch centered at 2^31 (unix epoch January 1st, 1970). /// </summary> internal uint DaysSinceEpochCentered { get; } public int Day { get; set; } public int Month { get; set; } public int Year { get; set; } /// <summary> /// Creates a new instance based on the days since unix epoch. /// </summary> /// <param name="days">An unsigned integer representing days with epoch centered at 2^31.</param> internal LocalDate(uint days) { DaysSinceEpochCentered = days; InitializeFromDaysSinceEpoch(days - LocalDate.DateCenter); } /// <summary> /// Port from https://github.com/HowardHinnant/date which is based on http://howardhinnant.github.io/date_algorithms.html /// There's a good explanation of the algorithm over there. /// </summary> /// <param name="daysSinceEpoch">Days since Epoch (January 1st, 1970), can be negative.</param> private void InitializeFromDaysSinceEpoch(long daysSinceEpoch) { var daysSinceShiftedEpoch = daysSinceEpoch + LocalDate.DaysFromYear0March1stToUnixEpoch; // shift epoch from 1970-01-01 to 0000-03-01 var era = // compute era (400 year period) (daysSinceShiftedEpoch >= 0 ? daysSinceShiftedEpoch : daysSinceShiftedEpoch - 146096) / 146097; var dayOfEra = (daysSinceShiftedEpoch - era * 146097); // [0, 146096] var yearOfEra = (dayOfEra - dayOfEra/1460 + dayOfEra/36524 - dayOfEra/146096) / 365; // [0, 399] var dayOfYear = dayOfEra - (365*yearOfEra + yearOfEra/4 - yearOfEra/100); // [0, 365] var monthInternal = (5*dayOfYear + 2)/153; // [0, 11] var yearInternal = yearOfEra + era * 400; // beginning in Mar 1st, NOT in Jan 1st var day = dayOfYear - (153*monthInternal+2)/5 + 1; // [1, 31] var monthCivil = monthInternal + (monthInternal < 10 ? 3 : -9); // [1, 12] var yearCivil = yearInternal + (monthCivil <= 2 ? 1 : 0); // shift to beginning in Jan 1st Year = (int) yearCivil; Month = (int) monthCivil; Day = (int) day; } /// <summary> /// Creates a new instance of LocalDate /// </summary> /// <param name="year">Year according to ISO-8601. Year 0 represents 1 BC.</param> /// <param name="month">The month number from 1 to 12</param> /// <param name="day">A day of the month from 1 to 31.</param> public LocalDate(int year, int month, int day) { if (year > 5881580 || year < -5877641) { throw new ArgumentOutOfRangeException("year", month, "Year is out of range"); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", month, "Month is out of range"); } if (year == 5881580 && month * 100 + day > 711) { throw new ArgumentOutOfRangeException("year", "Date is outside the boundaries of a LocalDate representation"); } if (year == -5877641 && month * 100 + day < 623) { throw new ArgumentOutOfRangeException("year", "Date is outside the boundaries of a LocalDate representation"); } Year = year; Month = month; Day = day; var value = DaysSinceYearZero(year) + DaysSinceJan1(year, month, day) - DaysFromYear0ToUnixEpoch + DateCenter + (year > 0 ? 1L : 0L); DaysSinceEpochCentered = Convert.ToUInt32(value); } /// <summary> /// Returns the value in days since year zero (1 BC). /// </summary> /// <param name="year"></param> private static long DaysSinceYearZero(int year) { return ( //days per year year * 365L + //adjusted per leap years LeapDays(year)); } /// <summary> /// Returns the amount of days since Jan 1, for a given month/day /// </summary> public static int DaysSinceJan1(int year, int month, int day) { var daysToMonth = IsLeapYear(year) ? DaysToMonthLeap : DaysToMonth; if (day < 1 || day > daysToMonth[month] - daysToMonth[month - 1]) { throw new ArgumentOutOfRangeException("day"); } return ( //days to the month in the year daysToMonth[month - 1] //the amount of month days + day - 1); } /// <param name="year">0-based year number: 0 equals to 1 AD</param> private static long LeapDays(long year) { var result = year/4 - year/100 + year/400; if (year > 0 && IsLeapYear((int)year)) { result--; } return result; } private static bool IsLeapYear(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } /// <summary> /// Compares this instance value to another and returns an indication of their relative values. /// </summary> /// <param name="other"></param> /// <returns></returns> public int CompareTo(LocalDate other) { if ((object) other == null) { return 1; } return DaysSinceEpochCentered.CompareTo(other.DaysSinceEpochCentered); } /// <summary> /// Determines if the value is equal to this instance. /// </summary> public bool Equals(LocalDate other) { return CompareTo(other) == 0; } /// <summary> /// Creates a new instance of <see cref="LocalDate"/> using the year, month and day provided in the form: /// yyyy-mm-dd or days since epoch (i.e. -1 for Dec 31, 1969). /// </summary> public static LocalDate Parse(string value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (RegexInteger.IsMatch(value)) { return new LocalDate(Convert.ToUInt32(DateCenter + long.Parse(value))); } var parts = value.Split('-'); if (parts.Length < 3) { throw new FormatException(BadFormatMessage); } var sign = parts[0].Length == 0 ? -1 : 1; var index = 0; if (sign == -1) { index = 1; if (parts.Length != 4) { throw new FormatException(BadFormatMessage); } } return new LocalDate(sign * Convert.ToInt32(parts[index]), Convert.ToInt32(parts[index + 1]), Convert.ToInt32(parts[index + 2])); } /// <summary> /// Returns the DateTimeOffset representation of the LocalDate for dates between 0001-01-01 and 9999-12-31 /// </summary> public DateTimeOffset ToDateTimeOffset() { if (Year < 1 || Year > 9999) { throw new ArgumentOutOfRangeException("The LocalDate can not be converted to DateTimeOffset", (Exception) null); } return new DateTimeOffset(Year, Month, Day, 0, 0, 0, 0, TimeSpan.Zero); } /// <summary> /// Returns the string representation of the LocalDate in yyyy-MM-dd format /// </summary> public override string ToString() { var yearString = Year.ToString(); if (Year >= 0 && Year < 1000) { yearString = Utils.FillZeros(Year, 4); } return yearString + "-" + Utils.FillZeros(Month) + "-" + Utils.FillZeros(Day); } public static bool operator ==(LocalDate value1, LocalDate value2) { // If both are null, or both are same instance, return true. if (ReferenceEquals(value1, value2)) { return true; } // If one is null, but not both, return false. if (((object)value1 == null) || ((object)value2 == null)) { return false; } return value1.Equals(value2); } public static bool operator >=(LocalDate value1, LocalDate value2) { return value1.CompareTo(value2) >= 0; } public static bool operator >(LocalDate value1, LocalDate value2) { return value1.CompareTo(value2) > 0; } public static bool operator <=(LocalDate value1, LocalDate value2) { return value1.CompareTo(value2) <= 0; } public static bool operator <(LocalDate value1, LocalDate value2) { return value1.CompareTo(value2) < 0; } public static bool operator !=(LocalDate value1, LocalDate value2) { // If both are null, or both are same instance, return false. if (ReferenceEquals(value1, value2)) { return false; } // If one is null, but not both, return true. if (((object)value1 == null) || ((object)value2 == null)) { return true; } return !value1.Equals(value2); } public override int GetHashCode() { return DaysSinceEpochCentered.GetHashCode(); } public override bool Equals(object obj) { var other = obj as LocalDate; return other != null && CompareTo(other) == 0; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { [Export(typeof(IPreviewFactoryService)), Shared] internal class PreviewFactoryService : ForegroundThreadAffinitizedObject, IPreviewFactoryService { private const double DefaultZoomLevel = 0.75; private readonly ITextViewRoleSet _previewRoleSet; private readonly ITextBufferFactoryService _textBufferFactoryService; private readonly IContentTypeRegistryService _contentTypeRegistryService; private readonly IProjectionBufferFactoryService _projectionBufferFactoryService; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; private readonly ITextDifferencingSelectorService _differenceSelectorService; private readonly IDifferenceBufferFactoryService _differenceBufferService; private readonly IWpfDifferenceViewerFactoryService _differenceViewerService; [ImportingConstructor] public PreviewFactoryService( ITextBufferFactoryService textBufferFactoryService, IContentTypeRegistryService contentTypeRegistryService, IProjectionBufferFactoryService projectionBufferFactoryService, ITextEditorFactoryService textEditorFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, ITextDifferencingSelectorService differenceSelectorService, IDifferenceBufferFactoryService differenceBufferService, IWpfDifferenceViewerFactoryService differenceViewerService) { _textBufferFactoryService = textBufferFactoryService; _contentTypeRegistryService = contentTypeRegistryService; _projectionBufferFactoryService = projectionBufferFactoryService; _editorOptionsFactoryService = editorOptionsFactoryService; _differenceSelectorService = differenceSelectorService; _differenceBufferService = differenceBufferService; _differenceViewerService = differenceViewerService; _previewRoleSet = textEditorFactoryService.CreateTextViewRoleSet( TextViewRoles.PreviewRole, PredefinedTextViewRoles.Analyzable); } public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, CancellationToken cancellationToken) { return GetSolutionPreviews(oldSolution, newSolution, DefaultZoomLevel, cancellationToken); } public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: The order in which previews are added to the below list is significant. // Preview for a changed document is preferred over preview for changed references and so on. var previewItems = new List<SolutionPreviewItem>(); SolutionChangeSummary changeSummary = null; if (newSolution != null) { var solutionChanges = newSolution.GetChanges(oldSolution); foreach (var projectChanges in solutionChanges.GetProjectChanges()) { cancellationToken.ThrowIfCancellationRequested(); var projectId = projectChanges.ProjectId; var oldProject = projectChanges.OldProject; var newProject = projectChanges.NewProject; foreach (var documentId in projectChanges.GetChangedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateChangedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), newSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetAddedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateAddedDocumentPreviewViewAsync(newSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetRemovedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, c => CreateRemovedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetChangedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateChangedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), newSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetAddedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateAddedAdditionalDocumentPreviewViewAsync(newSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetRemovedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, c => CreateRemovedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var metadataReference in projectChanges.GetAddedMetadataReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Adding_reference_0_to_1, metadataReference.Display, oldProject.Name))); } foreach (var metadataReference in projectChanges.GetRemovedMetadataReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Removing_reference_0_from_1, metadataReference.Display, oldProject.Name))); } foreach (var projectReference in projectChanges.GetAddedProjectReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Adding_reference_0_to_1, newSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name))); } foreach (var projectReference in projectChanges.GetRemovedProjectReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Removing_reference_0_from_1, oldSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name))); } foreach (var analyzer in projectChanges.GetAddedAnalyzerReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Adding_analyzer_reference_0_to_1, analyzer.Display, oldProject.Name))); } foreach (var analyzer in projectChanges.GetRemovedAnalyzerReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Removing_analyzer_reference_0_from_1, analyzer.Display, oldProject.Name))); } } foreach (var project in solutionChanges.GetAddedProjects()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(project.Id, null, string.Format(EditorFeaturesResources.Adding_project_0, project.Name))); } foreach (var project in solutionChanges.GetRemovedProjects()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(project.Id, null, string.Format(EditorFeaturesResources.Removing_project_0, project.Name))); } foreach (var projectChanges in solutionChanges.GetProjectChanges().Where(ProjectReferencesChanged)) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(projectChanges.OldProject.Id, null, string.Format(EditorFeaturesResources.Changing_project_references_for_0, projectChanges.OldProject.Name))); } changeSummary = new SolutionChangeSummary(oldSolution, newSolution, solutionChanges); } return new SolutionPreviewResult(previewItems, changeSummary); } private bool ProjectReferencesChanged(ProjectChanges projectChanges) { var oldProjectReferences = projectChanges.OldProject.ProjectReferences.ToDictionary(r => r.ProjectId); var newProjectReferences = projectChanges.NewProject.ProjectReferences.ToDictionary(r => r.ProjectId); // These are the set of project reference that remained in the project. We don't care // about project references that were added or removed. Those will already be reported. var preservedProjectIds = oldProjectReferences.Keys.Intersect(newProjectReferences.Keys); foreach (var projectId in preservedProjectIds) { var oldProjectReference = oldProjectReferences[projectId]; var newProjectReference = newProjectReferences[projectId]; if (!oldProjectReference.Equals(newProjectReference)) { return true; } } return false; } public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken) { return CreateAddedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken); } private Task<object> CreateAddedDocumentPreviewViewCoreAsync(ITextBuffer newBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var firstLine = string.Format(EditorFeaturesResources.Adding_0_to_1_with_content_colon, document.Name, document.Project.Name); var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService); var span = new SnapshotSpan(newBuffer.CurrentSnapshot, Span.FromBounds(0, newBuffer.CurrentSnapshot.Length)) .CreateTrackingSpan(SpanTrackingMode.EdgeExclusive); var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService); return CreateNewDifferenceViewerAsync(null, workspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var newBuffer = CreateNewBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var rightWorkspace = new PreviewWorkspace( document.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution); rightWorkspace.OpenDocument(document.Id); return CreateAddedDocumentPreviewViewCoreAsync(newBuffer, rightWorkspace, document, zoomLevel, cancellationToken); } public Task<object> CreateAddedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var newBuffer = CreateNewPlainTextBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var rightWorkspace = new PreviewWorkspace( document.Project.Solution.WithAdditionalDocumentText(document.Id, newBuffer.AsTextContainer().CurrentText)); rightWorkspace.OpenAdditionalDocument(document.Id); return CreateAddedDocumentPreviewViewCoreAsync(newBuffer, rightWorkspace, document, zoomLevel, cancellationToken); } public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken) { return CreateRemovedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken); } private Task<object> CreateRemovedDocumentPreviewViewCoreAsync(ITextBuffer oldBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var firstLine = string.Format(EditorFeaturesResources.Removing_0_from_1_with_content_colon, document.Name, document.Project.Name); var span = new SnapshotSpan(oldBuffer.CurrentSnapshot, Span.FromBounds(0, oldBuffer.CurrentSnapshot.Length)) .CreateTrackingSpan(SpanTrackingMode.EdgeExclusive); var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService); var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService); return CreateNewDifferenceViewerAsync(workspace, null, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and possibly open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var leftDocument = document.Project .RemoveDocument(document.Id) .AddDocument(document.Name, oldBuffer.AsTextContainer().CurrentText); var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution); leftWorkspace.OpenDocument(leftDocument.Id); return CreateRemovedDocumentPreviewViewCoreAsync(oldBuffer, leftWorkspace, leftDocument, zoomLevel, cancellationToken); } public Task<object> CreateRemovedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and possibly open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewPlainTextBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var leftDocumentId = DocumentId.CreateNewId(document.Project.Id); var leftSolution = document.Project.Solution .RemoveAdditionalDocument(document.Id) .AddAdditionalDocument(leftDocumentId, document.Name, oldBuffer.AsTextContainer().CurrentText); var leftDocument = leftSolution.GetAdditionalDocument(leftDocumentId); var leftWorkspace = new PreviewWorkspace(leftSolution); leftWorkspace.OpenAdditionalDocument(leftDocumentId); return CreateRemovedDocumentPreviewViewCoreAsync(oldBuffer, leftWorkspace, leftDocument, zoomLevel, cancellationToken); } public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) { return CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, DefaultZoomLevel, cancellationToken); } public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and currently open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewBuffer(oldDocument, cancellationToken); var newBuffer = CreateNewBuffer(newDocument, cancellationToken); // Convert the diffs to be line based. // Compute the diffs between the old text and the new. var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken); // Need to show the spans in the right that are different. // We also need to show the spans that are in conflict. var originalSpans = GetOriginalSpans(diffResult, cancellationToken); var changedSpans = GetChangedSpans(diffResult, cancellationToken); var description = default(string); var allSpans = default(NormalizedSpanCollection); if (newDocument.SupportsSyntaxTree) { var newRoot = newDocument.GetSyntaxRootSynchronously(cancellationToken); var conflictNodes = newRoot.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind); var conflictSpans = conflictNodes.Select(n => n.Span.ToSpan()).ToList(); var conflictDescriptions = conflictNodes.SelectMany(n => n.GetAnnotations(ConflictAnnotation.Kind)) .Select(a => ConflictAnnotation.GetDescription(a)) .Distinct(); var warningNodes = newRoot.GetAnnotatedNodesAndTokens(WarningAnnotation.Kind); var warningSpans = warningNodes.Select(n => n.Span.ToSpan()).ToList(); var warningDescriptions = warningNodes.SelectMany(n => n.GetAnnotations(WarningAnnotation.Kind)) .Select(a => WarningAnnotation.GetDescription(a)) .Distinct(); var suppressDiagnosticsNodes = newRoot.GetAnnotatedNodesAndTokens(SuppressDiagnosticsAnnotation.Kind); var suppressDiagnosticsSpans = suppressDiagnosticsNodes.Select(n => n.Span.ToSpan()).ToList(); AttachAnnotationsToBuffer(newBuffer, conflictSpans, warningSpans, suppressDiagnosticsSpans); description = conflictSpans.Count == 0 && warningSpans.Count == 0 ? null : string.Join(Environment.NewLine, conflictDescriptions.Concat(warningDescriptions)); allSpans = new NormalizedSpanCollection(conflictSpans.Concat(warningSpans).Concat(changedSpans)); } else { allSpans = new NormalizedSpanCollection(changedSpans); } var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken); var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, allSpans, cancellationToken); if (!originalLineSpans.Any()) { // This means that we have no differences (likely because of conflicts). // In such cases, use the same spans for the left (old) buffer as the right (new) buffer. originalLineSpans = changedLineSpans; } // Create PreviewWorkspaces around the buffers to be displayed on the left and right // so that all IDE services (colorizer, squiggles etc.) light up in these buffers. var leftDocument = oldDocument.Project .RemoveDocument(oldDocument.Id) .AddDocument(oldDocument.Name, oldBuffer.AsTextContainer().CurrentText, oldDocument.Folders, oldDocument.FilePath); var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution); leftWorkspace.OpenDocument(leftDocument.Id); var rightWorkspace = new PreviewWorkspace( newDocument.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution); rightWorkspace.OpenDocument(newDocument.Id); return CreateChangedDocumentViewAsync( oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans, leftWorkspace, rightWorkspace, zoomLevel, cancellationToken); } public Task<object> CreateChangedAdditionalDocumentPreviewViewAsync(TextDocument oldDocument, TextDocument newDocument, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and currently open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewPlainTextBuffer(oldDocument, cancellationToken); var newBuffer = CreateNewPlainTextBuffer(newDocument, cancellationToken); // Convert the diffs to be line based. // Compute the diffs between the old text and the new. var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken); // Need to show the spans in the right that are different. var originalSpans = GetOriginalSpans(diffResult, cancellationToken); var changedSpans = GetChangedSpans(diffResult, cancellationToken); string description = null; var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken); var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, changedSpans, cancellationToken); // TODO: Why aren't we attaching conflict / warning annotations here like we do for regular documents above? // Create PreviewWorkspaces around the buffers to be displayed on the left and right // so that all IDE services (colorizer, squiggles etc.) light up in these buffers. var leftDocumentId = DocumentId.CreateNewId(oldDocument.Project.Id); var leftSolution = oldDocument.Project.Solution .RemoveAdditionalDocument(oldDocument.Id) .AddAdditionalDocument(leftDocumentId, oldDocument.Name, oldBuffer.AsTextContainer().CurrentText); var leftWorkspace = new PreviewWorkspace(leftSolution); leftWorkspace.OpenAdditionalDocument(leftDocumentId); var rightWorkSpace = new PreviewWorkspace( oldDocument.Project.Solution.WithAdditionalDocumentText(oldDocument.Id, newBuffer.AsTextContainer().CurrentText)); rightWorkSpace.OpenAdditionalDocument(newDocument.Id); return CreateChangedDocumentViewAsync( oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans, leftWorkspace, rightWorkSpace, zoomLevel, cancellationToken); } private Task<object> CreateChangedDocumentViewAsync(ITextBuffer oldBuffer, ITextBuffer newBuffer, string description, List<LineSpan> originalSpans, List<LineSpan> changedSpans, PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!(originalSpans.Any() && changedSpans.Any())) { // Both line spans must be non-empty. Otherwise, below projection buffer factory API call will throw. // So if either is empty (signaling that there are no changes to preview in the document), then we bail out. // This can happen in cases where the user has already applied the fix and light bulb has already been dismissed, // but platform hasn't cancelled the preview operation yet. Since the light bulb has already been dismissed at // this point, the preview that we return will never be displayed to the user. So returning null here is harmless. return SpecializedTasks.Default<object>(); } var originalBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation( _contentTypeRegistryService, _editorOptionsFactoryService.GlobalOptions, oldBuffer.CurrentSnapshot, "...", description, originalSpans.ToArray()); var changedBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation( _contentTypeRegistryService, _editorOptionsFactoryService.GlobalOptions, newBuffer.CurrentSnapshot, "...", description, changedSpans.ToArray()); return CreateNewDifferenceViewerAsync(leftWorkspace, rightWorkspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } private static void AttachAnnotationsToBuffer( ITextBuffer newBuffer, IEnumerable<Span> conflictSpans, IEnumerable<Span> warningSpans, IEnumerable<Span> suppressDiagnosticsSpans) { // Attach the spans to the buffer. newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.ConflictSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, conflictSpans)); newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.WarningSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, warningSpans)); newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.SuppressDiagnosticsSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, suppressDiagnosticsSpans)); } private ITextBuffer CreateNewBuffer(Document document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // is it okay to create buffer from threads other than UI thread? var contentTypeService = document.Project.LanguageServices.GetService<IContentTypeLanguageService>(); var contentType = contentTypeService.GetDefaultContentType(); return _textBufferFactoryService.CreateTextBuffer( document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType); } private ITextBuffer CreateNewPlainTextBuffer(TextDocument document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var contentType = _textBufferFactoryService.TextContentType; return _textBufferFactoryService.CreateTextBuffer( document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType); } private async Task<object> CreateNewDifferenceViewerAsync( PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace, IProjectionBuffer originalBuffer, IProjectionBuffer changedBuffer, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // leftWorkspace can be null if the change is adding a document. // rightWorkspace can be null if the change is removing a document. // However both leftWorkspace and rightWorkspace can't be null at the same time. Contract.ThrowIfTrue((leftWorkspace == null) && (rightWorkspace == null)); var diffBuffer = _differenceBufferService.CreateDifferenceBuffer( originalBuffer, changedBuffer, new StringDifferenceOptions(), disableEditing: true); var diffViewer = _differenceViewerService.CreateDifferenceView(diffBuffer, _previewRoleSet); diffViewer.Closed += (s, e) => { // Workaround Editor bug. The editor has an issue where they sometimes crash when // trying to apply changes to projection buffer. So, when the user actually invokes // a SuggestedAction we may then edit a text buffer, which the editor will then // try to propagate through the projections we have here over that buffer. To ensure // that that doesn't happen, we clear out the projections first so that this crash // won't happen. originalBuffer.DeleteSpans(0, originalBuffer.CurrentSnapshot.SpanCount); changedBuffer.DeleteSpans(0, changedBuffer.CurrentSnapshot.SpanCount); leftWorkspace?.Dispose(); leftWorkspace = null; rightWorkspace?.Dispose(); rightWorkspace = null; }; const string DiffOverviewMarginName = "deltadifferenceViewerOverview"; if (leftWorkspace == null) { diffViewer.ViewMode = DifferenceViewMode.RightViewOnly; diffViewer.RightView.ZoomLevel *= zoomLevel; diffViewer.RightHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } else if (rightWorkspace == null) { diffViewer.ViewMode = DifferenceViewMode.LeftViewOnly; diffViewer.LeftView.ZoomLevel *= zoomLevel; diffViewer.LeftHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } else { diffViewer.ViewMode = DifferenceViewMode.Inline; diffViewer.InlineView.ZoomLevel *= zoomLevel; diffViewer.InlineHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } // Disable focus / tab stop for the diff viewer. diffViewer.RightView.VisualElement.Focusable = false; diffViewer.LeftView.VisualElement.Focusable = false; diffViewer.InlineView.VisualElement.Focusable = false; // This code path must be invoked on UI thread. AssertIsForeground(); // We use ConfigureAwait(true) to stay on the UI thread. await diffViewer.SizeToFitAsync().ConfigureAwait(true); leftWorkspace?.EnableDiagnostic(); rightWorkspace?.EnableDiagnostic(); return new DifferenceViewerPreview(diffViewer); } private List<LineSpan> CreateLineSpans(ITextSnapshot textSnapshot, NormalizedSpanCollection allSpans, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var result = new List<LineSpan>(); foreach (var span in allSpans) { cancellationToken.ThrowIfCancellationRequested(); var lineSpan = GetLineSpan(textSnapshot, span); MergeLineSpans(result, lineSpan); } return result; } // Find the lines that surround the span of the difference. Try to expand the span to // include both the previous and next lines so that we can show more context to the // user. private LineSpan GetLineSpan( ITextSnapshot snapshot, Span span) { var startLine = snapshot.GetLineNumberFromPosition(span.Start); var endLine = snapshot.GetLineNumberFromPosition(span.End); if (startLine > 0) { startLine--; } if (endLine < snapshot.LineCount) { endLine++; } return LineSpan.FromBounds(startLine, endLine); } // Adds a line span to the spans we've been collecting. If the line span overlaps or // abuts a previous span then the two are merged. private static void MergeLineSpans(List<LineSpan> lineSpans, LineSpan nextLineSpan) { if (lineSpans.Count > 0) { var lastLineSpan = lineSpans.Last(); // We merge them if there's no more than one line between the two. Otherwise // we'd show "..." between two spans where we could just show the actual code. if (nextLineSpan.Start >= lastLineSpan.Start && nextLineSpan.Start <= (lastLineSpan.End + 1)) { nextLineSpan = LineSpan.FromBounds(lastLineSpan.Start, nextLineSpan.End); lineSpans.RemoveAt(lineSpans.Count - 1); } } lineSpans.Add(nextLineSpan); } private IHierarchicalDifferenceCollection ComputeEditDifferences(TextDocument oldDocument, TextDocument newDocument, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Get the text that's actually in the editor. var oldText = oldDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var newText = newDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); // Defer to the editor to figure out what changes the client made. var diffService = _differenceSelectorService.GetTextDifferencingService( oldDocument.Project.LanguageServices.GetService<IContentTypeLanguageService>().GetDefaultContentType()); diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService; return diffService.DiffStrings(oldText.ToString(), newText.ToString(), new StringDifferenceOptions() { DifferenceType = StringDifferenceTypes.Word | StringDifferenceTypes.Line, }); } private NormalizedSpanCollection GetOriginalSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var lineSpans = new List<Span>(); foreach (var difference in diffResult) { cancellationToken.ThrowIfCancellationRequested(); var mappedSpan = diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left); lineSpans.Add(mappedSpan); } return new NormalizedSpanCollection(lineSpans); } private NormalizedSpanCollection GetChangedSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var lineSpans = new List<Span>(); foreach (var difference in diffResult) { cancellationToken.ThrowIfCancellationRequested(); var mappedSpan = diffResult.RightDecomposition.GetSpanInOriginal(difference.Right); lineSpans.Add(mappedSpan); } return new NormalizedSpanCollection(lineSpans); } } }
/* * 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.Reflection; using System.Threading; using log4net; using OpenSim.Framework; using OpenSim.Framework.RegionLoader.Filesystem; using OpenSim.Framework.RegionLoader.Web; using OpenSim.Region.CoreModules.Agent.AssetTransaction; using OpenSim.Region.CoreModules.Avatar.InstantMessage; using OpenSim.Region.CoreModules.Scripting.DynamicTexture; using OpenSim.Region.CoreModules.Scripting.LoadImageURL; using OpenSim.Region.CoreModules.Scripting.XMLRPC; namespace OpenSim.ApplicationPlugins.LoadRegions { public class LoadRegionsPlugin : IApplicationPlugin, IRegionCreator { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public event NewRegionCreated OnNewRegionCreated; private NewRegionCreated m_newRegionCreatedHandler; #region IApplicationPlugin Members // TODO: required by IPlugin, but likely not at all right private string m_name = "LoadRegionsPlugin"; private string m_version = "0.0"; public string Version { get { return m_version; } } public string Name { get { return m_name; } } protected OpenSimBase m_openSim; public void Initialise() { m_log.Error("[LOAD REGIONS PLUGIN]: " + Name + " cannot be default-initialized!"); throw new PluginNotInitialisedException(Name); } public void Initialise(OpenSimBase openSim) { m_openSim = openSim; m_openSim.ApplicationRegistry.RegisterInterface<IRegionCreator>(this); } public void PostInitialise() { //m_log.Info("[LOADREGIONS]: Load Regions addin being initialised"); IRegionLoader regionLoader; if (m_openSim.ConfigSource.Source.Configs["Startup"].GetString("region_info_source", "filesystem") == "filesystem") { m_log.Info("[LOAD REGIONS PLUGIN]: Loading region configurations from filesystem"); regionLoader = new RegionLoaderFileSystem(); } else { m_log.Info("[LOAD REGIONS PLUGIN]: Loading region configurations from web"); regionLoader = new RegionLoaderWebServer(); } regionLoader.SetIniConfigSource(m_openSim.ConfigSource.Source); RegionInfo[] regionsToLoad = regionLoader.LoadRegions(); m_log.Info("[LOAD REGIONS PLUGIN]: Loading specific shared modules..."); m_log.Info("[LOAD REGIONS PLUGIN]: DynamicTextureModule..."); m_openSim.ModuleLoader.LoadDefaultSharedModule(new DynamicTextureModule()); m_log.Info("[LOAD REGIONS PLUGIN]: LoadImageURLModule..."); m_openSim.ModuleLoader.LoadDefaultSharedModule(new LoadImageURLModule()); m_log.Info("[LOAD REGIONS PLUGIN]: XMLRPCModule..."); m_openSim.ModuleLoader.LoadDefaultSharedModule(new XMLRPCModule()); // m_log.Info("[LOADREGIONSPLUGIN]: AssetTransactionModule..."); // m_openSim.ModuleLoader.LoadDefaultSharedModule(new AssetTransactionModule()); m_log.Info("[LOAD REGIONS PLUGIN]: Done."); if (!CheckRegionsForSanity(regionsToLoad)) { m_log.Error("[LOAD REGIONS PLUGIN]: Halting startup due to conflicts in region configurations"); Environment.Exit(1); } for (int i = 0; i < regionsToLoad.Length; i++) { IScene scene; m_log.Debug("[LOAD REGIONS PLUGIN]: Creating Region: " + regionsToLoad[i].RegionName + " (ThreadID: " + Thread.CurrentThread.ManagedThreadId.ToString() + ")"); m_openSim.PopulateRegionEstateInfo(regionsToLoad[i]); m_openSim.CreateRegion(regionsToLoad[i], true, out scene); regionsToLoad[i].EstateSettings.Save(); if (scene != null) { m_newRegionCreatedHandler = OnNewRegionCreated; if (m_newRegionCreatedHandler != null) { m_newRegionCreatedHandler(scene); } } } m_openSim.ModuleLoader.PostInitialise(); m_openSim.ModuleLoader.ClearCache(); } public void Dispose() { } #endregion /// <summary> /// Check that region configuration information makes sense. /// </summary> /// <param name="regions"></param> /// <returns>True if we're sane, false if we're insane</returns> private bool CheckRegionsForSanity(RegionInfo[] regions) { if (regions.Length <= 1) return true; for (int i = 0; i < regions.Length - 1; i++) { for (int j = i + 1; j < regions.Length; j++) { if (regions[i].RegionID == regions[j].RegionID) { m_log.ErrorFormat( "[LOAD REGIONS PLUGIN]: Regions {0} and {1} have the same UUID {2}", regions[i].RegionName, regions[j].RegionName, regions[i].RegionID); return false; } else if ( regions[i].RegionLocX == regions[j].RegionLocX && regions[i].RegionLocY == regions[j].RegionLocY) { m_log.ErrorFormat( "[LOAD REGIONS PLUGIN]: Regions {0} and {1} have the same grid location ({2}, {3})", regions[i].RegionName, regions[j].RegionName, regions[i].RegionLocX, regions[i].RegionLocY); return false; } else if (regions[i].InternalEndPoint.Port == regions[j].InternalEndPoint.Port) { m_log.ErrorFormat( "[LOAD REGIONS PLUGIN]: Regions {0} and {1} have the same internal IP port {2}", regions[i].RegionName, regions[j].RegionName, regions[i].InternalEndPoint.Port); return false; } } } return true; } public void LoadRegionFromConfig(OpenSimBase openSim, ulong regionhandle) { m_log.Info("[LOADREGIONS]: Load Regions addin being initialised"); IRegionLoader regionLoader; if (openSim.ConfigSource.Source.Configs["Startup"].GetString("region_info_source", "filesystem") == "filesystem") { m_log.Info("[LOADREGIONS]: Loading Region Info from filesystem"); regionLoader = new RegionLoaderFileSystem(); } else { m_log.Info("[LOADREGIONS]: Loading Region Info from web"); regionLoader = new RegionLoaderWebServer(); } regionLoader.SetIniConfigSource(openSim.ConfigSource.Source); RegionInfo[] regionsToLoad = regionLoader.LoadRegions(); for (int i = 0; i < regionsToLoad.Length; i++) { if (regionhandle == regionsToLoad[i].RegionHandle) { IScene scene; m_log.Debug("[LOADREGIONS]: Creating Region: " + regionsToLoad[i].RegionName + " (ThreadID: " + Thread.CurrentThread.ManagedThreadId.ToString() + ")"); openSim.CreateRegion(regionsToLoad[i], true, out scene); } } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // using System; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Text; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Diagnostics.Contracts; namespace System.Security.Principal { // // Identifier authorities // internal enum IdentifierAuthority : long { NullAuthority = 0, WorldAuthority = 1, LocalAuthority = 2, CreatorAuthority = 3, NonUniqueAuthority = 4, NTAuthority = 5, SiteServerAuthority = 6, InternetSiteAuthority = 7, ExchangeAuthority = 8, ResourceManagerAuthority = 9, } // // SID name usage // internal enum SidNameUse { User = 1, Group = 2, Domain = 3, Alias = 4, WellKnownGroup = 5, DeletedAccount = 6, Invalid = 7, Unknown = 8, Computer = 9, } // // Well-known SID types // [System.Runtime.InteropServices.ComVisible(false)] public enum WellKnownSidType { NullSid = 0, WorldSid = 1, LocalSid = 2, CreatorOwnerSid = 3, CreatorGroupSid = 4, CreatorOwnerServerSid = 5, CreatorGroupServerSid = 6, NTAuthoritySid = 7, DialupSid = 8, NetworkSid = 9, BatchSid = 10, InteractiveSid = 11, ServiceSid = 12, AnonymousSid = 13, ProxySid = 14, EnterpriseControllersSid = 15, SelfSid = 16, AuthenticatedUserSid = 17, RestrictedCodeSid = 18, TerminalServerSid = 19, RemoteLogonIdSid = 20, LogonIdsSid = 21, LocalSystemSid = 22, LocalServiceSid = 23, NetworkServiceSid = 24, BuiltinDomainSid = 25, BuiltinAdministratorsSid = 26, BuiltinUsersSid = 27, BuiltinGuestsSid = 28, BuiltinPowerUsersSid = 29, BuiltinAccountOperatorsSid = 30, BuiltinSystemOperatorsSid = 31, BuiltinPrintOperatorsSid = 32, BuiltinBackupOperatorsSid = 33, BuiltinReplicatorSid = 34, BuiltinPreWindows2000CompatibleAccessSid = 35, BuiltinRemoteDesktopUsersSid = 36, BuiltinNetworkConfigurationOperatorsSid = 37, AccountAdministratorSid = 38, AccountGuestSid = 39, AccountKrbtgtSid = 40, AccountDomainAdminsSid = 41, AccountDomainUsersSid = 42, AccountDomainGuestsSid = 43, AccountComputersSid = 44, AccountControllersSid = 45, AccountCertAdminsSid = 46, AccountSchemaAdminsSid = 47, AccountEnterpriseAdminsSid = 48, AccountPolicyAdminsSid = 49, AccountRasAndIasServersSid = 50, NtlmAuthenticationSid = 51, DigestAuthenticationSid = 52, SChannelAuthenticationSid = 53, ThisOrganizationSid = 54, OtherOrganizationSid = 55, BuiltinIncomingForestTrustBuildersSid = 56, BuiltinPerformanceMonitoringUsersSid = 57, BuiltinPerformanceLoggingUsersSid = 58, BuiltinAuthorizationAccessSid = 59, WinBuiltinTerminalServerLicenseServersSid= 60, MaxDefined = WinBuiltinTerminalServerLicenseServersSid, } // // This class implements revision 1 SIDs // NOTE: The SecurityIdentifier class is immutable and must remain this way // [System.Runtime.InteropServices.ComVisible(false)] public sealed class SecurityIdentifier : IdentityReference, IComparable<SecurityIdentifier> { #region Public Constants // // Identifier authority must be at most six bytes long // internal static readonly long MaxIdentifierAuthority = 0xFFFFFFFFFFFF; // // Maximum number of subauthorities in a SID // internal static readonly byte MaxSubAuthorities = 15; // // Minimum length of a binary representation of a SID // public static readonly int MinBinaryLength = 1 + 1 + 6; // Revision (1) + subauth count (1) + identifier authority (6) // // Maximum length of a binary representation of a SID // public static readonly int MaxBinaryLength = 1 + 1 + 6 + MaxSubAuthorities * 4; // 4 bytes for each subauth #endregion #region Private Members // // Immutable properties of a SID // private IdentifierAuthority _IdentifierAuthority; private int[] _SubAuthorities; private byte[] _BinaryForm; private SecurityIdentifier _AccountDomainSid; bool _AccountDomainSidInitialized = false; // // Computed attributes of a SID // private string _SddlForm = null; #endregion #region Constructors // // Shared constructor logic // NOTE: subauthorities are really unsigned integers, but due to CLS // lack of support for unsigned integers the caller must perform // the typecast // private void CreateFromParts( IdentifierAuthority identifierAuthority, int[] subAuthorities ) { if ( subAuthorities == null ) { throw new ArgumentNullException( "subAuthorities" ); } Contract.EndContractBlock(); // // Check the number of subauthorities passed in // if ( subAuthorities.Length > MaxSubAuthorities ) { throw new ArgumentOutOfRangeException( "subAuthorities.Length", subAuthorities.Length, Environment.GetResourceString( "IdentityReference_InvalidNumberOfSubauthorities", MaxSubAuthorities)); } // // Identifier authority is atmost 6 bytes long // if ( identifierAuthority < 0 || (long) identifierAuthority > MaxIdentifierAuthority ) { throw new ArgumentOutOfRangeException( "identifierAuthority", identifierAuthority, Environment.GetResourceString( "IdentityReference_IdentifierAuthorityTooLarge" )); } // // Create a local copy of the data passed in // _IdentifierAuthority = identifierAuthority; _SubAuthorities = new int[ subAuthorities.Length ]; subAuthorities.CopyTo( _SubAuthorities, 0 ); // // Compute and store the binary form // // typedef struct _SID { // UCHAR Revision; // UCHAR SubAuthorityCount; // SID_IDENTIFIER_AUTHORITY IdentifierAuthority; // ULONG SubAuthority[ANYSIZE_ARRAY] // } SID, *PISID; // byte i; _BinaryForm = new byte[1 + 1 + 6 + 4 * this.SubAuthorityCount]; // // First two bytes contain revision and subauthority count // _BinaryForm[0] = Revision; _BinaryForm[1] = ( byte )this.SubAuthorityCount; // // Identifier authority takes up 6 bytes // for ( i = 0; i < 6; i++ ) { _BinaryForm[2+i] = ( byte )(((( ulong )this._IdentifierAuthority ) >> (( 5 - i ) * 8 )) & 0xFF ) ; } // // Subauthorities go last, preserving big-endian representation // for ( i = 0; i < this.SubAuthorityCount; i++ ) { byte shift; for ( shift = 0; shift < 4; shift += 1 ) { _BinaryForm[8 + 4*i + shift] = ( byte )((( ulong )_SubAuthorities[i] ) >> ( shift * 8 )); } } } private void CreateFromBinaryForm( byte[] binaryForm, int offset ) { // // Give us something to work with // if ( binaryForm == null ) { throw new ArgumentNullException( "binaryForm" ); } // // Negative offsets are not allowed // if ( offset < 0 ) { throw new ArgumentOutOfRangeException( "offset", offset, Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" )); } // // At least a minimum-size SID should fit in the buffer // if ( binaryForm.Length - offset < SecurityIdentifier.MinBinaryLength ) { throw new ArgumentOutOfRangeException( "binaryForm", Environment.GetResourceString( "ArgumentOutOfRange_ArrayTooSmall" )); } Contract.EndContractBlock(); IdentifierAuthority Authority; int[] SubAuthorities; // // Extract the elements of a SID // if ( binaryForm[offset] != Revision ) { // // Revision is incorrect // throw new ArgumentException( Environment.GetResourceString( "IdentityReference_InvalidSidRevision" ), "binaryForm" ); } // // Insist on the correct number of subauthorities // if ( binaryForm[offset + 1] > MaxSubAuthorities ) { throw new ArgumentException( Environment.GetResourceString( "IdentityReference_InvalidNumberOfSubauthorities", MaxSubAuthorities ), "binaryForm" ); } // // Make sure the buffer is big enough // int Length = 1 + 1 + 6 + 4 * binaryForm[offset + 1]; if ( binaryForm.Length - offset < Length ) { throw new ArgumentException( Environment.GetResourceString( "ArgumentOutOfRange_ArrayTooSmall" ), "binaryForm" ); } Authority = ( IdentifierAuthority )( ((( long )binaryForm[offset + 2]) << 40 ) + ((( long )binaryForm[offset + 3]) << 32 ) + ((( long )binaryForm[offset + 4]) << 24 ) + ((( long )binaryForm[offset + 5]) << 16 ) + ((( long )binaryForm[offset + 6]) << 8 ) + ((( long )binaryForm[offset + 7]) )); SubAuthorities = new int[binaryForm[offset + 1]]; // // Subauthorities are represented in big-endian format // for ( byte i = 0; i < binaryForm[offset + 1]; i++ ) { SubAuthorities[i] = ( int )( ((( uint )binaryForm[offset + 8 + 4*i + 0]) << 0 ) + ((( uint )binaryForm[offset + 8 + 4*i + 1]) << 8 ) + ((( uint )binaryForm[offset + 8 + 4*i + 2]) << 16 ) + ((( uint )binaryForm[offset + 8 + 4*i + 3]) << 24 )); } CreateFromParts( Authority, SubAuthorities ); return; } // // Constructs a SecurityIdentifier object from its string representation // Returns 'null' if string passed in is not a valid SID // NOTE: although there is a P/Invoke call involved in the implementation of this method, // there is no security risk involved, so no security demand is being made. // [System.Security.SecuritySafeCritical] // auto-generated public SecurityIdentifier( string sddlForm ) { byte[] resultSid; // // Give us something to work with // if ( sddlForm == null ) { throw new ArgumentNullException( "sddlForm" ); } Contract.EndContractBlock(); // // Call into the underlying O/S conversion routine // int Error = Win32.CreateSidFromString( sddlForm, out resultSid ); if ( Error == Win32Native.ERROR_INVALID_SID ) { throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidValue" ), "sddlForm" ); } else if ( Error == Win32Native.ERROR_NOT_ENOUGH_MEMORY ) { throw new OutOfMemoryException(); } else if ( Error != Win32Native.ERROR_SUCCESS ) { Contract.Assert( false, string.Format( CultureInfo.InvariantCulture, "Win32.CreateSidFromString returned unrecognized error {0}", Error )); throw new SystemException(Win32Native.GetMessage(Error)); } CreateFromBinaryForm( resultSid, 0 ); } // // Constructs a SecurityIdentifier object from its binary representation // public SecurityIdentifier( byte[] binaryForm, int offset ) { CreateFromBinaryForm( binaryForm, offset ); } // // Constructs a SecurityIdentifier object from an IntPtr // [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)] public SecurityIdentifier( IntPtr binaryForm ) : this( binaryForm, true ) { } [System.Security.SecurityCritical] // auto-generated internal SecurityIdentifier( IntPtr binaryForm, bool noDemand ) : this( Win32.ConvertIntPtrSidToByteArraySid( binaryForm ), 0 ) { } // // Constructs a well-known SID // The 'domainSid' parameter is optional and only used // by the well-known types that require it // NOTE: although there is a P/Invoke call involved in the implementation of this constructor, // there is no security risk involved, so no security demand is being made. // [System.Security.SecuritySafeCritical] // auto-generated public SecurityIdentifier( WellKnownSidType sidType, SecurityIdentifier domainSid ) { // // sidType must not be equal to LogonIdsSid // if (sidType == WellKnownSidType.LogonIdsSid) { throw new ArgumentException(Environment.GetResourceString("IdentityReference_CannotCreateLogonIdsSid"), "sidType"); } Contract.EndContractBlock(); byte[] resultSid; int Error; // // Check if well known sids are supported on this platform // if (!Win32.WellKnownSidApisSupported) { throw new PlatformNotSupportedException( Environment.GetResourceString( "PlatformNotSupported_RequiresW2kSP3" )); } // // sidType should not exceed the max defined value // if ((sidType < WellKnownSidType.NullSid) || (sidType > WellKnownSidType.MaxDefined)) { throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidValue" ), "sidType" ); } // // for sidType between 38 to 50, the domainSid parameter must be specified // if ((sidType >= WellKnownSidType.AccountAdministratorSid) && (sidType <= WellKnownSidType.AccountRasAndIasServersSid)) { if (domainSid == null) { throw new ArgumentNullException( "domainSid", Environment.GetResourceString( "IdentityReference_DomainSidRequired", sidType) ); } // // verify that the domain sid is a valid windows domain sid // to do that we call GetAccountDomainSid and the return value should be the same as the domainSid // SecurityIdentifier resultDomainSid; int ErrorCode; ErrorCode = Win32.GetWindowsAccountDomainSid( domainSid, out resultDomainSid ); if ( ErrorCode == Win32Native.ERROR_INSUFFICIENT_BUFFER ) { throw new OutOfMemoryException(); } else if ( ErrorCode == Win32Native.ERROR_NON_ACCOUNT_SID ) { // this means that the domain sid is not valid throw new ArgumentException( Environment.GetResourceString( "IdentityReference_NotAWindowsDomain" ), "domainSid" ); } else if ( ErrorCode != Win32Native.ERROR_SUCCESS ) { Contract.Assert( false, string.Format( CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", ErrorCode) ); throw new SystemException(Win32Native.GetMessage(ErrorCode)); } // // if domainSid is passed in as S-1-5-21-3-4-5-6, the above api will return S-1-5-21-3-4-5 as the domainSid // Since these do not match S-1-5-21-3-4-5-6 is not a valid domainSid (wrong number of subauthorities) // if (resultDomainSid != domainSid) { throw new ArgumentException( Environment.GetResourceString( "IdentityReference_NotAWindowsDomain" ), "domainSid" ); } } Error = Win32.CreateWellKnownSid( sidType, domainSid, out resultSid ); if ( Error == Win32Native.ERROR_INVALID_PARAMETER ) { throw new ArgumentException( Win32Native.GetMessage(Error), "sidType/domainSid" ); } else if ( Error != Win32Native.ERROR_SUCCESS ) { Contract.Assert( false, string.Format( CultureInfo.InvariantCulture, "Win32.CreateWellKnownSid returned unrecognized error {0}", Error )); throw new SystemException( Win32Native.GetMessage( Error )); } CreateFromBinaryForm( resultSid, 0 ); } internal SecurityIdentifier( SecurityIdentifier domainSid, uint rid ) { int i; int[] SubAuthorities = new int[ domainSid.SubAuthorityCount + 1 ]; for ( i = 0; i < domainSid.SubAuthorityCount; i++ ) { SubAuthorities[i] = domainSid.GetSubAuthority( i ); } SubAuthorities[i] = ( int )rid; CreateFromParts( domainSid.IdentifierAuthority, SubAuthorities ); } internal SecurityIdentifier( IdentifierAuthority identifierAuthority, int[] subAuthorities ) { CreateFromParts( identifierAuthority, subAuthorities ); } #endregion #region Static Properties // // Revision is always '1' // internal static byte Revision { get { return 1; } } #endregion #region Non-static Properties // // This is for internal consumption only, hence it is marked 'internal' // Making this call public would require a deep copy of the data to // prevent the caller from messing with the internal representation. // internal byte[] BinaryForm { get { return _BinaryForm; } } internal IdentifierAuthority IdentifierAuthority { get { return _IdentifierAuthority; } } internal int SubAuthorityCount { get { return _SubAuthorities.Length; } } public int BinaryLength { get { return _BinaryForm.Length; } } // // Returns the domain portion of a SID or null if the specified // SID is not an account SID // NOTE: although there is a P/Invoke call involved in the implementation of this method, // there is no security risk involved, so no security demand is being made. // public SecurityIdentifier AccountDomainSid { [System.Security.SecuritySafeCritical] // auto-generated get { if ( !_AccountDomainSidInitialized ) { _AccountDomainSid = GetAccountDomainSid(); _AccountDomainSidInitialized = true; } return _AccountDomainSid; } } #endregion #region Inherited properties and methods public override bool Equals( object o ) { if ( o == null ) { return false; } SecurityIdentifier sid = o as SecurityIdentifier; if ( sid == null ) { return false; } return ( this == sid ); // invokes operator== } public bool Equals( SecurityIdentifier sid ) { if ( sid == null ) { return false; } return ( this == sid ); // invokes operator== } public override int GetHashCode() { int hashCode = ((long)this.IdentifierAuthority).GetHashCode(); for(int i = 0; i < SubAuthorityCount; i++) { hashCode ^= this.GetSubAuthority(i); } return hashCode; } public override string ToString() { if ( _SddlForm == null ) { StringBuilder result = new StringBuilder(); // // Typecasting of _IdentifierAuthority to a long below is important, since // otherwise you would see this: "S-1-NTAuthority-32-544" // result.AppendFormat( "S-1-{0}", ( long )_IdentifierAuthority ); for ( int i = 0; i < SubAuthorityCount; i++ ) { result.AppendFormat( "-{0}", ( uint )( _SubAuthorities[i] )); } _SddlForm = result.ToString(); } return _SddlForm; } #if false public override string Scheme { get { return "ms-sid"; } } #endif public override string Value { get { return ToString().ToUpper(CultureInfo.InvariantCulture); } } internal static bool IsValidTargetTypeStatic( Type targetType ) { if ( targetType == typeof( NTAccount )) { return true; } else if ( targetType == typeof( SecurityIdentifier )) { return true; } else { return false; } } public override bool IsValidTargetType( Type targetType ) { return IsValidTargetTypeStatic( targetType ); } [System.Security.SecurityCritical] // auto-generated internal SecurityIdentifier GetAccountDomainSid() { SecurityIdentifier ResultSid; int Error; Error = Win32.GetWindowsAccountDomainSid( this, out ResultSid ); if ( Error == Win32Native.ERROR_INSUFFICIENT_BUFFER ) { throw new OutOfMemoryException(); } else if ( Error == Win32Native.ERROR_NON_ACCOUNT_SID ) { ResultSid = null; } else if ( Error != Win32Native.ERROR_SUCCESS ) { Contract.Assert( false, string.Format( CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", Error) ); throw new SystemException(Win32Native.GetMessage(Error)); } return ResultSid; } [System.Security.SecuritySafeCritical] // auto-generated public bool IsAccountSid() { if ( !_AccountDomainSidInitialized ) { _AccountDomainSid = GetAccountDomainSid(); _AccountDomainSidInitialized = true; } if (_AccountDomainSid == null) { return false; } return true; } [SecurityPermission(SecurityAction.Demand, ControlPrincipal = true)] [SecuritySafeCritical] public override IdentityReference Translate( Type targetType ) { if ( targetType == null ) { throw new ArgumentNullException( "targetType" ); } Contract.EndContractBlock(); if ( targetType == typeof( SecurityIdentifier )) { return this; // assumes SecurityIdentifier objects are immutable } else if ( targetType == typeof( NTAccount )) { IdentityReferenceCollection irSource = new IdentityReferenceCollection( 1 ); irSource.Add( this ); IdentityReferenceCollection irTarget; irTarget = SecurityIdentifier.Translate( irSource, targetType, true ); return irTarget[0]; } else { throw new ArgumentException( Environment.GetResourceString( "IdentityReference_MustBeIdentityReference" ), "targetType" ); } } #endregion #region Operators public static bool operator== ( SecurityIdentifier left, SecurityIdentifier right ) { object l = left; object r = right; if ( l == null && r == null ) { return true; } else if ( l == null || r == null ) { return false; } else { return ( left.CompareTo( right ) == 0 ); } } public static bool operator!= ( SecurityIdentifier left, SecurityIdentifier right ) { return !( left == right ); } #endregion #region IComparable implementation public int CompareTo( SecurityIdentifier sid ) { if ( sid == null ) { throw new ArgumentNullException( "sid" ); } Contract.EndContractBlock(); if ( this.IdentifierAuthority < sid.IdentifierAuthority ) { return -1; } if ( this.IdentifierAuthority > sid.IdentifierAuthority ) { return 1; } if ( this.SubAuthorityCount < sid.SubAuthorityCount ) { return -1; } if ( this.SubAuthorityCount > sid.SubAuthorityCount ) { return 1; } for ( int i = 0; i < this.SubAuthorityCount; i++ ) { int diff = this.GetSubAuthority( i ) - sid.GetSubAuthority( i ); if ( diff != 0 ) { return diff; } } return 0; } #endregion #region Public Methods internal int GetSubAuthority( int index ) { return this._SubAuthorities[ index ]; } // // Determines whether this SID is a well known SID of the specified type // // NOTE: although there is a P/Invoke call involved in the implementation of this method, // there is no security risk involved, so no security demand is being made. // [System.Security.SecuritySafeCritical] // auto-generated public bool IsWellKnown( WellKnownSidType type ) { return Win32.IsWellKnownSid( this, type ); } public void GetBinaryForm( byte[] binaryForm, int offset ) { _BinaryForm.CopyTo( binaryForm, offset ); } // // NOTE: although there is a P/Invoke call involved in the implementation of this method, // there is no security risk involved, so no security demand is being made. // [System.Security.SecuritySafeCritical] // auto-generated public bool IsEqualDomainSid( SecurityIdentifier sid ) { return Win32.IsEqualDomainSid( this, sid ); } [System.Security.SecurityCritical] // auto-generated private static IdentityReferenceCollection TranslateToNTAccounts( IdentityReferenceCollection sourceSids, out bool someFailed ) { if (sourceSids == null) { throw new ArgumentNullException("sourceSids"); } if (sourceSids.Count == 0) { throw new ArgumentException(Environment.GetResourceString("Arg_EmptyCollection"), "sourceSids"); } Contract.EndContractBlock(); IntPtr[] SidArrayPtr = new IntPtr[sourceSids.Count]; GCHandle[] HandleArray = new GCHandle[ sourceSids.Count ]; SafeLsaPolicyHandle LsaHandle = SafeLsaPolicyHandle.InvalidHandle; SafeLsaMemoryHandle ReferencedDomainsPtr = SafeLsaMemoryHandle.InvalidHandle; SafeLsaMemoryHandle NamesPtr = SafeLsaMemoryHandle.InvalidHandle; try { // // Pin all elements in the array of SIDs // int currentSid = 0; foreach ( IdentityReference id in sourceSids ) { SecurityIdentifier sid = id as SecurityIdentifier; if ( sid == null ) { throw new ArgumentException( Environment.GetResourceString( "Argument_ImproperType" ), "sourceSids" ); } HandleArray[currentSid] = GCHandle.Alloc(sid.BinaryForm, GCHandleType.Pinned); SidArrayPtr[currentSid] = HandleArray[currentSid].AddrOfPinnedObject(); currentSid++; } // // Open LSA policy (for lookup requires it) // LsaHandle = Win32.LsaOpenPolicy( null, PolicyRights.POLICY_LOOKUP_NAMES ); // // Perform the actual lookup // someFailed = false; uint ReturnCode; ReturnCode = Win32Native.LsaLookupSids( LsaHandle, sourceSids.Count, SidArrayPtr, ref ReferencedDomainsPtr, ref NamesPtr ); // // Make a decision regarding whether it makes sense to proceed // based on the return code and the value of the forceSuccess argument // if ( ReturnCode == Win32Native.STATUS_NO_MEMORY || ReturnCode == Win32Native.STATUS_INSUFFICIENT_RESOURCES ) { throw new OutOfMemoryException(); } else if ( ReturnCode == Win32Native.STATUS_ACCESS_DENIED ) { throw new UnauthorizedAccessException(); } else if ( ReturnCode == Win32Native.STATUS_NONE_MAPPED || ReturnCode == Win32Native.STATUS_SOME_NOT_MAPPED ) { someFailed = true; } else if ( ReturnCode != 0 ) { int win32ErrorCode = Win32Native.LsaNtStatusToWinError(unchecked((int)ReturnCode)); Contract.Assert( false, string.Format( CultureInfo.InvariantCulture, "Win32Native.LsaLookupSids returned {0}", win32ErrorCode)); throw new SystemException(Win32Native.GetMessage(win32ErrorCode)); } NamesPtr.Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_NAME))); Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr); // // Interpret the results and generate NTAccount objects // IdentityReferenceCollection Result = new IdentityReferenceCollection( sourceSids.Count ); if ( ReturnCode == 0 || ReturnCode == Win32Native.STATUS_SOME_NOT_MAPPED ) { // // Interpret the results and generate NT Account objects // Win32Native.LSA_REFERENCED_DOMAIN_LIST rdl = ReferencedDomainsPtr.Read<Win32Native.LSA_REFERENCED_DOMAIN_LIST>(0); string[] ReferencedDomains = new string[ rdl.Entries ]; for (int i = 0; i < rdl.Entries; i++) { Win32Native.LSA_TRUST_INFORMATION ti = ( Win32Native.LSA_TRUST_INFORMATION )Marshal.PtrToStructure( new IntPtr(( long )rdl.Domains + i * Marshal.SizeOf( typeof( Win32Native.LSA_TRUST_INFORMATION ))), typeof( Win32Native.LSA_TRUST_INFORMATION )); ReferencedDomains[i] = Marshal.PtrToStringUni(ti.Name.Buffer, ti.Name.Length / sizeof(char)); } Win32Native.LSA_TRANSLATED_NAME[] translatedNames = new Win32Native.LSA_TRANSLATED_NAME[sourceSids.Count]; NamesPtr.ReadArray(0, translatedNames, 0, translatedNames.Length); for (int i = 0; i < sourceSids.Count; i++) { Win32Native.LSA_TRANSLATED_NAME Ltn = translatedNames[i]; switch ((SidNameUse)Ltn.Use) { case SidNameUse.User: case SidNameUse.Group: case SidNameUse.Alias: case SidNameUse.Computer: case SidNameUse.WellKnownGroup: string account = Marshal.PtrToStringUni(Ltn.Name.Buffer, Ltn.Name.Length / sizeof(char)); ; string domain = ReferencedDomains[Ltn.DomainIndex]; Result.Add( new NTAccount( domain, account )); break; default: someFailed = true; Result.Add( sourceSids[i] ); break; } } } else { for (int i = 0; i < sourceSids.Count; i++) { Result.Add( sourceSids[i] ); } } return Result; } finally { for (int i = 0; i < sourceSids.Count; i++) { if ( HandleArray[i].IsAllocated ) { HandleArray[i].Free(); } } LsaHandle.Dispose(); ReferencedDomainsPtr.Dispose(); NamesPtr.Dispose(); } } [System.Security.SecurityCritical] // auto-generated internal static IdentityReferenceCollection Translate( IdentityReferenceCollection sourceSids, Type targetType, bool forceSuccess) { bool SomeFailed = false; IdentityReferenceCollection Result; Result = Translate( sourceSids, targetType, out SomeFailed ); if (forceSuccess && SomeFailed) { IdentityReferenceCollection UnmappedIdentities = new IdentityReferenceCollection(); foreach (IdentityReference id in Result) { if (id.GetType() != targetType) { UnmappedIdentities.Add(id); } } throw new IdentityNotMappedException(Environment.GetResourceString("IdentityReference_IdentityNotMapped"), UnmappedIdentities); } return Result; } [System.Security.SecurityCritical] // auto-generated internal static IdentityReferenceCollection Translate( IdentityReferenceCollection sourceSids, Type targetType, out bool someFailed ) { if ( sourceSids == null ) { throw new ArgumentNullException( "sourceSids" ); } Contract.EndContractBlock(); if ( targetType == typeof( NTAccount )) { return TranslateToNTAccounts( sourceSids, out someFailed ); } throw new ArgumentException( Environment.GetResourceString( "IdentityReference_MustBeIdentityReference" ), "targetType" ); } #endregion } }
using System; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.AspNet.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Umbraco.Core.Services; namespace Umbraco.Web.Routing { internal class PublishedContentRequestEngine { private readonly ITemplateService _templateService; private readonly PublishedContentRequest _pcr; private readonly IHttpContextAccessor _httpContextAccessor; private readonly RoutingContext _routingContext; private readonly ILogger _logger; /// <summary> /// Initializes a new instance of the <see cref="PublishedContentRequestEngine"/> class with a content request. /// </summary> /// <param name="templateService"></param> /// <param name="pcr">The content request.</param> /// <param name="loggerFactory"></param> /// <param name="httpContextAccessor"></param> public PublishedContentRequestEngine( ITemplateService templateService, PublishedContentRequest pcr, ILoggerFactory loggerFactory, IHttpContextAccessor httpContextAccessor) { if (templateService == null) throw new ArgumentNullException(nameof(templateService)); if (pcr == null) throw new ArgumentException("pcr is null."); if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory)); if (httpContextAccessor == null) throw new ArgumentNullException(nameof(httpContextAccessor)); _templateService = templateService; _pcr = pcr; _httpContextAccessor = httpContextAccessor; _logger = loggerFactory.CreateLogger(typeof(PublishedContentRequestEngine).FullName); _routingContext = pcr.RoutingContext; //var umbracoContext = _routingContext.UmbracoContext; //if (umbracoContext == null) throw new ArgumentException("pcr.RoutingContext.UmbracoContext is null."); //if (umbracoContext.RoutingContext != _routingContext) throw new ArgumentException("RoutingContext confusion."); // no! not set yet. //if (umbracoContext.PublishedContentRequest != _pcr) throw new ArgumentException("PublishedContentRequest confusion."); } #region Public /// <summary> /// Prepares the request. /// </summary> /// <returns> /// Returns false if the request was not successfully prepared /// </returns> public async Task<bool> PrepareRequestAsync() { if (_pcr.RouteData == null) return false; // note - at that point the original legacy module did something do handle IIS custom 404 errors // ie pages looking like /anything.aspx?404;/path/to/document - I guess the reason was to support // "directory urls" without having to do wildcard mapping to ASP.NET on old IIS. This is a pain // to maintain and probably not used anymore - removed as of 06/2012. @zpqrtbnk. // // to trigger Umbraco's not-found, one should configure IIS and/or ASP.NET cusom 404 errors // so that they point to a non-existing page eg /redirect-404.aspx // TODO: SD: We need more information on this for when we release 4.10.0 as I'm not sure what this means. //find domain //FindDomain(); // if request has been flagged to redirect then return // whoever called us is in charge of actually redirecting if (_pcr.IsRedirect) { return false; } // set the culture on the thread - once, so it's set when running document lookups if (_pcr.Culture != null) { CultureInfo.CurrentUICulture = CultureInfo.CurrentCulture = _pcr.Culture; } //find the published content if it's not assigned. This could be manually assigned with a custom route handler, or // with something like EnsurePublishedContentRequestAttribute or UmbracoVirtualNodeRouteHandler. Those in turn call this method // to setup the rest of the pipeline but we don't want to run the finders since there's one assigned. if (_pcr.PublishedContent == null && _pcr.RouteData.Values.ContainsKey("_umbracoRoute")) { // find the document & template await FindPublishedContentAndTemplateAsync(); } // handle wildcard domains //HandleWildcardDomains(); // set the culture on the thread -- again, 'cos it might have changed due to a finder or wildcard domain if (_pcr.Culture != null) { CultureInfo.CurrentUICulture = CultureInfo.CurrentCulture = _pcr.Culture; } // trigger the Prepared event - at that point it is still possible to change about anything // even though the request might be flagged for redirection - we'll redirect _after_ the event // // also, OnPrepared() will make the PublishedContentRequest readonly, so nothing can change // _pcr.OnPrepared(); // we don't take care of anything so if the content has changed, it's up to the user // to find out the appropriate template //complete the PCR and assign the remaining values return ConfigureRequest(); } /// <summary> /// Called by PrepareRequest once everything has been discovered, resolved and assigned to the PCR. This method /// finalizes the PCR with the values assigned. /// </summary> /// <returns> /// Returns false if the request was not successfully configured /// </returns> /// <remarks> /// This method logic has been put into it's own method in case developers have created a custom PCR or are assigning their own values /// but need to finalize it themselves. /// </remarks> public bool ConfigureRequest() { if (_pcr.HasPublishedContent == false) { return false; } // set the culture on the thread -- again, 'cos it might have changed in the event handler if (_pcr.Culture != null) { CultureInfo.CurrentUICulture = CultureInfo.CurrentCulture = _pcr.Culture; } // if request has been flagged to redirect, or has no content to display, // then return - whoever called us is in charge of actually redirecting if (_pcr.IsRedirect || _pcr.HasPublishedContent == false) { return false; } // we may be 404 _and_ have a content // can't go beyond that point without a PublishedContent to render // it's ok not to have a template, in order to give MVC a chance to hijack routes // note - the page() ctor below will cause the "page" to get the value of all its // "elements" ie of all the IPublishedContent property. If we use the object value, // that will trigger macro execution - which can't happen because macro execution // requires that _pcr.UmbracoPage is already initialized = catch-22. The "legacy" // pipeline did _not_ evaluate the macros, ie it is using the data value, and we // have to keep doing it because of that catch-22. return true; } /// <summary> /// Updates the request when there is no template to render the content. /// </summary> /// <remarks>This is called from Mvc when there's a document to render but no template.</remarks> public async Task UpdateRequestOnMissingTemplateAsync() { // clear content var content = _pcr.PublishedContent; _pcr.PublishedContent = null; await HandlePublishedContentAsync(); // will go 404 FindTemplate(); // if request has been flagged to redirect then return // whoever called us is in charge of redirecting if (_pcr.IsRedirect) return; if (_pcr.HasPublishedContent == false) { // means the engine could not find a proper document to handle 404 // restore the saved content so we know it exists _pcr.PublishedContent = content; return; } if (_pcr.HasTemplate == false) { // means we may have a document, but we have no template // at that point there isn't much we can do and there is no point returning // to Mvc since Mvc can't do much either return; } // see note in PrepareRequest() } #endregion #region Domain ///// <summary> ///// Finds the site root (if any) matching the http request, and updates the PublishedContentRequest accordingly. ///// </summary> ///// <returns>A value indicating whether a domain was found.</returns> //internal bool FindDomain() //{ // const string tracePrefix = "FindDomain: "; // // note - we are not handling schemes nor ports here. // _logger.LogDebug("{0}Uri=\"{1}\"", tracePrefix, _pcr.Uri); // // try to find a domain matching the current request // var domainAndUri = DomainHelper.DomainForUri(Services.DomainService.GetAll(false), _pcr.Uri); // // handle domain // if (domainAndUri != null && domainAndUri.UmbracoDomain.LanguageIsoCode.IsNullOrWhiteSpace() == false) // { // // matching an existing domain // _logger.LogDebug("{0}Matches domain=\"{1}\", rootId={2}, culture=\"{3}\"", // tracePrefix, // domainAndUri.UmbracoDomain.DomainName, // domainAndUri.UmbracoDomain.RootContentId, // domainAndUri.UmbracoDomain.LanguageIsoCode); // _pcr.UmbracoDomain = domainAndUri.UmbracoDomain; // _pcr.DomainUri = domainAndUri.Uri; // _pcr.Culture = new CultureInfo(domainAndUri.UmbracoDomain.LanguageIsoCode); // // canonical? not implemented at the moment // // if (...) // // { // // _pcr.RedirectUrl = "..."; // // return true; // // } // } // else // { // // not matching any existing domain // _logger.LogDebug("{0}Matches no domain", tracePrefix); // var defaultLanguage = Services.LocalizationService.GetAllLanguages().FirstOrDefault(); // _pcr.Culture = defaultLanguage == null ? CultureInfo.CurrentUICulture : new CultureInfo(defaultLanguage.IsoCode); // } // _logger.LogDebug("{0}Culture=\"{1}\"", tracePrefix, _pcr.Culture.Name); // return _pcr.UmbracoDomain != null; //} ///// <summary> ///// Looks for wildcard domains in the path and updates <c>Culture</c> accordingly. ///// </summary> //internal void HandleWildcardDomains() //{ // const string tracePrefix = "HandleWildcardDomains: "; // if (_pcr.HasPublishedContent == false) // return; // var nodePath = _pcr.PublishedContent.Path; // _logger.LogDebug("{0}Path=\"{1}\"", tracePrefix, nodePath); // var rootNodeId = _pcr.HasDomain ? _pcr.UmbracoDomain.RootContentId : (int?)null; // var domain = DomainHelper.FindWildcardDomainInPath(Services.DomainService.GetAll(true), nodePath, rootNodeId); // if (domain != null && domain.LanguageIsoCode.IsNullOrWhiteSpace() == false) // { // _pcr.Culture = new CultureInfo(domain.LanguageIsoCode); // _logger.LogDebug("{0}Got domain on node {1}, set culture to \"{2}\".", tracePrefix, domain.RootContentId, _pcr.Culture.Name); // } // else // { // _logger.LogDebug("{0}No match.", tracePrefix); // } //} #endregion #region Document and template /// <summary> /// Finds the Umbraco document (if any) matching the request, and updates the PublishedContentRequest accordingly. /// </summary> /// <returns>A value indicating whether a document and template were found.</returns> private async Task FindPublishedContentAndTemplateAsync() { // run the document finders await FindPublishedContentAsync(); // if request has been flagged to redirect then return // whoever called us is in charge of actually redirecting // -- do not process anything any further -- if (_pcr.IsRedirect) return; // not handling umbracoRedirect here but after LookupDocument2 // so internal redirect, 404, etc has precedence over redirect // handle not-found, redirects, access... await HandlePublishedContentAsync(); // find a template FindTemplate(); //// handle umbracoRedirect //FollowExternalRedirect(); } /// <summary> /// Tries to find the document matching the request, by running the IPublishedContentFinder instances. /// </summary> /// <exception cref="InvalidOperationException">There is no finder collection.</exception> internal async Task FindPublishedContentAsync() { //const string tracePrefix = "FindPublishedContent: "; // look for the document // the first successful finder, if any, will set this.PublishedContent, and may also set this.Template // some finders may implement caching if (_routingContext.PublishedContentFinders == null) throw new InvalidOperationException("There is no finder collection."); //iterate but return on first one that finds it foreach (var publishedContentFinder in _routingContext.PublishedContentFinders) { if (await publishedContentFinder.TryFindContentAsync(_pcr)) { break; } } // indicate that the published content (if any) we have at the moment is the // one that was found by the standard finders before anything else took place. _pcr.SetIsInitialPublishedContent(); } /// <summary> /// Handles the published content (if any). /// </summary> /// <remarks> /// Handles "not found", internal redirects, access validation... /// things that must be handled in one place because they can create loops /// </remarks> private async Task HandlePublishedContentAsync() { const string tracePrefix = "HandlePublishedContent: "; // because these might loop, we have to have some sort of infinite loop detection int i = 0, j = 0; const int maxLoop = 8; do { _logger.LogDebug("{0}{1}", tracePrefix, (i == 0 ? "Begin" : "Loop")); // handle not found if (_pcr.HasPublishedContent == false) { _pcr.Is404 = true; _logger.LogDebug("{0}No document, try last chance lookup", tracePrefix); // if it fails then give up, there isn't much more that we can do var lastChance = _routingContext.PublishedContentLastChanceFinder; if (lastChance == null || await lastChance.TryFindContentAsync(_pcr) == false) { _logger.LogDebug("{0}Failed to find a document, give up", tracePrefix); break; } _logger.LogDebug("{0}Found a document", tracePrefix); } //// follow internal redirects as long as it's not running out of control ie infinite loop of some sort //j = 0; //while (FollowInternalRedirects() && j++ < maxLoop) //{ } //if (j == maxLoop) // we're running out of control // break; //// ensure access //if (_pcr.HasPublishedContent) // EnsurePublishedContentAccess(); // loop while we don't have page, ie the redirect or access // got us to nowhere and now we need to run the notFoundLookup again // as long as it's not running out of control ie infinite loop of some sort } while (_pcr.HasPublishedContent == false && i++ < maxLoop); if (i == maxLoop || j == maxLoop) { _logger.LogDebug("{0}Looks like we're running into an infinite loop, abort", tracePrefix); _pcr.PublishedContent = null; } _logger.LogDebug("{0}End", tracePrefix); } ///// <summary> ///// Follows internal redirections through the <c>umbracoInternalRedirectId</c> document property. ///// </summary> ///// <returns>A value indicating whether redirection took place and led to a new published document.</returns> ///// <remarks> ///// <para>Redirecting to a different site root and/or culture will not pick the new site root nor the new culture.</para> ///// <para>As per legacy, if the redirect does not work, we just ignore it.</para> ///// </remarks> //private bool FollowInternalRedirects() //{ // const string tracePrefix = "FollowInternalRedirects: "; // if (_pcr.PublishedContent == null) // throw new InvalidOperationException("There is no PublishedContent."); // bool redirect = false; // var internalRedirect = _pcr.PublishedContent.GetPropertyValue<string>(Constants.Conventions.Content.InternalRedirectId); // if (string.IsNullOrWhiteSpace(internalRedirect) == false) // { // _logger.LogDebug("{0}Found umbracoInternalRedirectId={1}", () => tracePrefix, () => internalRedirect); // int internalRedirectId; // if (int.TryParse(internalRedirect, out internalRedirectId) == false) // internalRedirectId = -1; // if (internalRedirectId <= 0) // { // // bad redirect - log and display the current page (legacy behavior) // //_pcr.Document = null; // no! that would be to force a 404 // _logger.LogDebug("{0}Failed to redirect to id={1}: invalid value", () => tracePrefix, () => internalRedirect); // } // else if (internalRedirectId == _pcr.PublishedContent.Id) // { // // redirect to self // _logger.LogDebug("{0}Redirecting to self, ignore", () => tracePrefix); // } // else // { // // redirect to another page // var node = _routingContext.UmbracoContext.ContentCache.GetById(internalRedirectId); // _pcr.SetInternalRedirectPublishedContent(node); // don't use .PublishedContent here // if (node != null) // { // redirect = true; // _logger.LogDebug("{0}Redirecting to id={1}", () => tracePrefix, () => internalRedirectId); // } // else // { // _logger.LogDebug("{0}Failed to redirect to id={1}: no such published document", () => tracePrefix, () => internalRedirectId); // } // } // } // return redirect; //} ///// <summary> ///// Ensures that access to current node is permitted. ///// </summary> ///// <remarks>Redirecting to a different site root and/or culture will not pick the new site root nor the new culture.</remarks> //private void EnsurePublishedContentAccess() //{ // const string tracePrefix = "EnsurePublishedContentAccess: "; // if (_pcr.PublishedContent == null) // throw new InvalidOperationException("There is no PublishedContent."); // var path = _pcr.PublishedContent.Path; // var publicAccessAttempt = Services.PublicAccessService.IsProtected(path); // if (publicAccessAttempt) // { // _logger.LogDebug("{0}Page is protected, check for access", () => tracePrefix); // var membershipHelper = new MembershipHelper(_routingContext.UmbracoContext); // if (membershipHelper.IsLoggedIn() == false) // { // _logger.LogDebug("{0}Not logged in, redirect to login page", () => tracePrefix); // var loginPageId = publicAccessAttempt.Result.LoginNodeId; // if (loginPageId != _pcr.PublishedContent.Id) // _pcr.PublishedContent = _routingContext.UmbracoContext.ContentCache.GetById(loginPageId); // } // else if (Services.PublicAccessService.HasAccess(_pcr.PublishedContent.Id, Services.ContentService, _pcr.GetRolesForLogin(membershipHelper.CurrentUserName)) == false) // { // _logger.LogDebug("{0}Current member has not access, redirect to error page", () => tracePrefix); // var errorPageId = publicAccessAttempt.Result.NoAccessNodeId; // if (errorPageId != _pcr.PublishedContent.Id) // _pcr.PublishedContent = _routingContext.UmbracoContext.ContentCache.GetById(errorPageId); // } // else // { // _logger.LogDebug("{0}Current member has access", () => tracePrefix); // } // } // else // { // _logger.LogDebug("{0}Page is not protected", () => tracePrefix); // } //} /// <summary> /// Finds a template for the current node, if any. /// </summary> private void FindTemplate() { // NOTE: at the moment there is only 1 way to find a template, and then ppl must // use the Prepared event to change the template if they wish. Should we also // implement an ITemplateFinder logic? const string tracePrefix = "FindTemplate: "; if (_pcr.PublishedContent == null) { _pcr.ResetTemplate(); return; } // read the alternate template alias from querystring // only if the published content is the initial once, else the alternate template // does not apply // + optionnally, apply the alternate template on internal redirects var useAltTemplate = (_pcr.IsInitialPublishedContent || (_pcr.IsInternalRedirectPublishedContent)); string altTemplate = null; if (useAltTemplate) { altTemplate = _httpContextAccessor.HttpContext.Request.Query["altTemplate"]; } if (string.IsNullOrWhiteSpace(altTemplate)) { // we don't have an alternate template specified. use the current one if there's one already, // which can happen if a content lookup also set the template (LookupByNiceUrlAndTemplate...), // else lookup the template id on the document then lookup the template with that id. if (_pcr.HasTemplate) { _logger.LogDebug("{0}Has a template already, and no alternate template.", tracePrefix); return; } var templateId = _pcr.PublishedContent.TemplateId; if (templateId != Guid.Empty) { _logger.LogDebug("{0}Look for template id={1}", tracePrefix, templateId); var template = _templateService.GetTemplate(templateId); if (template == null) throw new InvalidOperationException("The template with Id " + templateId + " does not exist, the page cannot render"); _pcr.SetTemplate(template); _logger.LogDebug("{0}Got template id={1} alias=\"{2}\"", tracePrefix, template.Id, template.Alias); } else { _logger.LogDebug("{0}No specified template.", tracePrefix); } } else { // we have an alternate template specified. lookup the template with that alias // this means the we override any template that a content lookup might have set // so /path/to/page/template1?altTemplate=template2 will use template2 // ignore if the alias does not match - just trace if (_pcr.HasTemplate) _logger.LogDebug("{0}Has a template already, but also an alternate template.", tracePrefix); _logger.LogDebug("{0}Look for alternate template alias=\"{1}\"", tracePrefix, altTemplate); var template = _templateService.GetTemplate(altTemplate); if (template != null) { _pcr.SetTemplate(template); _logger.LogDebug("{0}Got template id={1} alias=\"{2}\"", tracePrefix, template.Id, template.Alias); } else { _logger.LogDebug("{0}The template with alias=\"{1}\" does not exist, ignoring.", tracePrefix, altTemplate); } } if (_pcr.HasTemplate == false) { _logger.LogDebug("{0}No template was found.", tracePrefix); // initial idea was: if we're not already 404 and UmbracoSettings.HandleMissingTemplateAs404 is true // then reset _pcr.Document to null to force a 404. // // but: because we want to let MVC hijack routes even though no template is defined, we decide that // a missing template is OK but the request will then be forwarded to MVC, which will need to take // care of everything. // // so, don't set _pcr.Document to null here } else { _logger.LogDebug("{0}Running with template id={1} alias=\"{2}\"", tracePrefix, _pcr.TemplateModel.Id, _pcr.TemplateModel.Alias); } } #endregion } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System; using System.ComponentModel; using System.Threading; using NLog.Common; using NLog.Internal; /// <summary> /// A target that buffers log events and sends them in batches to the wrapped target. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/BufferingWrapper-target">Documentation on NLog Wiki</seealso> [Target("BufferingWrapper", IsWrapper = true)] public class BufferingTargetWrapper : WrapperTargetBase { private LogEventInfoBuffer _buffer; private Timer _flushTimer; private readonly object _lockObject = new object(); /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> public BufferingTargetWrapper() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="wrappedTarget">The wrapped target.</param> public BufferingTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget) { Name = name; } /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> public BufferingTargetWrapper(Target wrappedTarget) : this(wrappedTarget, 100) { } /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="bufferSize">Size of the buffer.</param> public BufferingTargetWrapper(Target wrappedTarget, int bufferSize) : this(wrappedTarget, bufferSize, -1) { } /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="bufferSize">Size of the buffer.</param> /// <param name="flushTimeout">The flush timeout.</param> public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout) : this(wrappedTarget, bufferSize, flushTimeout, BufferingTargetWrapperOverflowAction.Flush) { } /// <summary> /// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="bufferSize">Size of the buffer.</param> /// <param name="flushTimeout">The flush timeout.</param> /// <param name="overflowAction">The action to take when the buffer overflows.</param> public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout, BufferingTargetWrapperOverflowAction overflowAction) { WrappedTarget = wrappedTarget; BufferSize = bufferSize; FlushTimeout = flushTimeout; SlidingTimeout = true; OverflowAction = overflowAction; } /// <summary> /// Gets or sets the number of log events to be buffered. /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(100)] public int BufferSize { get; set; } /// <summary> /// Gets or sets the timeout (in milliseconds) after which the contents of buffer will be flushed /// if there's no write in the specified period of time. Use -1 to disable timed flushes. /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(-1)] public int FlushTimeout { get; set; } /// <summary> /// Gets or sets a value indicating whether to use sliding timeout. /// </summary> /// <remarks> /// This value determines how the inactivity period is determined. If sliding timeout is enabled, /// the inactivity timer is reset after each write, if it is disabled - inactivity timer will /// count from the first event written to the buffer. /// </remarks> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(true)] public bool SlidingTimeout { get; set; } /// <summary> /// Gets or sets the action to take if the buffer overflows. /// </summary> /// <remarks> /// Setting to <see cref="BufferingTargetWrapperOverflowAction.Discard"/> will replace the /// oldest event with new events without sending events down to the wrapped target, and /// setting to <see cref="BufferingTargetWrapperOverflowAction.Flush"/> will flush the /// entire buffer to the wrapped target. /// </remarks> /// <docgen category='Buffering Options' order='100' /> [DefaultValue("Flush")] public BufferingTargetWrapperOverflowAction OverflowAction { get; set; } /// <summary> /// Flushes pending events in the buffer (if any), followed by flushing the WrappedTarget. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { WriteEventsInBuffer("Flush Async"); base.FlushAsync(asyncContinuation); } /// <summary> /// Initializes the target. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); _buffer = new LogEventInfoBuffer(BufferSize, false, 0); InternalLogger.Trace("BufferingWrapper(Name={0}): Create Timer", Name); _flushTimer = new Timer(FlushCallback, null, Timeout.Infinite, Timeout.Infinite); } /// <summary> /// Closes the target by flushing pending events in the buffer (if any). /// </summary> protected override void CloseTarget() { var currentTimer = _flushTimer; if (currentTimer != null) { _flushTimer = null; if (currentTimer.WaitForDispose(TimeSpan.FromSeconds(1))) { if (OverflowAction == BufferingTargetWrapperOverflowAction.Discard) { _buffer.GetEventsAndClear(); } else { WriteEventsInBuffer("Closing Target"); } } } base.CloseTarget(); } /// <summary> /// Adds the specified log event to the buffer and flushes /// the buffer in case the buffer gets full. /// </summary> /// <param name="logEvent">The log event.</param> protected override void Write(AsyncLogEventInfo logEvent) { PrecalculateVolatileLayouts(logEvent.LogEvent); int count = _buffer.Append(logEvent); if (count >= BufferSize) { // If the OverflowAction action is set to "Discard", the buffer will automatically // roll over the oldest item. if (OverflowAction == BufferingTargetWrapperOverflowAction.Flush) { WriteEventsInBuffer("Exceeding BufferSize"); } } else { if (FlushTimeout > 0 && (SlidingTimeout || count == 1)) { // reset the timer on first item added to the buffer or whenever SlidingTimeout is set to true _flushTimer.Change(FlushTimeout, -1); } } } private void FlushCallback(object state) { bool lockTaken = false; try { int timeoutMilliseconds = Math.Min(FlushTimeout / 2, 100); lockTaken = Monitor.TryEnter(_lockObject, timeoutMilliseconds); if (lockTaken) { if (_flushTimer == null) return; WriteEventsInBuffer(null); } else { if (_buffer.Count > 0) _flushTimer?.Change(FlushTimeout, -1); // Schedule new retry timer } } catch (Exception exception) { InternalLogger.Error(exception, "BufferingWrapper(Name={0}): Error in flush procedure.", Name); if (exception.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } } finally { if (lockTaken) { Monitor.Exit(_lockObject); } } } private void WriteEventsInBuffer(string reason) { if (WrappedTarget == null) { InternalLogger.Error("BufferingWrapper(Name={0}): WrappedTarget is NULL", Name); return; } lock (_lockObject) { AsyncLogEventInfo[] logEvents = _buffer.GetEventsAndClear(); if (logEvents.Length > 0) { if (reason != null) InternalLogger.Trace("BufferingWrapper(Name={0}): Writing {1} events ({2})", Name, logEvents.Length, reason); WrappedTarget.WriteAsyncLogEvents(logEvents); } } } } }