context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Globalization; /// <summary> /// String.System.IConvertible.ToInt32(IFormatProvider provider) /// This method supports the .NET Framework infrastructure and is /// not intended to be used directly from your code. /// Converts the value of the current String object to a 32-bit signed integer. /// </summary> class IConvertibleToInt32 { private const int c_MIN_STRING_LEN = 8; private const int c_MAX_STRING_LEN = 256; public static int Main() { IConvertibleToInt32 iege = new IConvertibleToInt32(); TestLibrary.TestFramework.BeginTestCase("for method: String.System.IConvertible.ToInt32(IFormatProvider)"); if (iege.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; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive test scenarioes public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Random numeric string"; const string c_TEST_ID = "P001"; string strSrc; IFormatProvider provider; Int32 i; bool expectedValue = true; bool actualValue = false; i = TestLibrary.Generator.GetInt32(-55); strSrc = i.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (i == ((IConvertible)strSrc).ToInt32(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Positive sign"; const string c_TEST_ID = "P002"; string strSrc; IFormatProvider provider; NumberFormatInfo ni = new NumberFormatInfo(); Int32 i; bool expectedValue = true; bool actualValue = false; i = TestLibrary.Generator.GetInt32(-55); // positive signs cannot have emdedded nulls ni.PositiveSign = TestLibrary.Generator.GetString(-55, false, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN).Replace((char)0, 'a'); strSrc = ni.PositiveSign + i.ToString(); provider = (IFormatProvider)ni; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (i == ((IConvertible)strSrc).ToInt32(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: string is Int32.MaxValue"; const string c_TEST_ID = "P003"; string strSrc; IFormatProvider provider; bool expectedValue = true; bool actualValue = false; strSrc = Int32.MaxValue.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (Int32.MaxValue == ((IConvertible)strSrc).ToInt32(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: string is Int32.MinValue"; const string c_TEST_ID = "P004"; string strSrc; IFormatProvider provider; bool expectedValue = true; bool actualValue = false; strSrc = Int32.MinValue.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (Int32.MinValue == ((IConvertible)strSrc).ToInt32(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest5() // new update 8-14-2006 Noter(v-yaduoj) { bool retVal = true; const string c_TEST_DESC = "PosTest5: Negative sign"; const string c_TEST_ID = "P005"; string strSrc; IFormatProvider provider; NumberFormatInfo ni = new NumberFormatInfo(); Int32 i; bool expectedValue = true; bool actualValue = false; i = TestLibrary.Generator.GetInt32(-55); ni.NegativeSign = TestLibrary.Generator.GetString(-55, false, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); strSrc = ni.NegativeSign + i.ToString(); provider = (IFormatProvider)ni; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = ((-1*i) == ((IConvertible)strSrc).ToInt32(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } #endregion // end for positive test scenarioes #region Negative test scenarios public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: The value of String object cannot be parsed"; const string c_TEST_ID = "N001"; string strSrc; IFormatProvider provider; strSrc = "p" + TestLibrary.Generator.GetString(-55, false, 9, c_MAX_STRING_LEN); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToInt32(provider); TestLibrary.TestFramework.LogError("009" + "TestId-" + c_TEST_ID, "FormatException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("010" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; const string c_TEST_DESC = "NegTest2: The value of String object is a number greater than MaxValue"; const string c_TEST_ID = "N002"; string strSrc; IFormatProvider provider; Int64 i; // new update 8-14-2006 Noter(v-yaduoj) i = TestLibrary.Generator.GetInt64(-55) % Int32.MaxValue + Int32.MaxValue + 1; strSrc = i.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { // new update 8-14-2006 Noter(v-yaduoj) ((IConvertible)strSrc).ToInt32(provider); TestLibrary.TestFramework.LogError("011" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("012" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; const string c_TEST_DESC = "NegTest3: The value of String object is a number less than MinValue"; const string c_TEST_ID = "N003"; string strSrc; IFormatProvider provider; Int64 i; // new update 8-14-2006 Noter(v-yaduoj) i = -1 * (TestLibrary.Generator.GetInt64(-55) % Int32.MaxValue) - Int32.MaxValue - 1; strSrc = i.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToInt32(provider); TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("014" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } #endregion private string GetDataString(string strSrc, IFormatProvider provider) { string str1, str2, str; int len1; if (null == strSrc) { str1 = "null"; len1 = 0; } else { str1 = strSrc; len1 = strSrc.Length; } str2 = (null == provider) ? "null" : provider.ToString(); str = string.Format("\n[Source string value]\n \"{0}\"", str1); str += string.Format("\n[Length of source string]\n {0}", len1); str += string.Format("\n[Format provider string]\n {0}", str2); return str; } }
#if !DISABLE_DHT // // MessageLoop.cs // // Authors: // Alan McGovern alan.mcgovern@gmail.com // // Copyright (C) 2008 Alan McGovern // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Text; using MonoTorrent.Dht.Messages; using System.Threading; using System.Net.Sockets; using System.Net; using MonoTorrent.BEncoding; using MonoTorrent.Dht.Listeners; using MonoTorrent.Common; using System.Diagnostics; namespace MonoTorrent.Dht { internal class MessageLoop { private struct SendDetails { public SendDetails(IPEndPoint destination, Message message) { Destination = destination; Message = message; SentAt = DateTime.MinValue; } public IPEndPoint Destination; public Message Message; public DateTime SentAt; } internal event EventHandler<SendQueryEventArgs> QuerySent; List<IAsyncResult> activeSends = new List<IAsyncResult>(); DhtEngine engine; DateTime lastSent; DhtListener listener; private object locker = new object(); Queue<SendDetails> sendQueue = new Queue<SendDetails>(); Queue<KeyValuePair<IPEndPoint, Message>> receiveQueue = new Queue<KeyValuePair<IPEndPoint, Message>>(); MonoTorrentCollection<SendDetails> waitingResponse = new MonoTorrentCollection<SendDetails>(); private bool CanSend { get { return activeSends.Count < 5 && sendQueue.Count > 0 && (DateTime.Now - lastSent) > TimeSpan.FromMilliseconds(5); } } public MessageLoop(DhtEngine engine, DhtListener listener) { this.engine = engine; this.listener = listener; listener.MessageReceived += new MessageReceived(MessageReceived); DhtEngine.MainLoop.QueueTimeout(TimeSpan.FromMilliseconds(5), delegate { if (engine.Disposed) return false; try { SendMessage(); ReceiveMessage(); TimeoutMessage(); } catch (Exception ex) { Debug.WriteLine("Error in DHT main loop:"); Debug.WriteLine(ex); } return !engine.Disposed; }); } void MessageReceived(byte[] buffer, IPEndPoint endpoint) { lock (locker) { // I should check the IP address matches as well as the transaction id // FIXME: This should throw an exception if the message doesn't exist, we need to handle this // and return an error message (if that's what the spec allows) try { Message message; if (MessageFactory.TryDecodeMessage((BEncodedDictionary)BEncodedValue.Decode(buffer, 0, buffer.Length, false), out message)) receiveQueue.Enqueue(new KeyValuePair<IPEndPoint, Message>(endpoint, message)); } catch (MessageException ex) { Console.WriteLine("Message Exception: {0}", ex); // Caused by bad transaction id usually - ignore } catch (Exception ex) { Console.WriteLine("OMGZERS! {0}", ex); //throw new Exception("IP:" + endpoint.Address.ToString() + "bad transaction:" + e.Message); } } } private void RaiseMessageSent(IPEndPoint endpoint, QueryMessage query, ResponseMessage response) { EventHandler<SendQueryEventArgs> h = QuerySent; if (h != null) h(this, new SendQueryEventArgs(endpoint, query, response)); } private void SendMessage() { SendDetails? send = null; if (CanSend) send = sendQueue.Dequeue(); if (send != null) { SendMessage(send.Value.Message, send.Value.Destination); SendDetails details = send.Value; details.SentAt = DateTime.UtcNow; if (details.Message is QueryMessage) waitingResponse.Add(details); } } internal void Start() { if (listener.Status != ListenerStatus.Listening) listener.Start(); } internal void Stop() { if (listener.Status != ListenerStatus.NotListening) listener.Stop(); } private void TimeoutMessage() { if (waitingResponse.Count > 0) { if ((DateTime.UtcNow - waitingResponse[0].SentAt) > engine.TimeOut) { SendDetails details = waitingResponse.Dequeue(); MessageFactory.UnregisterSend((QueryMessage)details.Message); RaiseMessageSent(details.Destination, (QueryMessage)details.Message, null); } } } private void ReceiveMessage() { if (receiveQueue.Count == 0) return; KeyValuePair<IPEndPoint, Message> receive = receiveQueue.Dequeue(); Message m = receive.Value; IPEndPoint source = receive.Key; for (int i = 0; i < waitingResponse.Count; i++) if (waitingResponse[i].Message.TransactionId.Equals(m.TransactionId)) waitingResponse.RemoveAt(i--); try { Node node = engine.RoutingTable.FindNode(m.Id); // What do i do with a null node? if (node == null) { node = new Node(m.Id, source); engine.RoutingTable.Add(node); } node.Seen(); m.Handle(engine, node); ResponseMessage response = m as ResponseMessage; if (response != null) { RaiseMessageSent(node.EndPoint, response.Query, response); } } catch (MessageException ex) { Console.WriteLine("Incoming message barfed: {0}", ex); // Normal operation (FIXME: do i need to send a response error message?) } catch (Exception ex) { Console.WriteLine("Handle Error for message: {0}", ex); this.EnqueueSend(new ErrorMessage(ErrorCode.GenericError, "Misshandle received message!"), source); } } private void SendMessage(Message message, IPEndPoint endpoint) { lastSent = DateTime.Now; byte[] buffer = message.Encode(); listener.Send(buffer, endpoint); } internal void EnqueueSend(Message message, IPEndPoint endpoint) { lock (locker) { if (message.TransactionId == null) { if (message is ResponseMessage) throw new ArgumentException("Message must have a transaction id"); do { message.TransactionId = TransactionId.NextId(); } while (MessageFactory.IsRegistered(message.TransactionId)); } // We need to be able to cancel a query message if we time out waiting for a response if (message is QueryMessage) MessageFactory.RegisterSend((QueryMessage)message); sendQueue.Enqueue(new SendDetails(endpoint, message)); } } internal void EnqueueSend(Message message, Node node) { EnqueueSend(message, node.EndPoint); } } } #endif
/* * ToolkitGraphicsBase.cs - Implementation of the * "System.Drawing.Toolkit.ToolkitGraphicsBase" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Drawing.Toolkit { using System.Drawing; using System.Drawing.Text; using System.Drawing.Drawing2D; using DotGNU.Images; // This base class provides some common functionality which should // help to make it easier to write "IToolkitGraphics" handlers. [NonStandardExtra] public abstract class ToolkitGraphicsBase : IToolkitGraphics { // Dirty bit flags for changed values. [Flags] public enum DirtyFlags { CompositingMode = (1 << 1), CompositingQuality = (1 << 2), InterpolationMode = (1 << 3), PixelOffsetMode = (1 << 4), RenderingOrigin = (1 << 5), SmoothingMode = (1 << 6), TextContrast = (1 << 7), TextRenderingHint = (1 << 8), All = -1 }; // enum DirtyFlags // Internal state. protected IToolkit toolkit; protected Region clip; protected CompositingMode compositingMode; protected CompositingQuality compositingQuality; protected InterpolationMode interpolationMode; protected PixelOffsetMode pixelOffsetMode; protected Point renderingOrigin; protected SmoothingMode smoothingMode; protected int textContrast; protected TextRenderingHint textRenderingHint; protected DirtyFlags dirtyFlags; protected IToolkitPen pen; protected IToolkitBrush brush; protected IToolkitFont font; // Constructor. protected ToolkitGraphicsBase(IToolkit toolkit) { this.toolkit = toolkit; clip = null; compositingMode = CompositingMode.SourceOver; compositingQuality = CompositingQuality.Default; interpolationMode = InterpolationMode.Default; pixelOffsetMode = PixelOffsetMode.Default; renderingOrigin = new Point(0, 0); smoothingMode = SmoothingMode.Default; textContrast = 4; textRenderingHint = TextRenderingHint.SystemDefault; dirtyFlags = DirtyFlags.All; } // Get or set the graphics object's properties. public IToolkit Toolkit { get { return toolkit; } } public virtual CompositingMode CompositingMode { get { return compositingMode; } set { if(compositingMode != value) { compositingMode = value; dirtyFlags |= DirtyFlags.CompositingMode; } } } public virtual CompositingQuality CompositingQuality { get { return compositingQuality; } set { if(compositingQuality != value) { compositingQuality = value; dirtyFlags |= DirtyFlags.CompositingQuality; } } } public virtual float DpiX { get { return Graphics.DefaultScreenDpi; } } public virtual float DpiY { get { return Graphics.DefaultScreenDpi; } } public virtual InterpolationMode InterpolationMode { get { return interpolationMode; } set { if(interpolationMode != value) { interpolationMode = value; dirtyFlags |= DirtyFlags.InterpolationMode; } } } public virtual PixelOffsetMode PixelOffsetMode { get { return pixelOffsetMode; } set { if(pixelOffsetMode != value) { pixelOffsetMode = value; dirtyFlags |= DirtyFlags.PixelOffsetMode; } } } public virtual Point RenderingOrigin { get { return renderingOrigin; } set { if(renderingOrigin != value) { renderingOrigin = value; dirtyFlags |= DirtyFlags.RenderingOrigin; } } } public virtual SmoothingMode SmoothingMode { get { return smoothingMode; } set { if(smoothingMode != value) { smoothingMode = value; dirtyFlags |= DirtyFlags.SmoothingMode; } } } public virtual int TextContrast { get { return textContrast; } set { if(textContrast != value) { textContrast = value; dirtyFlags |= DirtyFlags.TextContrast; } } } public virtual TextRenderingHint TextRenderingHint { get { return textRenderingHint; } set { if(textRenderingHint != value) { textRenderingHint = value; dirtyFlags |= DirtyFlags.TextRenderingHint; } } } // Determine if a particular section of the dirty flags are set. protected bool IsDirty(DirtyFlags flags) { return ((dirtyFlags & flags) != 0); } // Check if dirty flags are set and also clear them. protected bool CheckDirty(DirtyFlags flags) { bool result = ((dirtyFlags & flags) != 0); dirtyFlags &= ~flags; return result; } // Clear specific dirty flags. protected void ClearDirty(DirtyFlags flags) { dirtyFlags &= ~flags; } // Dispose of this object. public virtual void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected abstract void Dispose(bool disposing); ~ToolkitGraphicsBase() { Dispose(false); } // Clear the entire drawing surface. public abstract void Clear(Color color); // Draw a line between two points using the current pen. public abstract void DrawLine(int x1, int y1, int x2, int y2); // Draw a polygon using the current pen. public abstract void DrawPolygon(Point[] points); // Fill a polygon using the current brush. public abstract void FillPolygon(Point[] points, FillMode fillMode); // Draw a set of connected line segments using the current pen. public virtual void DrawLines(Point[] points) { for ( int i = 1;i < points.Length; i++ ) { if (points[i-1] != points[i]) DrawLine( points[i-1].X,points[i-1].Y,points[i].X,points[i].Y ); } } // Select a font public IToolkitFont Font { set { font = value; } get { return font; } } // Select a pen public IToolkitPen Pen { set { pen = value; } get { return pen; } } // Select a brush public IToolkitBrush Brush { set { brush = value; } get { return brush; } } // Draw the source parallelogram of an image into the parallelogram // defined by dest. Point[] has 3 Points, Top-Left, Top-Right and Bottom-Left. // The remaining point is inferred. public virtual void DrawImage(IToolkitImage image, Point[] src, Point[] dest) { int originX = dest[0].X; int originY = dest[0].Y; for (int i = 1; i < 3; i++) { if (originX > dest[i].X) originX = dest[i].X; if (originY > dest[i].Y) originY = dest[i].Y; } DotGNU.Images.Image gnuImage = (image as ToolkitImageBase).image; // Currently we only draw the first frame. Frame frame = gnuImage.GetFrame(0); frame = frame.AdjustImage(src[0].X, src[0].Y, src[1].X, src[1].Y, src[2].X, src[2].Y, dest[0].X - originX, dest[0].Y - originY, dest[1].X - originX, dest[1].Y - originY, dest[2].X - originX, dest[2].Y - originY); // Setup the new image and draw it. using (DotGNU.Images.Image newGnuImage = new DotGNU.Images.Image(gnuImage.Width, gnuImage.Height, gnuImage.PixelFormat)) { newGnuImage.AddFrame(frame); IToolkitImage newImage = Toolkit.CreateImage(newGnuImage, 0); DrawImage( newImage, originX, originY); } } #if CONFIG_EXTENDED_NUMERICS private static Point ComputePoint(float u, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { float px=0; float py=0; float blend; float u2=(1.0f-u); // Point 0 blend = u2*u2*u2; px += blend * x1; py += blend * y1; // Point 1 blend = 3 * u * u2 * u2; px += blend * x2; py += blend * y2; // Point 2 blend = 3 * u * u * u2; px += blend * x3; py += blend * y3; // Point 3 blend = u * u * u; px += blend * x4; py += blend * y4; return new Point((int)Math.Round(px),(int)Math.Round(py)); } private int ComputeSteps(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { double length=0L; length+=Math.Sqrt((x1-x2)*(x1-x2) + (y1-y2) * (y1-y2)); length+=Math.Sqrt((x2-x3)*(x2-x3) + (y2-y3) * (y2-y3)); length+=Math.Sqrt((x3-x4)*(x3-x4) + (y3-y4) * (y3-y4)); return (int)Math.Ceiling(length); } private Point[] ComputeBezier(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { int steps=ComputeSteps(x1,y1,x2,y2,x3,y3,x4,y4); Point [] points=new Point[steps]; for(int i=0;i<steps;i++) { float coeff=((float)i+1)/steps; points[i]=ComputePoint(coeff ,x1,y1,x2,y2,x3,y3,x4,y4); } return points; } private Point[] ComputeSplineSegment(Point p0,Point p1,Point T1, Point T2 ) { int steps=ComputeSteps(p0.X,p0.Y,T1.X,T1.Y,T2.X,T2.Y,p1.X,p1.Y); Point[] points = new Point[steps+1]; for(int i=0;i<=steps;i++) { float s=((float)i)/steps; float s2=s*s; float s3=s2*s; float h1 = 2*s3 - 3*s2 + 1; float h2 = -2*s3 + 3*s2; float h3 = s3 - 2*s2 + s; float h4 = s3 - s2; points[i].X=(int)(h1*p0.X+h2*p1.X+h3*T1.X+h4*T2.X); points[i].Y=(int)(h1*p0.Y+h2*p1.Y+h3*T1.Y+h4*T2.Y); } return points; } private Point[] ComputeTangent(Point[] points, float tension, bool closed, int numberOfSegments) { Point p0,p1; if (numberOfSegments<3) return null; Point[] tan=new Point[numberOfSegments]; for(int i=0;i<numberOfSegments;i++) { if(i==0) { if(closed) p0 = points[numberOfSegments-1]; else p0 = points[0]; } else p0 = points[i-1]; if(i==numberOfSegments-1) { if(closed) p1 = points[0]; else p1 = points[i]; } else p1 = points[i+1]; tan[i].X = (int)(tension*(p1.X - p0.X)); tan[i].Y = (int)(tension*(p1.Y - p0.Y)); } return tan; } // Draw a bezier curve using the current pen. public virtual void DrawBezier(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { // TODO: Optimize this to plot points without // involving line-drawing operations Point [] points = ComputeBezier(x1,y1,x2,y2,x3,y3,x4,y4); if (points.Length > 2) { DrawLines(points); } } // Fill a bezier curve using the current pen. public virtual void FillBezier(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, FillMode fillMode ) { // TODO: Optimize this to plot points without // involving line-drawing operations Point [] points = ComputeBezier(x1,y1,x2,y2,x3,y3,x4,y4); if (points.Length > 2) { FillPolygon(points,fillMode); } } // Draw a closed cardinal curve using the current pen. public virtual void DrawClosedCurve(Point[] points, float tension) { if(points.Length == 0) return; Point [] tangent=ComputeTangent(points,tension,true,points.Length); if (tangent == null) { DrawLines(points); return; } for(int i=0;i<points.Length-1;i++) DrawLines(ComputeSplineSegment(points[i],points[i+1],tangent[i],tangent[i+1])); DrawLines(ComputeSplineSegment(points[points.Length-1],points[0],tangent[points.Length-1],tangent[0])); } // Fill a closed cardinal curve using the current brush. public virtual void FillClosedCurve (Point[] points, float tension, FillMode fillMode) { if(points.Length == 0) return; Point [] tangent=ComputeTangent(points,tension,true,points.Length); if (tangent == null) { DrawLines(points); return; } Point[][] fpoints = new Point[points.Length][]; int size=0; for(int i=0;i<points.Length-1;i++) { fpoints[i]=ComputeSplineSegment(points[i],points[i+1],tangent[i],tangent[i+1]); DrawLines(fpoints[i]); size+=fpoints[i].Length; } fpoints[points.Length-1]= ComputeSplineSegment(points[points.Length-1],points[0],tangent[points.Length-1],tangent[0]); size+=fpoints[points.Length-1].Length; Point[] poly= new Point[size]; int z=0; for(int i=0;i<fpoints.Length;i++) for(int j=0;j<fpoints[i].Length;j++) poly[z++]=fpoints[i][j]; FillPolygon(poly,fillMode); } // Draw a cardinal curve using the current pen. public virtual void DrawCurve(Point[] points, int offset, int numberOfSegments, float tension) { Point [] tangent=ComputeTangent(points,tension,false,numberOfSegments+1); if (tangent == null) { DrawLines(points); return; } for(int i=0;i<numberOfSegments;i++) DrawLines(ComputeSplineSegment(points[i],points[i+1],tangent[i],tangent[i+1])); } #else // !CONFIG_EXTENDED_NUMERICS // Stub out spline operations if we don't have floating-point. // Draw a bezier curve using the current pen. public virtual void DrawBezier(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { // Nothing to do here. } // Draw a closed cardinal curve using the current pen. public virtual void DrawClosedCurve(Point[] points, float tension) { // Nothing to do here. } // Fill a closed cardinal curve using the current brush. public virtual void FillClosedCurve (Point[] points, float tension, FillMode fillMode) { // Nothing to do here. } // Draw a cardinal curve using the current pen. public virtual void DrawCurve(Point[] points, int offset, int numberOfSegments, float tension) { // Nothing to do here. } #endif // !CONFIG_EXTENDED_NUMERICS // Draw an arc within a rectangle defined by four points. public abstract void DrawArc (Point[] rect, float startAngle, float sweepAngle); // Draw a pie slice within a rectangle defined by four points. public abstract void DrawPie (Point[] rect, float startAngle, float sweepAngle); // Fill a pie slice within a rectangle defined by four points. public abstract void FillPie (Point[] rect, float startAngle, float sweepAngle); // Draw a string using the current font and brush. public abstract void DrawString (String s, int x, int y, StringFormat format); // Draw a string using the current font and brush within a // layout rectangle that is defined by four points. public virtual void DrawString (String s, Point[] layoutRectangle, StringFormat format) { // TODO: implement a default string draw, laying out // the text within the specified rectangle. } // Measure a string using the current font and a given layout rectangle. public abstract Size MeasureString (String s, Point[] layoutRectangle, StringFormat format, out int charactersFitted, out int linesFilled, bool ascentOnly); // Flush the graphics subsystem public virtual void Flush(FlushIntention intention) { // Nothing to do in the base class. } // Get the nearest color to a specified one. public virtual Color GetNearestColor(Color color) { // By default, we assume that the display is true color. return color; } // Add a metafile comment. public virtual void AddMetafileComment(byte[] data) { // Nothing to do in the base class. } // Get the HDC associated with this graphics object. public virtual IntPtr GetHdc() { // Nothing to do in the base class. return IntPtr.Zero; } // Release a HDC that was obtained using "GetHdc()". public virtual void ReleaseHdc(IntPtr hdc) { // Nothing to do in the base class. } // Set the clipping region to empty. public abstract void SetClipEmpty(); // Set the clipping region to infinite (i.e. disable clipping). public abstract void SetClipInfinite(); // Set the clipping region to a single rectangle. public abstract void SetClipRect(int x, int y, int width, int height); // Set the clipping region to a list of rectangles. public abstract void SetClipRects(Rectangle[] rects); // Set the clipping region to a complex mask. public abstract void SetClipMask(Object mask, int topx, int topy); // Get the line spacing for the font selected into this graphics object. public abstract int GetLineSpacing(); // Draw an image at the coordinates public abstract void DrawImage(IToolkitImage image, int x, int y); // Draw a bitmap-based glyph to a "Graphics" object. "bits" must be // in the form of an xbm bitmap. public abstract void DrawGlyph(int x, int y, byte[] bits, int bitsWidth, int bitsHeight, Color color); }; // class ToolkitGraphicsBase }; // namespace System.Drawing.Toolkit
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Binary.Metadata; using Apache.Ignite.Core.Impl.Binary.Structure; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Binary writer implementation. /// </summary> internal class BinaryWriter : IBinaryWriter, IBinaryRawWriter { /** Marshaller. */ private readonly Marshaller _marsh; /** Stream. */ private readonly IBinaryStream _stream; /** Builder (used only during build). */ private BinaryObjectBuilder _builder; /** Handles. */ private BinaryHandleDictionary<object, long> _hnds; /** Metadatas collected during this write session. */ private IDictionary<int, BinaryType> _metas; /** Current stack frame. */ private Frame _frame; /** Whether we are currently detaching an object. */ private bool _detaching; /** Schema holder. */ private readonly BinaryObjectSchemaHolder _schema = BinaryObjectSchemaHolder.Current; /// <summary> /// Gets the marshaller. /// </summary> internal Marshaller Marshaller { get { return _marsh; } } /// <summary> /// Write named boolean value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Boolean value.</param> public void WriteBoolean(string fieldName, bool val) { WriteFieldId(fieldName, BinaryUtils.TypeBool); WriteBooleanField(val); } /// <summary> /// Writes the boolean field. /// </summary> /// <param name="val">if set to <c>true</c> [value].</param> internal void WriteBooleanField(bool val) { _stream.WriteByte(BinaryUtils.TypeBool); _stream.WriteBool(val); } /// <summary> /// Write boolean value. /// </summary> /// <param name="val">Boolean value.</param> public void WriteBoolean(bool val) { _stream.WriteBool(val); } /// <summary> /// Write named boolean array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Boolean array.</param> public void WriteBooleanArray(string fieldName, bool[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayBool); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayBool); BinaryUtils.WriteBooleanArray(val, _stream); } } /// <summary> /// Write boolean array. /// </summary> /// <param name="val">Boolean array.</param> public void WriteBooleanArray(bool[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayBool); BinaryUtils.WriteBooleanArray(val, _stream); } } /// <summary> /// Write named byte value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Byte value.</param> public void WriteByte(string fieldName, byte val) { WriteFieldId(fieldName, BinaryUtils.TypeByte); WriteByteField(val); } /// <summary> /// Write byte field value. /// </summary> /// <param name="val">Byte value.</param> internal void WriteByteField(byte val) { _stream.WriteByte(BinaryUtils.TypeByte); _stream.WriteByte(val); } /// <summary> /// Write byte value. /// </summary> /// <param name="val">Byte value.</param> public void WriteByte(byte val) { _stream.WriteByte(val); } /// <summary> /// Write named byte array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Byte array.</param> public void WriteByteArray(string fieldName, byte[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayByte); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayByte); BinaryUtils.WriteByteArray(val, _stream); } } /// <summary> /// Write byte array. /// </summary> /// <param name="val">Byte array.</param> public void WriteByteArray(byte[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayByte); BinaryUtils.WriteByteArray(val, _stream); } } /// <summary> /// Write named short value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Short value.</param> public void WriteShort(string fieldName, short val) { WriteFieldId(fieldName, BinaryUtils.TypeShort); WriteShortField(val); } /// <summary> /// Write short field value. /// </summary> /// <param name="val">Short value.</param> internal void WriteShortField(short val) { _stream.WriteByte(BinaryUtils.TypeShort); _stream.WriteShort(val); } /// <summary> /// Write short value. /// </summary> /// <param name="val">Short value.</param> public void WriteShort(short val) { _stream.WriteShort(val); } /// <summary> /// Write named short array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Short array.</param> public void WriteShortArray(string fieldName, short[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayShort); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayShort); BinaryUtils.WriteShortArray(val, _stream); } } /// <summary> /// Write short array. /// </summary> /// <param name="val">Short array.</param> public void WriteShortArray(short[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayShort); BinaryUtils.WriteShortArray(val, _stream); } } /// <summary> /// Write named char value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Char value.</param> public void WriteChar(string fieldName, char val) { WriteFieldId(fieldName, BinaryUtils.TypeChar); WriteCharField(val); } /// <summary> /// Write char field value. /// </summary> /// <param name="val">Char value.</param> internal void WriteCharField(char val) { _stream.WriteByte(BinaryUtils.TypeChar); _stream.WriteChar(val); } /// <summary> /// Write char value. /// </summary> /// <param name="val">Char value.</param> public void WriteChar(char val) { _stream.WriteChar(val); } /// <summary> /// Write named char array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Char array.</param> public void WriteCharArray(string fieldName, char[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayChar); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayChar); BinaryUtils.WriteCharArray(val, _stream); } } /// <summary> /// Write char array. /// </summary> /// <param name="val">Char array.</param> public void WriteCharArray(char[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayChar); BinaryUtils.WriteCharArray(val, _stream); } } /// <summary> /// Write named int value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Int value.</param> public void WriteInt(string fieldName, int val) { WriteFieldId(fieldName, BinaryUtils.TypeInt); WriteIntField(val); } /// <summary> /// Writes the int field. /// </summary> /// <param name="val">The value.</param> internal void WriteIntField(int val) { _stream.WriteByte(BinaryUtils.TypeInt); _stream.WriteInt(val); } /// <summary> /// Write int value. /// </summary> /// <param name="val">Int value.</param> public void WriteInt(int val) { _stream.WriteInt(val); } /// <summary> /// Write named int array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Int array.</param> public void WriteIntArray(string fieldName, int[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayInt); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayInt); BinaryUtils.WriteIntArray(val, _stream); } } /// <summary> /// Write int array. /// </summary> /// <param name="val">Int array.</param> public void WriteIntArray(int[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayInt); BinaryUtils.WriteIntArray(val, _stream); } } /// <summary> /// Write named long value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Long value.</param> public void WriteLong(string fieldName, long val) { WriteFieldId(fieldName, BinaryUtils.TypeLong); WriteLongField(val); } /// <summary> /// Writes the long field. /// </summary> /// <param name="val">The value.</param> internal void WriteLongField(long val) { _stream.WriteByte(BinaryUtils.TypeLong); _stream.WriteLong(val); } /// <summary> /// Write long value. /// </summary> /// <param name="val">Long value.</param> public void WriteLong(long val) { _stream.WriteLong(val); } /// <summary> /// Write named long array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Long array.</param> public void WriteLongArray(string fieldName, long[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayLong); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayLong); BinaryUtils.WriteLongArray(val, _stream); } } /// <summary> /// Write long array. /// </summary> /// <param name="val">Long array.</param> public void WriteLongArray(long[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayLong); BinaryUtils.WriteLongArray(val, _stream); } } /// <summary> /// Write named float value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Float value.</param> public void WriteFloat(string fieldName, float val) { WriteFieldId(fieldName, BinaryUtils.TypeFloat); WriteFloatField(val); } /// <summary> /// Writes the float field. /// </summary> /// <param name="val">The value.</param> internal void WriteFloatField(float val) { _stream.WriteByte(BinaryUtils.TypeFloat); _stream.WriteFloat(val); } /// <summary> /// Write float value. /// </summary> /// <param name="val">Float value.</param> public void WriteFloat(float val) { _stream.WriteFloat(val); } /// <summary> /// Write named float array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Float array.</param> public void WriteFloatArray(string fieldName, float[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayFloat); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayFloat); BinaryUtils.WriteFloatArray(val, _stream); } } /// <summary> /// Write float array. /// </summary> /// <param name="val">Float array.</param> public void WriteFloatArray(float[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayFloat); BinaryUtils.WriteFloatArray(val, _stream); } } /// <summary> /// Write named double value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Double value.</param> public void WriteDouble(string fieldName, double val) { WriteFieldId(fieldName, BinaryUtils.TypeDouble); WriteDoubleField(val); } /// <summary> /// Writes the double field. /// </summary> /// <param name="val">The value.</param> internal void WriteDoubleField(double val) { _stream.WriteByte(BinaryUtils.TypeDouble); _stream.WriteDouble(val); } /// <summary> /// Write double value. /// </summary> /// <param name="val">Double value.</param> public void WriteDouble(double val) { _stream.WriteDouble(val); } /// <summary> /// Write named double array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Double array.</param> public void WriteDoubleArray(string fieldName, double[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayDouble); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayDouble); BinaryUtils.WriteDoubleArray(val, _stream); } } /// <summary> /// Write double array. /// </summary> /// <param name="val">Double array.</param> public void WriteDoubleArray(double[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayDouble); BinaryUtils.WriteDoubleArray(val, _stream); } } /// <summary> /// Write named decimal value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Decimal value.</param> public void WriteDecimal(string fieldName, decimal? val) { WriteFieldId(fieldName, BinaryUtils.TypeDecimal); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeDecimal); BinaryUtils.WriteDecimal(val.Value, _stream); } } /// <summary> /// Write decimal value. /// </summary> /// <param name="val">Decimal value.</param> public void WriteDecimal(decimal? val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeDecimal); BinaryUtils.WriteDecimal(val.Value, _stream); } } /// <summary> /// Write named decimal array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Decimal array.</param> public void WriteDecimalArray(string fieldName, decimal?[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayDecimal); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayDecimal); BinaryUtils.WriteDecimalArray(val, _stream); } } /// <summary> /// Write decimal array. /// </summary> /// <param name="val">Decimal array.</param> public void WriteDecimalArray(decimal?[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayDecimal); BinaryUtils.WriteDecimalArray(val, _stream); } } /// <summary> /// Write named date value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Date value.</param> public void WriteTimestamp(string fieldName, DateTime? val) { WriteFieldId(fieldName, BinaryUtils.TypeTimestamp); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeTimestamp); BinaryUtils.WriteTimestamp(val.Value, _stream); } } /// <summary> /// Write date value. /// </summary> /// <param name="val">Date value.</param> public void WriteTimestamp(DateTime? val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeTimestamp); BinaryUtils.WriteTimestamp(val.Value, _stream); } } /// <summary> /// Write named date array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Date array.</param> public void WriteTimestampArray(string fieldName, DateTime?[] val) { WriteFieldId(fieldName, BinaryUtils.TypeTimestamp); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayTimestamp); BinaryUtils.WriteTimestampArray(val, _stream); } } /// <summary> /// Write date array. /// </summary> /// <param name="val">Date array.</param> public void WriteTimestampArray(DateTime?[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayTimestamp); BinaryUtils.WriteTimestampArray(val, _stream); } } /// <summary> /// Write named string value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">String value.</param> public void WriteString(string fieldName, string val) { WriteFieldId(fieldName, BinaryUtils.TypeString); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeString); BinaryUtils.WriteString(val, _stream); } } /// <summary> /// Write string value. /// </summary> /// <param name="val">String value.</param> public void WriteString(string val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeString); BinaryUtils.WriteString(val, _stream); } } /// <summary> /// Write named string array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">String array.</param> public void WriteStringArray(string fieldName, string[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayString); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayString); BinaryUtils.WriteStringArray(val, _stream); } } /// <summary> /// Write string array. /// </summary> /// <param name="val">String array.</param> public void WriteStringArray(string[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayString); BinaryUtils.WriteStringArray(val, _stream); } } /// <summary> /// Write named GUID value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">GUID value.</param> public void WriteGuid(string fieldName, Guid? val) { WriteFieldId(fieldName, BinaryUtils.TypeGuid); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeGuid); BinaryUtils.WriteGuid(val.Value, _stream); } } /// <summary> /// Write GUID value. /// </summary> /// <param name="val">GUID value.</param> public void WriteGuid(Guid? val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeGuid); BinaryUtils.WriteGuid(val.Value, _stream); } } /// <summary> /// Write named GUID array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">GUID array.</param> public void WriteGuidArray(string fieldName, Guid?[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayGuid); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayGuid); BinaryUtils.WriteGuidArray(val, _stream); } } /// <summary> /// Write GUID array. /// </summary> /// <param name="val">GUID array.</param> public void WriteGuidArray(Guid?[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryUtils.TypeArrayGuid); BinaryUtils.WriteGuidArray(val, _stream); } } /// <summary> /// Write named enum value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Enum value.</param> public void WriteEnum<T>(string fieldName, T val) { WriteFieldId(fieldName, BinaryUtils.TypeEnum); WriteEnum(val); } /// <summary> /// Write enum value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="val">Enum value.</param> public void WriteEnum<T>(T val) { // ReSharper disable once CompareNonConstrainedGenericWithNull if (val == null) WriteNullField(); else { var desc = _marsh.GetDescriptor(val.GetType()); var metaHnd = _marsh.GetBinaryTypeHandler(desc); _stream.WriteByte(BinaryUtils.TypeEnum); BinaryUtils.WriteEnum(this, val); SaveMetadata(desc, metaHnd.OnObjectWriteFinished()); } } /// <summary> /// Write named enum array. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Enum array.</param> public void WriteEnumArray<T>(string fieldName, T[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArrayEnum); WriteEnumArray(val); } /// <summary> /// Write enum array. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="val">Enum array.</param> public void WriteEnumArray<T>(T[] val) { WriteEnumArrayInternal(val, null); } /// <summary> /// Writes the enum array. /// </summary> /// <param name="val">The value.</param> /// <param name="elementTypeId">The element type id.</param> public void WriteEnumArrayInternal(Array val, int? elementTypeId) { if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryUtils.TypeArrayEnum); BinaryUtils.WriteArray(val, this, elementTypeId); } } /// <summary> /// Write named object value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Object value.</param> public void WriteObject<T>(string fieldName, T val) { WriteFieldId(fieldName, BinaryUtils.TypeObject); // ReSharper disable once CompareNonConstrainedGenericWithNull if (val == null) WriteNullField(); else Write(val); } /// <summary> /// Write object value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="val">Object value.</param> public void WriteObject<T>(T val) { Write(val); } /// <summary> /// Write named object array. /// </summary> /// <typeparam name="T">Element type.</typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Object array.</param> public void WriteArray<T>(string fieldName, T[] val) { WriteFieldId(fieldName, BinaryUtils.TypeArray); WriteArray(val); } /// <summary> /// Write object array. /// </summary> /// <typeparam name="T">Element type.</typeparam> /// <param name="val">Object array.</param> public void WriteArray<T>(T[] val) { WriteArrayInternal(val); } /// <summary> /// Write object array. /// </summary> /// <param name="val">Object array.</param> public void WriteArrayInternal(Array val) { if (val == null) WriteNullRawField(); else { if (WriteHandle(_stream.Position, val)) return; _stream.WriteByte(BinaryUtils.TypeArray); BinaryUtils.WriteArray(val, this); } } /// <summary> /// Write named collection. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Collection.</param> public void WriteCollection(string fieldName, ICollection val) { WriteFieldId(fieldName, BinaryUtils.TypeCollection); WriteCollection(val); } /// <summary> /// Write collection. /// </summary> /// <param name="val">Collection.</param> public void WriteCollection(ICollection val) { if (val == null) WriteNullField(); else { if (WriteHandle(_stream.Position, val)) return; WriteByte(BinaryUtils.TypeCollection); BinaryUtils.WriteCollection(val, this); } } /// <summary> /// Write named dictionary. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Dictionary.</param> public void WriteDictionary(string fieldName, IDictionary val) { WriteFieldId(fieldName, BinaryUtils.TypeDictionary); WriteDictionary(val); } /// <summary> /// Write dictionary. /// </summary> /// <param name="val">Dictionary.</param> public void WriteDictionary(IDictionary val) { if (val == null) WriteNullField(); else { if (WriteHandle(_stream.Position, val)) return; WriteByte(BinaryUtils.TypeDictionary); BinaryUtils.WriteDictionary(val, this); } } /// <summary> /// Write NULL field. /// </summary> private void WriteNullField() { _stream.WriteByte(BinaryUtils.HdrNull); } /// <summary> /// Write NULL raw field. /// </summary> private void WriteNullRawField() { _stream.WriteByte(BinaryUtils.HdrNull); } /// <summary> /// Get raw writer. /// </summary> /// <returns> /// Raw writer. /// </returns> public IBinaryRawWriter GetRawWriter() { if (_frame.RawPos == 0) _frame.RawPos = _stream.Position; return this; } /// <summary> /// Set new builder. /// </summary> /// <param name="builder">Builder.</param> /// <returns>Previous builder.</returns> internal BinaryObjectBuilder SetBuilder(BinaryObjectBuilder builder) { BinaryObjectBuilder ret = _builder; _builder = builder; return ret; } /// <summary> /// Constructor. /// </summary> /// <param name="marsh">Marshaller.</param> /// <param name="stream">Stream.</param> internal BinaryWriter(Marshaller marsh, IBinaryStream stream) { _marsh = marsh; _stream = stream; } /// <summary> /// Write object. /// </summary> /// <param name="obj">Object.</param> public void Write<T>(T obj) { // Handle special case for null. // ReSharper disable once CompareNonConstrainedGenericWithNull if (obj == null) { _stream.WriteByte(BinaryUtils.HdrNull); return; } // We use GetType() of a real object instead of typeof(T) to take advantage of // automatic Nullable'1 unwrapping. Type type = obj.GetType(); // Handle common case when primitive is written. if (type.IsPrimitive) { WritePrimitive(obj, type); return; } // Handle enums. if (type.IsEnum) { WriteEnum(obj); return; } // Handle special case for builder. if (WriteBuilderSpecials(obj)) return; // Are we dealing with a well-known type? var handler = BinarySystemHandlers.GetWriteHandler(type); if (handler != null) { if (handler.SupportsHandles && WriteHandle(_stream.Position, obj)) return; handler.Write(this, obj); return; } // Suppose that we faced normal object and perform descriptor lookup. var desc = _marsh.GetDescriptor(type); // Writing normal object. var pos = _stream.Position; // Dealing with handles. if (desc.Serializer.SupportsHandles && WriteHandle(pos, obj)) return; // Skip header length as not everything is known now _stream.Seek(BinaryObjectHeader.Size, SeekOrigin.Current); // Write type name for unregistered types if (!desc.IsRegistered) WriteString(type.AssemblyQualifiedName); var headerSize = _stream.Position - pos; // Preserve old frame. var oldFrame = _frame; // Push new frame. _frame.RawPos = 0; _frame.Pos = pos; _frame.Struct = new BinaryStructureTracker(desc, desc.WriterTypeStructure); _frame.HasCustomTypeData = false; var schemaIdx = _schema.PushSchema(); try { // Write object fields. desc.Serializer.WriteBinary(obj, this); var dataEnd = _stream.Position; // Write schema var schemaOffset = dataEnd - pos; int schemaId; var flags = desc.UserType ? BinaryObjectHeader.Flag.UserType : BinaryObjectHeader.Flag.None; if (_frame.HasCustomTypeData) flags |= BinaryObjectHeader.Flag.CustomDotNetType; if (Marshaller.CompactFooter && desc.UserType) flags |= BinaryObjectHeader.Flag.CompactFooter; var hasSchema = _schema.WriteSchema(_stream, schemaIdx, out schemaId, ref flags); if (hasSchema) { flags |= BinaryObjectHeader.Flag.HasSchema; // Calculate and write header. if (_frame.RawPos > 0) _stream.WriteInt(_frame.RawPos - pos); // raw offset is in the last 4 bytes // Update schema in type descriptor if (desc.Schema.Get(schemaId) == null) desc.Schema.Add(schemaId, _schema.GetSchema(schemaIdx)); } else schemaOffset = headerSize; if (_frame.RawPos > 0) flags |= BinaryObjectHeader.Flag.HasRaw; var len = _stream.Position - pos; var hashCode = BinaryArrayEqualityComparer.GetHashCode(Stream, pos + BinaryObjectHeader.Size, dataEnd - pos - BinaryObjectHeader.Size); var header = new BinaryObjectHeader(desc.IsRegistered ? desc.TypeId : BinaryUtils.TypeUnregistered, hashCode, len, schemaId, schemaOffset, flags); BinaryObjectHeader.Write(header, _stream, pos); Stream.Seek(pos + len, SeekOrigin.Begin); // Seek to the end } finally { _schema.PopSchema(schemaIdx); } // Apply structure updates if any. _frame.Struct.UpdateWriterStructure(this); // Restore old frame. _frame = oldFrame; } /// <summary> /// Marks current object with a custom type data flag. /// </summary> public void SetCustomTypeDataFlag(bool hasCustomTypeData) { _frame.HasCustomTypeData = hasCustomTypeData; } /// <summary> /// Write primitive type. /// </summary> /// <param name="val">Object.</param> /// <param name="type">Type.</param> private unsafe void WritePrimitive<T>(T val, Type type) { // .Net defines 14 primitive types. We support 12 - excluding IntPtr and UIntPtr. // Types check sequence is designed to minimize comparisons for the most frequent types. if (type == typeof(int)) WriteIntField(TypeCaster<int>.Cast(val)); else if (type == typeof(long)) WriteLongField(TypeCaster<long>.Cast(val)); else if (type == typeof(bool)) WriteBooleanField(TypeCaster<bool>.Cast(val)); else if (type == typeof(byte)) WriteByteField(TypeCaster<byte>.Cast(val)); else if (type == typeof(short)) WriteShortField(TypeCaster<short>.Cast(val)); else if (type == typeof(char)) WriteCharField(TypeCaster<char>.Cast(val)); else if (type == typeof(float)) WriteFloatField(TypeCaster<float>.Cast(val)); else if (type == typeof(double)) WriteDoubleField(TypeCaster<double>.Cast(val)); else if (type == typeof(sbyte)) { var val0 = TypeCaster<sbyte>.Cast(val); WriteByteField(*(byte*)&val0); } else if (type == typeof(ushort)) { var val0 = TypeCaster<ushort>.Cast(val); WriteShortField(*(short*) &val0); } else if (type == typeof(uint)) { var val0 = TypeCaster<uint>.Cast(val); WriteIntField(*(int*)&val0); } else if (type == typeof(ulong)) { var val0 = TypeCaster<ulong>.Cast(val); WriteLongField(*(long*)&val0); } else throw BinaryUtils.GetUnsupportedTypeException(type, val); } /// <summary> /// Try writing object as special builder type. /// </summary> /// <param name="obj">Object.</param> /// <returns>True if object was written, false otherwise.</returns> private bool WriteBuilderSpecials<T>(T obj) { if (_builder != null) { // Special case for binary object during build. BinaryObject portObj = obj as BinaryObject; if (portObj != null) { if (!WriteHandle(_stream.Position, portObj)) _builder.ProcessBinary(_stream, portObj); return true; } // Special case for builder during build. BinaryObjectBuilder portBuilder = obj as BinaryObjectBuilder; if (portBuilder != null) { if (!WriteHandle(_stream.Position, portBuilder)) _builder.ProcessBuilder(_stream, portBuilder); return true; } } return false; } /// <summary> /// Add handle to handles map. /// </summary> /// <param name="pos">Position in stream.</param> /// <param name="obj">Object.</param> /// <returns><c>true</c> if object was written as handle.</returns> private bool WriteHandle(long pos, object obj) { if (_hnds == null) { // Cache absolute handle position. _hnds = new BinaryHandleDictionary<object, long>(obj, pos, ReferenceEqualityComparer<object>.Instance); return false; } long hndPos; if (!_hnds.TryGetValue(obj, out hndPos)) { // Cache absolute handle position. _hnds.Add(obj, pos); return false; } _stream.WriteByte(BinaryUtils.HdrHnd); // Handle is written as difference between position before header and handle position. _stream.WriteInt((int)(pos - hndPos)); return true; } /// <summary> /// Perform action with detached semantics. /// </summary> /// <param name="a"></param> internal void WithDetach(Action<BinaryWriter> a) { if (_detaching) a(this); else { _detaching = true; BinaryHandleDictionary<object, long> oldHnds = _hnds; _hnds = null; try { a(this); } finally { _detaching = false; if (oldHnds != null) { // Merge newly recorded handles with old ones and restore old on the stack. // Otherwise we can use current handles right away. if (_hnds != null) oldHnds.Merge(_hnds); _hnds = oldHnds; } } } } /// <summary> /// Stream. /// </summary> internal IBinaryStream Stream { get { return _stream; } } /// <summary> /// Gets collected metadatas. /// </summary> /// <returns>Collected metadatas (if any).</returns> internal ICollection<BinaryType> GetBinaryTypes() { return _metas == null ? null : _metas.Values; } /// <summary> /// Write field ID. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="fieldTypeId">Field type ID.</param> private void WriteFieldId(string fieldName, byte fieldTypeId) { if (_frame.RawPos != 0) throw new BinaryObjectException("Cannot write named fields after raw data is written."); var fieldId = _frame.Struct.GetFieldId(fieldName, fieldTypeId); _schema.PushField(fieldId, _stream.Position - _frame.Pos); } /// <summary> /// Saves metadata for this session. /// </summary> /// <param name="desc">The descriptor.</param> /// <param name="fields">Fields metadata.</param> internal void SaveMetadata(IBinaryTypeDescriptor desc, IDictionary<string, BinaryField> fields) { Debug.Assert(desc != null); if (_metas == null) { _metas = new Dictionary<int, BinaryType>(1) { {desc.TypeId, new BinaryType(desc, fields)} }; } else { BinaryType meta; if (_metas.TryGetValue(desc.TypeId, out meta)) meta.UpdateFields(fields); else _metas[desc.TypeId] = new BinaryType(desc, fields); } } /// <summary> /// Stores current writer stack frame. /// </summary> private struct Frame { /** Current object start position. */ public int Pos; /** Current raw position. */ public int RawPos; /** Current type structure tracker. */ public BinaryStructureTracker Struct; /** Custom type data. */ public bool HasCustomTypeData; } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Diagnostics; using Windows.Foundation; using Windows.Media.Core; using Windows.Media.Playback; using Windows.UI.Core; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace SDKTemplate { /// <summary> /// Demonstrates playing video lists using MediaPlaybackList. /// </summary> public sealed partial class Scenario7 : Page { private MainPage rootPage = MainPage.Current; private MediaPlaybackList playbackList = new MediaPlaybackList(); public Scenario7() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { // Create a static playback list InitializePlaybackList(); // Set list for playback mediaElement.SetPlaybackSource(playbackList); } void InitializePlaybackList() { // Initialize the playlist data/view model. // In a production app your data would be sourced from a data store or service. // Add content to the ListView and to the MediaPlaybackList. MediaModel media = new MediaModel(rootPage.MultiTrackVideoMediaUri) { Title = "Fitness", ArtUri = new Uri("ms-appx:///Assets/Media/multivideo.jpg") }; playlistView.Items.Add(media); playbackList.Items.Add(media.MediaPlaybackItem); media = new MediaModel(rootPage.CaptionedMediaUri) { Title = "Elephant's Dream", ArtUri = new Uri("ms-appx:///Assets/Media/ElephantsDream.jpg") }; playlistView.Items.Add(media); playbackList.Items.Add(media.MediaPlaybackItem); media = new MediaModel(rootPage.SintelMediaUri) { Title = "Sintel", ArtUri = new Uri("ms-appx:///Assets/Media/sintel.jpg") }; playlistView.Items.Add(media); playbackList.Items.Add(media.MediaPlaybackItem); // Subscribe for changes playbackList.CurrentItemChanged += PlaybackList_CurrentItemChanged; // Loop playbackList.AutoRepeatEnabled = true; } private void PlaybackList_CurrentItemChanged(MediaPlaybackList sender, CurrentMediaPlaybackItemChangedEventArgs args) { var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Synchronize our UI with the currently-playing item. playlistView.SelectedIndex = (int)sender.CurrentItemIndex; }); } /// <summary> /// MediaPlayer state changed event handlers. /// Note that we can subscribe to events even if Media Player is playing media in background /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void MediaElement_CurrentStateChanged(object sender, RoutedEventArgs e) { var currentState = mediaElement.CurrentState; // Update state label txtCurrentState.Text = currentState.ToString(); // Update controls UpdateTransportControls(currentState); } private void PlaylistView_ItemClick(object sender, ItemClickEventArgs e) { var item = e.ClickedItem as MediaModel; Debug.WriteLine("Clicked item: " + item.Title); // Start the background task if it wasn't running playbackList.MoveTo((uint)playbackList.Items.IndexOf(item.MediaPlaybackItem)); if (MediaElementState.Paused == mediaElement.CurrentState || MediaElementState.Stopped == mediaElement.CurrentState) { mediaElement.Play(); } } /// <summary> /// Sends message to the background task to skip to the previous track. /// </summary> private void prevButton_Click(object sender, RoutedEventArgs e) { playbackList.MovePrevious(); } /// <summary> /// If the task is already running, it will just play/pause MediaPlayer Instance /// Otherwise, initializes MediaPlayer Handlers and starts playback /// track or to pause if we're already playing. /// </summary> private void playButton_Click(object sender, RoutedEventArgs e) { if (MediaElementState.Playing == mediaElement.CurrentState) { mediaElement.Pause(); } else if (MediaElementState.Paused == mediaElement.CurrentState || MediaElementState.Stopped == mediaElement.CurrentState) { mediaElement.Play(); } } /// <summary> /// Tells the background audio agent to skip to the next track. /// </summary> /// <param name="sender">The button</param> /// <param name="e">Click event args</param> private void nextButton_Click(object sender, RoutedEventArgs e) { playbackList.MoveNext(); } private async void speedButton_Click(object sender, RoutedEventArgs e) { // Create menu and add commands var popupMenu = new PopupMenu(); popupMenu.Commands.Add(new UICommand("4.0x", command => mediaElement.PlaybackRate = 4.0)); popupMenu.Commands.Add(new UICommand("2.0x", command => mediaElement.PlaybackRate = 2.0)); popupMenu.Commands.Add(new UICommand("1.5x", command => mediaElement.PlaybackRate = 1.5)); popupMenu.Commands.Add(new UICommand("1.0x", command => mediaElement.PlaybackRate = 1.0)); popupMenu.Commands.Add(new UICommand("0.5x", command => mediaElement.PlaybackRate = 0.5)); // Get button transform and then offset it by half the button // width to center. This will show the popup just above the button. var button = (Button)sender; var transform = button.TransformToVisual(null); var point = transform.TransformPoint(new Point(button.ActualWidth / 2, 0)); // Show popup IUICommand result = await popupMenu.ShowAsync(point); if (result != null) { button.Content = result.Label; } } private void UpdateTransportControls(MediaElementState state) { nextButton.IsEnabled = true; prevButton.IsEnabled = true; if (state == MediaElementState.Playing) { playButtonSymbol.Symbol = Symbol.Pause; } else { playButtonSymbol.Symbol = Symbol.Play; } } } public class MediaModel { public MediaModel(Uri mediaUri) { MediaPlaybackItem = new MediaPlaybackItem(MediaSource.CreateFromUri(mediaUri)); } public string Title { get; set; } public Uri ArtUri { get; set; } public MediaPlaybackItem MediaPlaybackItem { get; private set; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Net.Http.Headers { public class EntityTagHeaderValue : ICloneable { private static EntityTagHeaderValue s_any; private string _tag; private bool _isWeak; public string Tag { get { return _tag; } } public bool IsWeak { get { return _isWeak; } } public static EntityTagHeaderValue Any { get { if (s_any == null) { s_any = new EntityTagHeaderValue(); s_any._tag = "*"; s_any._isWeak = false; } return s_any; } } public EntityTagHeaderValue(string tag) : this(tag, false) { } public EntityTagHeaderValue(string tag, bool isWeak) { if (string.IsNullOrEmpty(tag)) { throw new ArgumentException(SR.net_http_argument_empty_string, "tag"); } int length = 0; if ((HttpRuleParser.GetQuotedStringLength(tag, 0, out length) != HttpParseResult.Parsed) || (length != tag.Length)) { // Note that we don't allow 'W/' prefixes for weak ETags in the 'tag' parameter. If the user wants to // add a weak ETag, he can set 'isWeak' to true. throw new FormatException(SR.net_http_headers_invalid_etag_name); } _tag = tag; _isWeak = isWeak; } private EntityTagHeaderValue(EntityTagHeaderValue source) { Contract.Requires(source != null); _tag = source._tag; _isWeak = source._isWeak; } private EntityTagHeaderValue() { } public override string ToString() { if (_isWeak) { return "W/" + _tag; } return _tag; } public override bool Equals(object obj) { EntityTagHeaderValue other = obj as EntityTagHeaderValue; if (other == null) { return false; } // Since the tag is a quoted-string we treat it case-sensitive. return ((_isWeak == other._isWeak) && string.Equals(_tag, other._tag, StringComparison.Ordinal)); } public override int GetHashCode() { // Since the tag is a quoted-string we treat it case-sensitive. return _tag.GetHashCode() ^ _isWeak.GetHashCode(); } public static EntityTagHeaderValue Parse(string input) { int index = 0; return (EntityTagHeaderValue)GenericHeaderParser.SingleValueEntityTagParser.ParseValue( input, null, ref index); } public static bool TryParse(string input, out EntityTagHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (GenericHeaderParser.SingleValueEntityTagParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (EntityTagHeaderValue)output; return true; } return false; } internal static int GetEntityTagLength(string input, int startIndex, out EntityTagHeaderValue parsedValue) { Contract.Requires(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Caller must remove leading whitespaces. If not, we'll return 0. bool isWeak = false; int current = startIndex; char firstChar = input[startIndex]; if (firstChar == '*') { // We have '*' value, indicating "any" ETag. parsedValue = Any; current++; } else { // The RFC defines 'W/' as prefix, but we'll be flexible and also accept lower-case 'w'. if ((firstChar == 'W') || (firstChar == 'w')) { current++; // We need at least 3 more chars: the '/' character followed by two quotes. if ((current + 2 >= input.Length) || (input[current] != '/')) { return 0; } isWeak = true; current++; // we have a weak-entity tag. current = current + HttpRuleParser.GetWhitespaceLength(input, current); } int tagStartIndex = current; int tagLength = 0; if (HttpRuleParser.GetQuotedStringLength(input, current, out tagLength) != HttpParseResult.Parsed) { return 0; } parsedValue = new EntityTagHeaderValue(); if (tagLength == input.Length) { // Most of the time we'll have strong ETags without leading/trailing whitespaces. Debug.Assert(startIndex == 0); Debug.Assert(!isWeak); parsedValue._tag = input; parsedValue._isWeak = false; } else { parsedValue._tag = input.Substring(tagStartIndex, tagLength); parsedValue._isWeak = isWeak; } current = current + tagLength; } current = current + HttpRuleParser.GetWhitespaceLength(input, current); return current - startIndex; } object ICloneable.Clone() { if (this == s_any) { return s_any; } else { return new EntityTagHeaderValue(this); } } } }
namespace AngleSharp.Html.Dom.Events { using AngleSharp.Attributes; using AngleSharp.Dom; using AngleSharp.Dom.Events; using System; /// <summary> /// Represents the event args for a mouse event. /// </summary> [DomName("MouseEvent")] public class MouseEvent : UiEvent { #region ctor /// <summary> /// Creates a new event. /// </summary> public MouseEvent() { } /// <summary> /// Creates a new event and initializes it. /// </summary> /// <param name="type">The type of the event.</param> /// <param name="bubbles">If the event is bubbling.</param> /// <param name="cancelable">If the event is cancelable.</param> /// <param name="view">Sets the associated view for the UI event.</param> /// <param name="detail">Sets the detail id for the UI event.</param> /// <param name="screenX">Sets the screen X coordinate.</param> /// <param name="screenY">Sets the screen Y coordinate.</param> /// <param name="clientX">Sets the client X coordinate.</param> /// <param name="clientY">Sets the client Y coordinate.</param> /// <param name="ctrlKey">Sets if the control key was pressed.</param> /// <param name="altKey">Sets if the alt key was pressed.</param> /// <param name="shiftKey">Sets if the shift key was pressed.</param> /// <param name="metaKey">Sets if the meta key was pressed.</param> /// <param name="button">Sets which button has been pressed.</param> /// <param name="relatedTarget">The target of the mouse event.</param> [DomConstructor] [DomInitDict(offset: 1, optional: true)] public MouseEvent(String type, Boolean bubbles = false, Boolean cancelable = false, IWindow? view = null, Int32 detail = 0, Int32 screenX = 0, Int32 screenY = 0, Int32 clientX = 0, Int32 clientY = 0, Boolean ctrlKey = false, Boolean altKey = false, Boolean shiftKey = false, Boolean metaKey = false, MouseButton button = MouseButton.Primary, IEventTarget? relatedTarget = null) { Init(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget); } #endregion #region Properties /// <summary> /// Gets the screen X coordinates. /// </summary> [DomName("screenX")] public Int32 ScreenX { get; private set; } /// <summary> /// Gets the screen Y coordinates. /// </summary> [DomName("screenY")] public Int32 ScreenY { get; private set; } /// <summary> /// Gets the client X coordinates. /// </summary> [DomName("clientX")] public Int32 ClientX { get; private set; } /// <summary> /// Gets the client Y coordinates. /// </summary> [DomName("clientY")] public Int32 ClientY { get; private set; } /// <summary> /// Gets if the control key is pressed. /// </summary> [DomName("ctrlKey")] public Boolean IsCtrlPressed { get; private set; } /// <summary> /// Gets if the shift key is pressed. /// </summary> [DomName("shiftKey")] public Boolean IsShiftPressed { get; private set; } /// <summary> /// Gets if the alt key is pressed. /// </summary> [DomName("altKey")] public Boolean IsAltPressed { get; private set; } /// <summary> /// Gets if the meta key is pressed. /// </summary> [DomName("metaKey")] public Boolean IsMetaPressed { get; private set; } /// <summary> /// Gets which button has been pressed. /// </summary> [DomName("button")] public MouseButton Button { get; private set; } /// <summary> /// Gets the currently pressed buttons. /// </summary> [DomName("buttons")] public MouseButtons Buttons { get; private set; } /// <summary> /// Gets the target of the mouse event. /// </summary> [DomName("relatedTarget")] public IEventTarget? Target { get; private set; } /// <summary> /// Returns the current state of the specified modifier key. /// </summary> /// <param name="key">The modifier key to lookup.</param> /// <returns>True if the key is currently pressed, otherwise false.</returns> [DomName("getModifierState")] public Boolean GetModifierState(String key) { return false;//TODO } #endregion #region Methods /// <summary> /// Initializes the mouse event. /// </summary> /// <param name="type">The type of event.</param> /// <param name="bubbles">Determines if the event bubbles.</param> /// <param name="cancelable">Determines if the event is cancelable.</param> /// <param name="view">Sets the associated view for the UI event.</param> /// <param name="detail">Sets the detail id for the UIevent.</param> /// <param name="screenX">Sets the screen X coordinate.</param> /// <param name="screenY">Sets the screen Y coordinate.</param> /// <param name="clientX">Sets the client X coordinate.</param> /// <param name="clientY">Sets the client Y coordinate.</param> /// <param name="ctrlKey">Sets if the control key was pressed.</param> /// <param name="altKey">Sets if the alt key was pressed.</param> /// <param name="shiftKey">Sets if the shift key was pressed.</param> /// <param name="metaKey">Sets if the meta key was pressed.</param> /// <param name="button">Sets which button has been pressed.</param> /// <param name="target">The target of the mouse event.</param> [DomName("initMouseEvent")] public void Init(String type, Boolean bubbles, Boolean cancelable, IWindow? view, Int32 detail, Int32 screenX, Int32 screenY, Int32 clientX, Int32 clientY, Boolean ctrlKey, Boolean altKey, Boolean shiftKey, Boolean metaKey, MouseButton button, IEventTarget? target) { Init(type, bubbles, cancelable, view, detail); ScreenX = screenX; ScreenY = screenY; ClientX = clientX; ClientY = clientY; IsCtrlPressed = ctrlKey; IsMetaPressed = metaKey; IsShiftPressed = shiftKey; IsAltPressed = altKey; Button = button; Target = target; } #endregion } }
using System; using System.Collections; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Text; namespace Rawr.ProtWarr { [Rawr.Calculations.RawrModelInfo("ProtWarr", "Ability_Warrior_DefensiveStance", CharacterClass.Warrior)] public class CalculationsProtWarr : CalculationsBase { public override List<GemmingTemplate> DefaultGemmingTemplates { get { // Relevant Gem IDs for ProtWarr // Red int[] bold = { 39900, 39996, 40111, 42142 }; // Strength int[] delicate = { 39905, 39997, 40112, 42143 }; // Agility int[] subtle = { 39907, 40000, 40115, 42151 }; // Dodge int[] flashing = { 39908, 40001, 40116, 42152 }; // Parry int[] precise = { 39910, 40003, 40118, 42154 }; // Expertise // Purple int[] shifting = { 39935, 40023, 40130, 40130 }; // Agility + Stamina int[] sovereign = { 39934, 40022, 40129, 40129 }; // Strength + Stamina int[] regal = { 39938, 40031, 40138, 40138 }; // Dodge + Stamina int[] defender = { 39939, 40032, 40139, 40139 }; // Parry + Stamina int[] guardian = { 39940, 40034, 40141, 40141 }; // Expertise + Stamina // Blue int[] solid = { 39919, 40008, 40119, 36767 }; // Stamina // Green int[] enduring = { 39976, 40089, 40167, 40167 }; // Defense + Stamina // Yellow int[] thick = { 39916, 40015, 40126, 42157 }; // Defense // Orange int[] etched = { 39948, 40038, 40143, 40143 }; // Strength + Hit int[] champion = { 39949, 40039, 40144, 40144 }; // Strength + Defense int[] stalwart = { 39964, 40056, 40160, 40160 }; // Dodge + Defense int[] glimmering = { 39965, 40057, 40161, 40161 }; // Parry + Defense int[] accurate = { 39966, 40058, 40162, 40162 }; // Expertise + Hit int[] resolute = { 39967, 40059, 40163, 40163 }; // Expertise + Defense // Meta int[] austere = { 41380 }; string[] groupNames = new string[] { "Uncommon", "Rare", "Epic", "Jeweler" }; int[,][] gemmingTemplates = new int[,][] { //Red Yellow Blue Prismatic Meta { subtle, subtle, subtle, subtle, austere }, // Max Avoidance { subtle, stalwart, regal, subtle, austere }, // Avoidance Heavy { regal, enduring, solid, solid, austere }, // Balanced Avoidance { guardian, enduring, solid, solid, austere }, // Balanced TPS { solid, solid, solid, solid, austere }, // Max Health }; // Generate List of Gemming Templates List<GemmingTemplate> gemmingTemplate = new List<GemmingTemplate>(); for (int j = 0; j <= groupNames.GetUpperBound(0); j++) { for (int i = 0; i <= gemmingTemplates.GetUpperBound(0); i++) { gemmingTemplate.Add(new GemmingTemplate() { Model = "ProtWarr", Group = groupNames[j], RedId = gemmingTemplates[i, 0][j], YellowId = gemmingTemplates[i, 1][j], BlueId = gemmingTemplates[i, 2][j], PrismaticId = gemmingTemplates[i, 3][j], MetaId = gemmingTemplates[i, 4][0], Enabled = j == 1 }); } } return gemmingTemplate; } } #region Variables and Properties #if RAWR3 private ICalculationOptionsPanel _calculationOptionsPanel = null; public override ICalculationOptionsPanel CalculationOptionsPanel #else private CalculationOptionsPanelBase _calculationOptionsPanel = null; public override CalculationOptionsPanelBase CalculationOptionsPanel #endif { get { if (_calculationOptionsPanel == null) { _calculationOptionsPanel = new CalculationOptionsPanelProtWarr(); } return _calculationOptionsPanel; } } private string[] _characterDisplayCalculationLabels = null; public override string[] CharacterDisplayCalculationLabels { get { if (_characterDisplayCalculationLabels == null) _characterDisplayCalculationLabels = new string[] { "Base Stats:Health", "Base Stats:Strength", "Base Stats:Agility", "Base Stats:Stamina", "Defensive Stats:Armor", "Defensive Stats:Defense", "Defensive Stats:Dodge", "Defensive Stats:Parry", "Defensive Stats:Block", "Defensive Stats:Miss", "Defensive Stats:Block Value", "Defensive Stats:Resilience", "Defensive Stats:Chance to be Crit", "Defensive Stats:Guaranteed Reduction", "Defensive Stats:Avoidance", "Defensive Stats:Total Mitigation", "Defensive Stats:Attacker Speed", "Defensive Stats:Damage Taken", "Offensive Stats:Weapon Speed", "Offensive Stats:Attack Power", "Offensive Stats:Hit", "Offensive Stats:Haste", "Offensive Stats:Armor Penetration", "Offensive Stats:Crit", "Offensive Stats:Expertise", // Never really used in current WoW itemization, just taking up space //"Offensive Stats:Weapon Damage", "Offensive Stats:Missed Attacks", "Offensive Stats:Total Damage/sec", "Offensive Stats:Limited Threat/sec", "Offensive Stats:Unlimited Threat/sec*All white damage converted to Heroic Strikes.", "Resistances:Nature Resist", "Resistances:Fire Resist", "Resistances:Frost Resist", "Resistances:Shadow Resist", "Resistances:Arcane Resist", "Complex Stats:Ranking Mode*The currently selected ranking mode. Ranking modes can be changed in the Options tab.", @"Complex Stats:Overall Points*Overall Points are a sum of Mitigation and Survival Points. Overall is typically, but not always, the best way to rate gear. For specific encounters, closer attention to Mitigation and Survival Points individually may be important.", @"Complex Stats:Mitigation Points*Mitigation Points represent the amount of damage you mitigate, on average, through armor mitigation and avoidance. It is directly relational to your Damage Taken. Ideally, you want to maximize Mitigation Points, while maintaining 'enough' Survival Points (see Survival Points). If you find yourself dying due to healers running OOM, or being too busy healing you and letting other raid members die, then focus on Mitigation Points.", @"Complex Stats:Survival Points*Survival Points represents the total raw physical damage (pre-avoidance/block) you can take before dying. Unlike Mitigation Points, you should not attempt to maximize this, but rather get 'enough' of it, and then focus on Mitigation. 'Enough' can vary greatly by fight and by your healers. If you find that you are being killed by burst damage, focus on Survival Points.", @"Complex Stats:Threat Points*Threat Points represents the average between unlimited threat and limited threat scaled by the threat scale.", "Complex Stats:Nature Survival", "Complex Stats:Fire Survival", "Complex Stats:Frost Survival", "Complex Stats:Shadow Survival", "Complex Stats:Arcane Survival", }; return _characterDisplayCalculationLabels; } } private string[] _optimizableCalculationLabels = null; public override string[] OptimizableCalculationLabels { get { if (_optimizableCalculationLabels == null) _optimizableCalculationLabels = new string[] { "Health", "Unlimited TPS", "Limited TPS", "% Total Mitigation", "% Guaranteed Reduction", "% Chance to Avoid Attacks", "% Chance to be Crit", "% Chance to be Avoided", "% Chance to be Dodged", "% Chance to Miss", "Hit %", "Expertise %", "Burst Time", "TankPoints", "Nature Survival", "Fire Survival", "Frost Survival", "Shadow Survival", "Arcane Survival", }; return _optimizableCalculationLabels; } } private string[] _customChartNames = null; public override string[] CustomChartNames { get { if (_customChartNames == null) _customChartNames = new string[] { "Ability Damage", "Ability Threat", "Combat Table", "Item Budget", }; return _customChartNames; } } #if RAWR3 private Dictionary<string, System.Windows.Media.Color> _subPointNameColors = null; public override Dictionary<string, System.Windows.Media.Color> SubPointNameColors { get { if (_subPointNameColors == null) { _subPointNameColors = new Dictionary<string, System.Windows.Media.Color>(); _subPointNameColors.Add("Survival", System.Windows.Media.Colors.Blue); _subPointNameColors.Add("Mitigation", System.Windows.Media.Colors.Red); _subPointNameColors.Add("Threat", System.Windows.Media.Colors.Green); } return _subPointNameColors; } } #else private Dictionary<string, System.Drawing.Color> _subPointNameColors = null; public override Dictionary<string, System.Drawing.Color> SubPointNameColors { get { if (_subPointNameColors == null) { _subPointNameColors = new Dictionary<string, System.Drawing.Color>(); _subPointNameColors.Add("Survival", System.Drawing.Color.Blue); _subPointNameColors.Add("Mitigation", System.Drawing.Color.Red); _subPointNameColors.Add("Threat", System.Drawing.Color.Green); } return _subPointNameColors; } } #endif private List<ItemType> _relevantItemTypes = null; public override List<ItemType> RelevantItemTypes { get { if (_relevantItemTypes == null) { _relevantItemTypes = new List<ItemType>(new ItemType[] { ItemType.None, ItemType.Plate, ItemType.Bow, ItemType.Crossbow, ItemType.Gun, ItemType.Thrown, ItemType.Arrow, ItemType.Bullet, ItemType.FistWeapon, ItemType.Dagger, ItemType.OneHandAxe, ItemType.OneHandMace, ItemType.OneHandSword, ItemType.Shield }); } return _relevantItemTypes; } } public override void SetDefaults(Character character) { character.ActiveBuffs.Add(Buff.GetBuffByName("Strength of Earth Totem")); character.ActiveBuffs.Add(Buff.GetBuffByName("Enhancing Totems (Agility/Strength)")); character.ActiveBuffs.Add(Buff.GetBuffByName("Devotion Aura")); character.ActiveBuffs.Add(Buff.GetBuffByName("Improved Devotion Aura (Armor)")); character.ActiveBuffs.Add(Buff.GetBuffByName("Inspiration")); character.ActiveBuffs.Add(Buff.GetBuffByName("Blessing of Might")); character.ActiveBuffs.Add(Buff.GetBuffByName("Improved Blessing of Might")); character.ActiveBuffs.Add(Buff.GetBuffByName("Unleashed Rage")); character.ActiveBuffs.Add(Buff.GetBuffByName("Sanctified Retribution")); character.ActiveBuffs.Add(Buff.GetBuffByName("Grace")); character.ActiveBuffs.Add(Buff.GetBuffByName("Swift Retribution")); character.ActiveBuffs.Add(Buff.GetBuffByName("Commanding Shout")); character.ActiveBuffs.Add(Buff.GetBuffByName("Commanding Presence (Health)")); character.ActiveBuffs.Add(Buff.GetBuffByName("Leader of the Pack")); character.ActiveBuffs.Add(Buff.GetBuffByName("Windfury Totem")); character.ActiveBuffs.Add(Buff.GetBuffByName("Improved Windfury Totem")); character.ActiveBuffs.Add(Buff.GetBuffByName("Power Word: Fortitude")); character.ActiveBuffs.Add(Buff.GetBuffByName("Improved Power Word: Fortitude")); character.ActiveBuffs.Add(Buff.GetBuffByName("Mark of the Wild")); character.ActiveBuffs.Add(Buff.GetBuffByName("Improved Mark of the Wild")); character.ActiveBuffs.Add(Buff.GetBuffByName("Blessing of Kings")); character.ActiveBuffs.Add(Buff.GetBuffByName("Sunder Armor")); character.ActiveBuffs.Add(Buff.GetBuffByName("Faerie Fire")); character.ActiveBuffs.Add(Buff.GetBuffByName("Trauma")); character.ActiveBuffs.Add(Buff.GetBuffByName("Heart of the Crusader")); character.ActiveBuffs.Add(Buff.GetBuffByName("Insect Swarm")); character.ActiveBuffs.Add(Buff.GetBuffByName("Flask of Stoneblood")); character.ActiveBuffs.Add(Buff.GetBuffByName("Fish Feast")); } public override CharacterClass TargetClass { get { return CharacterClass.Warrior; } } public override ComparisonCalculationBase CreateNewComparisonCalculation() { return new ComparisonCalculationProtWarr(); } public override CharacterCalculationsBase CreateNewCharacterCalculations() { return new CharacterCalculationsProtWarr(); } public override ICalculationOptionBase DeserializeDataObject(string xml) { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(CalculationOptionsProtWarr)); System.IO.StringReader reader = new System.IO.StringReader(xml); CalculationOptionsProtWarr calcOpts = serializer.Deserialize(reader) as CalculationOptionsProtWarr; return calcOpts; } #endregion public override CharacterCalculationsBase GetCharacterCalculations(Character character, Item additionalItem, bool referenceCalculation, bool significantChange, bool needsDisplayCalculations) { CharacterCalculationsProtWarr calculatedStats = new CharacterCalculationsProtWarr(); CalculationOptionsProtWarr calcOpts = character.CalculationOptions as CalculationOptionsProtWarr; Stats stats = GetCharacterStats(character, additionalItem); AttackModelMode amm = AttackModelMode.Basic; if (character.WarriorTalents.UnrelentingAssault > 0) amm = AttackModelMode.UnrelentingAssault; else if (character.WarriorTalents.Shockwave > 0) amm = AttackModelMode.FullProtection; else if (character.WarriorTalents.Devastate > 0) amm = AttackModelMode.Devastate; DefendModel dm = new DefendModel(character, stats); AttackModel am = new AttackModel(character, stats, amm); calculatedStats.BasicStats = stats; calculatedStats.TargetLevel = calcOpts.TargetLevel; calculatedStats.ActiveBuffs = new List<Buff>(character.ActiveBuffs); calculatedStats.Abilities = am.Abilities; calculatedStats.Miss = dm.DefendTable.Miss; calculatedStats.Dodge = dm.DefendTable.Dodge; calculatedStats.Parry = dm.DefendTable.Parry; calculatedStats.Block = dm.DefendTable.Block; calculatedStats.Defense = (float)Math.Floor(stats.Defense + StatConversion.GetDefenseFromRating(stats.DefenseRating, CharacterClass.Warrior)); calculatedStats.BlockValue = stats.BlockValue; calculatedStats.DodgePlusMissPlusParry = calculatedStats.Dodge + calculatedStats.Miss + calculatedStats.Parry; calculatedStats.DodgePlusMissPlusParryPlusBlock = calculatedStats.Dodge + calculatedStats.Miss + calculatedStats.Parry + calculatedStats.Block; calculatedStats.CritReduction = Lookup.AvoidanceChance(character, stats, HitResult.Crit); calculatedStats.CritVulnerability = dm.DefendTable.Critical; calculatedStats.DefenseRatingNeeded = StatConversion.GetDefenseRatingNeeded(character, stats, calcOpts.TargetLevel); calculatedStats.ArmorReduction = Lookup.ArmorReduction(character, stats); calculatedStats.GuaranteedReduction = dm.GuaranteedReduction; calculatedStats.TotalMitigation = dm.Mitigation; calculatedStats.BaseAttackerSpeed = calcOpts.BossAttackSpeed; calculatedStats.AttackerSpeed = dm.ParryModel.BossAttackSpeed; calculatedStats.DamageTaken = dm.DamagePerSecond; calculatedStats.DamageTakenPerHit = dm.DamagePerHit; calculatedStats.DamageTakenPerBlock = dm.DamagePerBlock; calculatedStats.DamageTakenPerCrit = dm.DamagePerCrit; calculatedStats.ArcaneReduction = (1.0f - Lookup.MagicReduction(character, stats, DamageType.Arcane)); calculatedStats.FireReduction = (1.0f - Lookup.MagicReduction(character, stats, DamageType.Fire)); calculatedStats.FrostReduction = (1.0f - Lookup.MagicReduction(character, stats, DamageType.Frost)); calculatedStats.NatureReduction = (1.0f - Lookup.MagicReduction(character, stats, DamageType.Nature)); calculatedStats.ShadowReduction = (1.0f - Lookup.MagicReduction(character, stats, DamageType.Shadow)); calculatedStats.ArcaneSurvivalPoints = stats.Health / Lookup.MagicReduction(character, stats, DamageType.Arcane); calculatedStats.FireSurvivalPoints = stats.Health / Lookup.MagicReduction(character, stats, DamageType.Fire); calculatedStats.FrostSurvivalPoints = stats.Health / Lookup.MagicReduction(character, stats, DamageType.Frost); calculatedStats.NatureSurvivalPoints = stats.Health / Lookup.MagicReduction(character, stats, DamageType.Nature); calculatedStats.ShadowSurvivalPoints = stats.Health / Lookup.MagicReduction(character, stats, DamageType.Shadow); calculatedStats.Hit = Lookup.BonusHitPercentage(character, stats); calculatedStats.Crit = Lookup.BonusCritPercentage(character, stats); calculatedStats.Expertise = Lookup.BonusExpertisePercentage(character, stats); calculatedStats.Haste = Lookup.BonusHastePercentage(character, stats); calculatedStats.ArmorPenetration = Lookup.BonusArmorPenetrationPercentage(character, stats); calculatedStats.AvoidedAttacks = am.Abilities[Ability.None].AttackTable.AnyMiss; calculatedStats.DodgedAttacks = am.Abilities[Ability.None].AttackTable.Dodge; calculatedStats.ParriedAttacks = am.Abilities[Ability.None].AttackTable.Parry; calculatedStats.MissedAttacks = am.Abilities[Ability.None].AttackTable.Miss; calculatedStats.WeaponSpeed = Lookup.WeaponSpeed(character, stats); calculatedStats.TotalDamagePerSecond = am.DamagePerSecond; calculatedStats.UnlimitedThreat = am.ThreatPerSecond; am.RageModelMode = RageModelMode.Limited; calculatedStats.LimitedThreat = am.ThreatPerSecond; calculatedStats.ThreatModel = am.Name + "\n" + am.Description; calculatedStats.TankPoints = dm.TankPoints; calculatedStats.BurstTime = dm.BurstTime; calculatedStats.RankingMode = calcOpts.RankingMode; calculatedStats.ThreatPoints = (calcOpts.ThreatScale * ((calculatedStats.LimitedThreat + calculatedStats.UnlimitedThreat) / 2.0f)); switch (calcOpts.RankingMode) { case 2: // Tank Points Mode calculatedStats.SurvivalPoints = (dm.EffectiveHealth); calculatedStats.MitigationPoints = (dm.TankPoints - dm.EffectiveHealth); calculatedStats.ThreatPoints *= 3.0f; break; case 3: // Burst Time Mode float threatScale = Convert.ToSingle(Math.Pow(Convert.ToDouble(calcOpts.BossAttackValue) / 25000.0d, 4)); calculatedStats.SurvivalPoints = (dm.BurstTime * 100.0f); calculatedStats.MitigationPoints = 0.0f; calculatedStats.ThreatPoints = (calculatedStats.ThreatPoints / threatScale) * 2.0f; break; case 4: // Damage Output Mode calculatedStats.SurvivalPoints = 0.0f; calculatedStats.MitigationPoints = 0.0f; calculatedStats.ThreatPoints = calculatedStats.TotalDamagePerSecond; break; default: // Mitigation Scale Mode calculatedStats.SurvivalPoints = (dm.EffectiveHealth); calculatedStats.MitigationPoints = dm.Mitigation * calcOpts.BossAttackValue * calcOpts.MitigationScale * 100.0f; break; } calculatedStats.OverallPoints = calculatedStats.MitigationPoints + calculatedStats.SurvivalPoints + calculatedStats.ThreatPoints; return calculatedStats; } public override Stats GetCharacterStats(Character character, Item additionalItem) { CalculationOptionsProtWarr calcOpts = character.CalculationOptions as CalculationOptionsProtWarr; WarriorTalents talents = character.WarriorTalents; Stats statsRace = BaseStats.GetBaseStats(character.Level, CharacterClass.Warrior, character.Race); Stats statsBuffs = GetBuffsStats(character.ActiveBuffs); Stats statsItems = GetItemStats(character, additionalItem); Stats statsTalents = new Stats() { Parry = talents.Deflection * 0.01f, Dodge = talents.Anticipation * 0.01f, Block = talents.ShieldSpecialization * 0.01f, BonusBlockValueMultiplier = talents.ShieldMastery * 0.15f, PhysicalCrit = talents.Cruelty * 0.01f + ((character.MainHand != null && (character.MainHand.Type == ItemType.OneHandAxe)) ? talents.PoleaxeSpecialization * 0.01f : 0.0f), BonusCritMultiplier = ((character.MainHand != null && (character.MainHand.Type == ItemType.OneHandAxe)) ? talents.PoleaxeSpecialization * 0.01f : 0.0f), BonusDamageMultiplier = ((character.MainHand != null && (character.MainHand.Type == ItemType.OneHandAxe || character.MainHand.Type == ItemType.OneHandMace || character.MainHand.Type == ItemType.OneHandSword || character.MainHand.Type == ItemType.Dagger || character.MainHand.Type == ItemType.FistWeapon)) ? talents.OneHandedWeaponSpecialization * 0.02f : 0f), BonusStaminaMultiplier = talents.Vitality * 0.02f + talents.StrengthOfArms * 0.02f, BonusStrengthMultiplier = talents.Vitality * 0.02f + talents.StrengthOfArms * 0.02f, Expertise = talents.Vitality * 2.0f + talents.StrengthOfArms * 2.0f, BonusShieldSlamDamage = talents.GagOrder * 0.05f, DevastateCritIncrease = talents.SwordAndBoard * 0.05f, BaseArmorMultiplier = talents.Toughness * 0.02f, PhysicalHaste = talents.BloodFrenzy * 0.03f, PhysicalHit = talents.Precision * 0.01f, }; Stats statsGlyphs = new Stats() { BonusBlockValueMultiplier = (talents.GlyphOfBlocking ? 0.1f : 0.0f), }; Stats statsGearEnchantsBuffs = statsItems + statsBuffs; Stats statsTotal = statsRace + statsItems + statsBuffs + statsTalents + statsGlyphs; Stats statsProcs = new Stats(); // Base Stats statsTotal.BaseAgility = statsRace.Agility + statsTalents.Agility; statsTotal.Stamina = (float)Math.Floor((statsRace.Stamina + statsTalents.Stamina) * (1.0f + statsTotal.BonusStaminaMultiplier)); statsTotal.Stamina += (float)Math.Floor((statsItems.Stamina + statsBuffs.Stamina) * (1.0f + statsTotal.BonusStaminaMultiplier)); statsTotal.Strength = (float)Math.Floor((statsRace.Strength + statsTalents.Strength) * (1.0f + statsTotal.BonusStrengthMultiplier)); statsTotal.Strength += (float)Math.Floor((statsItems.Strength + statsBuffs.Strength) * (1.0f + statsTotal.BonusStrengthMultiplier)); statsTotal.Agility = (float)Math.Floor((statsRace.Agility + statsTalents.Agility) * (1.0f + statsTotal.BonusAgilityMultiplier)); statsTotal.Agility += (float)Math.Floor((statsItems.Agility + statsBuffs.Agility) * (1.0f + statsTotal.BonusAgilityMultiplier)); statsTotal.Health += StatConversion.GetHealthFromStamina(statsTotal.Stamina, CharacterClass.Warrior); if (character.ActiveBuffsContains("Commanding Shout")) statsBuffs.Health += statsBuffs.BonusCommandingShoutHP; statsTotal.Health *= (float)Math.Floor(1.0f + statsTotal.BonusHealthMultiplier); // Defensive Stats statsTotal.Armor = (float)Math.Ceiling(statsTotal.Armor * (1.0f + statsTotal.BaseArmorMultiplier)); statsTotal.BonusArmor += statsTotal.Agility * 2.0f; statsTotal.Armor += (float)Math.Ceiling(statsTotal.BonusArmor * (1.0f + statsTotal.BonusArmorMultiplier)); statsTotal.BlockValue += (float)Math.Floor(StatConversion.GetBlockValueFromStrength(statsTotal.Strength, CharacterClass.Warrior) - 10.0f); statsTotal.BlockValue = (float)Math.Floor(statsTotal.BlockValue * (1 + statsTotal.BonusBlockValueMultiplier)); statsTotal.NatureResistance += statsTotal.NatureResistanceBuff + statsTotal.AllResist; statsTotal.FireResistance += statsTotal.FireResistanceBuff + statsTotal.AllResist; statsTotal.FrostResistance += statsTotal.FrostResistanceBuff + statsTotal.AllResist; statsTotal.ShadowResistance += statsTotal.ShadowResistanceBuff + statsTotal.AllResist; statsTotal.ArcaneResistance += statsTotal.ArcaneResistanceBuff + statsTotal.AllResist; // Offensive Stats statsTotal.AttackPower += statsTotal.Strength * 2.0f + (float)Math.Floor(talents.ArmoredToTheTeeth * statsTotal.Armor / 108.0f); statsTotal.AttackPower *= (1 + statsTotal.BonusAttackPowerMultiplier); // Calculate Procs and Special Effects statsTotal += GetSpecialEffectStats(character, statsTotal); // Greatness/Highest Stat Effect statsTotal.Strength += (float)Math.Floor(statsTotal.HighestStat * (1 + statsTotal.BonusStrengthMultiplier)); return statsTotal; } private Stats GetSpecialEffectStats(Character character, Stats stats) { Stats statsSpecialEffects = new Stats(); float weaponSpeed = 1.0f; if (character.MainHand != null) weaponSpeed = character.MainHand.Speed; AttackModelMode amm = AttackModelMode.Basic; if (character.WarriorTalents.UnrelentingAssault > 0) amm = AttackModelMode.UnrelentingAssault; else if (character.WarriorTalents.Shockwave > 0) amm = AttackModelMode.FullProtection; else if (character.WarriorTalents.Devastate > 0) amm = AttackModelMode.Devastate; AttackModel am = new AttackModel(character, stats, amm); foreach (SpecialEffect effect in stats.SpecialEffects()) { switch (effect.Trigger) { case Trigger.Use: statsSpecialEffects += effect.GetAverageStats(0.0f, 1.0f, weaponSpeed); break; case Trigger.MeleeHit: case Trigger.PhysicalHit: statsSpecialEffects += effect.GetAverageStats((1.0f / am.AttacksPerSecond), 1.0f, weaponSpeed); break; case Trigger.MeleeCrit: case Trigger.PhysicalCrit: statsSpecialEffects += effect.GetAverageStats((1.0f / am.CritsPerSecond), 1.0f, weaponSpeed); break; case Trigger.DoTTick: if (character.WarriorTalents.DeepWounds > 0) statsSpecialEffects += effect.GetAverageStats(2.0f, 1.0f, weaponSpeed); break; case Trigger.DamageDone: statsSpecialEffects += effect.GetAverageStats((1.0f / am.AttacksPerSecond), 1.0f, weaponSpeed); break; case Trigger.DamageTaken: statsSpecialEffects += effect.GetAverageStats((1.0f / am.AttackerHitsPerSecond), 1.0f, weaponSpeed); break; } } // Base Stats statsSpecialEffects.Stamina = (float)Math.Floor(statsSpecialEffects.Stamina * (1.0f + stats.BonusStaminaMultiplier)); statsSpecialEffects.Strength = (float)Math.Floor(statsSpecialEffects.Strength * (1.0f + stats.BonusStrengthMultiplier)); statsSpecialEffects.Agility = (float)Math.Floor(statsSpecialEffects.Agility * (1.0f + stats.BonusAgilityMultiplier)); statsSpecialEffects.Health += (float)Math.Floor(statsSpecialEffects.Stamina * 10.0f); // Defensive Stats statsSpecialEffects.Armor = (float)Math.Floor(statsSpecialEffects.Armor * (1f + stats.BaseArmorMultiplier + statsSpecialEffects.BaseArmorMultiplier)); statsSpecialEffects.BonusArmor += statsSpecialEffects.Agility * 2.0f; statsSpecialEffects.BonusArmor = (float)Math.Floor(statsSpecialEffects.BonusArmor * (1.0f + stats.BonusArmorMultiplier + statsSpecialEffects.BonusArmorMultiplier)); statsSpecialEffects.Armor += statsSpecialEffects.BonusArmor; statsSpecialEffects.BlockValue += (float)Math.Floor(StatConversion.GetBlockValueFromStrength(statsSpecialEffects.Strength, CharacterClass.Warrior)); statsSpecialEffects.BlockValue = (float)Math.Floor(statsSpecialEffects.BlockValue * (1.0f + stats.BonusBlockValueMultiplier + statsSpecialEffects.BonusBlockValueMultiplier)); // Offensive Stats statsSpecialEffects.AttackPower += statsSpecialEffects.Strength * 2.0f; statsSpecialEffects.AttackPower += (float)Math.Floor(character.WarriorTalents.ArmoredToTheTeeth * statsSpecialEffects.Armor / 108.0f); statsSpecialEffects.AttackPower = (float)Math.Floor(statsSpecialEffects.AttackPower * (1.0f + stats.BonusAttackPowerMultiplier + statsSpecialEffects.BonusAttackPowerMultiplier)); return statsSpecialEffects; } public override ComparisonCalculationBase[] GetCustomChartData(Character character, string chartName) { CharacterCalculationsProtWarr calculations = GetCharacterCalculations(character) as CharacterCalculationsProtWarr; switch (chartName) { case "Ability Damage": case "Ability Threat": { ComparisonCalculationBase[] comparisons = new ComparisonCalculationBase[calculations.Abilities.Count]; int j = 0; foreach (AbilityModel ability in calculations.Abilities) { if (ability.Ability != Ability.Vigilance) { ComparisonCalculationProtWarr comparison = new ComparisonCalculationProtWarr(); comparison.Name = ability.Name; if (chartName == "Ability Damage") comparison.MitigationPoints = ability.Damage; if (chartName == "Ability Threat") comparison.ThreatPoints = ability.Threat; comparison.OverallPoints = comparison.SurvivalPoints + comparison.ThreatPoints + comparison.MitigationPoints; comparisons[j] = comparison; j++; } } return comparisons; } case "Combat Table": { ComparisonCalculationProtWarr calcMiss = new ComparisonCalculationProtWarr(); ComparisonCalculationProtWarr calcDodge = new ComparisonCalculationProtWarr(); ComparisonCalculationProtWarr calcParry = new ComparisonCalculationProtWarr(); ComparisonCalculationProtWarr calcBlock = new ComparisonCalculationProtWarr(); ComparisonCalculationProtWarr calcCrit = new ComparisonCalculationProtWarr(); ComparisonCalculationProtWarr calcCrush = new ComparisonCalculationProtWarr(); ComparisonCalculationProtWarr calcHit = new ComparisonCalculationProtWarr(); if (calculations != null) { calcMiss.Name = "Miss"; calcDodge.Name = "Dodge"; calcParry.Name = "Parry"; calcBlock.Name = "Block"; calcCrit.Name = "Crit"; calcCrush.Name = "Crush"; calcHit.Name = "Hit"; calcMiss.OverallPoints = calcMiss.MitigationPoints = calculations.Miss * 100.0f; calcDodge.OverallPoints = calcDodge.MitigationPoints = calculations.Dodge * 100.0f; calcParry.OverallPoints = calcParry.MitigationPoints = calculations.Parry * 100.0f; calcBlock.OverallPoints = calcBlock.MitigationPoints = calculations.Block * 100.0f; calcCrit.OverallPoints = calcCrit.SurvivalPoints = calculations.CritVulnerability * 100.0f; calcHit.OverallPoints = calcHit.SurvivalPoints = (1.0f - (calculations.DodgePlusMissPlusParryPlusBlock + calculations.CritVulnerability)) * 100.0f; } return new ComparisonCalculationBase[] { calcMiss, calcDodge, calcParry, calcBlock, calcCrit, calcCrush, calcHit }; } case "Item Budget": CharacterCalculationsProtWarr calcBaseValue = GetCharacterCalculations(character) as CharacterCalculationsProtWarr; CharacterCalculationsProtWarr calcDodgeValue = GetCharacterCalculations(character, new Item() { Stats = new Stats() { DodgeRating = 10f } }) as CharacterCalculationsProtWarr; CharacterCalculationsProtWarr calcParryValue = GetCharacterCalculations(character, new Item() { Stats = new Stats() { ParryRating = 10f } }) as CharacterCalculationsProtWarr; CharacterCalculationsProtWarr calcBlockValue = GetCharacterCalculations(character, new Item() { Stats = new Stats() { BlockRating = 10f } }) as CharacterCalculationsProtWarr; CharacterCalculationsProtWarr calcHasteValue = GetCharacterCalculations(character, new Item() { Stats = new Stats() { HasteRating = 10f } }) as CharacterCalculationsProtWarr; CharacterCalculationsProtWarr calcExpertiseValue = GetCharacterCalculations(character, new Item() { Stats = new Stats() { ExpertiseRating = 10f } }) as CharacterCalculationsProtWarr; CharacterCalculationsProtWarr calcHitValue = GetCharacterCalculations(character, new Item() { Stats = new Stats() { HitRating = 10f } }) as CharacterCalculationsProtWarr; CharacterCalculationsProtWarr calcBlockValueValue = GetCharacterCalculations(character, new Item() { Stats = new Stats() { BlockValue = 10f / 0.65f } }) as CharacterCalculationsProtWarr; CharacterCalculationsProtWarr calcHealthValue = GetCharacterCalculations(character, new Item() { Stats = new Stats() { Health = (10f * 10f) / 0.667f } }) as CharacterCalculationsProtWarr; CharacterCalculationsProtWarr calcResilValue = GetCharacterCalculations(character, new Item() { Stats = new Stats() { Resilience = 10f } }) as CharacterCalculationsProtWarr; //Differential Calculations for Agi CharacterCalculationsProtWarr calcAtAdd = calcBaseValue; float agiToAdd = 0f; while (calcBaseValue.OverallPoints == calcAtAdd.OverallPoints && agiToAdd < 2) { agiToAdd += 0.01f; calcAtAdd = GetCharacterCalculations(character, new Item() { Stats = new Stats() { Agility = agiToAdd } }) as CharacterCalculationsProtWarr; } CharacterCalculationsProtWarr calcAtSubtract = calcBaseValue; float agiToSubtract = 0f; while (calcBaseValue.OverallPoints == calcAtSubtract.OverallPoints && agiToSubtract > -2) { agiToSubtract -= 0.01f; calcAtSubtract = GetCharacterCalculations(character, new Item() { Stats = new Stats() { Agility = agiToSubtract } }) as CharacterCalculationsProtWarr; } agiToSubtract += 0.01f; ComparisonCalculationProtWarr comparisonAgi = new ComparisonCalculationProtWarr() { Name = "10 Agility", OverallPoints = 10 * (calcAtAdd.OverallPoints - calcBaseValue.OverallPoints) / (agiToAdd - agiToSubtract), MitigationPoints = 10 * (calcAtAdd.MitigationPoints - calcBaseValue.MitigationPoints) / (agiToAdd - agiToSubtract), SurvivalPoints = 10 * (calcAtAdd.SurvivalPoints - calcBaseValue.SurvivalPoints) / (agiToAdd - agiToSubtract), ThreatPoints = 10 * (calcAtAdd.ThreatPoints - calcBaseValue.ThreatPoints) / (agiToAdd - agiToSubtract) }; //Differential Calculations for Str calcAtAdd = calcBaseValue; float strToAdd = 0f; while (calcBaseValue.OverallPoints == calcAtAdd.OverallPoints && strToAdd < 2) { strToAdd += 0.01f; calcAtAdd = GetCharacterCalculations(character, new Item() { Stats = new Stats() { Strength = strToAdd } }) as CharacterCalculationsProtWarr; } calcAtSubtract = calcBaseValue; float strToSubtract = 0f; while (calcBaseValue.OverallPoints == calcAtSubtract.OverallPoints && strToSubtract > -2) { strToSubtract -= 0.01f; calcAtSubtract = GetCharacterCalculations(character, new Item() { Stats = new Stats() { Strength = strToSubtract } }) as CharacterCalculationsProtWarr; } strToSubtract += 0.01f; ComparisonCalculationProtWarr comparisonStr = new ComparisonCalculationProtWarr() { Name = "10 Strength", OverallPoints = 10 * (calcAtAdd.OverallPoints - calcBaseValue.OverallPoints) / (strToAdd - strToSubtract), MitigationPoints = 10 * (calcAtAdd.MitigationPoints - calcBaseValue.MitigationPoints) / (strToAdd - strToSubtract), SurvivalPoints = 10 * (calcAtAdd.SurvivalPoints - calcBaseValue.SurvivalPoints) / (strToAdd - strToSubtract), ThreatPoints = 10 * (calcAtAdd.ThreatPoints - calcBaseValue.ThreatPoints) / (strToAdd - strToSubtract) }; //Differential Calculations for Def calcAtAdd = calcBaseValue; float defToAdd = 0f; while (calcBaseValue.OverallPoints == calcAtAdd.OverallPoints && defToAdd < 20) { defToAdd += 0.01f; calcAtAdd = GetCharacterCalculations(character, new Item() { Stats = new Stats() { DefenseRating = defToAdd } }) as CharacterCalculationsProtWarr; } calcAtSubtract = calcBaseValue; float defToSubtract = 0f; while (calcBaseValue.OverallPoints == calcAtSubtract.OverallPoints && defToSubtract > -20) { defToSubtract -= 0.01f; calcAtSubtract = GetCharacterCalculations(character, new Item() { Stats = new Stats() { DefenseRating = defToSubtract } }) as CharacterCalculationsProtWarr; } defToSubtract += 0.01f; ComparisonCalculationProtWarr comparisonDef = new ComparisonCalculationProtWarr() { Name = "10 Defense Rating", OverallPoints = 10 * (calcAtAdd.OverallPoints - calcBaseValue.OverallPoints) / (defToAdd - defToSubtract), MitigationPoints = 10 * (calcAtAdd.MitigationPoints - calcBaseValue.MitigationPoints) / (defToAdd - defToSubtract), SurvivalPoints = 10 * (calcAtAdd.SurvivalPoints - calcBaseValue.SurvivalPoints) / (defToAdd - defToSubtract), ThreatPoints = 10 * (calcAtAdd.ThreatPoints - calcBaseValue.ThreatPoints) / (defToAdd - defToSubtract) }; //Differential Calculations for AC calcAtAdd = calcBaseValue; float acToAdd = 0f; while (calcBaseValue.OverallPoints == calcAtAdd.OverallPoints && acToAdd < 2) { acToAdd += 0.01f; calcAtAdd = GetCharacterCalculations(character, new Item() { Stats = new Stats() { Armor = acToAdd } }) as CharacterCalculationsProtWarr; } calcAtSubtract = calcBaseValue; float acToSubtract = 0f; while (calcBaseValue.OverallPoints == calcAtSubtract.OverallPoints && acToSubtract > -2) { acToSubtract -= 0.01f; calcAtSubtract = GetCharacterCalculations(character, new Item() { Stats = new Stats() { Armor = acToSubtract } }) as CharacterCalculationsProtWarr; } acToSubtract += 0.01f; ComparisonCalculationProtWarr comparisonAC = new ComparisonCalculationProtWarr() { Name = "100 Armor", OverallPoints = 100f * (calcAtAdd.OverallPoints - calcBaseValue.OverallPoints) / (acToAdd - acToSubtract), MitigationPoints = 100f * (calcAtAdd.MitigationPoints - calcBaseValue.MitigationPoints) / (acToAdd - acToSubtract), SurvivalPoints = 100f * (calcAtAdd.SurvivalPoints - calcBaseValue.SurvivalPoints) / (acToAdd - acToSubtract), ThreatPoints = 100f * (calcAtAdd.ThreatPoints - calcBaseValue.ThreatPoints) / (acToAdd - acToSubtract), }; //Differential Calculations for Sta calcAtAdd = calcBaseValue; float staToAdd = 0f; while (calcBaseValue.OverallPoints == calcAtAdd.OverallPoints && staToAdd < 2) { staToAdd += 0.01f; calcAtAdd = GetCharacterCalculations(character, new Item() { Stats = new Stats() { Stamina = staToAdd } }) as CharacterCalculationsProtWarr; } calcAtSubtract = calcBaseValue; float staToSubtract = 0f; while (calcBaseValue.OverallPoints == calcAtSubtract.OverallPoints && staToSubtract > -2) { staToSubtract -= 0.01f; calcAtSubtract = GetCharacterCalculations(character, new Item() { Stats = new Stats() { Stamina = staToSubtract } }) as CharacterCalculationsProtWarr; } staToSubtract += 0.01f; ComparisonCalculationProtWarr comparisonSta = new ComparisonCalculationProtWarr() { Name = "15 Stamina", OverallPoints = (10f / 0.667f) * (calcAtAdd.OverallPoints - calcBaseValue.OverallPoints) / (staToAdd - staToSubtract), MitigationPoints = (10f / 0.667f) * (calcAtAdd.MitigationPoints - calcBaseValue.MitigationPoints) / (staToAdd - staToSubtract), SurvivalPoints = (10f / 0.667f) * (calcAtAdd.SurvivalPoints - calcBaseValue.SurvivalPoints) / (staToAdd - staToSubtract), ThreatPoints = (10f / 0.667f) * (calcAtAdd.ThreatPoints - calcBaseValue.ThreatPoints) / (staToAdd - staToSubtract) }; return new ComparisonCalculationBase[] { comparisonStr, comparisonAgi, comparisonAC, comparisonSta, comparisonDef, new ComparisonCalculationProtWarr() { Name = "10 Dodge Rating", OverallPoints = (calcDodgeValue.OverallPoints - calcBaseValue.OverallPoints), MitigationPoints = (calcDodgeValue.MitigationPoints - calcBaseValue.MitigationPoints), SurvivalPoints = (calcDodgeValue.SurvivalPoints - calcBaseValue.SurvivalPoints), ThreatPoints = (calcDodgeValue.ThreatPoints - calcBaseValue.ThreatPoints)}, new ComparisonCalculationProtWarr() { Name = "10 Parry Rating", OverallPoints = (calcParryValue.OverallPoints - calcBaseValue.OverallPoints), MitigationPoints = (calcParryValue.MitigationPoints - calcBaseValue.MitigationPoints), SurvivalPoints = (calcParryValue.SurvivalPoints - calcBaseValue.SurvivalPoints), ThreatPoints = (calcParryValue.ThreatPoints - calcBaseValue.ThreatPoints)}, new ComparisonCalculationProtWarr() { Name = "10 Block Rating", OverallPoints = (calcBlockValue.OverallPoints - calcBaseValue.OverallPoints), MitigationPoints = (calcBlockValue.MitigationPoints - calcBaseValue.MitigationPoints), SurvivalPoints = (calcBlockValue.SurvivalPoints - calcBaseValue.SurvivalPoints), ThreatPoints = (calcBlockValue.ThreatPoints - calcBaseValue.ThreatPoints)}, new ComparisonCalculationProtWarr() { Name = "10 Haste Rating", OverallPoints = (calcHasteValue.OverallPoints - calcBaseValue.OverallPoints), MitigationPoints = (calcHasteValue.MitigationPoints - calcBaseValue.MitigationPoints), SurvivalPoints = (calcHasteValue.SurvivalPoints - calcBaseValue.SurvivalPoints), ThreatPoints = (calcHasteValue.ThreatPoints - calcBaseValue.ThreatPoints)}, new ComparisonCalculationProtWarr() { Name = "10 Expertise Rating", OverallPoints = (calcExpertiseValue.OverallPoints - calcBaseValue.OverallPoints), MitigationPoints = (calcExpertiseValue.MitigationPoints - calcBaseValue.MitigationPoints), SurvivalPoints = (calcExpertiseValue.SurvivalPoints - calcBaseValue.SurvivalPoints), ThreatPoints = (calcExpertiseValue.ThreatPoints - calcBaseValue.ThreatPoints)}, new ComparisonCalculationProtWarr() { Name = "10 Hit Rating", OverallPoints = (calcHitValue.OverallPoints - calcBaseValue.OverallPoints), MitigationPoints = (calcHitValue.MitigationPoints - calcBaseValue.MitigationPoints), SurvivalPoints = (calcHitValue.SurvivalPoints - calcBaseValue.SurvivalPoints), ThreatPoints = (calcHitValue.ThreatPoints - calcBaseValue.ThreatPoints)}, new ComparisonCalculationProtWarr() { Name = "15.38 Block Value", OverallPoints = (calcBlockValueValue.OverallPoints - calcBaseValue.OverallPoints), MitigationPoints = (calcBlockValueValue.MitigationPoints - calcBaseValue.MitigationPoints), SurvivalPoints = (calcBlockValueValue.SurvivalPoints - calcBaseValue.SurvivalPoints), ThreatPoints = (calcBlockValueValue.ThreatPoints - calcBaseValue.ThreatPoints)}, new ComparisonCalculationProtWarr() { Name = "150 Health", OverallPoints = (calcHealthValue.OverallPoints - calcBaseValue.OverallPoints), MitigationPoints = (calcHealthValue.MitigationPoints - calcBaseValue.MitigationPoints), SurvivalPoints = (calcHealthValue.SurvivalPoints - calcBaseValue.SurvivalPoints), ThreatPoints = (calcHealthValue.ThreatPoints - calcBaseValue.ThreatPoints)}, new ComparisonCalculationProtWarr() { Name = "10 Resilience", OverallPoints = (calcResilValue.OverallPoints - calcBaseValue.OverallPoints), MitigationPoints = (calcResilValue.MitigationPoints - calcBaseValue.MitigationPoints), SurvivalPoints = (calcResilValue.SurvivalPoints - calcBaseValue.SurvivalPoints), ThreatPoints = (calcResilValue.ThreatPoints - calcBaseValue.ThreatPoints)}, }; default: return new ComparisonCalculationBase[0]; } } //Hide the ranged weapon enchants. None of them apply to melee damage at all. public override bool EnchantFitsInSlot(Enchant enchant, Character character, ItemSlot slot) { return enchant.Slot == ItemSlot.Ranged ? false : base.EnchantFitsInSlot(enchant, character, slot); } public override bool IsItemRelevant(Item item) { // Bone Fishing Pole if (item.Id == 45991) return false; return base.IsItemRelevant(item); } public override Stats GetRelevantStats(Stats stats) { Stats relevantStats = new Stats() { Armor = stats.Armor, BonusArmor = stats.BonusArmor, AverageArmor = stats.AverageArmor, Stamina = stats.Stamina, Agility = stats.Agility, DodgeRating = stats.DodgeRating, ParryRating = stats.ParryRating, BlockRating = stats.BlockRating, BlockValue = stats.BlockValue, DefenseRating = stats.DefenseRating, Resilience = stats.Resilience, BonusAgilityMultiplier = stats.BonusAgilityMultiplier, BonusStrengthMultiplier = stats.BonusStrengthMultiplier, BonusAttackPowerMultiplier = stats.BonusAttackPowerMultiplier, BaseArmorMultiplier = stats.BaseArmorMultiplier, BonusArmorMultiplier = stats.BonusArmorMultiplier, BonusStaminaMultiplier = stats.BonusStaminaMultiplier, Health = stats.Health, BonusHealthMultiplier = stats.BonusHealthMultiplier, DamageTakenMultiplier = stats.DamageTakenMultiplier, Miss = stats.Miss, CritChanceReduction = stats.CritChanceReduction, AllResist = stats.AllResist, ArcaneResistance = stats.ArcaneResistance, NatureResistance = stats.NatureResistance, FireResistance = stats.FireResistance, FrostResistance = stats.FrostResistance, ShadowResistance = stats.ShadowResistance, ArcaneResistanceBuff = stats.ArcaneResistanceBuff, NatureResistanceBuff = stats.NatureResistanceBuff, FireResistanceBuff = stats.FireResistanceBuff, FrostResistanceBuff = stats.FrostResistanceBuff, ShadowResistanceBuff = stats.ShadowResistanceBuff, Strength = stats.Strength, AttackPower = stats.AttackPower, CritRating = stats.CritRating, PhysicalCrit = stats.PhysicalCrit, HitRating = stats.HitRating, PhysicalHit = stats.PhysicalHit, HasteRating = stats.HasteRating, PhysicalHaste = stats.PhysicalHaste, ExpertiseRating = stats.ExpertiseRating, ArmorPenetration = stats.ArmorPenetration, ArmorPenetrationRating = stats.ArmorPenetrationRating, WeaponDamage = stats.WeaponDamage, BonusCritMultiplier = stats.BonusCritMultiplier, ThreatIncreaseMultiplier = stats.ThreatIncreaseMultiplier, BonusDamageMultiplier = stats.BonusDamageMultiplier, BonusBlockValueMultiplier = stats.BonusBlockValueMultiplier, BonusBleedDamageMultiplier = stats.BonusBleedDamageMultiplier, HighestStat = stats.HighestStat, BonusCommandingShoutHP = stats.BonusCommandingShoutHP, BonusShieldSlamDamage = stats.BonusShieldSlamDamage, DevastateCritIncrease = stats.DevastateCritIncrease }; foreach (SpecialEffect effect in stats.SpecialEffects()) { if ((effect.Trigger == Trigger.Use || effect.Trigger == Trigger.MeleeCrit || effect.Trigger == Trigger.MeleeHit || effect.Trigger == Trigger.PhysicalCrit || effect.Trigger == Trigger.PhysicalHit || effect.Trigger == Trigger.DoTTick || effect.Trigger == Trigger.DamageDone || effect.Trigger == Trigger.DamageTaken) && HasRelevantStats(effect.Stats)) { relevantStats.AddSpecialEffect(effect); } } return relevantStats; } public override bool HasRelevantStats(Stats stats) { bool relevant = (stats.Agility + stats.Armor + stats.AverageArmor + stats.BonusArmor + stats.BonusAgilityMultiplier + stats.BonusStrengthMultiplier + stats.BonusAttackPowerMultiplier + stats.BonusArmorMultiplier + stats.BonusStaminaMultiplier + stats.DefenseRating + stats.DodgeRating + stats.ParryRating + stats.BlockRating + stats.BlockValue + stats.Health + stats.BonusHealthMultiplier + stats.DamageTakenMultiplier + stats.Miss + stats.Resilience + stats.Stamina + stats.AllResist + stats.ArcaneResistance + stats.NatureResistance + stats.FireResistance + stats.FrostResistance + stats.ShadowResistance + stats.ArcaneResistanceBuff + stats.NatureResistanceBuff + stats.FireResistanceBuff + stats.FrostResistanceBuff + stats.ShadowResistanceBuff + stats.Strength + stats.AttackPower + stats.CritRating + stats.HitRating + stats.HasteRating + stats.PhysicalHit + stats.PhysicalHaste + stats.PhysicalCrit + stats.ExpertiseRating + stats.ArmorPenetration + stats.ArmorPenetrationRating + stats.WeaponDamage + stats.BonusCritMultiplier + stats.CritChanceReduction + stats.ThreatIncreaseMultiplier + stats.BonusDamageMultiplier + stats.BonusBlockValueMultiplier + stats.BonusBleedDamageMultiplier + stats.HighestStat + stats.BonusCommandingShoutHP + stats.BonusShieldSlamDamage + stats.DevastateCritIncrease ) != 0; foreach (SpecialEffect effect in stats.SpecialEffects()) { if (effect.Trigger == Trigger.Use || effect.Trigger == Trigger.MeleeCrit || effect.Trigger == Trigger.MeleeHit || effect.Trigger == Trigger.PhysicalCrit || effect.Trigger == Trigger.PhysicalHit || effect.Trigger == Trigger.DoTTick || effect.Trigger == Trigger.DamageDone || effect.Trigger == Trigger.DamageTaken) { relevant |= HasRelevantStats(effect.Stats); if (relevant) break; } } return relevant; } } }
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 RelationOneToManySelf.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; } } }
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Public License (Ms-PL). // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details. // All other rights reserved. using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Layout; namespace Avalonia.Controls { /// <summary> /// Provides data for the /// <see cref="E:Avalonia.Controls.CalendarDatePicker.DateValidationError" /> /// event. /// </summary> public class CalendarDatePickerDateValidationErrorEventArgs : EventArgs { private bool _throwException; /// <summary> /// Initializes a new instance of the /// <see cref="T:Avalonia.Controls.CalendarDatePickerDateValidationErrorEventArgs" /> /// class. /// </summary> /// <param name="exception"> /// The initial exception from the /// <see cref="E:Avalonia.Controls.CalendarDatePicker.DateValidationError" /> /// event. /// </param> /// <param name="text"> /// The text that caused the /// <see cref="E:Avalonia.Controls.CalendarDatePicker.DateValidationError" /> /// event. /// </param> public CalendarDatePickerDateValidationErrorEventArgs(Exception exception, string text) { this.Text = text; this.Exception = exception; } /// <summary> /// Gets the initial exception associated with the /// <see cref="E:Avalonia.Controls.CalendarDatePicker.DateValidationError" /> /// event. /// </summary> /// <value> /// The exception associated with the validation failure. /// </value> public Exception Exception { get; private set; } /// <summary> /// Gets the text that caused the /// <see cref="E:Avalonia.Controls.CalendarDatePicker.DateValidationError" /> /// event. /// </summary> /// <value> /// The text that caused the validation failure. /// </value> public string Text { get; private set; } /// <summary> /// Gets or sets a value indicating whether /// <see cref="P:Avalonia.Controls.CalendarDatePickerDateValidationErrorEventArgs.Exception" /> /// should be thrown. /// </summary> /// <value> /// True if the exception should be thrown; otherwise, false. /// </value> /// <exception cref="T:System.ArgumentException"> /// If set to true and /// <see cref="P:Avalonia.Controls.CalendarDatePickerDateValidationErrorEventArgs.Exception" /> /// is null. /// </exception> public bool ThrowException { get { return this._throwException; } set { if (value && this.Exception == null) { throw new ArgumentException("Cannot Throw Null Exception"); } this._throwException = value; } } } /// <summary> /// Specifies date formats for a /// <see cref="T:Avalonia.Controls.CalendarDatePicker" />. /// </summary> public enum CalendarDatePickerFormat { /// <summary> /// Specifies that the date should be displayed using unabbreviated days /// of the week and month names. /// </summary> Long = 0, /// <summary> /// Specifies that the date should be displayed using abbreviated days /// of the week and month names. /// </summary> Short = 1, /// <summary> /// Specifies that the date should be displayed using a custom format string. /// </summary> Custom = 2 } public class CalendarDatePicker : TemplatedControl { private const string ElementTextBox = "PART_TextBox"; private const string ElementButton = "PART_Button"; private const string ElementPopup = "PART_Popup"; private const string ElementCalendar = "PART_Calendar"; private Calendar? _calendar; private string _defaultText; private Button? _dropDownButton; //private Canvas _outsideCanvas; //private Canvas _outsidePopupCanvas; private Popup? _popUp; private TextBox? _textBox; private IDisposable? _textBoxTextChangedSubscription; private IDisposable? _buttonPointerPressedSubscription; private DateTime? _onOpenSelectedDate; private bool _settingSelectedDate; private DateTime _displayDate; private DateTime? _displayDateStart; private DateTime? _displayDateEnd; private bool _isDropDownOpen; private DateTime? _selectedDate; private string? _text; private bool _suspendTextChangeHandler = false; private bool _isPopupClosing = false; private bool _ignoreButtonClick = false; /// <summary> /// Gets a collection of dates that are marked as not selectable. /// </summary> /// <value> /// A collection of dates that cannot be selected. The default value is /// an empty collection. /// </value> public CalendarBlackoutDatesCollection? BlackoutDates { get; private set; } public static readonly DirectProperty<CalendarDatePicker, DateTime> DisplayDateProperty = AvaloniaProperty.RegisterDirect<CalendarDatePicker, DateTime>( nameof(DisplayDate), o => o.DisplayDate, (o, v) => o.DisplayDate = v); public static readonly DirectProperty<CalendarDatePicker, DateTime?> DisplayDateStartProperty = AvaloniaProperty.RegisterDirect<CalendarDatePicker, DateTime?>( nameof(DisplayDateStart), o => o.DisplayDateStart, (o, v) => o.DisplayDateStart = v); public static readonly DirectProperty<CalendarDatePicker, DateTime?> DisplayDateEndProperty = AvaloniaProperty.RegisterDirect<CalendarDatePicker, DateTime?>( nameof(DisplayDateEnd), o => o.DisplayDateEnd, (o, v) => o.DisplayDateEnd = v); public static readonly StyledProperty<DayOfWeek> FirstDayOfWeekProperty = AvaloniaProperty.Register<CalendarDatePicker, DayOfWeek>(nameof(FirstDayOfWeek)); public static readonly DirectProperty<CalendarDatePicker, bool> IsDropDownOpenProperty = AvaloniaProperty.RegisterDirect<CalendarDatePicker, bool>( nameof(IsDropDownOpen), o => o.IsDropDownOpen, (o, v) => o.IsDropDownOpen = v); public static readonly StyledProperty<bool> IsTodayHighlightedProperty = AvaloniaProperty.Register<CalendarDatePicker, bool>(nameof(IsTodayHighlighted)); public static readonly DirectProperty<CalendarDatePicker, DateTime?> SelectedDateProperty = AvaloniaProperty.RegisterDirect<CalendarDatePicker, DateTime?>( nameof(SelectedDate), o => o.SelectedDate, (o, v) => o.SelectedDate = v, enableDataValidation: true, defaultBindingMode:BindingMode.TwoWay); public static readonly StyledProperty<CalendarDatePickerFormat> SelectedDateFormatProperty = AvaloniaProperty.Register<CalendarDatePicker, CalendarDatePickerFormat>( nameof(SelectedDateFormat), defaultValue: CalendarDatePickerFormat.Short, validate: IsValidSelectedDateFormat); public static readonly StyledProperty<string> CustomDateFormatStringProperty = AvaloniaProperty.Register<CalendarDatePicker, string>( nameof(CustomDateFormatString), defaultValue: "d", validate: IsValidDateFormatString); public static readonly DirectProperty<CalendarDatePicker, string?> TextProperty = AvaloniaProperty.RegisterDirect<CalendarDatePicker, string?>( nameof(Text), o => o.Text, (o, v) => o.Text = v); public static readonly StyledProperty<string?> WatermarkProperty = TextBox.WatermarkProperty.AddOwner<CalendarDatePicker>(); public static readonly StyledProperty<bool> UseFloatingWatermarkProperty = TextBox.UseFloatingWatermarkProperty.AddOwner<CalendarDatePicker>(); /// <summary> /// Defines the <see cref="HorizontalContentAlignment"/> property. /// </summary> public static readonly StyledProperty<HorizontalAlignment> HorizontalContentAlignmentProperty = ContentControl.HorizontalContentAlignmentProperty.AddOwner<CalendarDatePicker>(); /// <summary> /// Defines the <see cref="VerticalContentAlignment"/> property. /// </summary> public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty = ContentControl.VerticalContentAlignmentProperty.AddOwner<CalendarDatePicker>(); /// <summary> /// Gets or sets the date to display. /// </summary> /// <value> /// The date to display. The default /// <see cref="P:System.DateTime.Today" />. /// </value> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// The specified date is not in the range defined by /// <see cref="P:Avalonia.Controls.CalendarDatePicker.DisplayDateStart" /> /// and /// <see cref="P:Avalonia.Controls.CalendarDatePicker.DisplayDateEnd" />. /// </exception> public DateTime DisplayDate { get { return _displayDate; } set { SetAndRaise(DisplayDateProperty, ref _displayDate, value); } } /// <summary> /// Gets or sets the first date to be displayed. /// </summary> /// <value>The first date to display.</value> public DateTime? DisplayDateStart { get { return _displayDateStart; } set { SetAndRaise(DisplayDateStartProperty, ref _displayDateStart, value); } } /// <summary> /// Gets or sets the last date to be displayed. /// </summary> /// <value>The last date to display.</value> public DateTime? DisplayDateEnd { get { return _displayDateEnd; } set { SetAndRaise(DisplayDateEndProperty, ref _displayDateEnd, value); } } /// <summary> /// Gets or sets the day that is considered the beginning of the week. /// </summary> /// <value> /// A <see cref="T:System.DayOfWeek" /> representing the beginning of /// the week. The default is <see cref="F:System.DayOfWeek.Sunday" />. /// </value> public DayOfWeek FirstDayOfWeek { get { return GetValue(FirstDayOfWeekProperty); } set { SetValue(FirstDayOfWeekProperty, value); } } /// <summary> /// Gets or sets a value indicating whether the drop-down /// <see cref="T:Avalonia.Controls.Calendar" /> is open or closed. /// </summary> /// <value> /// True if the <see cref="T:Avalonia.Controls.Calendar" /> is /// open; otherwise, false. The default is false. /// </value> public bool IsDropDownOpen { get { return _isDropDownOpen; } set { SetAndRaise(IsDropDownOpenProperty, ref _isDropDownOpen, value); } } /// <summary> /// Gets or sets a value indicating whether the current date will be /// highlighted. /// </summary> /// <value> /// True if the current date is highlighted; otherwise, false. The /// default is true. /// </value> public bool IsTodayHighlighted { get { return GetValue(IsTodayHighlightedProperty); } set { SetValue(IsTodayHighlightedProperty, value); } } /// <summary> /// Gets or sets the currently selected date. /// </summary> /// <value> /// The date currently selected. The default is null. /// </value> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// The specified date is not in the range defined by /// <see cref="P:Avalonia.Controls.DatePicker.DisplayDateStart" /> /// and /// <see cref="P:Avalonia.Controls.DatePicker.DisplayDateEnd" />, /// or the specified date is in the /// <see cref="P:Avalonia.Controls.DatePicker.BlackoutDates" /> /// collection. /// </exception> public DateTime? SelectedDate { get { return _selectedDate; } set { SetAndRaise(SelectedDateProperty, ref _selectedDate, value); } } /// <summary> /// Gets or sets the format that is used to display the selected date. /// </summary> /// <value> /// The format that is used to display the selected date. The default is /// <see cref="F:Avalonia.Controls.DatePickerFormat.Short" />. /// </value> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// An specified format is not valid. /// </exception> public CalendarDatePickerFormat SelectedDateFormat { get { return GetValue(SelectedDateFormatProperty); } set { SetValue(SelectedDateFormatProperty, value); } } public string CustomDateFormatString { get { return GetValue(CustomDateFormatStringProperty); } set { SetValue(CustomDateFormatStringProperty, value); } } /// <summary> /// Gets or sets the text that is displayed by the /// <see cref="T:Avalonia.Controls.DatePicker" />. /// </summary> /// <value> /// The text displayed by the /// <see cref="T:Avalonia.Controls.DatePicker" />. /// </value> /// <exception cref="T:System.FormatException"> /// The text entered cannot be parsed to a valid date, and the exception /// is not suppressed. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// The text entered parses to a date that is not selectable. /// </exception> public string? Text { get { return _text; } set { SetAndRaise(TextProperty, ref _text, value); } } public string? Watermark { get { return GetValue(WatermarkProperty); } set { SetValue(WatermarkProperty, value); } } public bool UseFloatingWatermark { get { return GetValue(UseFloatingWatermarkProperty); } set { SetValue(UseFloatingWatermarkProperty, value); } } /// <summary> /// Gets or sets the horizontal alignment of the content within the control. /// </summary> public HorizontalAlignment HorizontalContentAlignment { get => GetValue(HorizontalContentAlignmentProperty); set => SetValue(HorizontalContentAlignmentProperty, value); } /// <summary> /// Gets or sets the vertical alignment of the content within the control. /// </summary> public VerticalAlignment VerticalContentAlignment { get => GetValue(VerticalContentAlignmentProperty); set => SetValue(VerticalContentAlignmentProperty, value); } /// <summary> /// Occurs when the drop-down /// <see cref="T:Avalonia.Controls.Calendar" /> is closed. /// </summary> public event EventHandler? CalendarClosed; /// <summary> /// Occurs when the drop-down /// <see cref="T:Avalonia.Controls.Calendar" /> is opened. /// </summary> public event EventHandler? CalendarOpened; /// <summary> /// Occurs when <see cref="P:Avalonia.Controls.DatePicker.Text" /> /// is assigned a value that cannot be interpreted as a date. /// </summary> public event EventHandler<CalendarDatePickerDateValidationErrorEventArgs>? DateValidationError; /// <summary> /// Occurs when the /// <see cref="P:Avalonia.Controls.CalendarDatePicker.SelectedDate" /> /// property is changed. /// </summary> public event EventHandler<SelectionChangedEventArgs>? SelectedDateChanged; static CalendarDatePicker() { FocusableProperty.OverrideDefaultValue<CalendarDatePicker>(true); IsDropDownOpenProperty.Changed.AddClassHandler<CalendarDatePicker>((x,e) => x.OnIsDropDownOpenChanged(e)); SelectedDateProperty.Changed.AddClassHandler<CalendarDatePicker>((x,e) => x.OnSelectedDateChanged(e)); SelectedDateFormatProperty.Changed.AddClassHandler<CalendarDatePicker>((x,e) => x.OnSelectedDateFormatChanged(e)); CustomDateFormatStringProperty.Changed.AddClassHandler<CalendarDatePicker>((x,e) => x.OnCustomDateFormatStringChanged(e)); TextProperty.Changed.AddClassHandler<CalendarDatePicker>((x,e) => x.OnTextChanged(e)); } /// <summary> /// Initializes a new instance of the /// <see cref="T:Avalonia.Controls.DatePicker" /> class. /// </summary> public CalendarDatePicker() { FirstDayOfWeek = DateTimeHelper.GetCurrentDateFormat().FirstDayOfWeek; _defaultText = string.Empty; DisplayDate = DateTime.Today; } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { if (_calendar != null) { _calendar.DayButtonMouseUp -= Calendar_DayButtonMouseUp; _calendar.DisplayDateChanged -= Calendar_DisplayDateChanged; _calendar.SelectedDatesChanged -= Calendar_SelectedDatesChanged; _calendar.PointerReleased -= Calendar_PointerReleased; _calendar.KeyDown -= Calendar_KeyDown; } _calendar = e.NameScope.Find<Calendar>(ElementCalendar); if (_calendar != null) { _calendar.SelectionMode = CalendarSelectionMode.SingleDate; _calendar.DayButtonMouseUp += Calendar_DayButtonMouseUp; _calendar.DisplayDateChanged += Calendar_DisplayDateChanged; _calendar.SelectedDatesChanged += Calendar_SelectedDatesChanged; _calendar.PointerReleased += Calendar_PointerReleased; _calendar.KeyDown += Calendar_KeyDown; var currentBlackoutDays = BlackoutDates; BlackoutDates = _calendar.BlackoutDates; if(currentBlackoutDays != null) { foreach (var range in currentBlackoutDays) { BlackoutDates.Add(range); } } } if (_popUp != null) { _popUp.Child = null; _popUp.Closed -= PopUp_Closed; } _popUp = e.NameScope.Find<Popup>(ElementPopup); if(_popUp != null) { _popUp.Closed += PopUp_Closed; if (IsDropDownOpen) { OpenDropDown(); } } if(_dropDownButton != null) { _dropDownButton.Click -= DropDownButton_Click; _buttonPointerPressedSubscription?.Dispose(); } _dropDownButton = e.NameScope.Find<Button>(ElementButton); if(_dropDownButton != null) { _dropDownButton.Click += DropDownButton_Click; _buttonPointerPressedSubscription = _dropDownButton.AddDisposableHandler(PointerPressedEvent, DropDownButton_PointerPressed, handledEventsToo: true); } if (_textBox != null) { _textBox.KeyDown -= TextBox_KeyDown; _textBox.GotFocus -= TextBox_GotFocus; _textBoxTextChangedSubscription?.Dispose(); } _textBox = e.NameScope.Find<TextBox>(ElementTextBox); if(!SelectedDate.HasValue) { SetWaterMarkText(); } if(_textBox != null) { _textBox.KeyDown += TextBox_KeyDown; _textBox.GotFocus += TextBox_GotFocus; _textBoxTextChangedSubscription = _textBox.GetObservable(TextBox.TextProperty).Subscribe(txt => TextBox_TextChanged()); if(SelectedDate.HasValue) { _textBox.Text = DateTimeToString(SelectedDate.Value); } else if(!String.IsNullOrEmpty(_defaultText)) { _textBox.Text = _defaultText; SetSelectedDate(); } } } protected override void UpdateDataValidation<T>(AvaloniaProperty<T> property, BindingValue<T> value) { if (property == SelectedDateProperty) { DataValidationErrors.SetError(this, value.Error); } } protected override void OnPointerWheelChanged(PointerWheelEventArgs e) { base.OnPointerWheelChanged(e); if (!e.Handled && SelectedDate.HasValue && _calendar != null) { DateTime selectedDate = this.SelectedDate.Value; DateTime? newDate = DateTimeHelper.AddDays(selectedDate, e.Delta.Y > 0 ? -1 : 1); if (newDate.HasValue && Calendar.IsValidDateSelection(_calendar, newDate.Value)) { SelectedDate = newDate; e.Handled = true; } } } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); if(IsEnabled && _textBox != null && e.NavigationMethod == NavigationMethod.Tab) { _textBox.Focus(); var text = _textBox.Text; if(!string.IsNullOrEmpty(text)) { _textBox.SelectionStart = 0; _textBox.SelectionEnd = text.Length; } } } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); SetSelectedDate(); } private void OnIsDropDownOpenChanged(AvaloniaPropertyChangedEventArgs e) { var oldValue = (bool)e.OldValue!; var value = (bool)e.NewValue!; if (_popUp != null && _popUp.Child != null) { if (value != oldValue) { if (_calendar!.DisplayMode != CalendarMode.Month) { _calendar.DisplayMode = CalendarMode.Month; } if (value) { OpenDropDown(); } else { _popUp.IsOpen = false; OnCalendarClosed(new RoutedEventArgs()); } } } } private void OnSelectedDateChanged(AvaloniaPropertyChangedEventArgs e) { var addedDate = (DateTime?)e.NewValue; var removedDate = (DateTime?)e.OldValue; if (SelectedDate != null) { DateTime day = SelectedDate.Value; // When the SelectedDateProperty change is done from // OnTextPropertyChanged method, two-way binding breaks if // BeginInvoke is not used: Threading.Dispatcher.UIThread.InvokeAsync(() => { _settingSelectedDate = true; Text = DateTimeToString(day); _settingSelectedDate = false; OnDateSelected(addedDate, removedDate); }); // When DatePickerDisplayDateFlag is TRUE, the SelectedDate // change is coming from the Calendar UI itself, so, we // shouldn't change the DisplayDate since it will automatically // be changed by the Calendar if ((day.Month != DisplayDate.Month || day.Year != DisplayDate.Year) && (_calendar == null || !_calendar.CalendarDatePickerDisplayDateFlag)) { DisplayDate = day; } if(_calendar != null) _calendar.CalendarDatePickerDisplayDateFlag = false; } else { _settingSelectedDate = true; SetWaterMarkText(); _settingSelectedDate = false; OnDateSelected(addedDate, removedDate); } } private void OnDateFormatChanged() { if (_textBox != null) { if (SelectedDate.HasValue) { Text = DateTimeToString(SelectedDate.Value); } else if (string.IsNullOrEmpty(_textBox.Text)) { SetWaterMarkText(); } else { DateTime? date = ParseText(_textBox.Text); if (date != null) { string? s = DateTimeToString((DateTime)date); Text = s; } } } } private void OnSelectedDateFormatChanged(AvaloniaPropertyChangedEventArgs e) { OnDateFormatChanged(); } private void OnCustomDateFormatStringChanged(AvaloniaPropertyChangedEventArgs e) { if(SelectedDateFormat == CalendarDatePickerFormat.Custom) { OnDateFormatChanged(); } } private void OnTextChanged(AvaloniaPropertyChangedEventArgs e) { var oldValue = (string?)e.OldValue; var value = (string?)e.NewValue; if (!_suspendTextChangeHandler) { if (value != null) { if (_textBox != null) { _textBox.Text = value; } else { _defaultText = value; } if (!_settingSelectedDate) { SetSelectedDate(); } } else { if (!_settingSelectedDate) { _settingSelectedDate = true; SelectedDate = null; _settingSelectedDate = false; } } } else { SetWaterMarkText(); } } /// <summary> /// Raises the /// <see cref="E:Avalonia.Controls.CalendarDatePicker.DateValidationError" /> /// event. /// </summary> /// <param name="e"> /// A /// <see cref="T:Avalonia.Controls.CalendarDatePickerDateValidationErrorEventArgs" /> /// that contains the event data. /// </param> protected virtual void OnDateValidationError(CalendarDatePickerDateValidationErrorEventArgs e) { DateValidationError?.Invoke(this, e); } private void OnDateSelected(DateTime? addedDate, DateTime? removedDate) { EventHandler<SelectionChangedEventArgs>? handler = this.SelectedDateChanged; if (null != handler) { Collection<DateTime> addedItems = new Collection<DateTime>(); Collection<DateTime> removedItems = new Collection<DateTime>(); if (addedDate.HasValue) { addedItems.Add(addedDate.Value); } if (removedDate.HasValue) { removedItems.Add(removedDate.Value); } handler(this, new SelectionChangedEventArgs(SelectingItemsControl.SelectionChangedEvent, removedItems, addedItems)); } } private void OnCalendarClosed(EventArgs e) { CalendarClosed?.Invoke(this, e); } private void OnCalendarOpened(EventArgs e) { CalendarOpened?.Invoke(this, e); } private void Calendar_DayButtonMouseUp(object? sender, PointerReleasedEventArgs e) { Focus(); IsDropDownOpen = false; } private void Calendar_DisplayDateChanged(object? sender, CalendarDateChangedEventArgs e) { if (e.AddedDate != this.DisplayDate) { SetValue(DisplayDateProperty, (DateTime) e.AddedDate!); } } private void Calendar_SelectedDatesChanged(object? sender, SelectionChangedEventArgs e) { Debug.Assert(e.AddedItems.Count < 2, "There should be less than 2 AddedItems!"); if (e.AddedItems.Count > 0 && SelectedDate.HasValue && DateTime.Compare((DateTime)e.AddedItems[0]!, SelectedDate.Value) != 0) { SelectedDate = (DateTime?)e.AddedItems[0]; } else { if (e.AddedItems.Count == 0) { SelectedDate = null; return; } if (!SelectedDate.HasValue) { if (e.AddedItems.Count > 0) { SelectedDate = (DateTime?)e.AddedItems[0]; } } } } private void Calendar_PointerReleased(object? sender, PointerReleasedEventArgs e) { if (e.InitialPressMouseButton == MouseButton.Left) { e.Handled = true; } } private void Calendar_KeyDown(object? sender, KeyEventArgs e) { Calendar? c = sender as Calendar ?? throw new ArgumentException("Sender must be Calendar.", nameof(sender)); if (!e.Handled && (e.Key == Key.Enter || e.Key == Key.Space || e.Key == Key.Escape) && c.DisplayMode == CalendarMode.Month) { Focus(); IsDropDownOpen = false; if (e.Key == Key.Escape) { SelectedDate = _onOpenSelectedDate; } } } private void TextBox_GotFocus(object? sender, RoutedEventArgs e) { IsDropDownOpen = false; } private void TextBox_KeyDown(object? sender, KeyEventArgs e) { if (!e.Handled) { e.Handled = ProcessDatePickerKey(e); } } private void TextBox_TextChanged() { if (_textBox != null) { _suspendTextChangeHandler = true; Text = _textBox.Text; _suspendTextChangeHandler = false; } } private void DropDownButton_PointerPressed(object? sender, PointerPressedEventArgs e) { _ignoreButtonClick = _isPopupClosing; } private void DropDownButton_Click(object? sender, RoutedEventArgs e) { if (!_ignoreButtonClick) { HandlePopUp(); } else { _ignoreButtonClick = false; } } private void PopUp_Closed(object? sender, EventArgs e) { IsDropDownOpen = false; if(!_isPopupClosing) { _isPopupClosing = true; Threading.Dispatcher.UIThread.InvokeAsync(() => _isPopupClosing = false); } } private void HandlePopUp() { if (IsDropDownOpen) { Focus(); IsDropDownOpen = false; } else { ProcessTextBox(); } } private void OpenDropDown() { if (_calendar != null) { _calendar.Focus(); OpenPopUp(); _calendar.ResetStates(); OnCalendarOpened(new RoutedEventArgs()); } } private void OpenPopUp() { _onOpenSelectedDate = SelectedDate; _popUp!.IsOpen = true; } /// <summary> /// Input text is parsed in the correct format and changed into a /// DateTime object. If the text can not be parsed TextParseError Event /// is thrown. /// </summary> /// <param name="text">Inherited code: Requires comment.</param> /// <returns> /// IT SHOULD RETURN NULL IF THE STRING IS NOT VALID, RETURN THE /// DATETIME VALUE IF IT IS VALID. /// </returns> private DateTime? ParseText(string text) { DateTime newSelectedDate; // TryParse is not used in order to be able to pass the exception to // the TextParseError event try { newSelectedDate = DateTime.Parse(text, DateTimeHelper.GetCurrentDateFormat()); if (Calendar.IsValidDateSelection(this._calendar!, newSelectedDate)) { return newSelectedDate; } else { var dateValidationError = new CalendarDatePickerDateValidationErrorEventArgs(new ArgumentOutOfRangeException(nameof(text), "SelectedDate value is not valid."), text); OnDateValidationError(dateValidationError); if (dateValidationError.ThrowException) { throw dateValidationError.Exception; } } } catch (FormatException ex) { CalendarDatePickerDateValidationErrorEventArgs textParseError = new CalendarDatePickerDateValidationErrorEventArgs(ex, text); OnDateValidationError(textParseError); if (textParseError.ThrowException) { throw textParseError.Exception; } } return null; } private string? DateTimeToString(DateTime d) { DateTimeFormatInfo dtfi = DateTimeHelper.GetCurrentDateFormat(); switch (SelectedDateFormat) { case CalendarDatePickerFormat.Short: return string.Format(CultureInfo.CurrentCulture, d.ToString(dtfi.ShortDatePattern, dtfi)); case CalendarDatePickerFormat.Long: return string.Format(CultureInfo.CurrentCulture, d.ToString(dtfi.LongDatePattern, dtfi)); case CalendarDatePickerFormat.Custom: return string.Format(CultureInfo.CurrentCulture, d.ToString(CustomDateFormatString, dtfi)); } return null; } private bool ProcessDatePickerKey(KeyEventArgs e) { switch (e.Key) { case Key.Enter: { SetSelectedDate(); return true; } case Key.Down: { if ((e.KeyModifiers & KeyModifiers.Control) == KeyModifiers.Control) { HandlePopUp(); return true; } break; } } return false; } private void ProcessTextBox() { SetSelectedDate(); IsDropDownOpen = true; _calendar!.Focus(); } private void SetSelectedDate() { if (_textBox != null) { if (!string.IsNullOrEmpty(_textBox.Text)) { string s = _textBox.Text; if (SelectedDate != null) { // If the string value of the SelectedDate and the // TextBox string value are equal, we do not parse the // string again if we do an extra parse, we lose data in // M/d/yy format. // ex: SelectedDate = DateTime(1008,12,19) but when // "12/19/08" is parsed it is interpreted as // DateTime(2008,12,19) string? selectedDate = DateTimeToString(SelectedDate.Value); if (selectedDate == s) { return; } } DateTime? d = SetTextBoxValue(s); if (SelectedDate != d) { SelectedDate = d; } } else { if (SelectedDate != null) { SelectedDate = null; } } } else { DateTime? d = SetTextBoxValue(_defaultText); if (SelectedDate != d) { SelectedDate = d; } } } private DateTime? SetTextBoxValue(string s) { if (string.IsNullOrEmpty(s)) { SetValue(TextProperty, s); return SelectedDate; } else { DateTime? d = ParseText(s); if (d != null) { SetValue(TextProperty, s); return d; } else { // If parse error: TextBox should have the latest valid // SelectedDate value: if (SelectedDate != null) { string? newtext = this.DateTimeToString(SelectedDate.Value); SetValue(TextProperty, newtext); return SelectedDate; } else { SetWaterMarkText(); return null; } } } } private void SetWaterMarkText() { if (_textBox != null) { if (string.IsNullOrEmpty(Watermark) && !UseFloatingWatermark) { DateTimeFormatInfo dtfi = DateTimeHelper.GetCurrentDateFormat(); Text = string.Empty; _defaultText = string.Empty; var watermarkFormat = "<{0}>"; string watermarkText; switch (SelectedDateFormat) { case CalendarDatePickerFormat.Long: { watermarkText = string.Format(CultureInfo.CurrentCulture, watermarkFormat, dtfi.LongDatePattern.ToString()); break; } case CalendarDatePickerFormat.Short: default: { watermarkText = string.Format(CultureInfo.CurrentCulture, watermarkFormat, dtfi.ShortDatePattern.ToString()); break; } } _textBox.Watermark = watermarkText; } else { _textBox.ClearValue(TextBox.WatermarkProperty); } } } private static bool IsValidSelectedDateFormat(CalendarDatePickerFormat value) { return value == CalendarDatePickerFormat.Long || value == CalendarDatePickerFormat.Short || value == CalendarDatePickerFormat.Custom; } private static bool IsValidDateFormatString(string formatString) { return !string.IsNullOrWhiteSpace(formatString); } private static DateTime DiscardDayTime(DateTime d) { int year = d.Year; int month = d.Month; DateTime newD = new DateTime(year, month, 1, 0, 0, 0); return newD; } private static DateTime? DiscardTime(DateTime? d) { if (d == null) { return null; } else { DateTime discarded = (DateTime) d; int year = discarded.Year; int month = discarded.Month; int day = discarded.Day; DateTime newD = new DateTime(year, month, day, 0, 0, 0); return newD; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using PcapDotNet.Packets.Http; namespace PcapDotNet.Packets.Transport { /// <summary> /// RFC 793. /// TCP Header Format /// <pre> /// +-----+-------------+----------+----+-----+-----+-----+-----+-----+-----+-----+-----+------------------+ /// | Bit | 0-3 | 4-6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16-31 | /// +-----+-------------+----------+----+-----+-----+-----+-----+-----+-----+-----+-----+------------------+ /// | 0 | Source Port | Destination Port | /// +-----+-----------------------------------------------------------------------------+------------------+ /// | 32 | Sequence Number | /// +-----+------------------------------------------------------------------------------------------------+ /// | 64 | Acknowledgment Number | /// +-----+-------------+----------+----+-----+-----+-----+-----+-----+-----+-----+-----+------------------+ /// | 96 | Data Offset | Reserved | NS | CWR | ECE | URG | ACK | PSH | RST | SYN | FIN | Window | /// +-----+-------------+----------+----+-----+-----+-----+-----+-----+-----+-----+-----+------------------+ /// | 128 | Checksum | Urgent Pointer | /// +-----+-----------------------------------------------------------------------------+------------------+ /// | 160 | Options + Padding | /// | ... | | /// +-----+------------------------------------------------------------------------------------------------+ /// </pre> /// </summary> public sealed class TcpDatagram : TransportDatagram { /// <summary> /// The minimum number of bytes the header takes. /// </summary> public const int HeaderMinimumLength = 20; /// <summary> /// The maximum number of bytes the header takes. /// </summary> public const int HeaderMaximumLength = 60; internal static class Offset { public const int SequenceNumber = 4; public const int AcknowledgmentNumber = 8; public const int HeaderLengthAndFlags = 12; public const int Window = 14; public const int Checksum = 16; public const int UrgentPointer = 18; public const int Options = 20; } private static class Mask { public const byte Reserved = 0x0E; public const ushort ControlBits = 0x01FF; } private static class Shift { public const int HeaderLength = 4; public const int Reserved = 1; } /// <summary> /// The sequence number of the first data octet in this segment (except when SYN is present). /// If SYN is present the sequence number is the initial sequence number (ISN) and the first data octet is ISN+1. /// </summary> public uint SequenceNumber { get { return ReadUInt(Offset.SequenceNumber, Endianity.Big); } } /// <summary> /// The sequence number of the data that will come after this data. /// </summary> public uint NextSequenceNumber { get { return (uint)(SequenceNumber + PayloadLength); } } /// <summary> /// If the ACK control bit is set this field contains the value of the next sequence number /// the sender of the segment is expecting to receive. /// Once a connection is established this is always sent. /// </summary> public uint AcknowledgmentNumber { get { return ReadUInt(Offset.AcknowledgmentNumber, Endianity.Big); } } /// <summary> /// The number of bytes in the TCP Header. /// This indicates where the data begins. /// The TCP header (even one including options) is an integral number of 32 bits (4 bytes) long. /// </summary> public int HeaderLength { get { return 4 * (this[Offset.HeaderLengthAndFlags] >> Shift.HeaderLength); } } /// <summary> /// Returns the actual header length. /// </summary> public int RealHeaderLength { get { return Math.Min(HeaderLength, Length); } } /// <summary> /// Reserved for future use. /// Must be zero. /// </summary> public byte Reserved { get { return (byte)((this[Offset.HeaderLengthAndFlags] & Mask.Reserved) >> Shift.Reserved); } } /// <summary> /// A collection of bits for the TCP control. /// </summary> public TcpControlBits ControlBits { get { return (TcpControlBits)(ReadUShort(Offset.HeaderLengthAndFlags, Endianity.Big) & Mask.ControlBits); } } /// <summary> /// The number of data octets beginning with the one indicated in the acknowledgment field which the sender of this segment is willing to accept. /// </summary> public ushort Window { get { return ReadUShort(Offset.Window, Endianity.Big); } } /// <summary> /// The checksum field is the 16 bit one's complement of the one's complement sum of all 16 bit words in the header and text. /// If a segment contains an odd number of header and text octets to be checksummed, /// the last octet is padded on the right with zeros to form a 16 bit word for checksum purposes. /// The pad is not transmitted as part of the segment. /// While computing the checksum, the checksum field itself is replaced with zeros. /// /// The checksum also covers a 96 bit pseudo header conceptually prefixed to the TCP header. /// This pseudo header contains the Source Address, the Destination Address, the Protocol, and TCP length. /// This gives the TCP protection against misrouted segments. /// This information is carried in the Internet Protocol and is transferred across the TCP/Network interface in the arguments or results of calls /// by the TCP on the IP. /// /// +--------+--------+--------+--------+ /// | Source Address | /// +--------+--------+--------+--------+ /// | Destination Address | /// +--------+--------+--------+--------+ /// | zero | PTCL | TCP Length | /// +--------+--------+--------+--------+ /// /// The TCP Length is the TCP header length plus the data length in octets (this is not an explicitly transmitted quantity, but is computed), /// and it does not count the 12 octets of the pseudo header. /// </summary> public override ushort Checksum { get { return ReadUShort(Offset.Checksum, Endianity.Big); } } /// <summary> /// True iff the checksum for the transport type is optional. /// </summary> public override bool IsChecksumOptional { get { return false; } } /// <summary> /// This field communicates the current value of the urgent pointer as a positive offset from the sequence number in this segment. /// The urgent pointer points to the sequence number of the octet following the urgent data. /// This field is only be interpreted in segments with the URG control bit set. /// </summary> public ushort UrgentPointer { get { return ReadUShort(Offset.UrgentPointer, Endianity.Big); } } /// <summary> /// Returns the TCP options contained in this TCP Datagram. /// </summary> public TcpOptions Options { get { if (_options == null && Length >= HeaderMinimumLength && HeaderLength >= HeaderMinimumLength) _options = new TcpOptions(Buffer, StartOffset + Offset.Options, RealHeaderLength - HeaderMinimumLength); return _options; } } /// <summary> /// The length of the TCP payload. /// </summary> public int PayloadLength { get { return Length - HeaderLength; } } /// <summary> /// True iff the NonceSum control bit is turned on. /// </summary> public bool IsNonceSum { get { return (ControlBits & TcpControlBits.NonceSum) == TcpControlBits.NonceSum; } } /// <summary> /// True iff the CongestionWindowReduced control bit is turned on. /// </summary> public bool IsCongestionWindowReduced { get { return (ControlBits & TcpControlBits.CongestionWindowReduced) == TcpControlBits.CongestionWindowReduced; } } /// <summary> /// True iff the ExplicitCongestionNotificationEcho control bit is turned on. /// </summary> public bool IsExplicitCongestionNotificationEcho { get { return (ControlBits & TcpControlBits.ExplicitCongestionNotificationEcho) == TcpControlBits.ExplicitCongestionNotificationEcho; } } /// <summary> /// True iff the Urgent control bit is turned on. /// </summary> public bool IsUrgent { get { return (ControlBits & TcpControlBits.Urgent) == TcpControlBits.Urgent; } } /// <summary> /// True iff the Acknowledgment control bit is turned on. /// </summary> public bool IsAcknowledgment { get { return (ControlBits & TcpControlBits.Acknowledgment) == TcpControlBits.Acknowledgment; } } /// <summary> /// True iff the Push control bit is turned on. /// </summary> public bool IsPush { get { return (ControlBits & TcpControlBits.Push) == TcpControlBits.Push; } } /// <summary> /// True iff the Reset control bit is turned on. /// </summary> public bool IsReset { get { return (ControlBits & TcpControlBits.Reset) == TcpControlBits.Reset; } } /// <summary> /// True iff the Synchronize control bit is turned on. /// </summary> public bool IsSynchronize { get { return (ControlBits & TcpControlBits.Synchronize) == TcpControlBits.Synchronize; } } /// <summary> /// True iff the Fin control bit is turned on. /// </summary> public bool IsFin { get { return (ControlBits & TcpControlBits.Fin) == TcpControlBits.Fin; } } /// <summary> /// Creates a Layer that represents the datagram to be used with PacketBuilder. /// </summary> public override ILayer ExtractLayer() { return new TcpLayer { Checksum = Checksum, SourcePort = SourcePort, DestinationPort = DestinationPort, SequenceNumber = SequenceNumber, AcknowledgmentNumber = AcknowledgmentNumber, ControlBits = ControlBits, Window = Window, UrgentPointer = UrgentPointer, Options = Options }; } /// <summary> /// The first HTTP message in this TCP datagram. /// </summary> public HttpDatagram Http { get { return HttpCollection == null ? null : HttpCollection[0]; } } /// <summary> /// All of the available HTTP messages in this TCP datagram. /// </summary> public ReadOnlyCollection<HttpDatagram> HttpCollection { get { if (_httpCollection == null && Length >= HeaderMinimumLength && Length >= HeaderLength) { List<HttpDatagram> httpList = new List<HttpDatagram>(); int httpParsed = 0; do { HttpDatagram httpDatagram = HttpDatagram.CreateDatagram(Buffer, StartOffset + HeaderLength + httpParsed, Length - HeaderLength - httpParsed); httpParsed += httpDatagram.Length; httpList.Add(httpDatagram); } while (Length > HeaderLength + httpParsed); _httpCollection = httpList.AsReadOnly(); } return _httpCollection; } } /// <summary> /// The payload of the TCP datagram. /// </summary> public override Datagram Payload { get { if (Length < HeaderMinimumLength || Length < HeaderLength) return null; return new Datagram(Buffer, StartOffset + HeaderLength, PayloadLength); } } /// <summary> /// The datagram is valid if the length is correct according to the header and the options are valid. /// </summary> protected override bool CalculateIsValid() { return Length >= HeaderMinimumLength && Length >= HeaderLength && HeaderLength >= HeaderMinimumLength && Options.IsValid; } internal TcpDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } internal override int ChecksumOffset { get { return Offset.Checksum; } } internal static void WriteHeader(byte[] buffer, int offset, ushort sourcePort, ushort destinationPort, uint sequenceNumber, uint acknowledgmentNumber, TcpControlBits controlBits, ushort window, ushort urgentPointer, TcpOptions options) { int headerLength = HeaderMinimumLength + options.BytesLength; WriteHeader(buffer, offset, sourcePort, destinationPort); buffer.Write(offset + Offset.SequenceNumber, sequenceNumber, Endianity.Big); buffer.Write(offset + Offset.AcknowledgmentNumber, acknowledgmentNumber, Endianity.Big); buffer.Write(offset + Offset.HeaderLengthAndFlags, (ushort)(((ushort)((headerLength / 4) << 12)) | (ushort)controlBits), Endianity.Big); buffer.Write(offset + Offset.Window, window, Endianity.Big); buffer.Write(offset + Offset.UrgentPointer, urgentPointer, Endianity.Big); options.Write(buffer, offset + Offset.Options); } private TcpOptions _options; private ReadOnlyCollection<HttpDatagram> _httpCollection; } }
using System; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityObject = UnityEngine.Object; namespace XposeCraft.Inspector { /// <summary> /// To use, inherit this generic class to a non-generic version (no need to be public) and annotate /// [CustomPropertyDrawer(typeof(MyDictionary))] where MyDictionary is the name of non-generic dictionary. /// Source: https://forum.unity3d.com/threads/finally-a-serializable-dictionary-for-unity-extracted-from-system-collections-generic.335797/ /// </summary> /// <typeparam name="TKey">The type of keys in the dictionary.</typeparam> /// <typeparam name="TValue">The type of values in the dictionary.</typeparam> public abstract class DictionaryDrawer<TKey, TValue> : PropertyDrawer { private const float ButtonWidth = 18f; private Dictionary<TKey, TValue> _dictionary; private bool _foldout; public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { CheckInitialize(property, label); if (_foldout) return (_dictionary.Count + 1) * 17f; return 17f; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { CheckInitialize(property, label); position.height = 17f; var foldoutRect = position; foldoutRect.width -= 2 * ButtonWidth; EditorGUI.BeginChangeCheck(); _foldout = EditorGUI.Foldout(foldoutRect, _foldout, label, true); if (EditorGUI.EndChangeCheck()) EditorPrefs.SetBool(label.text, _foldout); var buttonRect = position; buttonRect.x = position.width - ButtonWidth + position.x; buttonRect.width = ButtonWidth + 2; if (GUI.Button(buttonRect, new GUIContent("+", "Add item"), EditorStyles.miniButton)) { Undo.RecordObject(property.serializedObject.targetObject, "Add Dictionary Item"); AddNewItem(); } buttonRect.x -= ButtonWidth; if (GUI.Button(buttonRect, new GUIContent("X", "Clear dictionary"), EditorStyles.miniButtonRight)) { Undo.RecordObject(property.serializedObject.targetObject, "Clear Dictionary"); ClearDictionary(); } if (!_foldout) return; foreach (var item in _dictionary) { var key = item.Key; var value = item.Value; position.y += 17f; var keyRect = position; keyRect.width /= 2; keyRect.width -= 4; EditorGUI.BeginChangeCheck(); var newKey = DoField(keyRect, typeof(TKey), key); if (EditorGUI.EndChangeCheck()) { try { Undo.RecordObject( property.serializedObject.targetObject, "Change Key of Dictionary Item from " + key + " to " + newKey); _dictionary.Remove(key); _dictionary.Add(newKey, value); } catch (Exception e) { Debug.Log(e.Message); } break; } var valueRect = position; valueRect.x = position.width / 2 + 15; valueRect.width = keyRect.width - ButtonWidth; EditorGUI.BeginChangeCheck(); value = DoField(valueRect, typeof(TValue), value); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject( property.serializedObject.targetObject, "Change value of Dictionary Item with Key " + key + " to " + value); _dictionary[key] = value; break; } var removeRect = valueRect; removeRect.x = valueRect.xMax + 2; removeRect.width = ButtonWidth; if (GUI.Button(removeRect, new GUIContent("x", "Remove item"), EditorStyles.miniButtonRight)) { Undo.RecordObject(property.serializedObject.targetObject, "Remove Dictionary Item " + key); RemoveItem(key); break; } } } private void RemoveItem(TKey key) { _dictionary.Remove(key); } private void CheckInitialize(SerializedProperty property, GUIContent label) { if (_dictionary == null) { var target = property.serializedObject.targetObject; _dictionary = fieldInfo.GetValue(target) as Dictionary<TKey, TValue>; if (_dictionary == null) { _dictionary = new Dictionary<TKey, TValue>(); fieldInfo.SetValue(target, _dictionary); } _foldout = EditorPrefs.GetBool(label.text); } } private static readonly Dictionary<Type, Func<Rect, object, object>> _Fields = new Dictionary<Type, Func<Rect, object, object>> { {typeof(int), (rect, value) => EditorGUI.IntField(rect, (int) value)}, {typeof(float), (rect, value) => EditorGUI.FloatField(rect, (float) value)}, {typeof(string), (rect, value) => EditorGUI.TextField(rect, (string) value)}, {typeof(bool), (rect, value) => EditorGUI.Toggle(rect, (bool) value)}, {typeof(Vector2), (rect, value) => EditorGUI.Vector2Field(rect, GUIContent.none, (Vector2) value)}, {typeof(Vector3), (rect, value) => EditorGUI.Vector3Field(rect, GUIContent.none, (Vector3) value)}, {typeof(Bounds), (rect, value) => EditorGUI.BoundsField(rect, (Bounds) value)}, {typeof(Rect), (rect, value) => EditorGUI.RectField(rect, (Rect) value)}, }; private static T DoField<T>(Rect rect, Type type, T value) { Func<Rect, object, object> field; if (_Fields.TryGetValue(type, out field)) return (T) field(rect, value); if (type.IsEnum) return (T) (object) EditorGUI.EnumPopup(rect, (Enum) (object) value); if (typeof(UnityObject).IsAssignableFrom(type)) return (T) (object) EditorGUI.ObjectField(rect, (UnityObject) (object) value, type, true); // Only display the size of collections if (typeof(ICollection).IsAssignableFrom(type)) { var collection = (ICollection) value; EditorGUI.TextField(rect, "Size " + (collection == null ? 0 : collection.Count), GUIStyle.none); return value; } Debug.Log("Type is not supported: " + type); return value; } private void ClearDictionary() { _dictionary.Clear(); } private void AddNewItem() { TKey key; if (typeof(TKey) == typeof(string)) key = (TKey) (object) ""; else key = default(TKey); var value = default(TValue); try { _dictionary.Add(key, value); } catch (Exception e) { Debug.Log(e.Message); } } } }
using System; using System.Text; using System.Collections; using System.Text.RegularExpressions; using System.Security.Cryptography.X509Certificates; using System.Net; using System.IO; using AppUtil; using Vim25Api; namespace GetVMFiles { class GetVMFiles { private static AppUtil.AppUtil cb = null; static VimService _service; static ServiceContent _sic; private void getVMFiles(String[] args) { _service = cb.getConnection()._service; _sic = cb.getConnection()._sic; String vmName = cb.get_option("vmname"); String localpath = cb.get_option("localpath"); Hashtable downloadedDir = new Hashtable(); try { Cookie cookie = cb._connection._service.CookieContainer.GetCookies( new Uri(cb.get_option("url")))[0]; CookieContainer cookieContainer = new CookieContainer(); cookieContainer.Add(cookie); ManagedObjectReference vmmor = null; vmmor = cb.getServiceUtil().GetDecendentMoRef(null, "VirtualMachine", vmName); if (vmmor != null) { String dataCenterName = getDataCenter(vmmor); String[] vmDirectory = getVmDirectory(vmmor); if (vmDirectory[0] != null) { Console.WriteLine("Downloading Virtual Machine Configuration Directory"); String dataStoreName = vmDirectory[0].Substring(vmDirectory[0].IndexOf("[") + 1, vmDirectory[0].LastIndexOf("]") - 1); int length = vmDirectory[0].LastIndexOf("/") - vmDirectory[0].IndexOf("]") - 2; String configurationDir = vmDirectory[0].Substring(vmDirectory[0].IndexOf("]") + 2, length); String localDirPath = cb.get_option("localpath") + "/" + configurationDir + "#vm#" + dataStoreName; Directory.CreateDirectory(localDirPath); downloadDirectory(configurationDir, localDirPath, dataStoreName, dataCenterName); downloadedDir.Add(configurationDir + "#vm#" + dataStoreName, "Directory"); Console.WriteLine("Downloading Virtual Machine" + " Configuration Directory Complete"); } if(vmDirectory[1] != null) { Console.WriteLine("Downloading Virtual Machine Snapshot / Suspend / Log Directory"); for(int i=1; i < vmDirectory.Length; i++) { String dataStoreName = vmDirectory[i].Substring(vmDirectory[i].IndexOf("[") +1,vmDirectory[i].LastIndexOf("]")-1); String configurationDir = ""; ServiceContent sc = cb.getConnection().ServiceContent; String apiType = sc.about.apiType; if(apiType.Equals("VirtualCenter")) { configurationDir = vmDirectory[i].Substring(vmDirectory[i].IndexOf("]")+2); configurationDir = configurationDir.Substring(0,configurationDir.Length-1); } else { configurationDir = vmDirectory[i].Substring(vmDirectory[i].IndexOf("]")+2); } if(!downloadedDir.ContainsKey(configurationDir+"#vm#"+dataStoreName)) { String localDirPath = cb.get_option("localpath") + "/" + configurationDir + "#vm#" + dataStoreName; Directory.CreateDirectory(localDirPath); downloadDirectory(configurationDir, localDirPath, dataStoreName, dataCenterName); downloadedDir.Add(configurationDir + "#vm#" + dataStoreName, "Directory"); } else { Console.WriteLine("Already Downloaded"); } } Console.WriteLine("Downloading Virtual Machine Snapshot" +" / Suspend / Log Directory Complete"); } String [] virtualDiskLocations = getVDiskLocations(vmmor); if(virtualDiskLocations != null) { Console.WriteLine("Downloading Virtual Disks"); for(int i=0; i<virtualDiskLocations.Length; i++) { if(virtualDiskLocations[i]!=null) { String dataStoreName = virtualDiskLocations[i].Substring( virtualDiskLocations[i].IndexOf("[") +1,virtualDiskLocations[i].LastIndexOf("]")-1); String configurationDir = virtualDiskLocations[i].Substring( virtualDiskLocations[i].IndexOf("]") + 2, virtualDiskLocations[i].LastIndexOf("/") - virtualDiskLocations[i].IndexOf("]") - 2); if(!downloadedDir.ContainsKey(configurationDir+"#vdisk#"+dataStoreName)) { String localDirPath = cb.get_option("localpath") + "/" + configurationDir + "#vdisk#" + dataStoreName; Directory.CreateDirectory(localDirPath); downloadDirectory(configurationDir, localDirPath, dataStoreName, dataCenterName); downloadedDir.Add(configurationDir + "#vdisk#" + dataStoreName, "Directory"); } else { Console.WriteLine("Already Downloaded"); } } else { // Do Nothing } } Console.WriteLine("Downloading Virtual Disks Complete"); } else { // Do Nothing } } else { Console.WriteLine("Virtual Machine " + cb.get_option("vmname") + " Not Found."); } } catch (Exception e) { cb.log.LogLine("GetVMFiles failed for VM : " + vmName); throw e; } } private String getCookie() { Cookie cookie = cb._connection._service.CookieContainer.GetCookies( new Uri(cb.get_option("url")))[0]; String cookieString = cookie.ToString(); return cookieString; } private String [] getVmDirectory(ManagedObjectReference vmmor) { String [] vmDir = new String [4]; VirtualMachineConfigInfo vmConfigInfo = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty(vmmor,"config"); if(vmConfigInfo != null) { vmDir[0] = vmConfigInfo.files.vmPathName; vmDir[1] = vmConfigInfo.files.snapshotDirectory; vmDir[2] = vmConfigInfo.files.suspendDirectory; vmDir[3] = vmConfigInfo.files.logDirectory; } else { Console.WriteLine("Cannot Restore VM. Not Able "+"To Find The Virtual Machine Config Info"); } return vmDir; } private String getDataCenter(ManagedObjectReference vmmor) { ManagedObjectReference morParent = cb.getServiceUtil().GetMoRefProp(vmmor,"parent"); morParent = cb.getServiceUtil().GetMoRefProp(morParent, "parent"); if (!morParent.type.Equals("Datacenter")) { morParent = cb.getServiceUtil().GetMoRefProp(morParent, "parent"); } Object objdcName = cb.getServiceUtil().GetDynamicProperty(morParent, "name"); String dcName = objdcName.ToString(); return dcName; } private void downloadDirectory(String directoryName,String localDirectory, String dataStoreName, String dataCenter) { String serviceUrl = cb.getServiceUrl(); serviceUrl = serviceUrl.Substring(0,serviceUrl.LastIndexOf("sdk")-1); String httpUrl = serviceUrl+"/folder/"+directoryName+"?dcPath=" +dataCenter+"&dsName="+dataStoreName; httpUrl = httpUrl.Replace("\\ ","%20"); String [] linkMap = getListFiles(httpUrl); for(int i = 1; i < linkMap.Length; i++) { Console.WriteLine("Downloading VM File " + linkMap[i]); String urlString = serviceUrl + linkMap[i]; String fileName = localDirectory + linkMap[i].Substring(linkMap[i].LastIndexOf("/"), linkMap[i].LastIndexOf("?") - linkMap[i].LastIndexOf("/")); urlString = urlString.Replace("\\ ","%20"); getData(urlString, fileName); } } private String [] getListFiles(String urlString) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlString); request.Headers.Add(HttpRequestHeader.Cookie, getCookie()); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); String line = null; String xmlString = ""; using (StreamReader r = new StreamReader(response.GetResponseStream())) { while ((line = r.ReadLine()) != null) { xmlString = xmlString + line; } } xmlString = xmlString.Replace("&amp;","&"); ArrayList list = getFileLinks(xmlString);; String [] linkMap = new String[list.Count]; for(int i=0;i<list.Count;i++) { linkMap[i]=(String)list[i]; } return linkMap; } private ArrayList getFileLinks(String xmlString) { ArrayList linkMap = new ArrayList(); Regex regex = new Regex("<a href=\".*?\">"); MatchCollection regexMatcher = regex.Matches(xmlString); if (regexMatcher.Count > 0) { foreach (Match m in regexMatcher) { String data = m.Value; int ind = data.IndexOf("\"") + 1; int lind = data.LastIndexOf("\"") - ind; data = data.Substring(ind, lind); linkMap.Add(data); } } return linkMap; } private void getData(String urlString, String fileName) { WebClient client = new WebClient(); NetworkCredential nwCred = new NetworkCredential(); nwCred.UserName = cb.get_option("username"); nwCred.Password = cb.get_option("password"); client.Credentials = nwCred; try { client.DownloadFile(urlString, fileName); } catch (Exception e) { System.Console.WriteLine(e.InnerException); } } private String replaceSpecialChar(String fileName) { fileName = fileName.Replace(':', '_'); fileName = fileName.Replace('*', '_'); fileName = fileName.Replace('<', '_'); fileName = fileName.Replace('>', '_'); fileName = fileName.Replace('|', '_'); return fileName; } private String [] getVDiskLocations(ManagedObjectReference vmmor) { VirtualMachineConfigInfo vmConfigInfo = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty(vmmor, "config"); if(vmConfigInfo != null) { VirtualDevice [] vDevice = vmConfigInfo.hardware.device; int count = 0; String [] virtualDisk = new String [vDevice.Length]; for(int i=0; i<vDevice.Length; i++) { if (vDevice[i].GetType().FullName.Equals("VimApi.VirtualDisk")) { try { VirtualDeviceFileBackingInfo backingInfo = (VirtualDeviceFileBackingInfo) vDevice[i].backing; virtualDisk[count] = backingInfo.fileName; count++; } catch(Exception e){ // DO NOTHING } } } return virtualDisk; } else { Console.WriteLine("Connot Restore VM. Not Able To" +" Find The Virtual Machine Config Info"); return null; } } public static OptionSpec[] constructOptions() { OptionSpec[] useroptions = new OptionSpec[2]; useroptions[0] = new OptionSpec("vmname", "String", 1 , "Name of the Virtual Machine" , null); useroptions[1] = new OptionSpec("localpath", "String", 1 , "localpath to copy files" , null); return useroptions; } public static void Main(String[] args) { GetVMFiles obj = new GetVMFiles(); cb = AppUtil.AppUtil.initialize("GetVMFiles" , GetVMFiles.constructOptions() , args); cb.connect(); obj.getVMFiles(args); cb.disConnect(); Console.WriteLine("Please enter any key to exit: "); Console.Read(); } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace IO.Swagger.Model { /// <summary> /// Unique deed, consisting of property, borrower and charge information as well as clauses for the deed. /// </summary> [DataContract] public partial class OperativeDeedDeed : IEquatable<OperativeDeedDeed> { /// <summary> /// Initializes a new instance of the <see cref="OperativeDeedDeed" /> class. /// Initializes a new instance of the <see cref="OperativeDeedDeed" />class. /// </summary> /// <param name="TitleNumber">Unique Land Registry identifier for the registered estate..</param> /// <param name="Lender">Lender.</param> /// <param name="PropertyAddress">The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA.</param> /// <param name="AdditionalProvisions">AdditionalProvisions.</param> /// <param name="MdRef">Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345).</param> /// <param name="Borrowers">Borrowers.</param> /// <param name="EffectiveClause">Text to display the make effective clause.</param> /// <param name="ChargeClause">ChargeClause.</param> public OperativeDeedDeed(string TitleNumber = null, Lender Lender = null, string PropertyAddress = null, AdditionalProvisions AdditionalProvisions = null, string MdRef = null, OpBorrowers Borrowers = null, string EffectiveClause = null, ChargeClause ChargeClause = null) { this.TitleNumber = TitleNumber; this.Lender = Lender; this.PropertyAddress = PropertyAddress; this.AdditionalProvisions = AdditionalProvisions; this.MdRef = MdRef; this.Borrowers = Borrowers; this.EffectiveClause = EffectiveClause; this.ChargeClause = ChargeClause; } /// <summary> /// Unique Land Registry identifier for the registered estate. /// </summary> /// <value>Unique Land Registry identifier for the registered estate.</value> [DataMember(Name="title_number", EmitDefaultValue=false)] public string TitleNumber { get; set; } /// <summary> /// Gets or Sets Lender /// </summary> [DataMember(Name="lender", EmitDefaultValue=false)] public Lender Lender { get; set; } /// <summary> /// The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA /// </summary> /// <value>The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA</value> [DataMember(Name="property_address", EmitDefaultValue=false)] public string PropertyAddress { get; set; } /// <summary> /// Gets or Sets AdditionalProvisions /// </summary> [DataMember(Name="additional_provisions", EmitDefaultValue=false)] public AdditionalProvisions AdditionalProvisions { get; set; } /// <summary> /// Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345) /// </summary> /// <value>Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345)</value> [DataMember(Name="md_ref", EmitDefaultValue=false)] public string MdRef { get; set; } /// <summary> /// Gets or Sets Borrowers /// </summary> [DataMember(Name="borrowers", EmitDefaultValue=false)] public OpBorrowers Borrowers { get; set; } /// <summary> /// Text to display the make effective clause /// </summary> /// <value>Text to display the make effective clause</value> [DataMember(Name="effective_clause", EmitDefaultValue=false)] public string EffectiveClause { get; set; } /// <summary> /// Gets or Sets ChargeClause /// </summary> [DataMember(Name="charge_clause", EmitDefaultValue=false)] public ChargeClause ChargeClause { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class OperativeDeedDeed {\n"); sb.Append(" TitleNumber: ").Append(TitleNumber).Append("\n"); sb.Append(" Lender: ").Append(Lender).Append("\n"); sb.Append(" PropertyAddress: ").Append(PropertyAddress).Append("\n"); sb.Append(" AdditionalProvisions: ").Append(AdditionalProvisions).Append("\n"); sb.Append(" MdRef: ").Append(MdRef).Append("\n"); sb.Append(" Borrowers: ").Append(Borrowers).Append("\n"); sb.Append(" EffectiveClause: ").Append(EffectiveClause).Append("\n"); sb.Append(" ChargeClause: ").Append(ChargeClause).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as OperativeDeedDeed); } /// <summary> /// Returns true if OperativeDeedDeed instances are equal /// </summary> /// <param name="other">Instance of OperativeDeedDeed to be compared</param> /// <returns>Boolean</returns> public bool Equals(OperativeDeedDeed other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.TitleNumber == other.TitleNumber || this.TitleNumber != null && this.TitleNumber.Equals(other.TitleNumber) ) && ( this.Lender == other.Lender || this.Lender != null && this.Lender.Equals(other.Lender) ) && ( this.PropertyAddress == other.PropertyAddress || this.PropertyAddress != null && this.PropertyAddress.Equals(other.PropertyAddress) ) && ( this.AdditionalProvisions == other.AdditionalProvisions || this.AdditionalProvisions != null && this.AdditionalProvisions.Equals(other.AdditionalProvisions) ) && ( this.MdRef == other.MdRef || this.MdRef != null && this.MdRef.Equals(other.MdRef) ) && ( this.Borrowers == other.Borrowers || this.Borrowers != null && this.Borrowers.Equals(other.Borrowers) ) && ( this.EffectiveClause == other.EffectiveClause || this.EffectiveClause != null && this.EffectiveClause.Equals(other.EffectiveClause) ) && ( this.ChargeClause == other.ChargeClause || this.ChargeClause != null && this.ChargeClause.Equals(other.ChargeClause) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.TitleNumber != null) hash = hash * 59 + this.TitleNumber.GetHashCode(); if (this.Lender != null) hash = hash * 59 + this.Lender.GetHashCode(); if (this.PropertyAddress != null) hash = hash * 59 + this.PropertyAddress.GetHashCode(); if (this.AdditionalProvisions != null) hash = hash * 59 + this.AdditionalProvisions.GetHashCode(); if (this.MdRef != null) hash = hash * 59 + this.MdRef.GetHashCode(); if (this.Borrowers != null) hash = hash * 59 + this.Borrowers.GetHashCode(); if (this.EffectiveClause != null) hash = hash * 59 + this.EffectiveClause.GetHashCode(); if (this.ChargeClause != null) hash = hash * 59 + this.ChargeClause.GetHashCode(); return hash; } } } }
/* Copyright (c) 2013 Mitch Thompson Standard MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // TODO: Add support for SimpleJson parser for usage on WP8 using UnityEngine; using System.Collections; using System.Collections.Generic; public static class TexturePackerExtensions{ public static Rect TPHashtableToRect(this Hashtable table){ return new Rect((float)table["x"], (float)table["y"], (float)table["w"], (float)table["h"]); } public static Vector2 TPHashtableToVector2(this Hashtable table){ if(table.ContainsKey("x") && table.ContainsKey("y")){ return new Vector2((float)table["x"], (float)table["y"]); } else{ return new Vector2((float)table["w"], (float)table["h"]); } } public static Vector2 TPVector3toVector2(this Vector3 vec){ return new Vector2(vec.x, vec.y); } public static bool IsTexturePackerTable(this Hashtable table){ if(table == null) return false; if(table.ContainsKey("meta")){ Hashtable metaTable = (Hashtable)table["meta"]; if(metaTable.ContainsKey("app")){ return true; // if((string)metaTable["app"] == "http://www.texturepacker.com"){ // return true; // } } } return false; } } public class TexturePacker{ public class PackedFrame{ public string name; public Rect frame; public Rect spriteSourceSize; public Vector2 sourceSize; public bool rotated; public bool trimmed; Vector2 atlasSize; public PackedFrame(string name, Vector2 atlasSize, Hashtable table){ this.name = name; this.atlasSize = atlasSize; frame = ((Hashtable)table["frame"]).TPHashtableToRect(); spriteSourceSize = ((Hashtable)table["spriteSourceSize"]).TPHashtableToRect(); sourceSize = ((Hashtable)table["sourceSize"]).TPHashtableToVector2(); rotated = (bool)table["rotated"]; trimmed = (bool)table["trimmed"]; } public Mesh BuildBasicMesh(float scale, Color32 defaultColor){ return BuildBasicMesh(scale, defaultColor, Quaternion.identity); } public Mesh BuildBasicMesh(float scale, Color32 defaultColor, Quaternion rotation){ Mesh m = new Mesh(); Vector3[] verts = new Vector3[4]; Vector2[] uvs = new Vector2[4]; Color32[] colors = new Color32[4]; if(!rotated){ verts[0] = new Vector3(frame.x,frame.y,0); verts[1] = new Vector3(frame.x,frame.y+frame.height,0); verts[2] = new Vector3(frame.x+frame.width,frame.y+frame.height,0); verts[3] = new Vector3(frame.x+frame.width,frame.y,0); } else{ verts[0] = new Vector3(frame.x,frame.y,0); verts[1] = new Vector3(frame.x,frame.y+frame.width,0); verts[2] = new Vector3(frame.x+frame.height,frame.y+frame.width,0); verts[3] = new Vector3(frame.x+frame.height,frame.y,0); } uvs[0] = verts[0].TPVector3toVector2(); uvs[1] = verts[1].TPVector3toVector2(); uvs[2] = verts[2].TPVector3toVector2(); uvs[3] = verts[3].TPVector3toVector2(); for(int i = 0; i < uvs.Length; i++){ uvs[i].x /= atlasSize.x; uvs[i].y /= atlasSize.y; uvs[i].y = 1.0f - uvs[i].y; } if(rotated){ verts[3] = new Vector3(frame.x,frame.y,0); verts[0] = new Vector3(frame.x,frame.y+frame.height,0); verts[1] = new Vector3(frame.x+frame.width,frame.y+frame.height,0); verts[2] = new Vector3(frame.x+frame.width,frame.y,0); } //v-flip for(int i = 0; i < verts.Length; i++){ verts[i].y = atlasSize.y - verts[i].y; } //original origin for(int i = 0; i < verts.Length; i++){ verts[i].x -= frame.x - spriteSourceSize.x + (sourceSize.x/2.0f); verts[i].y -= (atlasSize.y - frame.y) - (sourceSize.y - spriteSourceSize.y) + (sourceSize.y/2.0f); } //scaler for(int i = 0; i < verts.Length; i++){ verts[i] *= scale; } //rotator if(rotation != Quaternion.identity){ for(int i = 0; i < verts.Length; i++){ verts[i] = rotation * verts[i]; } } for(int i = 0; i < colors.Length; i++){ colors[i] = defaultColor; } m.vertices = verts; m.uv = uvs; m.colors32 = colors; m.triangles = new int[6]{0,3,1,1,3,2}; m.RecalculateNormals(); m.RecalculateBounds(); m.name = name; return m; } } public class MetaData{ public string image; public string format; public Vector2 size; public float scale; public string smartUpdate; public MetaData(Hashtable table){ image = (string)table["image"]; format = (string)table["format"]; size = ((Hashtable)table["size"]).TPHashtableToVector2(); scale = float.Parse(table["scale"].ToString()); smartUpdate = (string)table["smartUpdate"]; } } public static Mesh[] ProcessToMeshes(string text){ return ProcessToMeshes(text, Quaternion.identity, 1f); } public static Mesh[] ProcessToMeshes(string text, Quaternion rotation, float extra_scale ) { if ( text == null ) { return null; } Hashtable table = text.hashtableFromJson(); if ( table == null ) { return null; } MetaData meta = new MetaData((Hashtable)table["meta"]); List<PackedFrame> frames = new List<PackedFrame>(); Hashtable frameTable = (Hashtable)table["frames"]; foreach(DictionaryEntry entry in frameTable){ frames.Add(new PackedFrame((string)entry.Key, meta.size, (Hashtable)entry.Value)); } List<Mesh> meshes = new List<Mesh>(); for(int i = 0; i < frames.Count; i++){ meshes.Add(frames[i].BuildBasicMesh(0.01f * extra_scale, new Color32(128,128,128,128), rotation)); } return meshes.ToArray(); } public static MetaData GetMetaData(string text){ Hashtable table = text.hashtableFromJson(); MetaData meta = new MetaData((Hashtable)table["meta"]); return meta; } }
#nullable enable // ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using Fluent.Extensibility; using Fluent.Internal; /// <summary> /// Represents adorner for KeyTips. /// KeyTipAdorners is chained to produce one from another. /// Detaching root adorner couses detaching all adorners in the chain /// </summary> public class KeyTipAdorner : Adorner { #region Events /// <summary> /// This event is occured when adorner is /// detached and is not able to be attached again /// </summary> public event EventHandler<KeyTipPressedResult>? Terminated; #endregion #region Fields // KeyTips that have been // found on this element private readonly List<KeyTipInformation> keyTipInformations = new List<KeyTipInformation>(); private readonly FrameworkElement oneOfAssociatedElements; // Parent adorner private readonly KeyTipAdorner? parentAdorner; private KeyTipAdorner? childAdorner; private readonly FrameworkElement keyTipElementContainer; // Is this adorner attached to the adorned element? private bool attached; private bool isAttaching; // Designate that this adorner is terminated private bool terminated; private AdornerLayer? adornerLayer; #endregion #region Properties /// <summary> /// Determines whether at least one on the adorners in the chain is alive /// </summary> public bool IsAdornerChainAlive { get { return this.isAttaching || this.attached || this.childAdorner?.IsAdornerChainAlive == true; } } /// <summary> /// Returns whether any key tips are visibile. /// </summary> public bool AreAnyKeyTipsVisible { get { return this.keyTipInformations.Any(x => x.IsVisible) || this.childAdorner?.AreAnyKeyTipsVisible == true; } } /// <summary> /// Gets the currently active <see cref="KeyTipAdorner"/> by following eventually present child adorners. /// </summary> public KeyTipAdorner ActiveKeyTipAdorner { get { return this.childAdorner?.IsAdornerChainAlive == true ? this.childAdorner.ActiveKeyTipAdorner : this; } } /// <summary> /// Gets a copied list of the currently available <see cref="KeyTipInformation"/>. /// </summary> public IReadOnlyList<KeyTipInformation> KeyTipInformations { get { return this.keyTipInformations.ToList(); } } #endregion #region Intialization /// <summary> /// Construcotor /// </summary> /// <param name="adornedElement">Element to adorn.</param> /// <param name="parentAdorner">Parent adorner or null.</param> /// <param name="keyTipElementContainer">The element which is container for elements.</param> public KeyTipAdorner(FrameworkElement adornedElement, FrameworkElement keyTipElementContainer, KeyTipAdorner? parentAdorner) : base(adornedElement) { this.parentAdorner = parentAdorner; this.keyTipElementContainer = keyTipElementContainer; // Try to find supported elements this.FindKeyTips(this.keyTipElementContainer, false); this.oneOfAssociatedElements = this.keyTipInformations.Count != 0 ? this.keyTipInformations[0].AssociatedElement : adornedElement // Maybe here is bug, coz we need keytipped item here... ; } // Find key tips on the given element private void FindKeyTips(FrameworkElement container, bool hide) { var children = GetVisibleChildren(container); foreach (var child in children) { var groupBox = child as RibbonGroupBox; var keys = KeyTip.GetKeys(child); if (keys is not null || child is IKeyTipInformationProvider) { if (groupBox is null) { this.GenerateAndAddRegularKeyTipInformations(keys, child, hide); // Do not search deeper in the tree continue; } if (keys is not null) { this.GenerateAndAddGroupBoxKeyTipInformation(hide, keys, child, groupBox); } } var innerHide = hide || groupBox?.State == RibbonGroupBoxState.Collapsed; this.FindKeyTips(child, innerHide); } } private void GenerateAndAddGroupBoxKeyTipInformation(bool hide, string keys, FrameworkElement child, RibbonGroupBox groupBox) { var keyTipInformation = new KeyTipInformation(keys, child, hide || groupBox.State != RibbonGroupBoxState.Collapsed); // Add to list & visual children collections this.AddKeyTipInformationElement(keyTipInformation); this.LogDebug("Found KeyTipped RibbonGroupBox \"{0}\" with keys \"{1}\".", keyTipInformation.AssociatedElement, keyTipInformation.Keys); } private void GenerateAndAddRegularKeyTipInformations(string? keys, FrameworkElement child, bool hide) { IEnumerable<KeyTipInformation>? informations = null; if (child is IKeyTipInformationProvider keyTipInformationProvider) { informations = keyTipInformationProvider.GetKeyTipInformations(hide); } else if (keys is not null) { informations = new[] { new KeyTipInformation(keys, child, hide) }; } if (informations is not null) { foreach (var keyTipInformation in informations) { // Add to list & visual children collections this.AddKeyTipInformationElement(keyTipInformation); this.LogDebug("Found KeyTipped element \"{0}\" with keys \"{1}\".", keyTipInformation.AssociatedElement, keyTipInformation.Keys); } } } private void AddKeyTipInformationElement(KeyTipInformation keyTipInformation) { this.keyTipInformations.Add(keyTipInformation); this.AddVisualChild(keyTipInformation.KeyTip); } private static IList<FrameworkElement> GetVisibleChildren(FrameworkElement element) { var logicalChildren = LogicalTreeHelper.GetChildren(element) .OfType<FrameworkElement>(); var children = logicalChildren; // Always using the visual tree is very expensive, so we only search through it when we got specific control types. // Using the visual tree here, in addition to the logical, partially fixes #244. if (element is ContentPresenter || element is ContentControl) { children = children .Concat(UIHelper.GetVisualChildren(element)) .OfType<FrameworkElement>(); } else if (element is ItemsControl itemsControl) { children = children.Concat(UIHelper.GetAllItemContainers<FrameworkElement>(itemsControl)); } // Don't show key tips for the selected content too early if (element is RibbonTabControl ribbonTabControl && ribbonTabControl.SelectedContent is FrameworkElement selectedContent) { children = children.Except(new[] { selectedContent }); } return children .Where(x => x.Visibility == Visibility.Visible) .Distinct() .ToList(); } #endregion #region Attach & Detach /// <summary> /// Attaches this adorner to the adorned element /// </summary> public void Attach() { if (this.attached) { return; } this.isAttaching = true; this.oneOfAssociatedElements.UpdateLayout(); this.LogDebug("Attach begin {0}", this.Visibility); if (this.oneOfAssociatedElements.IsLoaded == false) { // Delay attaching this.LogDebug("Delaying attach"); this.oneOfAssociatedElements.Loaded += this.OnDelayAttach; return; } this.adornerLayer = GetAdornerLayer(this.oneOfAssociatedElements); if (this.adornerLayer is null) { this.LogDebug("No adorner layer found"); this.isAttaching = false; return; } this.FilterKeyTips(string.Empty); // Show this adorner this.adornerLayer.Add(this); this.isAttaching = false; this.attached = true; this.LogDebug("Attach end"); } private void OnDelayAttach(object sender, EventArgs args) { this.LogDebug("Delay attach (control loaded)"); this.oneOfAssociatedElements.Loaded -= this.OnDelayAttach; this.Attach(); } /// <summary> /// Detaches this adorner from the adorned element /// </summary> public void Detach() { this.childAdorner?.Detach(); if (!this.attached) { return; } this.LogDebug("Detach Begin"); // Maybe adorner awaiting attaching, cancel it this.oneOfAssociatedElements.Loaded -= this.OnDelayAttach; // Show this adorner this.adornerLayer?.Remove(this); this.attached = false; this.LogDebug("Detach End"); } #endregion #region Termination /// <summary> /// Terminate whole key tip's adorner chain /// </summary> public void Terminate(KeyTipPressedResult keyTipPressedResult) { if (this.terminated) { return; } this.terminated = true; this.Detach(); this.parentAdorner?.Terminate(keyTipPressedResult); this.childAdorner?.Terminate(keyTipPressedResult); this.Terminated?.Invoke(this, keyTipPressedResult); this.LogDebug("Termination"); } #endregion #region Static Methods private static AdornerLayer? GetAdornerLayer(UIElement? element) { var current = element; while (true) { if (current is null) { return null; } var parent = (UIElement?)VisualTreeHelper.GetParent(current) ?? (UIElement?)LogicalTreeHelper.GetParent(current); current = parent; if (current is AdornerDecorator) { return AdornerLayer.GetAdornerLayer((UIElement)VisualTreeHelper.GetChild(current, 0)); } } } private static UIElement GetTopLevelElement(UIElement element) { while (true) { var current = VisualTreeHelper.GetParent(element) as UIElement; if (current is null) { return element; } element = current; } } #endregion #region Methods /// <summary> /// Back to the previous adorner. /// </summary> public void Back() { this.LogTrace("Invoking back."); var control = this.keyTipElementContainer as IKeyTipedControl; control?.OnKeyTipBack(); if (this.parentAdorner is not null) { this.LogDebug("Back"); this.Detach(); this.parentAdorner.Attach(); } else { this.Terminate(KeyTipPressedResult.Empty); } } /// <summary> /// Forwards to the elements with the given keys /// </summary> /// <param name="keys">Keys</param> /// <param name="click">If true the element will be clicked</param> /// <returns>If the element will be found the function will return true</returns> public bool Forward(string keys, bool click) { this.LogTrace("Trying to forward keys \"{0}\"...", keys); var keyTipInformation = this.TryGetKeyTipInformation(keys); if (keyTipInformation is null) { this.LogTrace("Found no element for keys \"{0}\".", keys); return false; } this.Forward(keys, keyTipInformation.AssociatedElement, click); return true; } /// <summary> /// Forwards to the elements with the given keys to a given element. /// </summary> /// <param name="keys">Keys</param> /// <param name="element">The element to forward to.</param> /// <param name="click">If true the element will be clicked</param> public void Forward(string keys, FrameworkElement element, bool click) { this.LogTrace("Forwarding keys \"{0}\" to element \"{1}\".", keys, GetControlLogText(element)); this.Detach(); var keyTipPressedResult = KeyTipPressedResult.Empty; if (click) { this.LogTrace("Invoking click."); var control = element as IKeyTipedControl; keyTipPressedResult = control?.OnKeyTipPressed() ?? KeyTipPressedResult.Empty; } var children = GetVisibleChildren(element); if (children.Count == 0) { this.Terminate(keyTipPressedResult); return; } // Panels aren't good elements to adorn. For example, trying to display KeyTips on MenuItems in SplitButton fails if using a panel. var validChild = children.FirstOrDefault(x => x is Panel == false) ?? children[0]; this.childAdorner = ReferenceEquals(GetTopLevelElement(validChild), GetTopLevelElement(element)) == false ? new KeyTipAdorner(validChild, element, this) : new KeyTipAdorner(element, element, this); // Stop if no further KeyTips can be displayed. if (this.childAdorner.keyTipInformations.Any() == false) { this.Terminate(keyTipPressedResult); return; } this.childAdorner.Attach(); } /// <summary> /// Gets <see cref="KeyTipInformation"/> by keys. /// </summary> /// <param name="keys">The keys to look for.</param> /// <returns>The <see cref="KeyTipInformation"/> associated with <paramref name="keys"/>.</returns> private KeyTipInformation? TryGetKeyTipInformation(string keys) { return this.keyTipInformations.FirstOrDefault(x => x.IsEnabled && x.Visibility == Visibility.Visible && keys.Equals(x.Keys, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Determines if an of the keytips contained in this adorner start with <paramref name="keys"/> /// </summary> /// <returns><c>true</c> if any keytip start with <paramref name="keys"/>. Otherwise <c>false</c>.</returns> public bool ContainsKeyTipStartingWith(string keys) { foreach (var keyTipInformation in this.keyTipInformations.Where(x => x.IsEnabled)) { var content = keyTipInformation.Keys; if (content.StartsWith(keys, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } // Hide / unhide keytips relative matching to entered keys internal void FilterKeyTips(string keys) { this.LogDebug("FilterKeyTips with \"{0}\"", keys); // Reset visibility if filter is empty if (string.IsNullOrEmpty(keys)) { foreach (var keyTipInformation in this.keyTipInformations) { keyTipInformation.Visibility = keyTipInformation.DefaultVisibility; } } // Backup current visibility of key tips foreach (var keyTipInformation in this.keyTipInformations) { keyTipInformation.BackupVisibility = keyTipInformation.Visibility; } // Hide / unhide keytips relative matching to entered keys foreach (var keyTipInformation in this.keyTipInformations) { var content = keyTipInformation.Keys; if (string.IsNullOrEmpty(keys)) { keyTipInformation.Visibility = keyTipInformation.BackupVisibility; } else { keyTipInformation.Visibility = content.StartsWith(keys, StringComparison.OrdinalIgnoreCase) ? keyTipInformation.BackupVisibility : Visibility.Collapsed; } } this.LogDebug("Filtered key tips: {0}", this.keyTipInformations.Count(x => x.Visibility == Visibility.Visible)); } #endregion #region Layout & Visual Children /// <inheritdoc /> protected override Size ArrangeOverride(Size finalSize) { this.LogDebug("ArrangeOverride"); foreach (var keyTipInformation in this.keyTipInformations) { keyTipInformation.KeyTip.Arrange(new Rect(keyTipInformation.Position, keyTipInformation.KeyTip.DesiredSize)); } return finalSize; } /// <inheritdoc /> protected override Size MeasureOverride(Size constraint) { this.LogDebug("MeasureOverride"); foreach (var keyTipInformation in this.keyTipInformations) { keyTipInformation.KeyTip.Measure(SizeConstants.Infinite); } this.UpdateKeyTipPositions(); var result = new Size(0, 0); foreach (var keyTipInformation in this.keyTipInformations) { var cornerX = keyTipInformation.KeyTip.DesiredSize.Width + keyTipInformation.Position.X; var cornerY = keyTipInformation.KeyTip.DesiredSize.Height + keyTipInformation.Position.Y; if (cornerX > result.Width) { result.Width = cornerX; } if (cornerY > result.Height) { result.Height = cornerY; } } return result; } private void UpdateKeyTipPositions() { this.LogDebug("UpdateKeyTipPositions"); if (this.keyTipInformations.Count == 0) { return; } double[]? rows = null; var groupBox = this.oneOfAssociatedElements as RibbonGroupBox ?? UIHelper.GetParent<RibbonGroupBox>(this.oneOfAssociatedElements); var panel = groupBox?.GetPanel(); if (panel is not null && groupBox is not null) { var layoutRoot = groupBox.GetLayoutRoot(); if (layoutRoot is not null) { var height = layoutRoot.DesiredSize.Height; rows = new[] { layoutRoot.TranslatePoint(new Point(0, 0), this.AdornedElement).Y, layoutRoot.TranslatePoint(new Point(0, panel.DesiredSize.Height / 2.0), this.AdornedElement).Y, layoutRoot.TranslatePoint(new Point(0, panel.DesiredSize.Height), this.AdornedElement).Y, layoutRoot.TranslatePoint(new Point(0, height + 1), this.AdornedElement).Y }; } } foreach (var keyTipInformation in this.keyTipInformations) { // Skip invisible keytips if (keyTipInformation.Visibility != Visibility.Visible) { continue; } // Update KeyTip Visibility var visualTargetIsVisible = keyTipInformation.VisualTarget.IsVisible; var visualTargetInVisualTree = VisualTreeHelper.GetParent(keyTipInformation.VisualTarget) is not null; keyTipInformation.Visibility = visualTargetIsVisible && visualTargetInVisualTree ? Visibility.Visible : Visibility.Collapsed; keyTipInformation.KeyTip.Margin = KeyTip.GetMargin(keyTipInformation.AssociatedElement); if (IsWithinQuickAccessToolbar(keyTipInformation.AssociatedElement)) { var x = (keyTipInformation.VisualTarget.DesiredSize.Width / 2.0) - (keyTipInformation.KeyTip.DesiredSize.Width / 2.0); var y = keyTipInformation.VisualTarget.DesiredSize.Height - (keyTipInformation.KeyTip.DesiredSize.Height / 2.0); if (KeyTip.GetAutoPlacement(keyTipInformation.AssociatedElement) == false) { switch (KeyTip.GetHorizontalAlignment(keyTipInformation.AssociatedElement)) { case HorizontalAlignment.Left: x = 0; break; case HorizontalAlignment.Right: x = keyTipInformation.VisualTarget.DesiredSize.Width - keyTipInformation.KeyTip.DesiredSize.Width; break; } } keyTipInformation.Position = keyTipInformation.VisualTarget.TranslatePoint(new Point(x, y), this.AdornedElement); } else if (keyTipInformation.AssociatedElement.Name == "PART_DialogLauncherButton") { // Dialog Launcher Button Exclusive Placement var keyTipSize = keyTipInformation.KeyTip.DesiredSize; var elementSize = keyTipInformation.VisualTarget.RenderSize; if (rows is null) { continue; } keyTipInformation.Position = keyTipInformation.VisualTarget.TranslatePoint(new Point( (elementSize.Width / 2.0) - (keyTipSize.Width / 2.0), 0), this.AdornedElement); keyTipInformation.Position = new Point(keyTipInformation.Position.X, rows[3]); } else if (KeyTip.GetAutoPlacement(keyTipInformation.AssociatedElement) == false) { var keyTipSize = keyTipInformation.KeyTip.DesiredSize; var elementSize = keyTipInformation.VisualTarget.RenderSize; double x = 0, y = 0; switch (KeyTip.GetHorizontalAlignment(keyTipInformation.AssociatedElement)) { case HorizontalAlignment.Left: break; case HorizontalAlignment.Right: x = elementSize.Width - keyTipSize.Width; break; case HorizontalAlignment.Center: case HorizontalAlignment.Stretch: x = (elementSize.Width / 2.0) - (keyTipSize.Width / 2.0); break; } switch (KeyTip.GetVerticalAlignment(keyTipInformation.AssociatedElement)) { case VerticalAlignment.Top: break; case VerticalAlignment.Bottom: y = elementSize.Height - keyTipSize.Height; break; case VerticalAlignment.Center: case VerticalAlignment.Stretch: y = (elementSize.Height / 2.0) - (keyTipSize.Height / 2.0); break; } keyTipInformation.Position = keyTipInformation.VisualTarget.TranslatePoint(new Point(x, y), this.AdornedElement); } else if (keyTipInformation.AssociatedElement is InRibbonGallery gallery && gallery.IsCollapsed == false) { // InRibbonGallery Exclusive Placement var keyTipSize = keyTipInformation.KeyTip.DesiredSize; var elementSize = keyTipInformation.VisualTarget.RenderSize; if (rows is null) { continue; } keyTipInformation.Position = keyTipInformation.VisualTarget.TranslatePoint(new Point( elementSize.Width - (keyTipSize.Width / 2.0), 0), this.AdornedElement); keyTipInformation.Position = new Point(keyTipInformation.Position.X, rows[2] - (keyTipSize.Height / 2)); } else if (keyTipInformation.AssociatedElement is RibbonTabItem || keyTipInformation.AssociatedElement is Backstage) { // Ribbon Tab Item Exclusive Placement var keyTipSize = keyTipInformation.KeyTip.DesiredSize; var elementSize = keyTipInformation.VisualTarget.RenderSize; keyTipInformation.Position = keyTipInformation.VisualTarget.TranslatePoint(new Point( (elementSize.Width / 2.0) - (keyTipSize.Width / 2.0), elementSize.Height - (keyTipSize.Height / 2.0)), this.AdornedElement); } else if (keyTipInformation.AssociatedElement is MenuItem) { // MenuItem Exclusive Placement var elementSize = keyTipInformation.VisualTarget.DesiredSize; keyTipInformation.Position = keyTipInformation.VisualTarget.TranslatePoint( new Point( (elementSize.Height / 3.0) + 2, (elementSize.Height / 4.0) + 2), this.AdornedElement); } else if (keyTipInformation.AssociatedElement.Parent is BackstageTabControl) { // Backstage Items Exclusive Placement var keyTipSize = keyTipInformation.KeyTip.DesiredSize; var elementSize = keyTipInformation.VisualTarget.DesiredSize; var parent = (UIElement)keyTipInformation.VisualTarget.Parent; var positionInParent = keyTipInformation.VisualTarget.TranslatePoint(default, parent); keyTipInformation.Position = parent.TranslatePoint( new Point( 5, positionInParent.Y + ((elementSize.Height / 2.0) - keyTipSize.Height)), this.AdornedElement); } else { if (RibbonProperties.GetSize(keyTipInformation.AssociatedElement) != RibbonControlSize.Large || IsTextBoxShapedControl(keyTipInformation.AssociatedElement)) { var x = keyTipInformation.KeyTip.DesiredSize.Width / 2.0; var y = keyTipInformation.KeyTip.DesiredSize.Height / 2.0; var point = new Point(x, y); var translatedPoint = keyTipInformation.VisualTarget.TranslatePoint(point, this.AdornedElement); // Snapping to rows if it present SnapToRowsIfPresent(rows, keyTipInformation, translatedPoint); keyTipInformation.Position = translatedPoint; } else { var x = (keyTipInformation.VisualTarget.DesiredSize.Width / 2.0) - (keyTipInformation.KeyTip.DesiredSize.Width / 2.0); var y = keyTipInformation.VisualTarget.DesiredSize.Height - 8; var point = new Point(x, y); var translatedPoint = keyTipInformation.VisualTarget.TranslatePoint(point, this.AdornedElement); // Snapping to rows if it present SnapToRowsIfPresent(rows, keyTipInformation, translatedPoint); keyTipInformation.Position = translatedPoint; } } } } private static bool IsTextBoxShapedControl(FrameworkElement element) { return element is Spinner || element is System.Windows.Controls.ComboBox || element is System.Windows.Controls.TextBox || element is System.Windows.Controls.CheckBox; } // Determines whether the element is children to RibbonToolBar private static bool IsWithinRibbonToolbarInTwoLine(DependencyObject element) { var ribbonToolBar = UIHelper.GetParent<RibbonToolBar>(element); var definition = ribbonToolBar?.GetCurrentLayoutDefinition(); if (definition is null) { return false; } if (definition.RowCount == 2 || definition.Rows.Count == 2) { return true; } return false; } // Determines whether the element is children to quick access toolbar private static bool IsWithinQuickAccessToolbar(DependencyObject element) { return UIHelper.GetParent<QuickAccessToolBar>(element) is not null; } private static void SnapToRowsIfPresent(double[]? rows, KeyTipInformation keyTipInformation, Point translatedPoint) { if (rows is null) { return; } var withinRibbonToolbar = IsWithinRibbonToolbarInTwoLine(keyTipInformation.VisualTarget); var index = 0; var mindistance = Math.Abs(rows[0] - translatedPoint.Y); for (var j = 1; j < rows.Length; j++) { if (withinRibbonToolbar && j == 1) { continue; } var distance = Math.Abs(rows[j] - translatedPoint.Y); if (distance < mindistance) { mindistance = distance; index = j; } } translatedPoint.Y = rows[index] - (keyTipInformation.KeyTip.DesiredSize.Height / 2.0); } /// <inheritdoc /> protected override int VisualChildrenCount => this.keyTipInformations.Count; /// <inheritdoc /> protected override Visual GetVisualChild(int index) { return this.keyTipInformations[index].KeyTip; } #endregion #region Logging [Conditional("DEBUG")] private void LogDebug(string format, params object[] args) { var message = this.GetMessageLog(format, args); Debug.WriteLine(message, "KeyTipAdorner"); } [Conditional("TRACE")] private void LogTrace(string format, params object[] args) { var message = this.GetMessageLog(format, args); Trace.WriteLine(message, "KeyTipAdorner"); } private string GetMessageLog(string format, object[] args) { var name = GetControlLogText(this.AdornedElement); var message = $"[{name}] {string.Format(format, args)}"; return message; } private static string GetControlLogText(UIElement control) { var name = control.GetType().Name; if (control is IHeaderedControl headeredControl) { name += $" ({headeredControl.Header})"; } return name; } #endregion } }
// <copyright file="WheelInputDevice.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using OpenQA.Selenium.Internal; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenQA.Selenium.Interactions { /// <summary> /// Represents a wheel input device, such as a mouse wheel. /// </summary> public class WheelInputDevice : InputDevice { /// <summary> /// Initializes a new instance of the <see cref="WheelInputDevice"/> class. /// </summary> public WheelInputDevice() : this(Guid.NewGuid().ToString()) { } /// <summary> /// Initializes a new instance of the <see cref="WheelInputDevice"/> class, given the device's name. /// </summary> /// <param name="deviceName">The unique name of this input device.</param> public WheelInputDevice(string deviceName) : base(deviceName) { } /// <summary> /// Gets the type of device for this input device. /// </summary> public override InputDeviceKind DeviceKind { get { return InputDeviceKind.Wheel; } } /// <summary> /// Returns a value for this input device that can be transmitted across the wire to a remote end. /// </summary> /// <returns>A <see cref="Dictionary{TKey, TValue}"/> representing this action.</returns> public override Dictionary<string, object> ToDictionary() { Dictionary<string, object> toReturn = new Dictionary<string, object>(); toReturn["type"] = "wheel"; toReturn["id"] = this.DeviceName; return toReturn; } /// <summary> /// Creates a wheel scroll action. /// </summary> /// <param name="deltaX">The distance along the X axis to scroll using the wheel.</param> /// <param name="deltaY">The distance along the Y axis to scroll using the wheel.</param> /// <param name="duration">The duration of the scroll action.</param> /// <returns></returns> public Interaction CreateWheelScroll(int deltaX, int deltaY, TimeSpan duration) { return new WheelScrollInteraction(this, null, CoordinateOrigin.Viewport, 0, 0, deltaX, deltaY, duration); } /// <summary> /// Creates a wheel scroll action beginning with an element. /// </summary> /// <param name="target">The <see cref="IWebElement"/> in which to begin the scroll.</param> /// <param name="xOffset">The horizontal offset from the center of the target element from which to start the scroll.</param> /// <param name="yOffset">The vertical offset from the center of the target element from which to start the scroll.</param> /// <param name="deltaX">The distance along the X axis to scroll using the wheel.</param> /// <param name="deltaY">The distance along the Y axis to scroll using the wheel.</param> /// <param name="duration">The duration of the scroll action.</param> /// <returns></returns> public Interaction CreateWheelScroll(IWebElement target, int xOffset, int yOffset, int deltaX, int deltaY, TimeSpan duration) { return new WheelScrollInteraction(this, target, CoordinateOrigin.Element, xOffset, yOffset, deltaX, deltaY, duration); } /// <summary> /// Creates a wheel scroll action. /// </summary> /// <param name="origin">The coordinate origin, either the view port or the current pointer position, from which to begin the scroll.</param> /// <param name="xOffset">The horizontal offset from the center of the origin from which to start the scroll.</param> /// <param name="yOffset">The vertical offset from the center of the origin from which to start the scroll.</param> /// <param name="deltaX">The distance along the X axis to scroll using the wheel.</param> /// <param name="deltaY">The distance along the Y axis to scroll using the wheel.</param> /// <param name="duration">The duration of the scroll action.</param> /// <returns></returns> public Interaction CreateWheelScroll(CoordinateOrigin origin, int xOffset, int yOffset, int deltaX, int deltaY, TimeSpan duration) { return new WheelScrollInteraction(this, null, origin, xOffset, yOffset, deltaX, deltaY, duration); } private class WheelScrollInteraction : Interaction { private IWebElement target; private int x = 0; private int y = 0; private int deltaX = 0; private int deltaY = 0; private TimeSpan duration = TimeSpan.MinValue; private CoordinateOrigin origin = CoordinateOrigin.Viewport; public WheelScrollInteraction(InputDevice sourceDevice, IWebElement target, CoordinateOrigin origin, int x, int y, int deltaX, int deltaY, TimeSpan duration) :base(sourceDevice) { if (target != null) { this.target = target; this.origin = CoordinateOrigin.Element; } else { if (this.origin != CoordinateOrigin.Element) { this.origin = origin; } } if (duration != TimeSpan.MinValue) { this.duration = duration; } this.x = x; this.y = y; this.deltaX = deltaX; this.deltaY = deltaY; } public override Dictionary<string, object> ToDictionary() { Dictionary<string, object> toReturn = new Dictionary<string, object>(); toReturn["type"] = "scroll"; if (this.duration != TimeSpan.MinValue) { toReturn["duration"] = Convert.ToInt64(this.duration.TotalMilliseconds); } if (this.target != null) { toReturn["origin"] = this.ConvertElement(); } else { toReturn["origin"] = this.origin.ToString().ToLowerInvariant(); } toReturn["x"] = this.x; toReturn["y"] = this.y; toReturn["deltaX"] = this.deltaX; toReturn["deltaY"] = this.deltaY; return toReturn; } private Dictionary<string, object> ConvertElement() { IWebDriverObjectReference elementReference = this.target as IWebDriverObjectReference; if (elementReference == null) { IWrapsElement elementWrapper = this.target as IWrapsElement; if (elementWrapper != null) { elementReference = elementWrapper.WrappedElement as IWebDriverObjectReference; } } if (elementReference == null) { throw new ArgumentException("Target element cannot be converted to IWebElementReference"); } Dictionary<string, object> elementDictionary = elementReference.ToDictionary(); return elementDictionary; } } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Text; using Mono.Collections.Generic; namespace Mono.Cecil { public class MethodReference : MemberReference, IMethodSignature, IGenericParameterProvider, IGenericContext { internal ParameterDefinitionCollection parameters; MethodReturnType return_type; bool has_this; bool explicit_this; MethodCallingConvention calling_convention; internal Collection<GenericParameter> generic_parameters; public virtual bool HasThis { get { return has_this; } set { has_this = value; } } public virtual bool ExplicitThis { get { return explicit_this; } set { explicit_this = value; } } public virtual MethodCallingConvention CallingConvention { get { return calling_convention; } set { calling_convention = value; } } public virtual bool HasParameters { get { return !parameters.IsNullOrEmpty (); } } public virtual Collection<ParameterDefinition> Parameters { get { if (parameters == null) parameters = new ParameterDefinitionCollection (this); return parameters; } } IGenericParameterProvider IGenericContext.Type { get { var declaring_type = this.DeclaringType; var instance = declaring_type as GenericInstanceType; if (instance != null) return instance.ElementType; return declaring_type; } } IGenericParameterProvider IGenericContext.Method { get { return this; } } GenericParameterType IGenericParameterProvider.GenericParameterType { get { return GenericParameterType.Method; } } public virtual bool HasGenericParameters { get { return !generic_parameters.IsNullOrEmpty (); } } public virtual Collection<GenericParameter> GenericParameters { get { if (generic_parameters != null) return generic_parameters; return generic_parameters = new GenericParameterCollection (this); } } public TypeReference ReturnType { get { var return_type = MethodReturnType; return return_type != null ? return_type.ReturnType : null; } set { var return_type = MethodReturnType; if (return_type != null) return_type.ReturnType = value; } } public virtual MethodReturnType MethodReturnType { get { return return_type; } set { return_type = value; } } public override string FullName { get { var builder = new StringBuilder (); builder.Append (ReturnType.FullName) .Append (" ") .Append (MemberFullName ()); this.MethodSignatureFullName (builder); return builder.ToString (); } } public virtual bool IsGenericInstance { get { return false; } } public override bool ContainsGenericParameter { get { if (this.ReturnType.ContainsGenericParameter || base.ContainsGenericParameter) return true; if (!HasParameters) return false; var parameters = this.Parameters; for (int i = 0; i < parameters.Count; i++) if (parameters [i].ParameterType.ContainsGenericParameter) return true; return false; } } internal MethodReference () { this.return_type = new MethodReturnType (this); this.token = new MetadataToken (TokenType.MemberRef); } public MethodReference (string name, TypeReference returnType) : base (name) { if (returnType == null) throw new ArgumentNullException ("returnType"); this.return_type = new MethodReturnType (this); this.return_type.ReturnType = returnType; this.token = new MetadataToken (TokenType.MemberRef); } public MethodReference (string name, TypeReference returnType, TypeReference declaringType) : this (name, returnType) { if (declaringType == null) throw new ArgumentNullException ("declaringType"); this.DeclaringType = declaringType; } public virtual MethodReference GetElementMethod () { return this; } protected override IMemberDefinition ResolveDefinition () { return this.Resolve (); } public new virtual MethodDefinition Resolve () { var module = this.Module; if (module == null) throw new NotSupportedException (); return module.Resolve (this); } } static partial class Mixin { public static bool IsVarArg (this IMethodSignature self) { return (self.CallingConvention & MethodCallingConvention.VarArg) != 0; } public static int GetSentinelPosition (this IMethodSignature self) { if (!self.HasParameters) return -1; var parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) if (parameters [i].ParameterType.IsSentinel) return i; return -1; } } }
using System; using System.Collections.Generic; using System.Drawing; namespace Delaunay { public class Site : ICoord { private static List<Site> _pool = new List<Site>(); public static Site Create(PointF p, int index, float weight, uint color) { if (_pool.Count > 0) { return _pool.Pop().Init(p, index, weight, color); } else { return new Site(typeof(PrivateConstructorEnforcer), p, index, weight, color); } } internal static void SortSites(List<Site> sites) { sites.SortFunc(Site.Compare); } /** * sort sites on y, then x, coord * also change each site's _siteIndex to match its new position in the list * so the _siteIndex can be used to identify the site for nearest-neighbor queries * * haha "also" - means more than one responsibility... * */ private static float Compare(Site s1, Site s2) { int returnValue = (int)Voronoi.CompareByYThenX(s1, s2); // swap _siteIndex values if necessary to match new ordering: int tempIndex; if (returnValue == -1) { if (s1._siteIndex > s2._siteIndex) { tempIndex = (int)s1._siteIndex; s1._siteIndex = s2._siteIndex; s2._siteIndex = (uint)tempIndex; } } else if (returnValue == 1) { if (s2._siteIndex > s1._siteIndex) { tempIndex = (int)s2._siteIndex; s2._siteIndex = s1._siteIndex; s1._siteIndex = (uint)tempIndex; } } return returnValue; } private static readonly float EPSILON = .005f; private static bool CloseEnough(PointF p0, PointF p1) { return Utilities.Distance(p0, p1) < EPSILON; } private PointF _coord; public PointF Coord() { //get { return _coord; //} } internal uint color; internal float weight; private uint _siteIndex; // the edges that define this Site's Voronoi region: private List<Edge> _edges; internal List<Edge> Edges { get { return _edges; } } // which end of each edge hooks up with the previous edge in _edges: private List<LR> _edgeOrientations; // ordered list of PointFs that define the region clipped to bounds: private List<PointF> _region; public Site(Type pce, PointF p, int index, float weight, uint color) { if (pce != typeof(PrivateConstructorEnforcer)) { throw new Exception("Site static readonlyructor is private"); } Init(p, index, weight, color); } private Site Init(PointF p, int index, float weight, uint color) { _coord = p; _siteIndex = (uint)index; this.weight = weight; this.color = color; _edges = new List<Edge>(); _region = null; return this; } public override string ToString() { return "Site " + _siteIndex + ": " + Coord().ToString(); } private void Move(PointF p) { Clear(); _coord = p; } public void Dispose() { _coord = PointF.Empty; Clear(); _pool.Add(this); } private void Clear() { if (_edges != null) { _edges.Clear(); _edges = null; } if (_edgeOrientations != null) { _edgeOrientations.Clear(); _edgeOrientations = null; } if (_region != null) { _region.Clear(); _region = null; } } internal void AddEdge(Edge edge) { _edges.Add(edge); } internal Edge NearestEdge() { _edges.SortFunc(Edge.CompareSitesDistances); return _edges[0]; } internal List<Site> NeighborSites() { if (_edges == null || _edges.Count == 0) { return new List<Site>(); } if (_edgeOrientations == null) { ReorderEdges(); } List<Site> list = new List<Site>(); foreach (Edge edge in _edges) { list.Add(NeighborSite(edge)); } return list; } private Site NeighborSite(Edge edge) { if (this == edge.LeftSite) { return edge.RightSite; } if (this == edge.RightSite) { return edge.LeftSite; } return null; } internal List<PointF> Region(RectangleF clippingBounds) { if (_edges == null || _edges.Count == 0) { return new List<PointF>(); } if (_edgeOrientations == null) { ReorderEdges(); _region = ClipToBounds(clippingBounds); if ((new Polygon(_region)).GetWinding() == Winding.CLOCKWISE) { _region.Reverse(); } } return _region; } private void ReorderEdges() { //trace("_edges:", _edges); EdgeReorderer reorderer = new EdgeReorderer(_edges, typeof(Vertex)); _edges = reorderer.Edges; //trace("reordered:", _edges); _edgeOrientations = reorderer.EdgeOrientations; reorderer.Dispose(); } private List<PointF> ClipToBounds(RectangleF bounds) { List<PointF> PointFs = new List<PointF>(); int n = _edges.Count; int i = 0; Edge edge; while (i < n && ((_edges[i] as Edge).Visible == false)) { ++i; } if (i == n) { // no edges visible return new List<PointF>(); } edge = _edges[i]; LR orientation = _edgeOrientations[i]; PointFs.Add(edge.ClippedEnds[orientation]); PointFs.Add(edge.ClippedEnds[LR.Other(orientation)]); for (int j = i + 1; j < n; ++j) { edge = _edges[j]; if (edge.Visible == false) { continue; } Connect(PointFs, j, bounds); } // close up the polygon by adding another corner PointF of the bounds if needed: Connect(PointFs, i, bounds, true); return PointFs; } private void Connect(List<PointF> PointFs, int j, RectangleF bounds) { Connect(PointFs, j, bounds, false); } private void Connect(List<PointF> PointFs, int j, RectangleF bounds, bool closingUp) { PointF rightPointF = PointFs[PointFs.Count - 1]; Edge newEdge = _edges[j] as Edge; LR newOrientation = _edgeOrientations[j]; // the PointF that must be connected to rightPointF: PointF newPointF = newEdge.ClippedEnds[newOrientation]; if (!CloseEnough(rightPointF, newPointF)) { // The PointFs do not coincide, so they must have been clipped at the bounds; // see if they are on the same border of the bounds: if (rightPointF.X != newPointF.X && rightPointF.Y != newPointF.Y) { // They are on different borders of the bounds; // insert one or two corners of bounds as needed to hook them up: // (NOTE this will not be corRectangleF if the region should take up more than // half of the bounds RectangleF, for then we will have gone the wrong way // around the bounds and included the smaller part rather than the larger) int rightCheck = BoundsCheck.Check(rightPointF, bounds); int newCheck = BoundsCheck.Check(newPointF, bounds); float px, py; //throw new NotImplementedException("Modified, might not work"); if (rightCheck == BoundsCheck.RIGHT) { px = bounds.Right; if (newCheck == BoundsCheck.BOTTOM) { py = bounds.Bottom; PointFs.Add(new PointF(px, py)); } else if (newCheck == BoundsCheck.TOP) { py = bounds.Top; PointFs.Add(new PointF(px, py)); } else if (newCheck == BoundsCheck.LEFT) { if (rightPointF.Y - bounds.Y + newPointF.Y - bounds.Y < bounds.Height) { py = bounds.Top; } else { py = bounds.Bottom; } PointFs.Add(new PointF(px, py)); PointFs.Add(new PointF(bounds.Left, py)); } } else if (rightCheck == BoundsCheck.LEFT) { px = bounds.Left; if (newCheck == BoundsCheck.BOTTOM) { py = bounds.Bottom; PointFs.Add(new PointF(px, py)); } else if (newCheck == BoundsCheck.TOP) { py = bounds.Top; PointFs.Add(new PointF(px, py)); } else if (newCheck == BoundsCheck.RIGHT) { if (rightPointF.Y - bounds.Y + newPointF.Y - bounds.Y < bounds.Height) { py = bounds.Top; } else { py = bounds.Bottom; } PointFs.Add(new PointF(px, py)); PointFs.Add(new PointF(bounds.Right, py)); } } else if (rightCheck == BoundsCheck.TOP) { py = bounds.Top; if (newCheck == BoundsCheck.RIGHT) { px = bounds.Right; PointFs.Add(new PointF(px, py)); } else if (newCheck == BoundsCheck.LEFT) { px = bounds.Left; PointFs.Add(new PointF(px, py)); } else if (newCheck == BoundsCheck.BOTTOM) { if (rightPointF.X - bounds.X + newPointF.X - bounds.X < bounds.Width) { px = bounds.Left; } else { px = bounds.Right; } PointFs.Add(new PointF(px, py)); PointFs.Add(new PointF(px, bounds.Bottom)); } } else if (rightCheck == BoundsCheck.BOTTOM) { py = bounds.Bottom; if (newCheck == BoundsCheck.RIGHT) { px = bounds.Right; PointFs.Add(new PointF(px, py)); } else if (newCheck == BoundsCheck.LEFT) { px = bounds.Left; PointFs.Add(new PointF(px, py)); } else if (newCheck == BoundsCheck.TOP) { if (rightPointF.X - bounds.X + newPointF.X - bounds.X < bounds.Width) { px = bounds.Left; } else { px = bounds.Right; } PointFs.Add(new PointF(px, py)); PointFs.Add(new PointF(px, bounds.Top)); } } } if (closingUp) { // newEdge's ends have already been added return; } PointFs.Add(newPointF); } PointF newRightPointF = newEdge.ClippedEnds[LR.Other(newOrientation)]; if (!CloseEnough(PointFs[0], newRightPointF)) { PointFs.Add(newRightPointF); } } internal float X { get { return _coord.X; } } internal float Y { get { return _coord.Y; } } internal float Dist(ICoord p) { return Utilities.Distance(p.Coord(), this._coord); } } class BoundsCheck { public static readonly int TOP = 1; public static readonly int BOTTOM = 2; public static readonly int LEFT = 4; public static readonly int RIGHT = 8; /** * * @param PointF * @param bounds * @return an int with the appropriate bits set if the PointF lies on the corresponding bounds lines * */ public static int Check(PointF point, RectangleF bounds) { int value = 0; if (point.X == bounds.Left) { value |= LEFT; } if (point.X == bounds.Right) { value |= RIGHT; } if (point.Y == bounds.Top) { value |= TOP; } if (point.Y == bounds.Bottom) { value |= BOTTOM; } return value; } public BoundsCheck() { throw new Exception("BoundsCheck constructor unused"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Immutable; using System.IO; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Text; namespace System.Reflection.PortableExecutable { /// <summary> /// An object used to read PE (Portable Executable) and COFF (Common Object File Format) headers from a stream. /// </summary> sealed class PEHeaders { private readonly CoffHeader coffHeader; private readonly PEHeader peHeader; private readonly ImmutableArray<SectionHeader> sectionHeaders; private readonly CorHeader corHeader; private readonly int metadataStartOffset = -1; private readonly int metadataSize; private readonly int coffHeaderStartOffset = -1; private readonly int corHeaderStartOffset = -1; private readonly int peHeaderStartOffset = -1; /// <summary> /// Reads PE headers from the current location in the stream. /// </summary> /// <param name="peStream">Stream containing PE image starting at the stream's current position and ending at the end of the stream.</param> /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> /// <exception cref="IOException">Error reading from the stream.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> public PEHeaders(Stream peStream) : this(peStream, null) { } /// <summary> /// Reads PE headers from the current location in the stream. /// </summary> /// <param name="peStream">Stream containing PE image of the given size starting at its current position.</param> /// <param name="size">Size of the PE image.</param> /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> /// <exception cref="IOException">Error reading from the stream.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception> public PEHeaders(Stream peStream, int size) : this(peStream, (int?)size) { } private PEHeaders(Stream peStream, int? sizeOpt) { if (peStream == null) { throw new ArgumentNullException("peStream"); } if (!peStream.CanRead || !peStream.CanSeek) { throw new ArgumentException(MetadataResources.StreamMustSupportReadAndSeek, "peStream"); } int size = PEBinaryReader.GetAndValidateSize(peStream, sizeOpt); var reader = new PEBinaryReader(peStream, size); bool isCoffOnly; SkipDosHeader(ref reader, out isCoffOnly); this.coffHeaderStartOffset = reader.CurrentOffset; this.coffHeader = new CoffHeader(ref reader); if (!isCoffOnly) { this.peHeaderStartOffset = reader.CurrentOffset; this.peHeader = new PEHeader(ref reader); } this.sectionHeaders = this.ReadSectionHeaders(ref reader); if (!isCoffOnly) { int offset; if (TryCalculateCorHeaderOffset(size, out offset)) { this.corHeaderStartOffset = offset; reader.Seek(offset); this.corHeader = new CorHeader(ref reader); } } CalculateMetadataLocation(size, out this.metadataStartOffset, out this.metadataSize); } /// <summary> /// Gets the offset (in bytes) from the start of the PE image to the start of the CLI metadata. /// or -1 if the image does not contain metadata. /// </summary> public int MetadataStartOffset { get { return metadataStartOffset; } } /// <summary> /// Gets the size of the CLI metadata 0 if the image does not contain metadata.) /// </summary> public int MetadataSize { get { return metadataSize; } } /// <summary> /// Gets the COFF header of the image. /// </summary> public CoffHeader CoffHeader { get { return coffHeader; } } /// <summary> /// Gets the byte offset from the start of the PE image to the start of the COFF header. /// </summary> public int CoffHeaderStartOffset { get { return coffHeaderStartOffset; } } /// <summary> /// Determines if the image is Coff only. /// </summary> public bool IsCoffOnly { get { return this.peHeader == null; } } /// <summary> /// Gets the PE header of the image or null if the image is COFF only. /// </summary> public PEHeader PEHeader { get { return peHeader; } } /// <summary> /// Gets the byte offset from the start of the image to /// </summary> public int PEHeaderStartOffset { get { return peHeaderStartOffset; } } /// <summary> /// Gets the PE section headers. /// </summary> public ImmutableArray<SectionHeader> SectionHeaders { get { return sectionHeaders; } } /// <summary> /// Gets the CLI header or null if the image does not have one. /// </summary> public CorHeader CorHeader { get { return corHeader; } } /// <summary> /// Gets the byte offset from the start of the image to the COR header or -1 if the image does not have one. /// </summary> public int CorHeaderStartOffset { get { return corHeaderStartOffset; } } /// <summary> /// Determines if the image represents a Windows console application. /// </summary> public bool IsConsoleApplication { get { return peHeader != null && peHeader.Subsystem == Subsystem.WindowsCui; } } /// <summary> /// Determines if the image represents a dynamically linked library. /// </summary> public bool IsDll { get { return (coffHeader.Characteristics & Characteristics.Dll) != 0; } } /// <summary> /// Determines if the image represents an executable. /// </summary> public bool IsExe { get { return (coffHeader.Characteristics & Characteristics.Dll) == 0; } } private bool TryCalculateCorHeaderOffset(long peStreamSize, out int startOffset) { if (!TryGetDirectoryOffset(peHeader.CorHeaderTableDirectory, out startOffset)) { startOffset = -1; return false; } int length = peHeader.CorHeaderTableDirectory.Size; if (length < COR20Constants.SizeOfCorHeader) { throw new BadImageFormatException(MetadataResources.InvalidCorHeaderSize); } return true; } private void SkipDosHeader(ref PEBinaryReader reader, out bool isCOFFOnly) { // Look for DOS Signature "MZ" ushort dosSig = reader.ReadUInt16(); if (dosSig != PEFileConstants.DosSignature) { // If image doesn't start with DOS signature, let's assume it is a // COFF (Common Object File Format), aka .OBJ file. // See CLiteWeightStgdbRW::FindObjMetaData in ndp\clr\src\MD\enc\peparse.cpp if (dosSig != 0 || reader.ReadUInt16() != 0xffff) { isCOFFOnly = true; reader.Seek(0); } else { // Might need to handle other formats. Anonymous or LTCG objects, for example. throw new BadImageFormatException(MetadataResources.UnknownFileFormat); } } else { isCOFFOnly = false; } if (!isCOFFOnly) { // Skip the DOS Header reader.Seek(PEFileConstants.PESignatureOffsetLocation); int ntHeaderOffset = reader.ReadInt32(); reader.Seek(ntHeaderOffset); // Look for PESignature "PE\0\0" uint ntSignature = reader.ReadUInt32(); if (ntSignature != PEFileConstants.PESignature) { throw new BadImageFormatException(MetadataResources.InvalidPESignature); } } } private ImmutableArray<SectionHeader> ReadSectionHeaders(ref PEBinaryReader reader) { int numberOfSections = this.coffHeader.NumberOfSections; if (numberOfSections < 0) { throw new BadImageFormatException(MetadataResources.InvalidNumberOfSections); } var builder = ImmutableArray.CreateBuilder<SectionHeader>(numberOfSections); for (int i = 0; i < numberOfSections; i++) { builder.Add(new SectionHeader(ref reader)); } return builder.ToImmutable(); } /// <summary> /// Gets the offset (in bytes) from the start of the image to the given directory entry. /// </summary> /// <param name="directory"></param> /// <param name="offset"></param> /// <returns>The section containing the directory could not be found.</returns> /// <exception cref="BadImageFormatException">The section containing the</exception> public bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset) { int sectionIndex = GetContainingSectionIndex(directory.RelativeVirtualAddress); if (sectionIndex < 0) { offset = -1; return false; } int relativeOffset = directory.RelativeVirtualAddress - sectionHeaders[sectionIndex].VirtualAddress; if (directory.Size > sectionHeaders[sectionIndex].VirtualSize - relativeOffset) { throw new BadImageFormatException(MetadataResources.SectionTooSmall); } offset = sectionHeaders[sectionIndex].PointerToRawData + relativeOffset; return true; } /// <summary> /// Searches sections of the PE image for the one that contains specified Relative Virtual Address. /// </summary> /// <param name="relativeVirtualAddress">Address.</param> /// <returns> /// Index of the section that contains <paramref name="relativeVirtualAddress"/>, /// or -1 if there is none. /// </returns> public int GetContainingSectionIndex(int relativeVirtualAddress) { for (int i = 0; i < sectionHeaders.Length; i++) { if (sectionHeaders[i].VirtualAddress <= relativeVirtualAddress && relativeVirtualAddress < sectionHeaders[i].VirtualAddress + sectionHeaders[i].VirtualSize) { return i; } } return -1; } private int IndexOfSection(string name) { for (int i = 0; i < SectionHeaders.Length; i++) { if (SectionHeaders[i].Name.Equals(name, StringComparison.Ordinal)) { return i; } } return -1; } private void CalculateMetadataLocation(long peImageSize, out int start, out int size) { if (IsCoffOnly) { int cormeta = IndexOfSection(".cormeta"); if (cormeta == -1) { start = -1; size = 0; return; } start = SectionHeaders[cormeta].PointerToRawData; size = SectionHeaders[cormeta].SizeOfRawData; } else if (corHeader == null) { start = 0; size = 0; return; } else { if (!TryGetDirectoryOffset(corHeader.MetadataDirectory, out start)) { throw new BadImageFormatException(MetadataResources.MissingDataDirectory); } size = corHeader.MetadataDirectory.Size; } if (start < 0 || start >= peImageSize || size <= 0 || start > peImageSize - size) { throw new BadImageFormatException(MetadataResources.InvalidMetadataSectionSpan); } } } }
// // Copyright (c) 2003-2006 Jaroslaw Kowalski <jaak@jkowalski.net> // Copyright (c) 2006-2014 Piotr Fusik <piotr@fusik.info> // // 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. // // 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. // using Sooda.ObjectMapper; using Sooda.ObjectMapper.FieldHandlers; using Sooda.QL; using Sooda.Schema; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.Globalization; using System.IO; namespace Sooda.Sql { public abstract class SqlBuilderBase : ISqlBuilder { private bool _useSafeLiterals = true; static string HashString(string input) { int sum = 0; for (int i = 0; i < input.Length; i++) sum += i * input[i]; sum &= 0xffff; return sum.ToString("x4"); } public string GetTruncatedIdentifier(string identifier) { if (identifier.Length <= MaxIdentifierLength) return identifier; string hash = HashString(identifier); return identifier.Substring(0, MaxIdentifierLength - 5) + "_" + hash; } public bool UseSafeLiterals { get { return _useSafeLiterals; } set { _useSafeLiterals = value; } } public virtual string GetDDLCommandTerminator() { return ";" + Environment.NewLine; } public virtual SqlOuterJoinSyntax OuterJoinSyntax { get { return SqlOuterJoinSyntax.Ansi; } } public virtual string StringConcatenationOperator { get { return "||"; } } public virtual int MaxIdentifierLength { get { return 30; } } public void GenerateCreateTableField(TextWriter xtw, Sooda.Schema.FieldInfo fieldInfo) { xtw.Write('\t'); xtw.Write(fieldInfo.DBColumnName); xtw.Write(' '); xtw.Write(GetSQLDataType(fieldInfo)); xtw.Write(' '); xtw.Write(GetSQLNullable(fieldInfo)); } void TerminateDDL(TextWriter xtw, string additionalSettings, string terminator) { if (!string.IsNullOrEmpty(additionalSettings)) { xtw.Write(' '); xtw.Write(additionalSettings); } xtw.Write(terminator ?? GetDDLCommandTerminator()); } public void GenerateCreateTable(TextWriter xtw, Sooda.Schema.TableInfo tableInfo, string additionalSettings, string terminator) { xtw.WriteLine("create table {0} (", tableInfo.DBTableName); Dictionary<string, bool> processedFields = new Dictionary<string, bool>(); for (int i = 0; i < tableInfo.Fields.Count; ++i) { if (!processedFields.ContainsKey(tableInfo.Fields[i].DBColumnName)) { GenerateCreateTableField(xtw, tableInfo.Fields[i]); if (i == tableInfo.Fields.Count - 1) xtw.WriteLine(); else xtw.WriteLine(','); processedFields.Add(tableInfo.Fields[i].DBColumnName, true); } } xtw.Write(')'); TerminateDDL(xtw, additionalSettings, terminator); } public virtual string GetAlterTableStatement(Sooda.Schema.TableInfo tableInfo) { return String.Format("alter table {0} add primary key", tableInfo.DBTableName); } public void GeneratePrimaryKey(TextWriter xtw, Sooda.Schema.TableInfo tableInfo, string additionalSettings, string terminator) { bool first = true; foreach (Sooda.Schema.FieldInfo fi in tableInfo.Fields) { if (fi.IsPrimaryKey) { if (first) { xtw.Write(GetAlterTableStatement(tableInfo)); xtw.Write(" ("); } else { xtw.Write(", "); } xtw.Write(fi.DBColumnName); first = false; } } if (!first) { xtw.Write(')'); TerminateDDL(xtw, additionalSettings, terminator); } } public void GenerateForeignKeys(TextWriter xtw, Sooda.Schema.TableInfo tableInfo, string terminator) { foreach (Sooda.Schema.FieldInfo fi in tableInfo.Fields) { if (fi.References != null) { xtw.Write("alter table {0} add constraint {1} foreign key ({2}) references {3}({4})", tableInfo.DBTableName, GetConstraintName(tableInfo.DBTableName, fi.DBColumnName), fi.DBColumnName, fi.ReferencedClass.UnifiedTables[0].DBTableName, fi.ReferencedClass.GetFirstPrimaryKeyField().DBColumnName ); xtw.Write(terminator ?? GetDDLCommandTerminator()); } } } public void GenerateIndex(TextWriter xtw, FieldInfo fi, string additionalSettings, string terminator) { string table = fi.Table.DBTableName; xtw.Write("create index {0} on {1} ({2})", GetIndexName(table, fi.DBColumnName), table, fi.DBColumnName); TerminateDDL(xtw, additionalSettings, terminator); } public void GenerateIndices(TextWriter xtw, Sooda.Schema.TableInfo tableInfo, string additionalSettings, string terminator) { foreach (Sooda.Schema.FieldInfo fi in tableInfo.Fields) { if (fi.References != null) GenerateIndex(xtw, fi, additionalSettings, terminator); } } public void GenerateSoodaDynamicField(TextWriter xtw, string terminator) { xtw.WriteLine("create table SoodaDynamicField ("); xtw.WriteLine("\tclass varchar(32) not null,"); xtw.WriteLine("\tfield varchar(32) not null,"); xtw.WriteLine("\ttype varchar(32) not null,"); xtw.WriteLine("\tnullable int not null,"); xtw.WriteLine("\tfieldsize int null,"); xtw.WriteLine("\tprecision int null,"); xtw.WriteLine("\tconstraint PK_SoodaDynamicField primary key (class, field)"); xtw.Write(')'); xtw.Write(terminator ?? GetDDLCommandTerminator()); } public virtual string GetConstraintName(string tableName, string foreignKey) { return GetTruncatedIdentifier(String.Format("FK_{0}_{1}", tableName, foreignKey)); } public virtual string GetIndexName(string tableName, string column) { return GetTruncatedIdentifier(String.Format("IDX_{0}_{1}", tableName, column)); } public abstract string GetSQLDataType(Sooda.Schema.FieldInfo fi); public abstract string GetSQLOrderBy(Sooda.Schema.FieldInfo fi, bool start); public virtual string GetSQLNullable(Sooda.Schema.FieldInfo fi) { if (fi.IsDynamic) return "not null"; if (fi.IsNullable) return "null"; if (fi.ReferencedClass == null || fi.IsPrimaryKey || fi.ParentRelation != null || fi.ReadOnly || fi.ParentClass.ReadOnly) return "not null"; if (fi.PrecommitTypedValue == SchemaInfo.NullPrecommitValue) return "null"; return "not null"; } protected virtual bool SetDbTypeFromValue(IDbDataParameter parameter, object value, SoqlLiteralValueModifiers modifiers) { DbType dbType; if (!paramTypes.TryGetValue(value.GetType(), out dbType)) return false; parameter.DbType = dbType; return true; } private static readonly Dictionary<Type, DbType> paramTypes = new Dictionary<Type, DbType>(); static SqlBuilderBase() { paramTypes[typeof(SByte)] = DbType.SByte; paramTypes[typeof(Int16)] = DbType.Int16; paramTypes[typeof(Int32)] = DbType.Int32; paramTypes[typeof(Int64)] = DbType.Int64; paramTypes[typeof(Single)] = DbType.Single; paramTypes[typeof(Double)] = DbType.Double; paramTypes[typeof(String)] = DbType.String; paramTypes[typeof(Boolean)] = DbType.Boolean; paramTypes[typeof(Decimal)] = DbType.Decimal; paramTypes[typeof(Guid)] = DbType.Guid; paramTypes[typeof(TimeSpan)] = DbType.Int32; paramTypes[typeof(byte[])] = DbType.Binary; paramTypes[typeof(System.Drawing.Image)] = DbType.Binary; paramTypes[typeof(System.Drawing.Bitmap)] = DbType.Binary; } public virtual string QuoteIdentifier(string s) { for (int i = 0; i < s.Length; i++) { char c = s[i]; if (!(c >= 'A' && c <= 'Z') && !(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && !(c == '_' && i > 0)) return "\"" + s + "\""; } return s; } public abstract SqlTopSupportMode TopSupport { get; } protected bool IsStringSafeForLiteral(string v) { if (v.Length > 500) return false; foreach (char ch in v) { switch (ch) { // we are very conservative about what 'safe' means case ' ': case '.': case ',': case '-': case '%': case '_': case '@': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': break; default: return false; } } return true; } public virtual string EndInsert(string tableName) { return ""; } public virtual string BeginInsert(string tableName) { return ""; } protected virtual string AddParameterFromValue(IDbCommand command, object v, SoqlLiteralValueModifiers modifiers) { IDbDataParameter p = command.CreateParameter(); p.Direction = ParameterDirection.Input; p.ParameterName = GetNameForParameter(command.Parameters.Count); if (modifiers != null) FieldHandlerFactory.GetFieldHandler(modifiers.DataTypeOverride).SetupDBParameter(p, v); else { SetDbTypeFromValue(p, v, modifiers); p.Value = v; } command.Parameters.Add(p); return p.ParameterName; } public void BuildCommandWithParameters(System.Data.IDbCommand command, bool append, string query, object[] par, bool isRaw) { if (append) { if (command.CommandText == null) command.CommandText = ""; else if (command.CommandText.Length > 0) command.CommandText += ";\n"; } else { command.CommandText = ""; command.Parameters.Clear(); } System.Text.StringBuilder sb = new System.Text.StringBuilder(query.Length * 2); StringCollection paramNames = new StringCollection(); for (int i = 0; i < query.Length; ++i) { char c = query[i]; if (c == '\'') { int j = ++i; for (;;++j) { if (j >= query.Length) throw new ArgumentException("Query has unbalanced quotes"); if (query[j] == '\'') { if (j + 1 >= query.Length || query[j + 1] != '\'') break; // double apostrophe j++; } } string stringValue = query.Substring(i, j - i); char modifier = j + 1 < query.Length ? query[j + 1] : ' '; string paramName; switch (modifier) { case 'V': sb.Append('\''); sb.Append(stringValue); sb.Append('\''); j++; break; case 'D': paramName = AddParameterFromValue(command, DateTime.ParseExact(stringValue, "yyyyMMddHH:mm:ss", CultureInfo.InvariantCulture), null); sb.Append(paramName); j++; break; case 'A': stringValue = stringValue.Replace("''", "'"); paramName = AddParameterFromValue(command, stringValue, SoqlLiteralValueModifiers.AnsiString); sb.Append(paramName); j++; break; default: if (!isRaw && (!UseSafeLiterals || !IsStringSafeForLiteral(stringValue))) { stringValue = stringValue.Replace("''", "'"); paramName = AddParameterFromValue(command, stringValue, null); sb.Append(paramName); } else { sb.Append('\''); sb.Append(stringValue); sb.Append('\''); } break; } i = j; } else if (c == '{') { c = query[i + 1]; if (c == 'L') { // {L:fieldDataTypeName:value int startPos = i + 3; int endPos = query.IndexOf(':', startPos); if (endPos < 0) throw new ArgumentException("Missing ':' in literal specification"); SoqlLiteralValueModifiers modifier = SoqlParser.ParseLiteralValueModifiers(query.Substring(startPos, endPos - startPos)); FieldDataType fdt = modifier.DataTypeOverride; int valueStartPos = endPos + 1; bool anyEscape = false; for (i = valueStartPos; i < query.Length && query[i] != '}'; ++i) { if (query[i] == '\\') { i++; anyEscape = true; } } string literalValue = query.Substring(valueStartPos, i - valueStartPos); if (anyEscape) { literalValue = literalValue.Replace("\\}", "}"); literalValue = literalValue.Replace("\\\\", "\\"); } SoodaFieldHandler fieldHandler = FieldHandlerFactory.GetFieldHandler(fdt); object v = fieldHandler.RawDeserialize(literalValue); if (v == null) { sb.Append("null"); } else if (UseSafeLiterals && v is int) { sb.Append((int)v); } else if (UseSafeLiterals && v is string && IsStringSafeForLiteral((string)v)) { sb.Append('\''); sb.Append((string)v); sb.Append('\''); } else { IDbDataParameter p = command.CreateParameter(); p.Direction = ParameterDirection.Input; p.ParameterName = GetNameForParameter(command.Parameters.Count); fieldHandler.SetupDBParameter(p, v); command.Parameters.Add(p); sb.Append(p.ParameterName); } } else if (c >= '0' && c <= '9') { i++; int paramNumber = 0; do { paramNumber = paramNumber * 10 + c - '0'; c = query[++i]; } while (c >= '0' && c <= '9'); SoqlLiteralValueModifiers modifiers = null; if (c == ':') { int startPos = i + 1; i = query.IndexOf('}', startPos); if (i < 0) throw new ArgumentException("Missing '}' in parameter specification"); modifiers = SoqlParser.ParseLiteralValueModifiers(query.Substring(startPos, i - startPos)); } else if (c != '}') throw new ArgumentException("Missing '}' in parameter specification"); object v = par[paramNumber]; if (v is SoodaObject) { v = ((SoodaObject)v).GetPrimaryKeyValue(); } if (v == null) { sb.Append("null"); } else if (UseSafeLiterals && v is int) { sb.Append((int)v); } else if (UseSafeLiterals && v is string && IsStringSafeForLiteral((string)v)) { sb.Append('\''); sb.Append((string)v); sb.Append('\''); } else { sb.Append(AddNumberedParameter(command, v, modifiers, paramNames, paramNumber)); } } else { throw new ArgumentException("Unexpected character in parameter specification"); } } else if (c == '(' || c == ' ' || c == ',' || c == '=' || c == '>' || c == '<' || c == '+' || c == '-' || c == '*' || c == '/') { sb.Append(c); if (i < query.Length - 1) { c = query[i + 1]; if (c >= '0' && c <= '9' && !UseSafeLiterals) { int v = 0; double f = 0; double dp = 0; bool isDouble = false; do { if (c != '.') { if (!isDouble) v = v * 10 + c - '0'; else { f = f + dp * (c - '0'); dp = dp * 0.1; } } else { isDouble = true; f = v; dp = 0.1; } i++; if (i < query.Length - 1) c = query[i+1]; } while (((c >= '0' && c <= '9') || c == '.') && (i < query.Length - 1)); if (!isDouble) { string paramName = AddParameterFromValue(command, v, null); sb.Append(paramName); } else { string paramName = AddParameterFromValue(command, f, null); sb.Append(paramName); } } } } else { sb.Append(c); } } command.CommandText += sb.ToString(); } public virtual bool HandleFatalException(IDbConnection connection, Exception e) { return true; } public virtual bool IsNullValue(object val, Sooda.Schema.FieldInfo fi) { return val == null; } protected abstract string AddNumberedParameter(IDbCommand command, object v, SoqlLiteralValueModifiers modifiers, StringCollection paramNames, int paramNumber); protected abstract string GetNameForParameter(int pos); } }
using TribalWars.Browsers.Control; using TribalWars.Controls.AccordeonDetails; using TribalWars.Controls.AccordeonLocation; using TribalWars.Maps.AttackPlans.Controls; using TribalWars.Maps.Controls; using TribalWars.Maps.Markers; using TribalWars.Maps.Monitoring; using TribalWars.Maps.Polygons; namespace TribalWars.Forms { partial class MainForm { /// <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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.FormSplitter = new System.Windows.Forms.SplitContainer(); this.LeftSplitter = new System.Windows.Forms.SplitContainer(); this.MiniMap = new TribalWars.Maps.Controls.MiniMapControl(); this.LeftNavigation = new Ascend.Windows.Forms.NavigationPane(); this.LeftNavigation_Location = new Ascend.Windows.Forms.NavigationPanePage(); this.locationControl1 = new TribalWars.Controls.AccordeonLocation.LocationControl(); this.LeftNavigation_QuickFind = new Ascend.Windows.Forms.NavigationPanePage(); this.detailsControl1 = new TribalWars.Controls.AccordeonDetails.DetailsControl(); this.LeftNavigation_Markers = new Ascend.Windows.Forms.NavigationPanePage(); this.markersContainerControl1 = new TribalWars.Maps.Markers.MarkersControl(); this.LeftNavigation_Distance = new Ascend.Windows.Forms.NavigationPanePage(); this._attackPlan = new TribalWars.Maps.AttackPlans.Controls.AttackPlanCollectionControl(); this.Tabs = new Janus.Windows.UI.Tab.UITab(); this.TabsMap = new Janus.Windows.UI.Tab.UITabPage(); this.Map = new TribalWars.Maps.Controls.MapControl(); this.TabsBrowser = new Janus.Windows.UI.Tab.UITabPage(); this.browserControl1 = new TribalWars.Browsers.Control.BrowserControl(); this.TabsPolygon = new Janus.Windows.UI.Tab.UITabPage(); this.Polygon = new TribalWars.Maps.Polygons.PolygonControl(); this.TabsMonitoring = new Janus.Windows.UI.Tab.UITabPage(); this.monitoringControl1 = new TribalWars.Maps.Monitoring.MonitoringControl(); this.FormToolbarContainer = new System.Windows.Forms.ToolStripContainer(); this.ToolStrip = new System.Windows.Forms.ToolStrip(); this.ToolstripButtonCreateWorld = new System.Windows.Forms.ToolStripButton(); this.ToolStripOpen = new System.Windows.Forms.ToolStripButton(); this.ToolStripDownload = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.ToolStripSettings = new System.Windows.Forms.ToolStripDropDownButton(); this.ToolStripSave = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.ToolStripHome = new System.Windows.Forms.ToolStripButton(); this.ToolStripActiveRectangle = new System.Windows.Forms.ToolStripButton(); this.ToolStripDraw = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.ToolStripIconDisplay = new System.Windows.Forms.ToolStripButton(); this.ToolStripShapeDisplay = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.ToolStripDefaultManipulator = new System.Windows.Forms.ToolStripButton(); this.ToolStripPolygonManipulator = new System.Windows.Forms.ToolStripButton(); this.ToolStripAttackManipulator = new System.Windows.Forms.ToolStripButton(); this.ToolStripChurchManipulator = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator(); this.toolStripLocationChangerControl1 = new TribalWars.Controls.Common.ToolStripControlHostWrappers.ToolStripLocationChangerControl(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.ToolStripProgramSettings = new System.Windows.Forms.ToolStripButton(); this.ToolStripAbout = new System.Windows.Forms.ToolStripButton(); this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog(); this.PickColor = new System.Windows.Forms.ColorDialog(); this.Status = new System.Windows.Forms.StatusStrip(); this.ProgressBar = new System.Windows.Forms.ToolStripProgressBar(); this.StatusMessage = new System.Windows.Forms.ToolStripStatusLabel(); this.StatusDataTime = new System.Windows.Forms.ToolStripStatusLabel(); this.StatusXY = new System.Windows.Forms.ToolStripStatusLabel(); this.StatusVillage = new System.Windows.Forms.ToolStripStatusLabel(); this.StatusPlayer = new System.Windows.Forms.ToolStripStatusLabel(); this.StatusTribe = new System.Windows.Forms.ToolStripStatusLabel(); this.StatusSettings = new System.Windows.Forms.ToolStripStatusLabel(); this.StatusWorld = new System.Windows.Forms.ToolStripStatusLabel(); this.StatusServerTime = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripStatusLabel5 = new System.Windows.Forms.ToolStripStatusLabel(); this.ServerTimeTimer = new System.Windows.Forms.Timer(this.components); this.GeneralTooltip = new System.Windows.Forms.ToolTip(this.components); this.MenuBar = new System.Windows.Forms.MenuStrip(); this.MenuToolstrip = new System.Windows.Forms.ToolStripMenuItem(); this.MenuFileNew = new System.Windows.Forms.ToolStripMenuItem(); this.MenuFileLoadWorld = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator(); this.MenuFileWorldDownload = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.MenuFileSaveSettings = new System.Windows.Forms.ToolStripMenuItem(); this.MenuFileSaveSettingsAs = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.MenuFileSetActivePlayer = new System.Windows.Forms.ToolStripMenuItem(); this.MenuFileSynchronizeTime = new System.Windows.Forms.ToolStripMenuItem(); this.setLanguageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.SetLanguage_English = new System.Windows.Forms.ToolStripMenuItem(); this.SetLanguage_Dutch = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.MenuFileExit = new System.Windows.Forms.ToolStripMenuItem(); this.mapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.MenuMapMonitoringArea = new System.Windows.Forms.ToolStripMenuItem(); this.MenuMapSetHomeLocation = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripSeparator(); this.MenuMapIconDisplay = new System.Windows.Forms.ToolStripMenuItem(); this.MenuMapShapeDisplay = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripSeparator(); this.MenuMapInteractionDefault = new System.Windows.Forms.ToolStripMenuItem(); this.MenuMapInteractionPolygon = new System.Windows.Forms.ToolStripMenuItem(); this.MenuMapInteractionPlanAttacks = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripSeparator(); this.MenuMapSelectPane0 = new System.Windows.Forms.ToolStripMenuItem(); this.MenuMapSelectPane1 = new System.Windows.Forms.ToolStripMenuItem(); this.MenuMapSelectPane2 = new System.Windows.Forms.ToolStripMenuItem(); this.MenuMapSelectPane3 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.MenuMapScreenshot = new System.Windows.Forms.ToolStripMenuItem(); this.MenuMapSeeScreenshots = new System.Windows.Forms.ToolStripMenuItem(); this.windowsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.MenuWindowsManageYourVillages = new System.Windows.Forms.ToolStripMenuItem(); this.MenuWindowsImportVillageCoordinates = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripSeparator(); this.MenuWindowsManageYourAttackersPool = new System.Windows.Forms.ToolStripMenuItem(); this.otherToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.MenuWindowsAddTimes = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.MenuHelpReportBug = new System.Windows.Forms.ToolStripMenuItem(); this.MenuHelpAbout = new System.Windows.Forms.ToolStripMenuItem(); this.BottomToolStripPanel = new System.Windows.Forms.ToolStripPanel(); this.TopToolStripPanel = new System.Windows.Forms.ToolStripPanel(); this.RightToolStripPanel = new System.Windows.Forms.ToolStripPanel(); this.LeftToolStripPanel = new System.Windows.Forms.ToolStripPanel(); this.ContentPanel = new System.Windows.Forms.ToolStripContentPanel(); this.VillageTooltip = new System.Windows.Forms.ToolTip(this.components); this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); ((System.ComponentModel.ISupportInitialize)(this.FormSplitter)).BeginInit(); this.FormSplitter.Panel1.SuspendLayout(); this.FormSplitter.Panel2.SuspendLayout(); this.FormSplitter.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.LeftSplitter)).BeginInit(); this.LeftSplitter.Panel1.SuspendLayout(); this.LeftSplitter.Panel2.SuspendLayout(); this.LeftSplitter.SuspendLayout(); this.LeftNavigation.SuspendLayout(); this.LeftNavigation_Location.SuspendLayout(); this.LeftNavigation_QuickFind.SuspendLayout(); this.LeftNavigation_Markers.SuspendLayout(); this.LeftNavigation_Distance.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.Tabs)).BeginInit(); this.Tabs.SuspendLayout(); this.TabsMap.SuspendLayout(); this.TabsBrowser.SuspendLayout(); this.TabsPolygon.SuspendLayout(); this.TabsMonitoring.SuspendLayout(); this.FormToolbarContainer.ContentPanel.SuspendLayout(); this.FormToolbarContainer.TopToolStripPanel.SuspendLayout(); this.FormToolbarContainer.SuspendLayout(); this.ToolStrip.SuspendLayout(); this.Status.SuspendLayout(); this.MenuBar.SuspendLayout(); this.SuspendLayout(); // // FormSplitter // this.FormSplitter.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.FormSplitter, "FormSplitter"); this.FormSplitter.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.FormSplitter.Name = "FormSplitter"; // // FormSplitter.Panel1 // this.FormSplitter.Panel1.BackColor = System.Drawing.Color.Transparent; this.FormSplitter.Panel1.Controls.Add(this.LeftSplitter); resources.ApplyResources(this.FormSplitter.Panel1, "FormSplitter.Panel1"); // // FormSplitter.Panel2 // this.FormSplitter.Panel2.BackColor = System.Drawing.Color.Transparent; this.FormSplitter.Panel2.Controls.Add(this.Tabs); resources.ApplyResources(this.FormSplitter.Panel2, "FormSplitter.Panel2"); this.FormSplitter.TabStop = false; // // LeftSplitter // resources.ApplyResources(this.LeftSplitter, "LeftSplitter"); this.LeftSplitter.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.LeftSplitter.Name = "LeftSplitter"; // // LeftSplitter.Panel1 // this.LeftSplitter.Panel1.Controls.Add(this.MiniMap); // // LeftSplitter.Panel2 // this.LeftSplitter.Panel2.Controls.Add(this.LeftNavigation); this.LeftSplitter.TabStop = false; // // MiniMap // this.MiniMap.BackColor = System.Drawing.Color.Green; resources.ApplyResources(this.MiniMap, "MiniMap"); this.MiniMap.Name = "MiniMap"; // // LeftNavigation // this.LeftNavigation.ButtonActiveGradientHighColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(225)))), ((int)(((byte)(155))))); this.LeftNavigation.ButtonActiveGradientLowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(165)))), ((int)(((byte)(78))))); this.LeftNavigation.ButtonBorderColor = System.Drawing.SystemColors.MenuHighlight; this.LeftNavigation.ButtonFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold); this.LeftNavigation.ButtonForeColor = System.Drawing.SystemColors.ControlText; this.LeftNavigation.ButtonGradientHighColor = System.Drawing.SystemColors.ButtonHighlight; this.LeftNavigation.ButtonGradientLowColor = System.Drawing.SystemColors.GradientActiveCaption; this.LeftNavigation.ButtonHighlightGradientHighColor = System.Drawing.Color.White; this.LeftNavigation.ButtonHighlightGradientLowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(165)))), ((int)(((byte)(78))))); this.LeftNavigation.CaptionBorderColor = System.Drawing.SystemColors.ActiveCaption; this.LeftNavigation.CaptionFont = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold); this.LeftNavigation.CaptionForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.LeftNavigation.CaptionGradientHighColor = System.Drawing.SystemColors.GradientActiveCaption; this.LeftNavigation.CaptionGradientLowColor = System.Drawing.SystemColors.ActiveCaption; this.LeftNavigation.Controls.Add(this.LeftNavigation_Location); this.LeftNavigation.Controls.Add(this.LeftNavigation_QuickFind); this.LeftNavigation.Controls.Add(this.LeftNavigation_Markers); this.LeftNavigation.Controls.Add(this.LeftNavigation_Distance); this.LeftNavigation.Cursor = System.Windows.Forms.Cursors.Default; resources.ApplyResources(this.LeftNavigation, "LeftNavigation"); this.LeftNavigation.FooterGradientHighColor = System.Drawing.SystemColors.ButtonHighlight; this.LeftNavigation.FooterGradientLowColor = System.Drawing.SystemColors.GradientActiveCaption; this.LeftNavigation.FooterHeight = 30; this.LeftNavigation.FooterHighlightGradientHighColor = System.Drawing.Color.White; this.LeftNavigation.FooterHighlightGradientLowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(165)))), ((int)(((byte)(78))))); this.LeftNavigation.Name = "LeftNavigation"; this.LeftNavigation.NavigationPages.AddRange(new Ascend.Windows.Forms.NavigationPanePage[] { this.LeftNavigation_Location, this.LeftNavigation_QuickFind, this.LeftNavigation_Markers, this.LeftNavigation_Distance}); this.LeftNavigation.VisibleButtonCount = 0; // // LeftNavigation_Location // this.LeftNavigation_Location.ActiveGradientHighColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(225)))), ((int)(((byte)(155))))); this.LeftNavigation_Location.ActiveGradientLowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(165)))), ((int)(((byte)(78))))); resources.ApplyResources(this.LeftNavigation_Location, "LeftNavigation_Location"); this.LeftNavigation_Location.ButtonFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold); this.LeftNavigation_Location.ButtonForeColor = System.Drawing.SystemColors.ControlText; this.LeftNavigation_Location.Controls.Add(this.locationControl1); this.LeftNavigation_Location.GradientHighColor = System.Drawing.SystemColors.ButtonHighlight; this.LeftNavigation_Location.GradientLowColor = System.Drawing.SystemColors.GradientActiveCaption; this.LeftNavigation_Location.HighlightGradientHighColor = System.Drawing.Color.White; this.LeftNavigation_Location.HighlightGradientLowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(165)))), ((int)(((byte)(78))))); this.LeftNavigation_Location.Image = ((System.Drawing.Image)(resources.GetObject("LeftNavigation_Location.Image"))); this.LeftNavigation_Location.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.LeftNavigation_Location.ImageFooter = null; this.LeftNavigation_Location.ImageIndex = -1; this.LeftNavigation_Location.ImageIndexFooter = -1; this.LeftNavigation_Location.ImageKey = ""; this.LeftNavigation_Location.ImageKeyFooter = ""; this.LeftNavigation_Location.ImageList = null; this.LeftNavigation_Location.ImageListFooter = null; this.LeftNavigation_Location.Key = "LeftNavigation_Location"; this.LeftNavigation_Location.Name = "LeftNavigation_Location"; this.LeftNavigation_Location.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.LeftNavigation_Location.ToolTipText = null; // // locationControl1 // resources.ApplyResources(this.locationControl1, "locationControl1"); this.locationControl1.BackColor = System.Drawing.Color.Transparent; this.locationControl1.Name = "locationControl1"; // // LeftNavigation_QuickFind // this.LeftNavigation_QuickFind.ActiveGradientHighColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(225)))), ((int)(((byte)(155))))); this.LeftNavigation_QuickFind.ActiveGradientLowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(165)))), ((int)(((byte)(78))))); resources.ApplyResources(this.LeftNavigation_QuickFind, "LeftNavigation_QuickFind"); this.LeftNavigation_QuickFind.ButtonFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold); this.LeftNavigation_QuickFind.ButtonForeColor = System.Drawing.SystemColors.ControlText; this.LeftNavigation_QuickFind.Controls.Add(this.detailsControl1); this.LeftNavigation_QuickFind.GradientHighColor = System.Drawing.SystemColors.ButtonHighlight; this.LeftNavigation_QuickFind.GradientLowColor = System.Drawing.SystemColors.GradientActiveCaption; this.LeftNavigation_QuickFind.HighlightGradientHighColor = System.Drawing.Color.White; this.LeftNavigation_QuickFind.HighlightGradientLowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(165)))), ((int)(((byte)(78))))); this.LeftNavigation_QuickFind.Image = ((System.Drawing.Image)(resources.GetObject("LeftNavigation_QuickFind.Image"))); this.LeftNavigation_QuickFind.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.LeftNavigation_QuickFind.ImageFooter = null; this.LeftNavigation_QuickFind.ImageIndex = -1; this.LeftNavigation_QuickFind.ImageIndexFooter = -1; this.LeftNavigation_QuickFind.ImageKey = ""; this.LeftNavigation_QuickFind.ImageKeyFooter = ""; this.LeftNavigation_QuickFind.ImageList = null; this.LeftNavigation_QuickFind.ImageListFooter = null; this.LeftNavigation_QuickFind.Key = "LeftNavigation_QuickFind"; this.LeftNavigation_QuickFind.Name = "LeftNavigation_QuickFind"; this.LeftNavigation_QuickFind.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.LeftNavigation_QuickFind.ToolTipText = null; // // detailsControl1 // resources.ApplyResources(this.detailsControl1, "detailsControl1"); this.detailsControl1.BackColor = System.Drawing.Color.Transparent; this.detailsControl1.Name = "detailsControl1"; // // LeftNavigation_Markers // this.LeftNavigation_Markers.ActiveGradientHighColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(225)))), ((int)(((byte)(155))))); this.LeftNavigation_Markers.ActiveGradientLowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(165)))), ((int)(((byte)(78))))); resources.ApplyResources(this.LeftNavigation_Markers, "LeftNavigation_Markers"); this.LeftNavigation_Markers.ButtonFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold); this.LeftNavigation_Markers.ButtonForeColor = System.Drawing.SystemColors.ControlText; this.LeftNavigation_Markers.Controls.Add(this.markersContainerControl1); this.LeftNavigation_Markers.GradientHighColor = System.Drawing.SystemColors.ButtonHighlight; this.LeftNavigation_Markers.GradientLowColor = System.Drawing.SystemColors.GradientActiveCaption; this.LeftNavigation_Markers.HighlightGradientHighColor = System.Drawing.Color.White; this.LeftNavigation_Markers.HighlightGradientLowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(165)))), ((int)(((byte)(78))))); this.LeftNavigation_Markers.Image = ((System.Drawing.Image)(resources.GetObject("LeftNavigation_Markers.Image"))); this.LeftNavigation_Markers.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.LeftNavigation_Markers.ImageFooter = null; this.LeftNavigation_Markers.ImageIndex = -1; this.LeftNavigation_Markers.ImageIndexFooter = -1; this.LeftNavigation_Markers.ImageKey = ""; this.LeftNavigation_Markers.ImageKeyFooter = ""; this.LeftNavigation_Markers.ImageList = null; this.LeftNavigation_Markers.ImageListFooter = null; this.LeftNavigation_Markers.Key = "LeftNavigation_Markers"; this.LeftNavigation_Markers.Name = "LeftNavigation_Markers"; this.LeftNavigation_Markers.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.LeftNavigation_Markers.ToolTipText = null; // // markersContainerControl1 // resources.ApplyResources(this.markersContainerControl1, "markersContainerControl1"); this.markersContainerControl1.BackColor = System.Drawing.Color.Transparent; this.markersContainerControl1.Name = "markersContainerControl1"; // // LeftNavigation_Distance // this.LeftNavigation_Distance.ActiveGradientHighColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(225)))), ((int)(((byte)(155))))); this.LeftNavigation_Distance.ActiveGradientLowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(165)))), ((int)(((byte)(78))))); resources.ApplyResources(this.LeftNavigation_Distance, "LeftNavigation_Distance"); this.LeftNavigation_Distance.ButtonFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold); this.LeftNavigation_Distance.ButtonForeColor = System.Drawing.SystemColors.ControlText; this.LeftNavigation_Distance.Controls.Add(this._attackPlan); this.LeftNavigation_Distance.GradientHighColor = System.Drawing.SystemColors.ButtonHighlight; this.LeftNavigation_Distance.GradientLowColor = System.Drawing.SystemColors.GradientActiveCaption; this.LeftNavigation_Distance.HighlightGradientHighColor = System.Drawing.Color.White; this.LeftNavigation_Distance.HighlightGradientLowColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(165)))), ((int)(((byte)(78))))); this.LeftNavigation_Distance.Image = ((System.Drawing.Image)(resources.GetObject("LeftNavigation_Distance.Image"))); this.LeftNavigation_Distance.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.LeftNavigation_Distance.ImageFooter = null; this.LeftNavigation_Distance.ImageIndex = -1; this.LeftNavigation_Distance.ImageIndexFooter = -1; this.LeftNavigation_Distance.ImageKey = ""; this.LeftNavigation_Distance.ImageKeyFooter = ""; this.LeftNavigation_Distance.ImageList = null; this.LeftNavigation_Distance.ImageListFooter = null; this.LeftNavigation_Distance.Key = "LeftNavigation_Distance"; this.LeftNavigation_Distance.Name = "LeftNavigation_Distance"; this.LeftNavigation_Distance.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.LeftNavigation_Distance.ToolTipText = null; // // _attackPlan // resources.ApplyResources(this._attackPlan, "_attackPlan"); this._attackPlan.Name = "_attackPlan"; // // Tabs // resources.ApplyResources(this.Tabs, "Tabs"); this.Tabs.InputFocusTab = this.TabsMap; this.Tabs.Name = "Tabs"; this.Tabs.TabPages.AddRange(new Janus.Windows.UI.Tab.UITabPage[] { this.TabsMap, this.TabsBrowser, this.TabsPolygon, this.TabsMonitoring}); // // TabsMap // this.TabsMap.Controls.Add(this.Map); resources.ApplyResources(this.TabsMap, "TabsMap"); this.TabsMap.Key = "Map"; this.TabsMap.Name = "TabsMap"; this.TabsMap.TabStop = true; // // Map // this.Map.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.Map, "Map"); this.Map.Name = "Map"; // // TabsBrowser // this.TabsBrowser.Controls.Add(this.browserControl1); resources.ApplyResources(this.TabsBrowser, "TabsBrowser"); this.TabsBrowser.Key = "TWStats"; this.TabsBrowser.Name = "TabsBrowser"; this.TabsBrowser.TabStop = true; // // browserControl1 // this.browserControl1.ActiveVillage = 0; resources.ApplyResources(this.browserControl1, "browserControl1"); this.browserControl1.GameBrowser = false; this.browserControl1.Name = "browserControl1"; // // TabsPolygon // this.TabsPolygon.Controls.Add(this.Polygon); resources.ApplyResources(this.TabsPolygon, "TabsPolygon"); this.TabsPolygon.Key = "Polygon"; this.TabsPolygon.Name = "TabsPolygon"; this.TabsPolygon.TabStop = true; // // Polygon // this.Polygon.BackColor = System.Drawing.SystemColors.Control; resources.ApplyResources(this.Polygon, "Polygon"); this.Polygon.Name = "Polygon"; // // TabsMonitoring // this.TabsMonitoring.Controls.Add(this.monitoringControl1); resources.ApplyResources(this.TabsMonitoring, "TabsMonitoring"); this.TabsMonitoring.Key = "Monitoring"; this.TabsMonitoring.Name = "TabsMonitoring"; this.TabsMonitoring.TabStop = true; // // monitoringControl1 // this.monitoringControl1.BackColor = System.Drawing.SystemColors.Control; resources.ApplyResources(this.monitoringControl1, "monitoringControl1"); this.monitoringControl1.Name = "monitoringControl1"; // // FormToolbarContainer // // // FormToolbarContainer.ContentPanel // this.FormToolbarContainer.ContentPanel.Controls.Add(this.FormSplitter); this.FormToolbarContainer.ContentPanel.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional; resources.ApplyResources(this.FormToolbarContainer.ContentPanel, "FormToolbarContainer.ContentPanel"); resources.ApplyResources(this.FormToolbarContainer, "FormToolbarContainer"); this.FormToolbarContainer.Name = "FormToolbarContainer"; // // FormToolbarContainer.TopToolStripPanel // this.FormToolbarContainer.TopToolStripPanel.Controls.Add(this.ToolStrip); // // ToolStrip // resources.ApplyResources(this.ToolStrip, "ToolStrip"); this.ToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.ToolstripButtonCreateWorld, this.ToolStripOpen, this.ToolStripDownload, this.toolStripSeparator6, this.ToolStripSettings, this.ToolStripSave, this.toolStripSeparator4, this.ToolStripHome, this.ToolStripActiveRectangle, this.ToolStripDraw, this.toolStripSeparator5, this.ToolStripIconDisplay, this.ToolStripShapeDisplay, this.toolStripSeparator3, this.ToolStripDefaultManipulator, this.ToolStripPolygonManipulator, this.ToolStripAttackManipulator, this.ToolStripChurchManipulator, this.toolStripSeparator, this.toolStripLocationChangerControl1, this.toolStripSeparator7, this.ToolStripProgramSettings, this.ToolStripAbout}); this.ToolStrip.Name = "ToolStrip"; // // ToolstripButtonCreateWorld // this.ToolstripButtonCreateWorld.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.ToolstripButtonCreateWorld, "ToolstripButtonCreateWorld"); this.ToolstripButtonCreateWorld.Name = "ToolstripButtonCreateWorld"; this.ToolstripButtonCreateWorld.Click += new System.EventHandler(this.ToolstripButtonCreateWorld_Click); // // ToolStripOpen // this.ToolStripOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.ToolStripOpen, "ToolStripOpen"); this.ToolStripOpen.Name = "ToolStripOpen"; this.ToolStripOpen.Click += new System.EventHandler(this.ToolStripOpen_Click); // // ToolStripDownload // this.ToolStripDownload.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.ToolStripDownload, "ToolStripDownload"); this.ToolStripDownload.Name = "ToolStripDownload"; this.ToolStripDownload.Click += new System.EventHandler(this.MenuFileWorldDownload_Click); // // toolStripSeparator6 // this.toolStripSeparator6.Name = "toolStripSeparator6"; resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6"); // // ToolStripSettings // this.ToolStripSettings.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; resources.ApplyResources(this.ToolStripSettings, "ToolStripSettings"); this.ToolStripSettings.Name = "ToolStripSettings"; // // ToolStripSave // this.ToolStripSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.ToolStripSave, "ToolStripSave"); this.ToolStripSave.Name = "ToolStripSave"; this.ToolStripSave.Click += new System.EventHandler(this.ToolStripSave_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4"); // // ToolStripHome // this.ToolStripHome.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.ToolStripHome.Image = global::TribalWars.Properties.Resources.Home2; resources.ApplyResources(this.ToolStripHome, "ToolStripHome"); this.ToolStripHome.Name = "ToolStripHome"; this.ToolStripHome.Click += new System.EventHandler(this.ToolStripHome_Click); // // ToolStripActiveRectangle // this.ToolStripActiveRectangle.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.ToolStripActiveRectangle, "ToolStripActiveRectangle"); this.ToolStripActiveRectangle.Name = "ToolStripActiveRectangle"; this.ToolStripActiveRectangle.Click += new System.EventHandler(this.ToolStripActiveRectangle_Click); // // ToolStripDraw // this.ToolStripDraw.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.ToolStripDraw, "ToolStripDraw"); this.ToolStripDraw.Name = "ToolStripDraw"; this.ToolStripDraw.Click += new System.EventHandler(this.ToolStripDraw_Click); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5"); // // ToolStripIconDisplay // this.ToolStripIconDisplay.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.ToolStripIconDisplay.Image = global::TribalWars.Properties.Resources.Village; resources.ApplyResources(this.ToolStripIconDisplay, "ToolStripIconDisplay"); this.ToolStripIconDisplay.Name = "ToolStripIconDisplay"; this.ToolStripIconDisplay.Tag = "ChangeHighlight"; this.ToolStripIconDisplay.Click += new System.EventHandler(this.ToolStripIconDisplay_Click); // // ToolStripShapeDisplay // this.ToolStripShapeDisplay.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.ToolStripShapeDisplay.Image = global::TribalWars.Properties.Resources.shapes; resources.ApplyResources(this.ToolStripShapeDisplay, "ToolStripShapeDisplay"); this.ToolStripShapeDisplay.Name = "ToolStripShapeDisplay"; this.ToolStripShapeDisplay.Tag = "ChangeHighlight"; this.ToolStripShapeDisplay.Click += new System.EventHandler(this.ToolStripShapeDisplay_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3"); // // ToolStripDefaultManipulator // this.ToolStripDefaultManipulator.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.ToolStripDefaultManipulator, "ToolStripDefaultManipulator"); this.ToolStripDefaultManipulator.Name = "ToolStripDefaultManipulator"; this.ToolStripDefaultManipulator.Tag = "ChangeHighlight"; this.ToolStripDefaultManipulator.Click += new System.EventHandler(this.ToolStripDefaultManipulator_Click); // // ToolStripPolygonManipulator // this.ToolStripPolygonManipulator.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.ToolStripPolygonManipulator, "ToolStripPolygonManipulator"); this.ToolStripPolygonManipulator.Name = "ToolStripPolygonManipulator"; this.ToolStripPolygonManipulator.Tag = "ChangeHighlight"; this.ToolStripPolygonManipulator.Click += new System.EventHandler(this.ToolStripPolygonManipulator_Click); // // ToolStripAttackManipulator // this.ToolStripAttackManipulator.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.ToolStripAttackManipulator, "ToolStripAttackManipulator"); this.ToolStripAttackManipulator.Name = "ToolStripAttackManipulator"; this.ToolStripAttackManipulator.Tag = "ChangeHighlight"; this.ToolStripAttackManipulator.Click += new System.EventHandler(this.ToolStripAttackManipulator_Click); // // ToolStripChurchManipulator // this.ToolStripChurchManipulator.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.ToolStripChurchManipulator, "ToolStripChurchManipulator"); this.ToolStripChurchManipulator.Name = "ToolStripChurchManipulator"; this.ToolStripChurchManipulator.Click += new System.EventHandler(this.ToolStripChurchManipulator_Click); // // toolStripSeparator // this.toolStripSeparator.Name = "toolStripSeparator"; resources.ApplyResources(this.toolStripSeparator, "toolStripSeparator"); // // toolStripLocationChangerControl1 // resources.ApplyResources(this.toolStripLocationChangerControl1, "toolStripLocationChangerControl1"); this.toolStripLocationChangerControl1.BackColor = System.Drawing.Color.Transparent; this.toolStripLocationChangerControl1.Name = "toolStripLocationChangerControl1"; // // toolStripSeparator7 // this.toolStripSeparator7.Name = "toolStripSeparator7"; resources.ApplyResources(this.toolStripSeparator7, "toolStripSeparator7"); // // ToolStripProgramSettings // this.ToolStripProgramSettings.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.ToolStripProgramSettings, "ToolStripProgramSettings"); this.ToolStripProgramSettings.Name = "ToolStripProgramSettings"; this.ToolStripProgramSettings.Click += new System.EventHandler(this.ToolStripProgramSettings_Click); // // ToolStripAbout // this.ToolStripAbout.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.ToolStripAbout, "ToolStripAbout"); this.ToolStripAbout.Name = "ToolStripAbout"; this.ToolStripAbout.Click += new System.EventHandler(this.MenuHelpAbout_Click); // // Status // this.Status.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.ProgressBar, this.StatusMessage, this.StatusDataTime, this.StatusXY, this.StatusVillage, this.StatusPlayer, this.StatusTribe, this.StatusSettings, this.StatusWorld, this.StatusServerTime, this.toolStripStatusLabel5}); resources.ApplyResources(this.Status, "Status"); this.Status.Name = "Status"; this.Status.ShowItemToolTips = true; // // ProgressBar // this.ProgressBar.Name = "ProgressBar"; resources.ApplyResources(this.ProgressBar, "ProgressBar"); // // StatusMessage // this.StatusMessage.Name = "StatusMessage"; resources.ApplyResources(this.StatusMessage, "StatusMessage"); this.StatusMessage.Spring = true; // // StatusDataTime // resources.ApplyResources(this.StatusDataTime, "StatusDataTime"); this.StatusDataTime.AutoToolTip = true; this.StatusDataTime.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Right) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom))); this.StatusDataTime.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter; this.StatusDataTime.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.StatusDataTime.Name = "StatusDataTime"; // // StatusXY // resources.ApplyResources(this.StatusXY, "StatusXY"); this.StatusXY.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Right) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom))); this.StatusXY.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter; this.StatusXY.Name = "StatusXY"; // // StatusVillage // resources.ApplyResources(this.StatusVillage, "StatusVillage"); this.StatusVillage.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Right) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom))); this.StatusVillage.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter; this.StatusVillage.Name = "StatusVillage"; // // StatusPlayer // resources.ApplyResources(this.StatusPlayer, "StatusPlayer"); this.StatusPlayer.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Right) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom))); this.StatusPlayer.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter; this.StatusPlayer.Name = "StatusPlayer"; // // StatusTribe // resources.ApplyResources(this.StatusTribe, "StatusTribe"); this.StatusTribe.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Right) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom))); this.StatusTribe.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter; this.StatusTribe.Name = "StatusTribe"; // // StatusSettings // this.StatusSettings.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Right) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom))); this.StatusSettings.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter; this.StatusSettings.Name = "StatusSettings"; this.StatusSettings.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never; resources.ApplyResources(this.StatusSettings, "StatusSettings"); // // StatusWorld // this.StatusWorld.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Right) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom))); this.StatusWorld.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter; this.StatusWorld.Name = "StatusWorld"; resources.ApplyResources(this.StatusWorld, "StatusWorld"); // // StatusServerTime // resources.ApplyResources(this.StatusServerTime, "StatusServerTime"); this.StatusServerTime.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Right) | System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom))); this.StatusServerTime.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter; this.StatusServerTime.Name = "StatusServerTime"; this.StatusServerTime.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never; // // toolStripStatusLabel5 // resources.ApplyResources(this.toolStripStatusLabel5, "toolStripStatusLabel5"); this.toolStripStatusLabel5.Name = "toolStripStatusLabel5"; // // ServerTimeTimer // this.ServerTimeTimer.Enabled = true; this.ServerTimeTimer.Interval = 1000; this.ServerTimeTimer.Tick += new System.EventHandler(this.ServerTimeTimer_Tick); // // MenuBar // this.MenuBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuToolstrip, this.mapToolStripMenuItem, this.windowsToolStripMenuItem, this.helpToolStripMenuItem}); resources.ApplyResources(this.MenuBar, "MenuBar"); this.MenuBar.Name = "MenuBar"; // // MenuToolstrip // this.MenuToolstrip.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuFileNew, this.MenuFileLoadWorld, this.toolStripMenuItem4, this.MenuFileWorldDownload, this.toolStripSeparator1, this.MenuFileSaveSettings, this.MenuFileSaveSettingsAs, this.toolStripSeparator2, this.MenuFileSetActivePlayer, this.MenuFileSynchronizeTime, this.setLanguageToolStripMenuItem, this.toolStripMenuItem1, this.MenuFileExit}); this.MenuToolstrip.Name = "MenuToolstrip"; resources.ApplyResources(this.MenuToolstrip, "MenuToolstrip"); // // MenuFileNew // resources.ApplyResources(this.MenuFileNew, "MenuFileNew"); this.MenuFileNew.Name = "MenuFileNew"; this.MenuFileNew.Click += new System.EventHandler(this.MenuFileNew_Click); // // MenuFileLoadWorld // resources.ApplyResources(this.MenuFileLoadWorld, "MenuFileLoadWorld"); this.MenuFileLoadWorld.Name = "MenuFileLoadWorld"; this.MenuFileLoadWorld.Click += new System.EventHandler(this.MenuFileLoadWorld_Click); // // toolStripMenuItem4 // this.toolStripMenuItem4.Name = "toolStripMenuItem4"; resources.ApplyResources(this.toolStripMenuItem4, "toolStripMenuItem4"); // // MenuFileWorldDownload // resources.ApplyResources(this.MenuFileWorldDownload, "MenuFileWorldDownload"); this.MenuFileWorldDownload.Name = "MenuFileWorldDownload"; this.MenuFileWorldDownload.Click += new System.EventHandler(this.MenuFileWorldDownload_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1"); // // MenuFileSaveSettings // resources.ApplyResources(this.MenuFileSaveSettings, "MenuFileSaveSettings"); this.MenuFileSaveSettings.Name = "MenuFileSaveSettings"; this.MenuFileSaveSettings.Click += new System.EventHandler(this.MenuFileSaveSettings_Click); // // MenuFileSaveSettingsAs // this.MenuFileSaveSettingsAs.Name = "MenuFileSaveSettingsAs"; resources.ApplyResources(this.MenuFileSaveSettingsAs, "MenuFileSaveSettingsAs"); this.MenuFileSaveSettingsAs.Click += new System.EventHandler(this.MenuFileSaveSettingsAs_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2"); // // MenuFileSetActivePlayer // this.MenuFileSetActivePlayer.Image = global::TribalWars.Properties.Resources.Player; this.MenuFileSetActivePlayer.Name = "MenuFileSetActivePlayer"; resources.ApplyResources(this.MenuFileSetActivePlayer, "MenuFileSetActivePlayer"); this.MenuFileSetActivePlayer.Click += new System.EventHandler(this.MenuFileSetActivePlayer_Click); // // MenuFileSynchronizeTime // this.MenuFileSynchronizeTime.Name = "MenuFileSynchronizeTime"; resources.ApplyResources(this.MenuFileSynchronizeTime, "MenuFileSynchronizeTime"); this.MenuFileSynchronizeTime.Click += new System.EventHandler(this.MenuFileSynchronizeTime_Click); // // setLanguageToolStripMenuItem // this.setLanguageToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.SetLanguage_English, this.SetLanguage_Dutch}); this.setLanguageToolStripMenuItem.Name = "setLanguageToolStripMenuItem"; resources.ApplyResources(this.setLanguageToolStripMenuItem, "setLanguageToolStripMenuItem"); // // SetLanguage_English // this.SetLanguage_English.Name = "SetLanguage_English"; resources.ApplyResources(this.SetLanguage_English, "SetLanguage_English"); this.SetLanguage_English.Click += new System.EventHandler(this.SetLanguage_English_Click); // // SetLanguage_Dutch // this.SetLanguage_Dutch.Name = "SetLanguage_Dutch"; resources.ApplyResources(this.SetLanguage_Dutch, "SetLanguage_Dutch"); this.SetLanguage_Dutch.Click += new System.EventHandler(this.SetLanguage_Dutch_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; resources.ApplyResources(this.toolStripMenuItem1, "toolStripMenuItem1"); // // MenuFileExit // this.MenuFileExit.Name = "MenuFileExit"; resources.ApplyResources(this.MenuFileExit, "MenuFileExit"); this.MenuFileExit.Click += new System.EventHandler(this.MenuFileExit_Click); // // mapToolStripMenuItem // this.mapToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuMapMonitoringArea, this.MenuMapSetHomeLocation, this.toolStripMenuItem8, this.MenuMapIconDisplay, this.MenuMapShapeDisplay, this.toolStripMenuItem6, this.MenuMapInteractionDefault, this.MenuMapInteractionPolygon, this.MenuMapInteractionPlanAttacks, this.toolStripMenuItem5, this.MenuMapSelectPane0, this.MenuMapSelectPane1, this.MenuMapSelectPane2, this.MenuMapSelectPane3, this.toolStripMenuItem2, this.MenuMapScreenshot, this.MenuMapSeeScreenshots}); this.mapToolStripMenuItem.Name = "mapToolStripMenuItem"; resources.ApplyResources(this.mapToolStripMenuItem, "mapToolStripMenuItem"); // // MenuMapMonitoringArea // resources.ApplyResources(this.MenuMapMonitoringArea, "MenuMapMonitoringArea"); this.MenuMapMonitoringArea.Name = "MenuMapMonitoringArea"; this.MenuMapMonitoringArea.Click += new System.EventHandler(this.ToolStripActiveRectangle_Click); // // MenuMapSetHomeLocation // this.MenuMapSetHomeLocation.Image = global::TribalWars.Properties.Resources.Home2; resources.ApplyResources(this.MenuMapSetHomeLocation, "MenuMapSetHomeLocation"); this.MenuMapSetHomeLocation.Name = "MenuMapSetHomeLocation"; this.MenuMapSetHomeLocation.Click += new System.EventHandler(this.MenuMapSetHomeLocation_Click); // // toolStripMenuItem8 // this.toolStripMenuItem8.Name = "toolStripMenuItem8"; resources.ApplyResources(this.toolStripMenuItem8, "toolStripMenuItem8"); // // MenuMapIconDisplay // this.MenuMapIconDisplay.Image = global::TribalWars.Properties.Resources.Village; this.MenuMapIconDisplay.Name = "MenuMapIconDisplay"; resources.ApplyResources(this.MenuMapIconDisplay, "MenuMapIconDisplay"); this.MenuMapIconDisplay.Click += new System.EventHandler(this.ToolStripIconDisplay_Click); // // MenuMapShapeDisplay // this.MenuMapShapeDisplay.Image = global::TribalWars.Properties.Resources.shapes; this.MenuMapShapeDisplay.Name = "MenuMapShapeDisplay"; resources.ApplyResources(this.MenuMapShapeDisplay, "MenuMapShapeDisplay"); this.MenuMapShapeDisplay.Click += new System.EventHandler(this.ToolStripShapeDisplay_Click); // // toolStripMenuItem6 // this.toolStripMenuItem6.Name = "toolStripMenuItem6"; resources.ApplyResources(this.toolStripMenuItem6, "toolStripMenuItem6"); // // MenuMapInteractionDefault // this.MenuMapInteractionDefault.Checked = true; this.MenuMapInteractionDefault.CheckState = System.Windows.Forms.CheckState.Checked; this.MenuMapInteractionDefault.Image = global::TribalWars.Properties.Resources.DefaultInteraction; this.MenuMapInteractionDefault.Name = "MenuMapInteractionDefault"; resources.ApplyResources(this.MenuMapInteractionDefault, "MenuMapInteractionDefault"); this.MenuMapInteractionDefault.Click += new System.EventHandler(this.MenuMapInteractionDefault_Click); // // MenuMapInteractionPolygon // this.MenuMapInteractionPolygon.Image = global::TribalWars.Properties.Resources.Polygon; this.MenuMapInteractionPolygon.Name = "MenuMapInteractionPolygon"; resources.ApplyResources(this.MenuMapInteractionPolygon, "MenuMapInteractionPolygon"); this.MenuMapInteractionPolygon.Click += new System.EventHandler(this.MenuMapInteractionPolygon_Click); // // MenuMapInteractionPlanAttacks // this.MenuMapInteractionPlanAttacks.Image = global::TribalWars.Properties.Resources.barracks; this.MenuMapInteractionPlanAttacks.Name = "MenuMapInteractionPlanAttacks"; resources.ApplyResources(this.MenuMapInteractionPlanAttacks, "MenuMapInteractionPlanAttacks"); this.MenuMapInteractionPlanAttacks.Click += new System.EventHandler(this.MenuMapInteractionPlanAttacks_Click); // // toolStripMenuItem5 // this.toolStripMenuItem5.Name = "toolStripMenuItem5"; resources.ApplyResources(this.toolStripMenuItem5, "toolStripMenuItem5"); // // MenuMapSelectPane0 // resources.ApplyResources(this.MenuMapSelectPane0, "MenuMapSelectPane0"); this.MenuMapSelectPane0.Name = "MenuMapSelectPane0"; this.MenuMapSelectPane0.Tag = "0"; this.MenuMapSelectPane0.Click += new System.EventHandler(this.MenuMapSelectPane_Click); // // MenuMapSelectPane1 // resources.ApplyResources(this.MenuMapSelectPane1, "MenuMapSelectPane1"); this.MenuMapSelectPane1.Name = "MenuMapSelectPane1"; this.MenuMapSelectPane1.Tag = "1"; this.MenuMapSelectPane1.Click += new System.EventHandler(this.MenuMapSelectPane_Click); // // MenuMapSelectPane2 // resources.ApplyResources(this.MenuMapSelectPane2, "MenuMapSelectPane2"); this.MenuMapSelectPane2.Name = "MenuMapSelectPane2"; this.MenuMapSelectPane2.Tag = "2"; this.MenuMapSelectPane2.Click += new System.EventHandler(this.MenuMapSelectPane_Click); // // MenuMapSelectPane3 // resources.ApplyResources(this.MenuMapSelectPane3, "MenuMapSelectPane3"); this.MenuMapSelectPane3.Name = "MenuMapSelectPane3"; this.MenuMapSelectPane3.Tag = "3"; this.MenuMapSelectPane3.Click += new System.EventHandler(this.MenuMapSelectPane_Click); // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; resources.ApplyResources(this.toolStripMenuItem2, "toolStripMenuItem2"); // // MenuMapScreenshot // this.MenuMapScreenshot.Name = "MenuMapScreenshot"; resources.ApplyResources(this.MenuMapScreenshot, "MenuMapScreenshot"); this.MenuMapScreenshot.Click += new System.EventHandler(this.MenuMapScreenshot_Click); // // MenuMapSeeScreenshots // this.MenuMapSeeScreenshots.Name = "MenuMapSeeScreenshots"; resources.ApplyResources(this.MenuMapSeeScreenshots, "MenuMapSeeScreenshots"); this.MenuMapSeeScreenshots.Click += new System.EventHandler(this.MenuMapSeeScreenshots_Click); // // windowsToolStripMenuItem // this.windowsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuWindowsManageYourVillages, this.MenuWindowsImportVillageCoordinates, this.toolStripMenuItem7, this.MenuWindowsManageYourAttackersPool, this.otherToolStripMenuItem}); this.windowsToolStripMenuItem.Name = "windowsToolStripMenuItem"; resources.ApplyResources(this.windowsToolStripMenuItem, "windowsToolStripMenuItem"); // // MenuWindowsManageYourVillages // this.MenuWindowsManageYourVillages.Name = "MenuWindowsManageYourVillages"; resources.ApplyResources(this.MenuWindowsManageYourVillages, "MenuWindowsManageYourVillages"); this.MenuWindowsManageYourVillages.Click += new System.EventHandler(this.MenuWindowsManageYourVillages_Click); // // MenuWindowsImportVillageCoordinates // this.MenuWindowsImportVillageCoordinates.Name = "MenuWindowsImportVillageCoordinates"; resources.ApplyResources(this.MenuWindowsImportVillageCoordinates, "MenuWindowsImportVillageCoordinates"); this.MenuWindowsImportVillageCoordinates.Click += new System.EventHandler(this.MenuWindowsImportVillageCoordinates_Click); // // toolStripMenuItem7 // this.toolStripMenuItem7.Name = "toolStripMenuItem7"; resources.ApplyResources(this.toolStripMenuItem7, "toolStripMenuItem7"); // // MenuWindowsManageYourAttackersPool // this.MenuWindowsManageYourAttackersPool.Image = global::TribalWars.Properties.Resources.star; this.MenuWindowsManageYourAttackersPool.Name = "MenuWindowsManageYourAttackersPool"; resources.ApplyResources(this.MenuWindowsManageYourAttackersPool, "MenuWindowsManageYourAttackersPool"); this.MenuWindowsManageYourAttackersPool.Click += new System.EventHandler(this.MenuWindowsManageYourAttackersPool_Click); // // otherToolStripMenuItem // this.otherToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuWindowsAddTimes}); this.otherToolStripMenuItem.Name = "otherToolStripMenuItem"; resources.ApplyResources(this.otherToolStripMenuItem, "otherToolStripMenuItem"); // // MenuWindowsAddTimes // this.MenuWindowsAddTimes.Name = "MenuWindowsAddTimes"; resources.ApplyResources(this.MenuWindowsAddTimes, "MenuWindowsAddTimes"); this.MenuWindowsAddTimes.Click += new System.EventHandler(this.MenuWindowsAddTimes_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuHelpReportBug, this.MenuHelpAbout}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; resources.ApplyResources(this.helpToolStripMenuItem, "helpToolStripMenuItem"); // // MenuHelpReportBug // resources.ApplyResources(this.MenuHelpReportBug, "MenuHelpReportBug"); this.MenuHelpReportBug.Name = "MenuHelpReportBug"; this.MenuHelpReportBug.Click += new System.EventHandler(this.MenuHelpReportBug_Click); // // MenuHelpAbout // this.MenuHelpAbout.Name = "MenuHelpAbout"; resources.ApplyResources(this.MenuHelpAbout, "MenuHelpAbout"); this.MenuHelpAbout.Click += new System.EventHandler(this.MenuHelpAbout_Click); // // BottomToolStripPanel // resources.ApplyResources(this.BottomToolStripPanel, "BottomToolStripPanel"); this.BottomToolStripPanel.Name = "BottomToolStripPanel"; this.BottomToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal; this.BottomToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); // // TopToolStripPanel // resources.ApplyResources(this.TopToolStripPanel, "TopToolStripPanel"); this.TopToolStripPanel.Name = "TopToolStripPanel"; this.TopToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal; this.TopToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); // // RightToolStripPanel // resources.ApplyResources(this.RightToolStripPanel, "RightToolStripPanel"); this.RightToolStripPanel.Name = "RightToolStripPanel"; this.RightToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal; this.RightToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); // // LeftToolStripPanel // resources.ApplyResources(this.LeftToolStripPanel, "LeftToolStripPanel"); this.LeftToolStripPanel.Name = "LeftToolStripPanel"; this.LeftToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal; this.LeftToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); // // ContentPanel // this.ContentPanel.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional; resources.ApplyResources(this.ContentPanel, "ContentPanel"); // // VillageTooltip // this.VillageTooltip.AutoPopDelay = 10000; this.VillageTooltip.InitialDelay = 500; this.VillageTooltip.IsBalloon = true; this.VillageTooltip.ReshowDelay = 100; this.VillageTooltip.ShowAlways = true; // // saveFileDialog1 // this.saveFileDialog1.DefaultExt = "sets"; resources.ApplyResources(this.saveFileDialog1, "saveFileDialog1"); this.saveFileDialog1.RestoreDirectory = true; // // MainForm // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.FormToolbarContainer); this.Controls.Add(this.Status); this.Controls.Add(this.MenuBar); this.MainMenuStrip = this.MenuBar; this.Name = "MainForm"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing); this.Load += new System.EventHandler(this.FormMain_Load); this.FormSplitter.Panel1.ResumeLayout(false); this.FormSplitter.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.FormSplitter)).EndInit(); this.FormSplitter.ResumeLayout(false); this.LeftSplitter.Panel1.ResumeLayout(false); this.LeftSplitter.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.LeftSplitter)).EndInit(); this.LeftSplitter.ResumeLayout(false); this.LeftNavigation.ResumeLayout(false); this.LeftNavigation_Location.ResumeLayout(false); this.LeftNavigation_QuickFind.ResumeLayout(false); this.LeftNavigation_Markers.ResumeLayout(false); this.LeftNavigation_Distance.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.Tabs)).EndInit(); this.Tabs.ResumeLayout(false); this.TabsMap.ResumeLayout(false); this.TabsBrowser.ResumeLayout(false); this.TabsPolygon.ResumeLayout(false); this.TabsMonitoring.ResumeLayout(false); this.FormToolbarContainer.ContentPanel.ResumeLayout(false); this.FormToolbarContainer.TopToolStripPanel.ResumeLayout(false); this.FormToolbarContainer.TopToolStripPanel.PerformLayout(); this.FormToolbarContainer.ResumeLayout(false); this.FormToolbarContainer.PerformLayout(); this.ToolStrip.ResumeLayout(false); this.ToolStrip.PerformLayout(); this.Status.ResumeLayout(false); this.Status.PerformLayout(); this.MenuBar.ResumeLayout(false); this.MenuBar.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1; private System.Windows.Forms.ColorDialog PickColor; private System.Windows.Forms.StatusStrip Status; private System.Windows.Forms.Timer ServerTimeTimer; private System.Windows.Forms.ToolStripProgressBar ProgressBar; private System.Windows.Forms.ToolTip GeneralTooltip; private System.Windows.Forms.ToolTip VillageTooltip; private System.Windows.Forms.MenuStrip MenuBar; internal System.Windows.Forms.ToolStripStatusLabel StatusMessage; private System.Windows.Forms.ToolStripStatusLabel StatusServerTime; internal System.Windows.Forms.ToolStripStatusLabel StatusXY; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel5; private System.Windows.Forms.ToolStripPanel BottomToolStripPanel; private System.Windows.Forms.ToolStripPanel TopToolStripPanel; private System.Windows.Forms.ToolStrip ToolStrip; private System.Windows.Forms.ToolStripButton ToolStripOpen; private System.Windows.Forms.ToolStripButton ToolStripSave; private System.Windows.Forms.ToolStripSeparator toolStripSeparator; private System.Windows.Forms.ToolStripButton ToolStripDraw; private System.Windows.Forms.ToolStripPanel RightToolStripPanel; private System.Windows.Forms.ToolStripPanel LeftToolStripPanel; private System.Windows.Forms.ToolStripContentPanel ContentPanel; private System.Windows.Forms.SplitContainer FormSplitter; private System.Windows.Forms.ToolStripContainer FormToolbarContainer; private System.Windows.Forms.ToolStripMenuItem MenuToolstrip; private System.Windows.Forms.ToolStripMenuItem MenuFileNew; private System.Windows.Forms.ToolStripMenuItem MenuFileLoadWorld; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem MenuFileSaveSettings; private System.Windows.Forms.ToolStripMenuItem MenuFileSaveSettingsAs; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem MenuFileExit; private Ascend.Windows.Forms.NavigationPanePage LeftNavigation_Markers; private Ascend.Windows.Forms.NavigationPanePage LeftNavigation_QuickFind; private System.Windows.Forms.ToolStripMenuItem mapToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem MenuMapScreenshot; internal System.Windows.Forms.ToolStripStatusLabel StatusPlayer; internal System.Windows.Forms.ToolStripStatusLabel StatusTribe; internal System.Windows.Forms.ToolStripStatusLabel StatusVillage; private System.Windows.Forms.ToolStripDropDownButton ToolStripSettings; //private Controls.YouTreeold YouTree; private Ascend.Windows.Forms.NavigationPanePage LeftNavigation_Distance; private AttackPlanCollectionControl _attackPlan; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem MenuFileWorldDownload; private Ascend.Windows.Forms.NavigationPanePage LeftNavigation_Location; //private TribalWars.Controls.Accordeon.Location.LocationControl locationControl1; private MarkersControl markersContainerControl1; private MapControl Map; private PolygonControl Polygon; //private TribalWars.Controls.Accordeon.Details.DetailsControl QuickDetails; //private TribalWars.Controls.Main.Monitoring.MonitoringControl monitoringControl1; private BrowserControl browserControl1; private System.Windows.Forms.ToolStripButton ToolStripDownload; private System.Windows.Forms.ToolStripButton ToolStripHome; internal System.Windows.Forms.ToolStripStatusLabel StatusSettings; internal System.Windows.Forms.ToolStripStatusLabel StatusWorld; private Janus.Windows.UI.Tab.UITab Tabs; private Janus.Windows.UI.Tab.UITabPage TabsMap; private Janus.Windows.UI.Tab.UITabPage TabsBrowser; private Janus.Windows.UI.Tab.UITabPage TabsPolygon; private Janus.Windows.UI.Tab.UITabPage TabsMonitoring; private System.Windows.Forms.ToolStripButton ToolStripIconDisplay; private System.Windows.Forms.ToolStripButton ToolStripShapeDisplay; private MiniMapControl MiniMap; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripButton ToolStripDefaultManipulator; private System.Windows.Forms.ToolStripButton ToolStripPolygonManipulator; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private Ascend.Windows.Forms.NavigationPane LeftNavigation; private DetailsControl detailsControl1; private LocationControl locationControl1; private System.Windows.Forms.SaveFileDialog saveFileDialog1; private System.Windows.Forms.ToolStripMenuItem MenuMapSeeScreenshots; private MonitoringControl monitoringControl1; private System.Windows.Forms.ToolStripButton ToolstripButtonCreateWorld; private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.ToolStripButton ToolStripActiveRectangle; private System.Windows.Forms.ToolStripMenuItem MenuFileSynchronizeTime; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripButton ToolStripProgramSettings; private System.Windows.Forms.ToolStripMenuItem MenuFileSetActivePlayer; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem MenuHelpAbout; private System.Windows.Forms.ToolStripButton ToolStripAbout; private System.Windows.Forms.ToolStripMenuItem MenuMapSetHomeLocation; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripButton ToolStripAttackManipulator; private System.Windows.Forms.ToolStripMenuItem MenuMapIconDisplay; private System.Windows.Forms.ToolStripMenuItem MenuMapShapeDisplay; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem5; private System.Windows.Forms.ToolStripMenuItem MenuMapSelectPane0; private System.Windows.Forms.ToolStripMenuItem MenuMapSelectPane1; private System.Windows.Forms.ToolStripMenuItem MenuMapSelectPane2; private System.Windows.Forms.ToolStripMenuItem MenuMapSelectPane3; private System.Windows.Forms.ToolStripMenuItem MenuHelpReportBug; private System.Windows.Forms.SplitContainer LeftSplitter; private System.Windows.Forms.ToolStripMenuItem windowsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem MenuWindowsManageYourVillages; private System.Windows.Forms.ToolStripMenuItem MenuWindowsImportVillageCoordinates; private System.Windows.Forms.ToolStripButton ToolStripChurchManipulator; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem6; private System.Windows.Forms.ToolStripMenuItem MenuMapInteractionDefault; private System.Windows.Forms.ToolStripMenuItem MenuMapInteractionPolygon; private System.Windows.Forms.ToolStripMenuItem MenuMapInteractionPlanAttacks; private System.Windows.Forms.ToolStripStatusLabel StatusDataTime; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem7; private System.Windows.Forms.ToolStripMenuItem otherToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem MenuWindowsAddTimes; private System.Windows.Forms.ToolStripMenuItem MenuMapMonitoringArea; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem8; private Controls.Common.ToolStripControlHostWrappers.ToolStripLocationChangerControl toolStripLocationChangerControl1; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; private System.Windows.Forms.ToolStripMenuItem MenuWindowsManageYourAttackersPool; private System.Windows.Forms.ToolStripMenuItem setLanguageToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem SetLanguage_English; private System.Windows.Forms.ToolStripMenuItem SetLanguage_Dutch; } }
using System; using System.Collections.Generic; using Abp.Application.Services; using Abp.AspNetCore.Configuration; using Abp.Extensions; using Castle.Windsor.MsDependencyInjection; using Abp.Reflection; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.Internal; using Microsoft.Extensions.DependencyInjection; using System.Linq; using System.Reflection; using Abp.Collections.Extensions; using Abp.Web.Api.ProxyScripting.Generators; using JetBrains.Annotations; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace Abp.AspNetCore.Mvc.Conventions { public class AbpAppServiceConvention : IApplicationModelConvention { private readonly Lazy<AbpAspNetCoreConfiguration> _configuration; public AbpAppServiceConvention(IServiceCollection services) { _configuration = new Lazy<AbpAspNetCoreConfiguration>(() => { return services .GetSingletonService<AbpBootstrapper>() .IocManager .Resolve<AbpAspNetCoreConfiguration>(); }, true); } public void Apply(ApplicationModel application) { foreach (var controller in application.Controllers) { var type = controller.ControllerType.AsType(); var configuration = GetControllerSettingOrNull(type); if (typeof(IApplicationService).GetTypeInfo().IsAssignableFrom(type)) { controller.ControllerName = controller.ControllerName.RemovePostFix(ApplicationService.CommonPostfixes); configuration?.ControllerModelConfigurer(controller); ConfigureArea(controller, configuration); ConfigureRemoteService(controller, configuration); } else { var remoteServiceAtt = ReflectionHelper.GetSingleAttributeOrDefault<RemoteServiceAttribute>(type.GetTypeInfo()); if (remoteServiceAtt != null && remoteServiceAtt.IsEnabledFor(type)) { ConfigureRemoteService(controller, configuration); } } } } private void ConfigureArea(ControllerModel controller, [CanBeNull] AbpControllerAssemblySetting configuration) { if (configuration == null) { return; } if (controller.RouteValues.ContainsKey("area")) { return; } controller.RouteValues["area"] = configuration.ModuleName; } private void ConfigureRemoteService(ControllerModel controller, [CanBeNull] AbpControllerAssemblySetting configuration) { ConfigureApiExplorer(controller); ConfigureSelector(controller, configuration); ConfigureParameters(controller); } private void ConfigureParameters(ControllerModel controller) { foreach (var action in controller.Actions) { foreach (var prm in action.Parameters) { if (prm.BindingInfo != null) { continue; } if (!TypeHelper.IsPrimitiveExtendedIncludingNullable(prm.ParameterInfo.ParameterType)) { if (CanUseFormBodyBinding(action, prm)) { prm.BindingInfo = BindingInfo.GetBindingInfo(new[] { new FromBodyAttribute() }); } } } } } private bool CanUseFormBodyBinding(ActionModel action, ParameterModel parameter) { if (_configuration.Value.FormBodyBindingIgnoredTypes.Any(t => t.IsAssignableFrom(parameter.ParameterInfo.ParameterType))) { return false; } foreach (var selector in action.Selectors) { if (selector.ActionConstraints == null) { continue; } foreach (var actionConstraint in selector.ActionConstraints) { var httpMethodActionConstraint = actionConstraint as HttpMethodActionConstraint; if (httpMethodActionConstraint == null) { continue; } if (httpMethodActionConstraint.HttpMethods.All(hm => hm.IsIn("GET", "DELETE", "TRACE", "HEAD"))) { return false; } } } return true; } private void ConfigureApiExplorer(ControllerModel controller) { if (controller.ApiExplorer.GroupName.IsNullOrEmpty()) { controller.ApiExplorer.GroupName = controller.ControllerName; } if (controller.ApiExplorer.IsVisible == null) { var controllerType = controller.ControllerType.AsType(); var remoteServiceAtt = ReflectionHelper.GetSingleAttributeOrDefault<RemoteServiceAttribute>(controllerType.GetTypeInfo()); if (remoteServiceAtt != null) { controller.ApiExplorer.IsVisible = remoteServiceAtt.IsEnabledFor(controllerType) && remoteServiceAtt.IsMetadataEnabledFor(controllerType); } else { controller.ApiExplorer.IsVisible = true; } } foreach (var action in controller.Actions) { ConfigureApiExplorer(action); } } private void ConfigureApiExplorer(ActionModel action) { if (action.ApiExplorer.IsVisible == null) { var remoteServiceAtt = ReflectionHelper.GetSingleAttributeOrDefault<RemoteServiceAttribute>(action.ActionMethod); if (remoteServiceAtt != null) { action.ApiExplorer.IsVisible = remoteServiceAtt.IsEnabledFor(action.ActionMethod) && remoteServiceAtt.IsMetadataEnabledFor(action.ActionMethod); } } } private void ConfigureSelector(ControllerModel controller, [CanBeNull] AbpControllerAssemblySetting configuration) { RemoveEmptySelectors(controller.Selectors); if (controller.Selectors.Any(selector => selector.AttributeRouteModel != null)) { return; } var moduleName = GetModuleNameOrDefault(controller.ControllerType.AsType()); foreach (var action in controller.Actions) { ConfigureSelector(moduleName, controller.ControllerName, action, configuration); } } private void ConfigureSelector(string moduleName, string controllerName, ActionModel action, [CanBeNull] AbpControllerAssemblySetting configuration) { RemoveEmptySelectors(action.Selectors); var remoteServiceAtt = ReflectionHelper.GetSingleAttributeOrDefault<RemoteServiceAttribute>(action.ActionMethod); if (remoteServiceAtt != null && !remoteServiceAtt.IsEnabledFor(action.ActionMethod)) { return; } if (!action.Selectors.Any()) { AddAbpServiceSelector(moduleName, controllerName, action, configuration); } else { NormalizeSelectorRoutes(moduleName, controllerName, action); } } private void AddAbpServiceSelector(string moduleName, string controllerName, ActionModel action, [CanBeNull] AbpControllerAssemblySetting configuration) { var abpServiceSelectorModel = new SelectorModel { AttributeRouteModel = CreateAbpServiceAttributeRouteModel(moduleName, controllerName, action) }; var verb = configuration?.UseConventionalHttpVerbs == true ? ProxyScriptingHelper.GetConventionalVerbForMethodName(action.ActionName) : ProxyScriptingHelper.DefaultHttpVerb; abpServiceSelectorModel.ActionConstraints.Add(new HttpMethodActionConstraint(new[] { verb })); action.Selectors.Add(abpServiceSelectorModel); } private static void NormalizeSelectorRoutes(string moduleName, string controllerName, ActionModel action) { foreach (var selector in action.Selectors) { if (selector.AttributeRouteModel == null) { selector.AttributeRouteModel = CreateAbpServiceAttributeRouteModel( moduleName, controllerName, action ); } } } private string GetModuleNameOrDefault(Type controllerType) { return GetControllerSettingOrNull(controllerType)?.ModuleName ?? AbpControllerAssemblySetting.DefaultServiceModuleName; } [CanBeNull] private AbpControllerAssemblySetting GetControllerSettingOrNull(Type controllerType) { return _configuration.Value.ControllerAssemblySettings.GetSettingOrNull(controllerType); } private static AttributeRouteModel CreateAbpServiceAttributeRouteModel(string moduleName, string controllerName, ActionModel action) { return new AttributeRouteModel( new RouteAttribute( $"api/services/{moduleName}/{controllerName}/{action.ActionName}" ) ); } private static void RemoveEmptySelectors(IList<SelectorModel> selectors) { selectors .Where(IsEmptySelector) .ToList() .ForEach(s => selectors.Remove(s)); } private static bool IsEmptySelector(SelectorModel selector) { return selector.AttributeRouteModel == null && selector.ActionConstraints.IsNullOrEmpty(); } } }
using System; using System.Linq; using Xunit; using Yeast.Features.Abstractions; using Yeast.Features.Tests.Mocks; namespace Yeast.Features.Tests { public class FeatureManagerBuilderTests { [Fact] public void MergesProvidedFeatures() { // Arrange var builder = new FeatureManagerBuilder(); var featureA = new MockFeatureInfo("FeatureA"); var featureB = new MockFeatureInfo("FeatureB"); // Act builder.AddFeatureProvider(new MockFeatureProvider { Features = new[] { featureA } }); builder.AddFeatureProvider(new MockFeatureProvider { Features = new[] { featureB } }); var manager = builder.Build(); // Assert Assert.Equal(2, manager.AvailableFeatures.Count()); Assert.Contains(featureA, manager.AvailableFeatures); Assert.Contains(featureB, manager.AvailableFeatures); } [Fact] public void EnablesFeaturesByName() { // Arrange var builder = new FeatureManagerBuilder(); var featureA = new MockFeatureInfo("FeatureA"); var featureB = new MockFeatureInfo("FeatureB"); var featureC = new MockFeatureInfo("FeatureC"); // Act builder.AddFeatureProvider(new MockFeatureProvider { Features = new[] { featureA, featureB, featureC } }); builder.EnableFeature(featureA.Name); builder.EnableFeature(featureB.Name); var manager = builder.Build(); // Assert Assert.Equal(2, manager.EnabledFeatures.Count()); Assert.Contains(featureA, manager.EnabledFeatures); Assert.Contains(featureB, manager.EnabledFeatures); Assert.DoesNotContain(featureC, manager.EnabledFeatures); } [Fact] public void EnablesFeaturesByInstance() { // Arrange var builder = new FeatureManagerBuilder(); var featureA = new MockFeatureInfo("FeatureA"); var featureB = new MockFeatureInfo("FeatureB"); var featureC = new MockFeatureInfo("FeatureC"); // Act builder.AddFeatureProvider(new MockFeatureProvider { Features = new[] { featureA, featureB, featureC } }); builder.EnableFeature(featureA); builder.EnableFeature(featureB); var manager = builder.Build(); // Assert Assert.Equal(2, manager.EnabledFeatures.Count()); Assert.Contains(featureA, manager.EnabledFeatures); Assert.Contains(featureB, manager.EnabledFeatures); Assert.DoesNotContain(featureC, manager.EnabledFeatures); } [Fact] public void EnablesFeaturesByType() { // Arrange var builder = new FeatureManagerBuilder(); var featureA = new MockFeatureInfo("FeatureA"); var featureB = new MockInheritedFeatureInfo("FeatureB"); var featureC = new MockInheritedFeatureInfoWithInterface("FeatureC"); // Act builder.AddFeatureProvider(new MockFeatureProvider { Features = new[] { featureA, featureB, featureC } }); builder.EnableFeature(typeof(MockInheritedFeatureInfo)); var manager = builder.Build(); // Assert Assert.Equal(1, manager.EnabledFeatures.Count()); Assert.DoesNotContain(featureA, manager.EnabledFeatures); Assert.Contains(featureB, manager.EnabledFeatures); Assert.DoesNotContain(featureC, manager.EnabledFeatures); } [Fact] public void EnablesFeaturesByInterface() { // Arrange var builder = new FeatureManagerBuilder(); var featureA = new MockFeatureInfo("FeatureA"); var featureB = new MockInheritedFeatureInfo("FeatureB"); var featureC = new MockInheritedFeatureInfoWithInterface("FeatureC"); // Act builder.AddFeatureProvider(new MockFeatureProvider { Features = new[] { featureA, featureB, featureC } }); builder.EnableFeature(typeof(IMockInheritedFeatureInfo)); var manager = builder.Build(); // Assert Assert.Equal(1, manager.EnabledFeatures.Count()); Assert.DoesNotContain(featureA, manager.EnabledFeatures); Assert.DoesNotContain(featureB, manager.EnabledFeatures); Assert.Contains(featureC, manager.EnabledFeatures); } public static TheoryData<FeatureInfo[], Action<IFeatureManagerBuilder>> ThrowsOnUnavailableFeaturesData { get { return new TheoryData<FeatureInfo[], Action<IFeatureManagerBuilder>>() { { new [] { new MockFeatureInfo("FeatureA"), new MockFeatureInfo("FeatureB") }, (builder) => builder.EnableFeature("Foo") }, { new [] { new MockFeatureInfo("FeatureA"), new MockFeatureInfo("FeatureB") }, (builder) => builder.EnableFeature(new MockFeatureInfo("FeatureA")) }, { new [] { new MockFeatureInfo("FeatureA"), new MockFeatureInfo("FeatureB") }, (builder) => builder.EnableFeature(typeof(MockInheritedFeatureInfo)) }, { new [] { new MockFeatureInfo("FeatureA"), new MockFeatureInfo("FeatureB") }, (builder) => builder.EnableFeature(typeof(IMockInheritedFeatureInfo)) } }; } } [Theory] [MemberData(nameof(ThrowsOnUnavailableFeaturesData))] public void ThrowsOnUnavailableFeatures(FeatureInfo[] availableFeatures, Action<IFeatureManagerBuilder> enableAction) { // Arrange var builder = new FeatureManagerBuilder(); // Act builder.AddFeatureProvider(new MockFeatureProvider { Features = availableFeatures }); enableAction.Invoke(builder); Action buildAction = () => builder.Build(); // Assert Assert.Throws<InvalidOperationException>(buildAction); } [Fact] public void RemovesProvidedFeaturesDuplicates() { // Arrange var builder = new FeatureManagerBuilder(); var featureA = new MockFeatureInfo("FeatureA"); // Act builder.AddFeatureProvider(new MockFeatureProvider { Features = new[] { featureA } }); builder.AddFeatureProvider(new MockFeatureProvider { Features = new[] { featureA } }); var manager = builder.Build(); // Assert Assert.Equal(1, manager.AvailableFeatures.Count()); Assert.Contains(featureA, manager.AvailableFeatures); } [Fact] public void DontCreatesEnabledFeaturesDuplicates() { // Arrange var builder = new FeatureManagerBuilder(); var featureA = new MockFeatureInfo("FeatureA"); // Act builder.AddFeatureProvider(new MockFeatureProvider { Features = new[] { featureA } }); builder.EnableFeature(featureA.Name); builder.EnableFeature(featureA.Name); var manager = builder.Build(); // Assert Assert.Equal(1, manager.EnabledFeatures.Count()); Assert.Same(featureA, manager.EnabledFeatures.First()); } [Fact] public void SortsFeaturesByPriority() { // Arrange var builder = new FeatureManagerBuilder(); var featureA = new MockFeatureInfo("FeatureA", 0); var featureB = new MockFeatureInfo("FeatureB", 10); var featureC = new MockFeatureInfo("FeatureC", -10); // Act builder.AddFeatureProvider(new MockFeatureProvider { Features = new[] { featureA, featureB, featureC } }); builder.EnableFeature(featureC.Name); builder.EnableFeature(featureB.Name); var manager = builder.Build(); // Assert Assert.Equal(new[] { featureB, featureA, featureC }, manager.AvailableFeatures); Assert.Equal(new[] { featureB, featureC }, manager.EnabledFeatures); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Linq; using System.Collections.Generic; using System.Text; using Microsoft.Test.ModuleCore; using Xunit; namespace System.Xml.Linq.Tests { public class RegressionTests { [Fact] public void XPIEmptyStringShouldNotBeAllowed() { var pi = new XProcessingInstruction("PI", "data"); Assert.Throws<ArgumentNullException>(() => pi.Target = string.Empty); } [Fact] public void RemovingMixedContent() { XElement a = XElement.Parse(@"<A>t1<B/>t2</A>"); a.Nodes().Skip(1).Remove(); Assert.Equal("<A>t1</A>", a.ToString(SaveOptions.DisableFormatting)); } [Fact] public void CannotParseDTD() { string xml = "<!DOCTYPE x []><x/>"; XElement e = XElement.Parse(xml); Assert.Equal("<x />", e.ToString(SaveOptions.DisableFormatting)); } //[Variation(Desc = "Replace content")] public void ReplaceContent() { XElement a = XElement.Parse("<A><B><C/></B></A>"); a.Element("B").ReplaceNodes(a.Nodes()); XElement x = a; foreach (string s in (new string[] { "A", "B", "B" })) { TestLog.Compare(x.Name.LocalName, s, s); x = x.FirstNode as XElement; } } [Fact] public void DuplicateNamespaceDeclarationIsAllowed() { XElement element = XElement.Parse("<A xmlns:p='ns'/>"); Assert.Throws<InvalidOperationException>(() => element.Add(new XAttribute(XNamespace.Xmlns + "p", "ns"))); } [Fact] public void ManuallyDeclaredPrefixNamespacePairIsNotReflectedInTheXElementSerialization() { var element = XElement.Parse("<A/>"); element.Add(new XAttribute(XNamespace.Xmlns + "p", "ns")); element.Add(new XElement("{ns}B", null)); MemoryStream sourceStream = new MemoryStream(); element.Save(sourceStream); sourceStream.Position = 0; // creating the following element with expected output so we can compare XElement target = XElement.Parse("<A xmlns:p=\"ns\"><p:B /></A>"); MemoryStream targetStream = new MemoryStream(); target.Save(targetStream); targetStream.Position = 0; XmlDiff.XmlDiff diff = new XmlDiff.XmlDiff(); Assert.True(diff.Compare(sourceStream, targetStream)); } [Fact] public void XNameGetDoesThrowWhenPassingNulls1() { Assert.Throws<ArgumentNullException>(() => XName.Get(null, null)); } [Fact] public void XNameGetDoesThrowWhenPassingNulls2() { Assert.Throws<ArgumentNullException>(() => XName.Get(null, "MyName")); } [Fact] public void HashingNamePartsShouldBeSameAsHashingExpandedNameWhenUsingNamespaces() { // shouldn't throw XElement element1 = new XElement( XName.Get("e1", "ns1"), "e1 should be in \"ns1\"", new XElement( XName.Get("e2", "ns-default1"), "e2 should be in ns-default1", new XElement( XName.Get("e3", "ns-default2"), "e3 should be in ns-default2", new XElement(XName.Get("e4", "ns2"), "e4 should be in ns2")))); } [Fact] public void CreatingNewXElementsPassingNullReaderAndOrNullXNameShouldThrow() { Assert.Throws<ArgumentNullException>(() => new XElement((XName)null)); Assert.Throws<ArgumentNullException>(() => (XElement)XNode.ReadFrom((XmlReader)null)); } [Fact] public void XNodeAddBeforeSelfPrependingTextNodeToTextNodeDoesDisconnectTheOriginalNode() { XElement e = new XElement("e1", new XElement("e2"), "text1", new XElement("e3")); XNode t = e.FirstNode.NextNode; t.AddBeforeSelf("text2"); t.AddBeforeSelf("text3"); Assert.Equal("text2text3text1", e.Value); } [Fact] public void ReadSubtreeOnXReaderThrows() { XElement xe = new XElement( "root", new XElement("A", new XElement("B", "data")), new XProcessingInstruction("PI", "joke")); using (XmlReader r = xe.CreateReader()) { r.Read(); r.Read(); using (XmlReader subR = r.ReadSubtree()) { subR.Read(); } } } [Fact] public void StackOverflowForDeepNesting() { StringBuilder sb = new StringBuilder(); for (long l = 0; l < 6600; l++) sb.Append("<A>"); sb.Append("<A/>"); for (long l = 0; l < 6600; l++) sb.Append("</A>"); XElement e = XElement.Parse(sb.ToString()); } [Fact] public void EmptyCDataTextNodeIsNotPreservedInTheTree() { // The Empty CData text node is not preserved in the tree XDocument d = XDocument.Parse("<root><![CDATA[]]></root>"); Assert.Equal(1, d.Element("root").Nodes().Count()); Assert.IsType<XCData>(d.Root.FirstNode); Assert.Equal(string.Empty, (d.Root.FirstNode as XCData).Value); } [Fact] public void XDocumentToStringThrowsForXDocumentContainingOnlyWhitespaceNodes() { // XDocument.ToString() throw exception for the XDocument containing whitespace node only XDocument d = new XDocument(); d.Add(" "); string s = d.ToString(); } [Fact] public void NametableReturnsIncorrectXNamespace() { XNamespace ns = XNamespace.Get("h"); Assert.NotSame(XNamespace.Xml, ns); } [Fact] public void XmlNamespaceSerialization() { // shouldn't throw XElement e = new XElement( "a", new XAttribute(XNamespace.Xmlns.GetName("ns"), "def"), new XElement( "b", new XAttribute(XNamespace.Xmlns.GetName("ns1"), "def"), new XElement("{def}c", new XAttribute(XNamespace.Xmlns.GetName("ns1"), "abc")))); } [Theory] [MemberData("GetObjects")] public void CreatingXElementsFromNewDev10Types(object t, Type type) { XElement e = new XElement("e1", new XElement("e2"), "text1", new XElement("e3"), t); e.Add(t); e.FirstNode.ReplaceWith(t); XNode n = e.FirstNode.NextNode; n.AddBeforeSelf(t); n.AddAnnotation(t); n.ReplaceWith(t); e.FirstNode.AddAfterSelf(t); e.AddFirst(t); e.Annotation(type); e.Annotations(type); e.RemoveAnnotations(type); e.ReplaceAll(t); e.ReplaceAttributes(t); e.ReplaceNodes(t); e.SetAttributeValue("a", t); e.SetElementValue("e2", t); e.SetValue(t); XAttribute a = new XAttribute("a", t); XStreamingElement se = new XStreamingElement("se", t); se.Add(t); Assert.Throws<ArgumentException>(() => new XDocument(t)); Assert.Throws<ArgumentException>(() => new XDocument(t)); } public static IEnumerable<object[]> GetObjects() { var d = new Dictionary<int, string>(); d.Add(7, "a"); yield return new object[] { Tuple.Create(1, "Melitta", 7.5), typeof(Tuple) }; yield return new object[] { new Guid(), typeof(Guid) }; yield return new object[] { d, typeof(Dictionary<int, string>) }; } } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors using System; using System.Collections.Generic; using System.Text; using Generator.Enums; using Generator.IO; namespace Generator.Documentation.Python { sealed class PythonDocCommentWriter : DocCommentWriter { const string PYTHON_PACKAGE_NAME = "iced_x86"; readonly IdentifierConverter idConverter; readonly bool isInRootModule; readonly string typeSeparator; readonly StringBuilder sb; readonly string linePrefix; readonly bool pythonDocComments; int summaryLineNumber; bool hasColonText; static readonly Dictionary<string, string> toTypeInfo = new Dictionary<string, string>(StringComparer.Ordinal) { { "bcd", "bcd" }, { "bf16", "bfloat16" }, { "f16", "f16" }, { "f32", "f32" }, { "f64", "f64" }, { "f80", "f80" }, { "f128", "f128" }, { "i8", "i8" }, { "i16", "i16" }, { "i32", "i32" }, { "i64", "i64" }, { "i128", "i128" }, { "i256", "i256" }, { "i512", "i512" }, { "u8", "u8" }, { "u16", "u16" }, { "u32", "u32" }, { "u52", "u52" }, { "u64", "u64" }, { "u128", "u128" }, { "u256", "u256" }, { "u512", "u512" }, }; public PythonDocCommentWriter(IdentifierConverter idConverter, TargetLanguage language, bool isInRootModule, string typeSeparator = ".") { this.idConverter = idConverter; this.isInRootModule = isInRootModule; this.typeSeparator = typeSeparator; sb = new StringBuilder(); switch (language) { case TargetLanguage.Python: linePrefix = string.Empty; pythonDocComments = true; break; case TargetLanguage.Rust: linePrefix = "/// "; pythonDocComments = false; break; default: throw new InvalidOperationException(); } } string GetStringAndReset() { while (sb.Length > 0 && char.IsWhiteSpace(sb[^1])) sb.Length--; var s = sb.ToString(); sb.Clear(); return s; } static string Escape(string s) { s = s.Replace(@"\", @"\\"); s = s.Replace("`", @"\`"); s = s.Replace("\"", @"\"""); s = s.Replace("*", @"\*"); return s; } void RawWriteWithComment(FileWriter writer, bool writeEmpty = true) { var s = GetStringAndReset(); if (s.Length == 0 && !writeEmpty) return; if (summaryLineNumber == 0 && hasColonText) { // The first line has type info and it's everything before the colon s = ": " + s; } s = (linePrefix + s).TrimEnd(); summaryLineNumber++; hasColonText = false; if (s.Length == 0) writer.WriteLineNoIndent(s); else writer.WriteLine(s); } public void BeginWrite(FileWriter writer) { if (sb.Length != 0) throw new InvalidOperationException(); if (pythonDocComments) writer.WriteLine(@""""""""); } public void EndWrite(FileWriter writer) { RawWriteWithComment(writer, false); if (pythonDocComments) writer.WriteLine(@""""""""); } public void WriteSummary(FileWriter writer, string? documentation, string typeName) { if (string.IsNullOrEmpty(documentation)) return; summaryLineNumber = 0; hasColonText = false; BeginWrite(writer); WriteDoc(writer, documentation, typeName); EndWrite(writer); } public void Write(string text) => sb.Append(text); public void WriteLine(FileWriter writer, string text) { Write(text); RawWriteWithComment(writer); } public void WriteDocLine(FileWriter writer, string text, string typeName) { WriteDoc(writer, text, typeName); RawWriteWithComment(writer); } void WriteDoc(FileWriter writer, string documentation, string typeName) { foreach (var info in GetTokens(typeName, documentation)) { string t, m; switch (info.kind) { case TokenKind.NewParagraph: if (!string.IsNullOrEmpty(info.value) && !string.IsNullOrEmpty(info.value2)) throw new InvalidOperationException(); RawWriteWithComment(writer); RawWriteWithComment(writer); break; case TokenKind.String: hasColonText |= info.value.Contains(':', StringComparison.Ordinal); sb.Append(Escape(info.value)); if (!string.IsNullOrEmpty(info.value2)) throw new InvalidOperationException(); break; case TokenKind.Code: sb.Append("``"); sb.Append(info.value); sb.Append("``"); if (!string.IsNullOrEmpty(info.value2)) throw new InvalidOperationException(); break; case TokenKind.PrimitiveType: if (!toTypeInfo.TryGetValue(info.value, out var type)) throw new InvalidOperationException($"Unknown type '{info.value}, comment: {documentation}"); sb.Append("``"); sb.Append(idConverter.Type(type)); sb.Append("``"); if (!string.IsNullOrEmpty(info.value2)) throw new InvalidOperationException(); break; case TokenKind.Type: sb.Append(":class:`"); if (!isInRootModule && info.value != typeName) sb.Append(PYTHON_PACKAGE_NAME + "."); t = RemoveNamespace(idConverter.Type(info.value)); sb.Append(t); sb.Append('`'); if (!string.IsNullOrEmpty(info.value2)) throw new InvalidOperationException(); break; case TokenKind.EnumFieldReference: case TokenKind.FieldReference: sb.Append(":class:`"); WriteTypeName(typeName, info.value); if (info.kind == TokenKind.EnumFieldReference) { if (PythonUtils.UppercaseEnum(info.value)) m = info.value2.ToUpperInvariant(); else m = idConverter.EnumField(info.value2); } else m = idConverter.Field(info.value2); sb.Append(m); sb.Append('`'); break; case TokenKind.Property: sb.Append(":class:`"); WriteTypeName(typeName, info.value); m = TranslatePropertyName(info.value, idConverter.PropertyDoc(info.value2)); sb.Append(m); sb.Append('`'); break; case TokenKind.Method: sb.Append(":class:`"); WriteTypeName(typeName, info.value); m = idConverter.MethodDoc(TranslateMethodName(info.value2)); sb.Append(m); sb.Append('`'); break; default: throw new InvalidOperationException(); } } } static string TranslatePropertyName(string typeName, string propertyName) { if (typeName == "Instruction" && propertyName == "memory_displacement64") propertyName = "memory_displacement"; return propertyName; } void WriteTypeName(string thisTypeName, string currentTypeName) { if (!isInRootModule && currentTypeName != thisTypeName) sb.Append(PYTHON_PACKAGE_NAME + "."); if (currentTypeName != thisTypeName) { sb.Append(idConverter.Type(currentTypeName)); sb.Append(typeSeparator); } } } }
// 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; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests.LegacyTests { public class SelectManyTests : EnumerableTests { [Fact] public void EmptySource() { Assert.Empty(Enumerable.Empty<StringWithIntArray>().SelectMany(e => e.total)); } [Fact] public void EmptySourceIndexedSelector() { Assert.Empty(Enumerable.Empty<StringWithIntArray>().SelectMany((e, i) => e.total)); } [Fact] public void EmptySourceResultSelector() { Assert.Empty(Enumerable.Empty<StringWithIntArray>().SelectMany(e => e.total, (e, f) => f.ToString())); } [Fact] public void EmptySourceResultSelectorIndexedSelector() { Assert.Empty(Enumerable.Empty<StringWithIntArray>().SelectMany((e, i) => e.total, (e, f) => f.ToString())); } [Fact] public void SingleElement() { int?[] expected = { 90, 55, null, 43, 89 }; StringWithIntArray[] source = { new StringWithIntArray { name = "Prakash", total = expected } }; Assert.Equal(expected, source.SelectMany(e => e.total)); } [Fact] public void NonEmptySelectingEmpty() { StringWithIntArray[] source = { new StringWithIntArray { name="Prakash", total=new int?[0] }, new StringWithIntArray { name="Bob", total=new int?[0] }, new StringWithIntArray { name="Chris", total=new int?[0] }, new StringWithIntArray { name=null, total=new int?[0] }, new StringWithIntArray { name="Prakash", total=new int?[0] } }; Assert.Empty(source.SelectMany(e => e.total)); } [Fact] public void NonEmptySelectingEmptyIndexedSelector() { StringWithIntArray[] source = { new StringWithIntArray { name="Prakash", total=new int?[0] }, new StringWithIntArray { name="Bob", total=new int?[0] }, new StringWithIntArray { name="Chris", total=new int?[0] }, new StringWithIntArray { name=null, total=new int?[0] }, new StringWithIntArray { name="Prakash", total=new int?[0] } }; Assert.Empty(source.SelectMany((e, i) => e.total)); } [Fact] public void NonEmptySelectingEmptyWithResultSelector() { StringWithIntArray[] source = { new StringWithIntArray { name="Prakash", total=new int?[0] }, new StringWithIntArray { name="Bob", total=new int?[0] }, new StringWithIntArray { name="Chris", total=new int?[0] }, new StringWithIntArray { name=null, total=new int?[0] }, new StringWithIntArray { name="Prakash", total=new int?[0] } }; Assert.Empty(source.SelectMany(e => e.total, (e, f) => f.ToString())); } [Fact] public void NonEmptySelectingEmptyIndexedSelectorWithResultSelector() { StringWithIntArray[] source = { new StringWithIntArray { name="Prakash", total=new int?[0] }, new StringWithIntArray { name="Bob", total=new int?[0] }, new StringWithIntArray { name="Chris", total=new int?[0] }, new StringWithIntArray { name=null, total=new int?[0] }, new StringWithIntArray { name="Prakash", total=new int?[0] } }; Assert.Empty(source.SelectMany((e, i) => e.total, (e, f) => f.ToString())); } [Fact] public void ResultsSelected() { StringWithIntArray[] source = { new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} }, new StringWithIntArray { name="Bob", total=new int?[]{5, 6} }, new StringWithIntArray { name="Chris", total=new int?[0] }, new StringWithIntArray { name=null, total=new int?[]{8, 9} }, new StringWithIntArray { name="Prakash", total=new int?[]{-10, 100} } }; int?[] expected = { 1, 2, 3, 4, 5, 6, 8, 9, -10, 100 }; Assert.Equal(expected, source.SelectMany(e => e.total)); } [Fact] public void SourceEmptyIndexUsed() { Assert.Empty(Enumerable.Empty<StringWithIntArray>().SelectMany((e, index) => e.total)); } [Fact] public void SingleElementIndexUsed() { int?[] expected = { 90, 55, null, 43, 89 }; StringWithIntArray[] source = { new StringWithIntArray { name = "Prakash", total = expected } }; Assert.Equal(expected, source.SelectMany((e, index) => e.total)); } [Fact] public void NonEmptySelectingEmptyIndexUsed() { StringWithIntArray[] source = { new StringWithIntArray { name="Prakash", total= new int?[0] }, new StringWithIntArray { name="Bob", total=new int?[0] }, new StringWithIntArray { name="Chris", total=new int?[0] }, new StringWithIntArray { name=null, total=new int?[0] }, new StringWithIntArray { name="Prakash", total=new int?[0] } }; Assert.Empty(source.SelectMany((e, index) => e.total)); } [Fact] public void ResultsSelectedIndexUsed() { StringWithIntArray[] source = { new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} }, new StringWithIntArray { name="Bob", total=new int?[]{5, 6} }, new StringWithIntArray { name="Chris", total=new int?[0] }, new StringWithIntArray { name=null, total=new int?[]{8, 9} }, new StringWithIntArray { name="Prakash", total=new int?[]{-10, 100} } }; int?[] expected = { 1, 2, 3, 4, 5, 6, 8, 9, -10, 100 }; Assert.Equal(expected, source.SelectMany((e, index) => e.total)); } [Fact] public void IndexCausingFirstToBeSelected() { StringWithIntArray[] source = { new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} }, new StringWithIntArray { name="Bob", total=new int?[]{5, 6} }, new StringWithIntArray { name="Chris", total=new int?[0] }, new StringWithIntArray { name=null, total=new int?[]{8, 9} }, new StringWithIntArray { name="Prakash", total=new int?[]{-10, 100} } }; Assert.Equal(source.First().total, source.SelectMany((e, i) => i == 0 ? e.total : Enumerable.Empty<int?>())); } [Fact] public void IndexCausingLastToBeSelected() { StringWithIntArray[] source = { new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} }, new StringWithIntArray { name="Bob", total=new int?[]{5, 6} }, new StringWithIntArray { name="Chris", total=new int?[0] }, new StringWithIntArray { name=null, total=new int?[]{8, 9} }, new StringWithIntArray { name="Robert", total=new int?[]{-10, 100} } }; Assert.Equal(source.Last().total, source.SelectMany((e, i) => i == 4 ? e.total : Enumerable.Empty<int?>())); } [Fact] [OuterLoop] public void IndexOverflow() { var selected = new FastInfiniteEnumerator<int>().SelectMany((e, i) => Enumerable.Empty<int>()); using (var en = selected.GetEnumerator()) Assert.Throws<OverflowException>(() => { while(en.MoveNext()) { } }); } [Fact] public void ResultSelector() { StringWithIntArray[] source = { new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} }, new StringWithIntArray { name="Bob", total=new int?[]{5, 6} }, new StringWithIntArray { name="Chris", total=new int?[0] }, new StringWithIntArray { name=null, total=new int?[]{8, 9} }, new StringWithIntArray { name="Prakash", total=new int?[]{-10, 100} } }; string[] expected = { "1", "2", "3", "4", "5", "6", "8", "9", "-10", "100" }; Assert.Equal(expected, source.SelectMany(e => e.total, (e, f) => f.ToString())); } [Fact] public void NullResultSelector() { Func<StringWithIntArray, int?, string> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => Enumerable.Empty<StringWithIntArray>().SelectMany(e => e.total, resultSelector)); } [Fact] public void NullResultSelectorIndexedSelector() { Func<StringWithIntArray, int?, string> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => Enumerable.Empty<StringWithIntArray>().SelectMany((e, i) => e.total, resultSelector)); } [Fact] public void NullSourceWithResultSelector() { StringWithIntArray[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.SelectMany(e => e.total, (e, f) => f.ToString())); } [Fact] public void NullCollectionSelector() { Func<StringWithIntArray, IEnumerable<int?>> collectionSelector = null; Assert.Throws<ArgumentNullException>("collectionSelector", () => Enumerable.Empty<StringWithIntArray>().SelectMany(collectionSelector, (e, f) => f.ToString())); } [Fact] public void NullIndexedCollectionSelector() { Func<StringWithIntArray, int, IEnumerable<int?>> collectionSelector = null; Assert.Throws<ArgumentNullException>("collectionSelector", () => Enumerable.Empty<StringWithIntArray>().SelectMany(collectionSelector, (e, f) => f.ToString())); } [Fact] public void NullSource() { StringWithIntArray[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.SelectMany(e => e.total)); } [Fact] public void NullSourceIndexedSelector() { StringWithIntArray[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.SelectMany((e, i) => e.total)); } [Fact] public void NullSourceIndexedSelectorWithResultSelector() { StringWithIntArray[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.SelectMany((e, i) => e.total, (e, f) => f.ToString())); } [Fact] public void NullSelector() { Func<StringWithIntArray, int[]> selector = null; Assert.Throws<ArgumentNullException>("selector", () => new StringWithIntArray[0].SelectMany(selector)); } [Fact] public void NullIndexedSelector() { Func<StringWithIntArray, int, int[]> selector = null; Assert.Throws<ArgumentNullException>("selector", () => new StringWithIntArray[0].SelectMany(selector)); } [Fact] public void IndexCausingFirstToBeSelectedWithResultSelector() { StringWithIntArray[] source = { new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} }, new StringWithIntArray { name="Bob", total=new int?[]{5, 6} }, new StringWithIntArray { name="Chris", total=new int?[0] }, new StringWithIntArray { name=null, total=new int?[]{8, 9} }, new StringWithIntArray { name="Prakash", total=new int?[]{-10, 100} } }; string[] expected = { "1", "2", "3", "4" }; Assert.Equal(expected, source.SelectMany((e, i) => i == 0 ? e.total : Enumerable.Empty<int?>(), (e, f) => f.ToString())); } [Fact] public void IndexCausingLastToBeSelectedWithResultSelector() { StringWithIntArray[] source = { new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} }, new StringWithIntArray { name="Bob", total=new int?[]{5, 6} }, new StringWithIntArray { name="Chris", total=new int?[0] }, new StringWithIntArray { name=null, total=new int?[]{8, 9} }, new StringWithIntArray { name="Robert", total=new int?[]{-10, 100} } }; string[] expected = { "-10", "100" }; Assert.Equal(expected, source.SelectMany((e, i) => i == 4 ? e.total : Enumerable.Empty<int?>(), (e, f) => f.ToString())); } [Fact] public void ForcedToEnumeratorDoesntEnumerate() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).SelectMany(i => new int[0]); // Don't insist on this behaviour, but check its correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateIndexed() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).SelectMany((e, i) => new int[0]); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateResultSel() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).SelectMany(i => new int[0], (e, i) => e); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateIndexedResultSel() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).SelectMany((e, i) => new int[0], (e, i) => e); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } } }
// Copyright (C) 2009-2017 Luca Piccioni // // 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.Diagnostics; using System.Runtime.InteropServices; namespace OpenGL.Objects { /// <summary> /// Generic image. /// </summary> public class Image : Resource, IMedia<ImageInfo> { #region Constructors /// <summary> /// Default constructor. /// </summary> public Image() { } /// <summary> /// Construct an image. /// </summary> /// <param name="format"> /// A <see cref="PixelLayout"/> indicating the image pixel format. /// </param> /// <param name="width"> /// A <see cref="UInt32"/> indicating the image width, in pixels. /// </param> /// <param name="height"> /// A <see cref="UInt32"/> indicating the image height, in pixels. /// </param> public Image(PixelLayout format, uint width, uint height) { if (format == PixelLayout.None) throw new ArgumentException("invalid", "format"); if (width == 0) throw new ArgumentException("invalid", "width"); if (height == 0) throw new ArgumentException("invalid", "height"); // Allocate Create(format, width, height); } #endregion #region Image Pixels /// <summary> /// Allocate pixel data for this Image. /// </summary> /// <param name="format"> /// A <see cref="PixelLayout"/> indicating the image pixel format. /// </param> /// <param name="w"> /// A <see cref="Int32"/> indicating the image width, in pixels. /// </param> /// <param name="h"> /// A <see cref="Int32"/> indicating the image height, in pixels. /// </param> public void Create(PixelLayout format, uint w, uint h) { switch (format) { // Single plane formats case PixelLayout.R8: case PixelLayout.R16: case PixelLayout.GRAY16S: case PixelLayout.RF: case PixelLayout.RHF: //case PixelLayout.GRAYAF: case PixelLayout.RGB8: case PixelLayout.RGB15: case PixelLayout.RGB16: case PixelLayout.RGB24: case PixelLayout.RGB48: case PixelLayout.RGBF: case PixelLayout.RGBHF: case PixelLayout.RGBD: case PixelLayout.SRGB24: case PixelLayout.SBGR24: //case PixelLayout.RGB30A2: case PixelLayout.RGBA32: case PixelLayout.RGBA64: case PixelLayout.RGBAF: case PixelLayout.RGBAHF: case PixelLayout.BGR8: case PixelLayout.BGR15: case PixelLayout.BGR16: case PixelLayout.BGR24: case PixelLayout.BGR48: case PixelLayout.BGRF: case PixelLayout.BGRHF: //case PixelLayout.BGR30A2: case PixelLayout.BGRA32: case PixelLayout.BGRA64: case PixelLayout.BGRAF: case PixelLayout.BGRAHF: case PixelLayout.CMY24: case PixelLayout.CMYK32: case PixelLayout.CMYK64: case PixelLayout.CMYKA40: case PixelLayout.Depth16: case PixelLayout.Depth24: case PixelLayout.Depth32: case PixelLayout.DepthF: case PixelLayout.Depth24Stencil8: case PixelLayout.Depth32FStencil8: case PixelLayout.Integer1: case PixelLayout.Integer2: case PixelLayout.Integer3: case PixelLayout.Integer4: case PixelLayout.UInteger1: case PixelLayout.UInteger2: case PixelLayout.UInteger3: case PixelLayout.UInteger4: _PixelBuffers = new AlignedMemoryBuffer(w * h * format.GetBytesCount(), 16); // Define planes _PixelPlanes = new IntPtr[] { _PixelBuffers.AlignedBuffer }; break; case PixelLayout.YUYV: case PixelLayout.YYUV: case PixelLayout.YVYU: case PixelLayout.UYVY: case PixelLayout.VYUY: if (((w % 2) != 0) || ((h % 2) != 0)) throw new InvalidOperationException(String.Format("invalid image extents for pixel format {0}", format)); // Define planes _PixelBuffers = new AlignedMemoryBuffer(w * h * format.GetBytesCount(), 16); _PixelPlanes = new IntPtr[] { _PixelBuffers.AlignedBuffer }; break; case PixelLayout.YVU410: case PixelLayout.YUV410: if (((w % 16) != 0) || ((h % 16) != 0)) throw new InvalidOperationException(String.Format("invalid image extents for pixel format {0}", format)); _PixelBuffers = new AlignedMemoryBuffer(w * h + (w * h / 16) * 2, 16); // Define planes _PixelPlanes = new IntPtr[3]; _PixelPlanes[0] = _PixelBuffers.AlignedBuffer; _PixelPlanes[1] = new IntPtr(_PixelBuffers.AlignedBuffer.ToInt64() + w * h); _PixelPlanes[2] = new IntPtr(_PixelBuffers.AlignedBuffer.ToInt64() + w * h + (w * h / 16)); break; case PixelLayout.YVU420: case PixelLayout.YUV420: if (((w % 4) != 0) || ((h % 4) != 0)) throw new InvalidOperationException(String.Format("invalid image extents for pixel format {0}", format)); _PixelBuffers = new AlignedMemoryBuffer(w * h + (w * h / 4), 16); // Define planes _PixelPlanes = new IntPtr[3]; _PixelPlanes[0] = _PixelBuffers.AlignedBuffer; _PixelPlanes[1] = new IntPtr(_PixelBuffers.AlignedBuffer.ToInt64() + w * h); _PixelPlanes[2] = new IntPtr(_PixelBuffers.AlignedBuffer.ToInt64() + w * h + (w * h / 4)); break; case PixelLayout.YUV422P: if ((w % 2) != 0) throw new InvalidOperationException(String.Format("invalid image extents for pixel format {0}", format)); _PixelBuffers = new AlignedMemoryBuffer(w * h + (w * h / 2), 16); // Define planes _PixelPlanes = new IntPtr[3]; _PixelPlanes[0] = _PixelBuffers.AlignedBuffer; _PixelPlanes[1] = new IntPtr(_PixelBuffers.AlignedBuffer.ToInt64() + w * h); _PixelPlanes[2] = new IntPtr(_PixelBuffers.AlignedBuffer.ToInt64() + w * h + (w * h / 2)); break; case PixelLayout.YUV411P: if ((w % 4) != 0) throw new InvalidOperationException(String.Format("invalid image extents for pixel format {0}", format)); _PixelBuffers = new AlignedMemoryBuffer(w * h + (w * h / 4), 16); // Define planes _PixelPlanes = new IntPtr[3]; _PixelPlanes[0] = _PixelBuffers.AlignedBuffer; _PixelPlanes[1] = new IntPtr(_PixelBuffers.AlignedBuffer.ToInt64() + w * h); _PixelPlanes[2] = new IntPtr(_PixelBuffers.AlignedBuffer.ToInt64() + w * h + (w * h / 4)); break; case PixelLayout.Y41P: if ((w % 8) != 0) throw new InvalidOperationException(String.Format("invalid image extents for pixel format {0}", format)); _PixelBuffers = new AlignedMemoryBuffer(w * h * 12 / 8, 16); // Define planes _PixelPlanes = new IntPtr[3]; _PixelPlanes[0] = _PixelBuffers.AlignedBuffer; _PixelPlanes[1] = new IntPtr(_PixelBuffers.AlignedBuffer.ToInt64() + w * h); _PixelPlanes[2] = new IntPtr(_PixelBuffers.AlignedBuffer.ToInt64() + w * h + (w * h / 4)); break; default: throw new NotSupportedException(String.Format("pixel format {0} is not supported", format)); } // Set image information _ImageInfo.PixelType = format; _ImageInfo.Width = w; _ImageInfo.Height = h; Debug.Assert(_PixelPlanes != null); Debug.Assert(_PixelPlanes.Length != 0); Debug.Assert(Array.TrueForAll(_PixelPlanes, delegate(IntPtr pixelPlane) { return (pixelPlane != IntPtr.Zero); })); } /// <summary> /// Image width property. /// </summary> public uint Width { get { return (_ImageInfo.Width); } protected set { _ImageInfo.Width = value; } } /// <summary> /// Image height property. /// </summary> public uint Height { get { return (_ImageInfo.Height); } protected set { _ImageInfo.Height = value; } } /// <summary> /// Gets the image buffer for every image plane scanlines. Image planes are allocated contiguosly, as defined /// by the specific pixel format, if planar. /// </summary> public IntPtr ImageBuffer { get { return (_PixelBuffers.AlignedBuffer); } } /// <summary> /// Gets the image planes scan-lines. /// </summary> public IntPtr[] ImagePlanes { get { return (_PixelPlanes); } } /// <summary> /// Image line width, in bytes /// </summary> public uint Stride { get { return (_ImageInfo.Width * PixelLayout.GetBytesCount()); } } /// <summary> /// Image size, in bytes. /// </summary> public uint Size { get { return (_PixelBuffers != null ? _PixelBuffers.Size : 0); } } /// <summary> /// Image pixel format. /// </summary> /// <returns> /// It returns a <see cref="PixelLayout"/> that specify the image color resolution. /// </returns> public PixelLayout PixelLayout { get { return (_ImageInfo.PixelType); } } /// <summary> /// Pixel arrays defining image layers. /// </summary> private AlignedMemoryBuffer _PixelBuffers; /// <summary> /// Pixel arrays pointers mapped onto pixel planes. /// </summary> private IntPtr[] _PixelPlanes; #endregion #region Managed Pixel Access public void SetPixel<T>(uint w, uint h, T value) where T : struct { Marshal.StructureToPtr(value, GetPixelDataOffset(w, h), false); } public T GetPixel<T>(uint w, uint h) where T : struct { return (T)Marshal.PtrToStructure(GetPixelDataOffset(w, h), typeof(T)); } private IntPtr GetPixelDataOffset(uint w, uint h) { switch (PixelLayout) { // Single plane formats case PixelLayout.R8: case PixelLayout.R16: case PixelLayout.GRAY16S: //case PixelLayout.GRAYF: case PixelLayout.RHF: //case PixelLayout.GRAYAF: case PixelLayout.RGB8: case PixelLayout.RGB15: case PixelLayout.RGB16: case PixelLayout.RGB24: case PixelLayout.RGB48: case PixelLayout.RGBF: case PixelLayout.RGBHF: case PixelLayout.RGBD: case PixelLayout.SRGB24: case PixelLayout.SBGR24: //case PixelLayout.RGB30A2: case PixelLayout.RGBA32: case PixelLayout.RGBA64: case PixelLayout.RGBAF: case PixelLayout.RGBAHF: case PixelLayout.BGR8: case PixelLayout.BGR15: case PixelLayout.BGR16: case PixelLayout.BGR24: case PixelLayout.BGR48: case PixelLayout.BGRF: case PixelLayout.BGRHF: //case PixelLayout.BGR30A2: case PixelLayout.BGRA32: case PixelLayout.BGRA64: case PixelLayout.BGRAF: case PixelLayout.BGRAHF: case PixelLayout.CMY24: case PixelLayout.CMYK32: case PixelLayout.CMYK64: case PixelLayout.CMYKA40: case PixelLayout.Depth16: case PixelLayout.Depth24: case PixelLayout.Depth32: case PixelLayout.DepthF: case PixelLayout.Depth24Stencil8: case PixelLayout.Depth32FStencil8: case PixelLayout.Integer1: case PixelLayout.Integer2: case PixelLayout.Integer3: case PixelLayout.Integer4: case PixelLayout.UInteger1: case PixelLayout.UInteger2: case PixelLayout.UInteger3: case PixelLayout.UInteger4: return new IntPtr(_PixelBuffers.AlignedBuffer.ToInt64() + (w * PixelLayout.GetBytesCount()) + (h * Width * PixelLayout.GetBytesCount())); default: throw new NotSupportedException(String.Format("pixel format {0} is not supported", PixelLayout)); } } #endregion #region Image Transformation #region Flipping /// <summary> /// Flip the image vertically. /// </summary> public void FlipVertically() { IntPtr imageData = ImageBuffer; byte[] tmpScanline = new byte[Stride]; unsafe { byte* hImageDataPtrBottom = (byte*)imageData.ToPointer(); byte* hImageDataPtrTop = hImageDataPtrBottom + Stride * (Height - 1); while (hImageDataPtrBottom < hImageDataPtrTop) { // Copy to temporary scaline Marshal.Copy(new IntPtr(hImageDataPtrTop), tmpScanline, 0, (int)Stride); // Swap scan lines Memory.Copy(hImageDataPtrTop, hImageDataPtrBottom, Stride); Marshal.Copy(tmpScanline, 0, new IntPtr(hImageDataPtrBottom), (int)Stride); hImageDataPtrBottom += Stride; hImageDataPtrTop -= Stride; } } } #endregion #endregion #region Resource Overrides /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting managed/unmanaged resources. /// </summary> /// <param name="disposing"> /// </param> protected override void Dispose(bool disposing) { if (disposing) { if (_PixelBuffers != null) { // Release the buffer buffer _PixelBuffers.Dispose(); _PixelBuffers = null; } } } #endregion #region IMedia<ImageInfo> Implementation /// <summary> /// Gets the media information of this instance. /// </summary> public ImageInfo MediaInformation { get { // Ensure updated information _ImageInfo.PixelType = this.PixelLayout; _ImageInfo.Width = Width; _ImageInfo.Height = Height; // Other information may be modified by external code return (_ImageInfo); } } /// <summary> /// Media information. /// </summary> private readonly ImageInfo _ImageInfo = new ImageInfo(); #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace StacksOfWax.SimpleApi.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 UnityEngine; using System; using System.Collections; using System.Reflection; using System.Runtime.InteropServices; namespace FourthSky { namespace Android { public static class AndroidVersions { public const int BASE = 1; public const int BASE_1_1 = 2; public const int CUPCAKE = 3; public const int DONUT = 4; public const int ECLAIR = 5; public const int ECLAIR_0_1 = 6; public const int ECLAIR_MR1 = 7; public const int FROYO = 8; public const int GINGERBREAD = 9; public const int GINGERBREAD_MR1 = 10; public const int HONEYCOMB = 11; public const int HONEYCOMB_MR1 = 12; public const int HONEYCOMB_MR2 = 13; public const int ICE_CREAM_SANDWICH = 14; public const int ICE_CREAM_SANDWICH_MR1 = 15; public const int JELLY_BEAN = 16; public const int JELLY_BEAN_MR1 = 17; public const int JELLY_BEAN_MR2 = 18; public const int KITKAT = 19; } public static class AndroidSystem { // Delegate for activity result public delegate void OnActivityResultDelegate(int requestCode, int resultCode, AndroidJavaObject intent); public static event OnActivityResultDelegate OnActivityResult; // Delegate for on new intent public delegate void OnNewIntentDelegate(AndroidJavaObject intent); public static event OnNewIntentDelegate OnNewIntent; #region internal callback objects private delegate void OnActivityResultInternal(int requestCode, int resultCode, IntPtr intentPtr); private static OnActivityResultInternal onActivityResultInternal; private static GCHandle onActivityResultInternalHandle; private static IntPtr onActivityResultInternalPtr = IntPtr.Zero; private static void OnActivityResultInternalImpl(int requestCode, int resultCode, IntPtr intentPtr) { if (OnActivityResult != null) { AndroidJavaObject intent = AndroidSystem.ConstructJavaObjectFromPtr (intentPtr); // Invoke callback AndroidSystem.OnActivityResult(requestCode, resultCode, intent); // Release callback objects, to prevent memory leak onActivityResultInternalHandle.Free(); onActivityResultInternal = null; } } private delegate void OnNewIntentInternal(IntPtr intentPtr); private static OnNewIntentInternal onNewIntentInternal; private static GCHandle onNewIntentInternalHandle; private static IntPtr onNewIntentInternalPtr; private static void OnNewIntentInternalImpl(IntPtr intentPtr) { if (OnNewIntent != null) { AndroidJavaObject intent = AndroidSystem.ConstructJavaObjectFromPtr (intentPtr); AndroidSystem.OnNewIntent(intent); // Release callback objects, to prevent memory leak onNewIntentInternalHandle.Free(); onNewIntentInternal = null; } } #endregion // Stores current Android version private static int SDK_VERSION = -1; // Name of activities used for Android System plugin internal static readonly string PLUGIN_PACKAGE = "com.fourthsky.unity.androidtools"; private static readonly string PLUGIN_ACTIVITY = PLUGIN_PACKAGE + ".UnityPlayerActivityEx"; private static readonly string PLUGIN_NATIVE_ACTIVITY = PLUGIN_PACKAGE + ".UnityPlayerNativeActivityEx"; //private static readonly string ACTIVITY_CALLBACKS = PLUGIN_PACKAGE + ".UnityActivityCallbacks"; // Android class names internal static readonly string UNITY_PLAYER = "com.unity3d.player.UnityPlayer"; internal static readonly string INTENT = "android.content.Intent"; internal static readonly string INTENT_FILTER = "android.content.IntentFilter"; internal static readonly string PARCELABLE = "android.os.Parcelable"; // Constants for return of StartActivityForResult public const int RESULT_OK = -1; public const int RESULT_CANCELED = 0x0; public const int RESULT_FIRST_USER = 0x1; /// <summary> /// Gets the Android version. /// </summary> /// <value>Android version in device.</value> public static int Version { get { #if UNITY_ANDROID if (SDK_VERSION == -1) { using (AndroidJavaClass Build_VERSION = new AndroidJavaClass("android.os.Build$VERSION")) { SDK_VERSION = Build_VERSION.GetStatic<int>("SDK_INT"); } } #endif return SDK_VERSION; } } public static bool ActivityCallbacksSupported { get { #if UNITY_ANDROID string className = UnityActivity.Call<AndroidJavaObject>("getClass").Call<string>("getName"); return (className == PLUGIN_ACTIVITY || className == PLUGIN_NATIVE_ACTIVITY); #else return false; #endif } } public static AndroidJavaObject UnityActivity { get { #if UNITY_ANDROID using (AndroidJavaClass unityPlayerClass = new AndroidJavaClass(UNITY_PLAYER)) { return unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity"); } #else return null; #endif } } public static AndroidJavaObject UnityContext { get { #if UNITY_ANDROID using (AndroidJavaClass unityPlayerClass = new AndroidJavaClass(UNITY_PLAYER)) { using (AndroidJavaObject activityInstance = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity")) { return activityInstance.Call<AndroidJavaObject>("getApplicationContext"); } } #else return null; #endif } } public static string PackageName { get { #if UNITY_ANDROID return AndroidSystem.UnityActivity.Call<string>("getPackageName"); #else return ""; #endif } } // TODO implement public static Hashtable ParseBundle(AndroidJavaObject bundleObject) { return null; } private static bool RegisterOnActivityResultCallback(OnActivityResultDelegate callback) { #if UNITY_ANDROID // Store the callback OnActivityResult = callback; if (onActivityResultInternalPtr == IntPtr.Zero) { // Get native pointer for delegate onActivityResultInternal = new OnActivityResultInternal(OnActivityResultInternalImpl); onActivityResultInternalHandle = GCHandle.Alloc(onActivityResultInternal); onActivityResultInternalPtr = Marshal.GetFunctionPointerForDelegate (onActivityResultInternal); if (onActivityResultInternalPtr == IntPtr.Zero) { Debug.LogError("Cannot get unmanaged pointer for OnActivityResult delegate, pointer value is " + onActivityResultInternalPtr.ToInt32()); return false; } return RegisterOnActivityResultCallback(onActivityResultInternalPtr); } #endif return false; } public static bool RegisterOnNewIntentCallback(OnNewIntentDelegate callback) { #if UNITY_ANDROID // Store the callback OnNewIntent = callback; if (onNewIntentInternalPtr == IntPtr.Zero) { // Get native pointer for delegate onNewIntentInternal = new OnNewIntentInternal(OnNewIntentInternalImpl); onNewIntentInternalHandle = GCHandle.Alloc(onNewIntentInternal); onNewIntentInternalPtr = Marshal.GetFunctionPointerForDelegate (onNewIntentInternal); if (onNewIntentInternalPtr == IntPtr.Zero) { Debug.LogError("Cannot get unmanaged pointer for OnNewIntent delegate"); return false; } return RegisterOnNewIntentCallback(onNewIntentInternalPtr); } #endif return false; } #if UNITY_ANDROID [DllImport("unityandroidsystem")] public static extern bool RegisterOnActivityResultCallback(IntPtr callbackPtr); [DllImport("unityandroidsystem")] public static extern bool RegisterOnNewIntentCallback (IntPtr callbackPtr); #endif public static AndroidJavaObject ConstructJavaObjectFromPtr(IntPtr javaPtr) { #if UNITY_ANDROID #if UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 return new AndroidJavaObject(javaPtr); #else // Starting with Unity 4.2, AndroidJavaObject constructor with IntPtr arg is private, // so, construct using brute force :) Type t = typeof(AndroidJavaObject); Type[] types = new Type[1]; types[0] = typeof(IntPtr); ConstructorInfo javaObjConstructor = t.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, types, null); return javaObjConstructor.Invoke(new object[] { javaPtr }) as AndroidJavaObject; #endif #else return null; #endif } public static void SendBroadcast(string action, Hashtable extras = null) { #if UNITY_ANDROID if (!Application.isEditor) { using (AndroidJavaClass unityPlayerClass = new AndroidJavaClass(AndroidSystem.UNITY_PLAYER)) { using (AndroidJavaObject activityInstance = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity")) { AndroidJavaObject intent = new AndroidJavaObject(AndroidSystem.INTENT, action); // Add args to intent if (extras != null) { foreach (DictionaryEntry entry in extras) { if (entry.Value is short) { intent.Call<AndroidJavaObject>("putExtra", (string)entry.Key, (short)entry.Value); } else if (entry.Value is int) { intent.Call<AndroidJavaObject>("putExtra", (string)entry.Key, (int)entry.Value); } else if (entry.Value is long) { intent.Call<AndroidJavaObject>("putExtra", (string)entry.Key, (long)entry.Value); } else if (entry.Value is float) { intent.Call<AndroidJavaObject>("putExtra", (string)entry.Key, (float)entry.Value); } else if (entry.Value is double) { intent.Call<AndroidJavaObject>("putExtra", (string)entry.Key, (double)entry.Value); } else if (entry.Value is string) { intent.Call<AndroidJavaObject>("putExtra", (string)entry.Key, (string)entry.Value); } else if (entry.Value is AndroidJavaObject) { AndroidJavaObject javaObj = entry.Value as AndroidJavaObject; using (AndroidJavaClass _Parcelable = new AndroidJavaClass(AndroidSystem.PARCELABLE)) { if (AndroidJNI.IsInstanceOf(javaObj.GetRawObject(), _Parcelable.GetRawClass())) { intent.Call<AndroidJavaObject>("putExtra", (string)entry.Key, javaObj); } else { throw new ArgumentException("Argument is not a Android Parcelable", "extra." + entry.Key); } } } } } activityInstance.Call("sendBroadcast", intent); } } } #endif } public static bool StartActivityForResult(string action, int requestCode, OnActivityResultDelegate callback) { return StartActivityForResult(action, null, requestCode, callback); } public static bool StartActivityForResult(string action, AndroidJavaObject uriData, int requestCode, OnActivityResultDelegate callback) { if (callback == null) { throw new System.ArgumentNullException("OnActivityResult callback cannot be null"); } if (string.IsNullOrEmpty(action)) { throw new System.ArgumentNullException(""); } #if UNITY_ANDROID // Create intent AndroidJavaObject intent = uriData != null ? new AndroidJavaObject(AndroidSystem.INTENT, action, uriData) : new AndroidJavaObject(AndroidSystem.INTENT, action); // Start given action return StartActivityForResult (intent, requestCode, callback); #else return false; #endif } public static bool StartActivityForResult(AndroidJavaObject intent, int requestCode, OnActivityResultDelegate callback) { bool ret = false; #if UNITY_ANDROID using (AndroidJavaObject activityInstance = AndroidSystem.UnityActivity) { // Register given callback ret = RegisterOnActivityResultCallback(callback); activityInstance.Call("startActivityForResult", intent, requestCode); } #endif return ret; } } } }
// 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.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Microsoft.AspNetCore.SignalR.Client.SourceGenerator { internal partial class HubServerProxyGenerator { public class Emitter { private readonly SourceProductionContext _context; private readonly SourceGenerationSpec _spec; public Emitter(SourceProductionContext context, SourceGenerationSpec spec) { _context = context; _spec = spec; } public void Emit() { if (string.IsNullOrEmpty(_spec.GetterClassAccessibility) || string.IsNullOrEmpty(_spec.GetterMethodAccessibility) || string.IsNullOrEmpty(_spec.GetterClassName) || string.IsNullOrEmpty(_spec.GetterMethodName) || string.IsNullOrEmpty(_spec.GetterTypeParameterName) || string.IsNullOrEmpty(_spec.GetterHubConnectionParameterName)) { return; } // Generate extensions and other user facing mostly-static code in a single source file EmitExtensions(); // Generate hub proxy code in its own source file for each hub proxy type foreach (var classSpec in _spec.Classes) { EmitProxy(classSpec); } } private void EmitExtensions() { var getProxyBody = new StringBuilder(); foreach (var classSpec in _spec.Classes) { var fqIntfTypeName = classSpec.FullyQualifiedInterfaceTypeName; var fqClassTypeName = $"{_spec.GetterNamespace}.{_spec.GetterClassName}.{classSpec.ClassTypeName}"; getProxyBody.Append($@" if (typeof({_spec.GetterTypeParameterName}) == typeof({fqIntfTypeName})) {{ return ({_spec.GetterTypeParameterName}) ({fqIntfTypeName}) new {fqClassTypeName}({_spec.GetterHubConnectionParameterName}); }}"); } var getProxy = $@"// <auto-generated> // Generated by Microsoft.AspNetCore.Client.SourceGenerator // </auto-generated> #nullable enable using Microsoft.AspNetCore.SignalR.Client; namespace {_spec.GetterNamespace} {{ {_spec.GetterClassAccessibility} static partial class {_spec.GetterClassName} {{ {_spec.GetterMethodAccessibility} static partial {_spec.GetterTypeParameterName} {_spec.GetterMethodName}<{_spec.GetterTypeParameterName}>(this HubConnection {_spec.GetterHubConnectionParameterName}) {{ {getProxyBody.ToString()} throw new System.ArgumentException(nameof({_spec.GetterTypeParameterName})); }} }} }}"; _context.AddSource("HubServerProxy.g.cs", SourceText.From(getProxy.ToString(), Encoding.UTF8)); } private void EmitProxy(ClassSpec classSpec) { var methods = new StringBuilder(); foreach (var methodSpec in classSpec.Methods) { var signature = new StringBuilder($"public {methodSpec.FullyQualifiedReturnTypeName} {methodSpec.Name}("); var callArgs = new StringBuilder(""); var signatureArgs = new StringBuilder(""); var first = true; foreach (var argumentSpec in methodSpec.Arguments) { if (!first) { signatureArgs.Append(", "); } first = false; signatureArgs.Append($"{argumentSpec.FullyQualifiedTypeName} {argumentSpec.Name}"); callArgs.Append($", {argumentSpec.Name}"); } signature.Append(signatureArgs); signature.Append(')'); // Prepare method body var body = ""; if (methodSpec.Support != SupportClassification.Supported) { body = methodSpec.SupportHint is null ? "throw new System.NotSupportedException();" : $"throw new System.NotSupportedException(\"{methodSpec.SupportHint}\");"; } else { // Get specific hub connection extension method call var specificCall = GetSpecificCall(methodSpec); // Handle ValueTask var prefix = ""; var suffix = ""; if (methodSpec.IsReturnTypeValueTask) { if (methodSpec.InnerReturnTypeName is not null) { prefix = $"new System.Threading.Tasks.ValueTask<{methodSpec.InnerReturnTypeName}>("; } else { prefix = "new System.Threading.Tasks.ValueTask("; } suffix = $")"; } // Bake it all together body = $"return {prefix}this.connection.{specificCall}(\"{methodSpec.Name}\"{callArgs}){suffix};"; } var method = $@" {signature} {{ {body} }} "; methods.Append(method); } var proxy = $@"// <auto-generated> // Generated by Microsoft.AspNetCore.Client.SourceGenerator // </auto-generated> #nullable enable using Microsoft.AspNetCore.SignalR.Client; namespace {_spec.GetterNamespace} {{ {_spec.GetterClassAccessibility} static partial class {_spec.GetterClassName} {{ private sealed class {classSpec.ClassTypeName} : {classSpec.FullyQualifiedInterfaceTypeName} {{ private readonly HubConnection connection; internal {classSpec.ClassTypeName}(HubConnection connection) {{ this.connection = connection; }} {methods.ToString()} }} }} }}"; _context.AddSource($"HubServerProxy.{classSpec.ClassTypeName}.g.cs", SourceText.From(proxy.ToString(), Encoding.UTF8)); } private string GetSpecificCall(MethodSpec methodSpec) { if (methodSpec.Stream.HasFlag(StreamSpec.ServerToClient) && !methodSpec.Stream.HasFlag(StreamSpec.AsyncEnumerable)) { return $"StreamAsChannelAsync<{methodSpec.InnerReturnTypeName}>"; } if (methodSpec.Stream.HasFlag(StreamSpec.ServerToClient) && methodSpec.Stream.HasFlag(StreamSpec.AsyncEnumerable)) { return $"StreamAsync<{methodSpec.InnerReturnTypeName}>"; } if (methodSpec.InnerReturnTypeName is not null) { return $"InvokeAsync<{methodSpec.InnerReturnTypeName}>"; } if (methodSpec.Stream.HasFlag(StreamSpec.ClientToServer)) { return "SendAsync"; } return "InvokeAsync"; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// Operations for managing Product Groups. /// </summary> internal partial class ProductGroupsOperations : IServiceOperations<ApiManagementClient>, IProductGroupsOperations { /// <summary> /// Initializes a new instance of the ProductGroupsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ProductGroupsOperations(ApiManagementClient client) { this._client = client; } private ApiManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.ApiManagement.ApiManagementClient. /// </summary> public ApiManagementClient Client { get { return this._client; } } /// <summary> /// Assigns group to product. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='gid'> /// Required. Identifier of the Group. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> AddAsync(string resourceGroupName, string serviceName, string pid, string gid, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (pid == null) { throw new ArgumentNullException("pid"); } if (gid == null) { throw new ArgumentNullException("gid"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("pid", pid); tracingParameters.Add("gid", gid); TracingAdapter.Enter(invocationId, this, "AddAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/products/"; url = url + Uri.EscapeDataString(pid); url = url + "/groups/"; url = url + Uri.EscapeDataString(gid); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// List all Product Groups. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='query'> /// Optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List Groups operation response details. /// </returns> public async Task<GroupListResponse> ListAsync(string resourceGroupName, string serviceName, string pid, QueryParameters query, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (pid == null) { throw new ArgumentNullException("pid"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("pid", pid); tracingParameters.Add("query", query); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/products/"; url = url + Uri.EscapeDataString(pid); url = url + "/groups"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); List<string> odataFilter = new List<string>(); if (query != null && query.Filter != null) { odataFilter.Add(Uri.EscapeDataString(query.Filter)); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } if (query != null && query.Top != null) { queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString())); } if (query != null && query.Skip != null) { queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString())); } if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GroupListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GroupListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { GroupPaged resultInstance = new GroupPaged(); result.Result = resultInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { GroupContract groupContractInstance = new GroupContract(); resultInstance.Values.Add(groupContractInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); groupContractInstance.IdPath = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); groupContractInstance.Name = nameInstance; } JToken descriptionValue = valueValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); groupContractInstance.Description = descriptionInstance; } JToken builtInValue = valueValue["builtIn"]; if (builtInValue != null && builtInValue.Type != JTokenType.Null) { bool builtInInstance = ((bool)builtInValue); groupContractInstance.System = builtInInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true)); groupContractInstance.Type = typeInstance; } JToken externalIdValue = valueValue["externalId"]; if (externalIdValue != null && externalIdValue.Type != JTokenType.Null) { string externalIdInstance = ((string)externalIdValue); groupContractInstance.ExternalId = externalIdInstance; } } } JToken countValue = responseDoc["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); resultInstance.TotalCount = countInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); resultInstance.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// List all Product Groups. /// </summary> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List Groups operation response details. /// </returns> public async Task<GroupListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GroupListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GroupListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { GroupPaged resultInstance = new GroupPaged(); result.Result = resultInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { GroupContract groupContractInstance = new GroupContract(); resultInstance.Values.Add(groupContractInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); groupContractInstance.IdPath = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); groupContractInstance.Name = nameInstance; } JToken descriptionValue = valueValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); groupContractInstance.Description = descriptionInstance; } JToken builtInValue = valueValue["builtIn"]; if (builtInValue != null && builtInValue.Type != JTokenType.Null) { bool builtInInstance = ((bool)builtInValue); groupContractInstance.System = builtInInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true)); groupContractInstance.Type = typeInstance; } JToken externalIdValue = valueValue["externalId"]; if (externalIdValue != null && externalIdValue.Type != JTokenType.Null) { string externalIdInstance = ((string)externalIdValue); groupContractInstance.ExternalId = externalIdInstance; } } } JToken countValue = responseDoc["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); resultInstance.TotalCount = countInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); resultInstance.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Removes group assignement from product. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='gid'> /// Required. Identifier of the Group. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> RemoveAsync(string resourceGroupName, string serviceName, string pid, string gid, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (pid == null) { throw new ArgumentNullException("pid"); } if (gid == null) { throw new ArgumentNullException("gid"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("pid", pid); tracingParameters.Add("gid", gid); TracingAdapter.Enter(invocationId, this, "RemoveAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/products/"; url = url + Uri.EscapeDataString(pid); url = url + "/groups/"; url = url + Uri.EscapeDataString(gid); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftLeftLogicalUInt3232() { var test = new SimpleUnaryOpTest__ShiftLeftLogicalUInt3232(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftLeftLogicalUInt3232 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt32); private const int RetElementCount = VectorSize / sizeof(UInt32); private static UInt32[] _data = new UInt32[Op1ElementCount]; private static Vector128<UInt32> _clsVar; private Vector128<UInt32> _fld; private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable; static SimpleUnaryOpTest__ShiftLeftLogicalUInt3232() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftLeftLogicalUInt3232() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.ShiftLeftLogical( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr), 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.ShiftLeftLogical( Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)), 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.ShiftLeftLogical( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)), 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr), (byte)32 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)), (byte)32 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)), (byte)32 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.ShiftLeftLogical( _clsVar, 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr); var result = Sse2.ShiftLeftLogical(firstOp, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical(firstOp, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical(firstOp, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftLeftLogicalUInt3232(); var result = Sse2.ShiftLeftLogical(test._fld, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.ShiftLeftLogical(_fld, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt32> firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { if (0 != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (0!= result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical)}<UInt32>(Vector128<UInt32><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System.Xml.Serialization; using VotingInfo.Database.Contracts; using VotingInfo.Database.Contracts.Data; ////////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend. // //Override methods in the logic front class. // ////////////////////////////////////////////////////////////// namespace VotingInfo.Database.Logic.Data { [Serializable] public abstract partial class OrganizationMetaDataLogicBase : LogicBase<OrganizationMetaDataLogicBase> { //Put your code in a separate file. This is auto generated. [XmlArray] public List<OrganizationMetaDataContract> Results; public OrganizationMetaDataLogicBase() { Results = new List<OrganizationMetaDataContract>(); } /// <summary> /// Run OrganizationMetaData_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <returns>The new ID</returns> public virtual int? Insert(int fldContentInspectionId , int fldOrganizationId , int fldMetaDataId , string fldMetaDataValue ) { int? result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@OrganizationId", fldOrganizationId) , new SqlParameter("@MetaDataId", fldMetaDataId) , new SqlParameter("@MetaDataValue", fldMetaDataValue) }); result = (int?)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Run OrganizationMetaData_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The new ID</returns> public virtual int? Insert(int fldContentInspectionId , int fldOrganizationId , int fldMetaDataId , string fldMetaDataValue , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@OrganizationId", fldOrganizationId) , new SqlParameter("@MetaDataId", fldMetaDataId) , new SqlParameter("@MetaDataValue", fldMetaDataValue) }); return (int?)cmd.ExecuteScalar(); } } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>1, if insert was successful</returns> public int Insert(OrganizationMetaDataContract row) { int? result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@OrganizationId", row.OrganizationId) , new SqlParameter("@MetaDataId", row.MetaDataId) , new SqlParameter("@MetaDataValue", row.MetaDataValue) }); result = (int?)cmd.ExecuteScalar(); row.OrganizationMetaDataId = result; } }); return result != null ? 1 : 0; } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>1, if insert was successful</returns> public int Insert(OrganizationMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { int? result = null; using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@OrganizationId", row.OrganizationId) , new SqlParameter("@MetaDataId", row.MetaDataId) , new SqlParameter("@MetaDataValue", row.MetaDataValue) }); result = (int?)cmd.ExecuteScalar(); row.OrganizationMetaDataId = result; } return result != null ? 1 : 0; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<OrganizationMetaDataContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = InsertAll(rows, x, null); }); return rowCount; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<OrganizationMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Insert(row, connection, transaction); return rowCount; } /// <summary> /// Run OrganizationMetaData_Update. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> public virtual int Update(int fldOrganizationMetaDataId , int fldContentInspectionId , int fldOrganizationId , int fldMetaDataId , string fldMetaDataValue ) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationMetaDataId", fldOrganizationMetaDataId) , new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@OrganizationId", fldOrganizationId) , new SqlParameter("@MetaDataId", fldMetaDataId) , new SqlParameter("@MetaDataValue", fldMetaDataValue) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run OrganizationMetaData_Update. /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(int fldOrganizationMetaDataId , int fldContentInspectionId , int fldOrganizationId , int fldMetaDataId , string fldMetaDataValue , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationMetaDataId", fldOrganizationMetaDataId) , new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@OrganizationId", fldOrganizationId) , new SqlParameter("@MetaDataId", fldMetaDataId) , new SqlParameter("@MetaDataValue", fldMetaDataValue) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(OrganizationMetaDataContract row) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationMetaDataId", row.OrganizationMetaDataId) , new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@OrganizationId", row.OrganizationId) , new SqlParameter("@MetaDataId", row.MetaDataId) , new SqlParameter("@MetaDataValue", row.MetaDataValue) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(OrganizationMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationMetaDataId", row.OrganizationMetaDataId) , new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@OrganizationId", row.OrganizationId) , new SqlParameter("@MetaDataId", row.MetaDataId) , new SqlParameter("@MetaDataValue", row.MetaDataValue) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<OrganizationMetaDataContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = UpdateAll(rows, x, null); }); return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<OrganizationMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Update(row, connection, transaction); return rowCount; } /// <summary> /// Run OrganizationMetaData_Delete. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> public virtual int Delete(int fldOrganizationMetaDataId ) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationMetaDataId", fldOrganizationMetaDataId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run OrganizationMetaData_Delete. /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(int fldOrganizationMetaDataId , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationMetaDataId", fldOrganizationMetaDataId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(OrganizationMetaDataContract row) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationMetaDataId", row.OrganizationMetaDataId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(OrganizationMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationMetaDataId", row.OrganizationMetaDataId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<OrganizationMetaDataContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = DeleteAll(rows, x, null); }); return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<OrganizationMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Delete(row, connection, transaction); return rowCount; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldOrganizationMetaDataId ) { bool result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Exists]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationMetaDataId", fldOrganizationMetaDataId) }); result = (bool)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldOrganizationMetaDataId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Exists]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationMetaDataId", fldOrganizationMetaDataId) }); return (bool)cmd.ExecuteScalar(); } } /// <summary> /// Run OrganizationMetaData_Search, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public virtual bool Search(string fldMetaDataValue ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Search]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@MetaDataValue", fldMetaDataValue) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run OrganizationMetaData_Search, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public virtual bool Search(string fldMetaDataValue , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_Search]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@MetaDataValue", fldMetaDataValue) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run OrganizationMetaData_SelectAll, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <returns>A collection of OrganizationMetaDataRow.</returns> public virtual bool SelectAll() { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_SelectAll]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run OrganizationMetaData_SelectAll, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_SelectAll]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run OrganizationMetaData_SelectBy_OrganizationMetaDataId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public virtual bool SelectBy_OrganizationMetaDataId(int fldOrganizationMetaDataId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_SelectBy_OrganizationMetaDataId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationMetaDataId", fldOrganizationMetaDataId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run OrganizationMetaData_SelectBy_OrganizationMetaDataId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldOrganizationMetaDataId">Value for OrganizationMetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public virtual bool SelectBy_OrganizationMetaDataId(int fldOrganizationMetaDataId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_SelectBy_OrganizationMetaDataId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationMetaDataId", fldOrganizationMetaDataId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run OrganizationMetaData_SelectBy_ContentInspectionId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_SelectBy_ContentInspectionId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run OrganizationMetaData_SelectBy_ContentInspectionId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_SelectBy_ContentInspectionId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run OrganizationMetaData_SelectBy_OrganizationId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public virtual bool SelectBy_OrganizationId(int fldOrganizationId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_SelectBy_OrganizationId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationId", fldOrganizationId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run OrganizationMetaData_SelectBy_OrganizationId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public virtual bool SelectBy_OrganizationId(int fldOrganizationId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_SelectBy_OrganizationId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationId", fldOrganizationId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run OrganizationMetaData_SelectBy_MetaDataId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public virtual bool SelectBy_MetaDataId(int fldMetaDataId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_SelectBy_MetaDataId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@MetaDataId", fldMetaDataId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run OrganizationMetaData_SelectBy_MetaDataId, and return results as a list of OrganizationMetaDataRow. /// </summary> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of OrganizationMetaDataRow.</returns> public virtual bool SelectBy_MetaDataId(int fldMetaDataId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[OrganizationMetaData_SelectBy_MetaDataId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@MetaDataId", fldMetaDataId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Read all items into this collection /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadAll(SqlDataReader reader) { var canRead = ReadOne(reader); var result = canRead; while (canRead) canRead = ReadOne(reader); return result; } /// <summary> /// Read one item into Results /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadOne(SqlDataReader reader) { if (reader.Read()) { Results.Add( new OrganizationMetaDataContract { OrganizationMetaDataId = reader.GetInt32(0), ContentInspectionId = reader.GetInt32(1), OrganizationId = reader.GetInt32(2), MetaDataId = reader.GetInt32(3), MetaDataValue = reader.GetString(4), }); return true; } return false; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public virtual int Save(OrganizationMetaDataContract row) { if(row == null) return 0; if(row.OrganizationMetaDataId != null) return Update(row); return Insert(row); } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Save(OrganizationMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { if(row == null) return 0; if(row.OrganizationMetaDataId != null) return Update(row, connection, transaction); return Insert(row, connection, transaction); } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<OrganizationMetaDataContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { foreach(var row in rows) rowCount += Save(row, x, null); }); return rowCount; } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<OrganizationMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Save(row, connection, transaction); return rowCount; } } }
///////////////////////////////////////////////////////////////////////////// // Copyright (c) 2003 CenterSpace Software, LLC // // // // This code is free software under the Artistic license. // // // // CenterSpace Software // // 301 SW 4th Street - Suite #240 // // Corvallis, Oregon, 97333 // // USA // // http://www.centerspace.net // ///////////////////////////////////////////////////////////////////////////// /* A C-program for MT19937, with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto. Before using, initialize the state by using init_genrand(seed) or init_by_array(init_key, key_length). Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, 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. 3. The names of its contributors may not 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. Any feedback is very welcome. http://www.math.keio.ac.jp/matumoto/emt.html email: matumoto@math.keio.ac.jp */ using System; namespace CenterSpace.Free { /// <summary> /// Class MersenneTwister generates random numbers from a uniform distribution using /// the Mersenne Twister algorithm. /// </summary> /// <remarks>Caution: MT is for MonteCarlo, and is NOT SECURE for CRYPTOGRAPHY /// as it is.</remarks> public class MersenneTwister { #region Constants ------------------------------------------------------- // Period parameters. private const int N = 624; private const int M = 397; private const uint MATRIX_A = 0x9908b0dfU; // constant vector a private const uint UPPER_MASK = 0x80000000U; // most significant w-r bits private const uint LOWER_MASK = 0x7fffffffU; // least significant r bits private const int MAX_RAND_INT = 0x7fffffff; #endregion Constants #region Instance Variables ---------------------------------------------- // mag01[x] = x * MATRIX_A for x=0,1 private uint[] mag01 = {0x0U, MATRIX_A}; // the array for the state vector private uint[] mt = new uint[N]; // mti==N+1 means mt[N] is not initialized private int mti = N+1; #endregion Instance Variables #region Constructors ---------------------------------------------------- /// <summary> /// Creates a random number generator using the time of day in milliseconds as /// the seed. /// </summary> public MersenneTwister() { init_genrand( (uint)DateTime.Now.Millisecond ); } /// <summary> /// Creates a random number generator initialized with the given seed. /// </summary> /// <param name="seed">The seed.</param> public MersenneTwister( int seed ) { init_genrand( (uint)seed ); } /// <summary> /// Creates a random number generator initialized with the given array. /// </summary> /// <param name="init">The array for initializing keys.</param> public MersenneTwister( int[] init ) { uint[] initArray = new uint[init.Length]; for ( int i = 0; i < init.Length; ++i ) initArray[i] = (uint)init[i]; init_by_array( initArray, (uint)initArray.Length ); } #endregion Constructors #region Properties ------------------------------------------------------ /// <summary> /// Gets the maximum random integer value. All random integers generated /// by instances of this class are less than or equal to this value. This /// value is <c>0x7fffffff</c> (<c>2,147,483,647</c>). /// </summary> public static int MaxRandomInt { get { return 0x7fffffff; } } #endregion Properties #region Member Functions ------------------------------------------------ /// <summary> /// Returns a random integer greater than or equal to zero and /// less than or equal to <c>MaxRandomInt</c>. /// </summary> /// <returns>The next random integer.</returns> public int Next() { return genrand_int31(); } /// <summary> /// Returns a positive random integer less than the specified maximum. /// </summary> /// <param name="maxValue">The maximum value. Must be greater than zero.</param> /// <returns>A positive random integer less than or equal to <c>maxValue</c>.</returns> public int Next( int maxValue ) { return Next( 0, maxValue ); } /// <summary> /// Returns a random integer within the specified range. /// </summary> /// <param name="minValue">The lower bound.</param> /// <param name="maxValue">The upper bound.</param> /// <returns>A random integer greater than or equal to <c>minValue</c>, and less than /// or equal to <c>maxValue</c>.</returns> public int Next( int minValue, int maxValue ) { if ( minValue > maxValue ) { int tmp = maxValue; maxValue = minValue; minValue = tmp; } return (int)( Math.Floor((maxValue-minValue+1)*genrand_real2() + minValue) ); } /// <summary> /// Returns a random number between 0.0 and 1.0. /// </summary> /// <returns>A single-precision floating point number greater than or equal to 0.0, /// and less than 1.0.</returns> public float NextFloat() { return (float) genrand_real2(); } /// <summary> /// Returns a random number greater than or equal to zero, and either strictly /// less than one, or less than or equal to one, depending on the value of the /// given boolean parameter. /// </summary> /// <param name="includeOne"> /// If <c>true</c>, the random number returned will be /// less than or equal to one; otherwise, the random number returned will /// be strictly less than one. /// </param> /// <returns> /// If <c>includeOne</c> is <c>true</c>, this method returns a /// single-precision random number greater than or equal to zero, and less /// than or equal to one. If <c>includeOne</c> is <c>false</c>, this method /// returns a single-precision random number greater than or equal to zero and /// strictly less than one. /// </returns> public float NextFloat( bool includeOne ) { if ( includeOne ) { return (float) genrand_real1(); } return (float) genrand_real2(); } /// <summary> /// Returns a random number greater than 0.0 and less than 1.0. /// </summary> /// <returns>A random number greater than 0.0 and less than 1.0.</returns> public float NextFloatPositive() { return (float) genrand_real3(); } /// <summary> /// Returns a random number between 0.0 and 1.0. /// </summary> /// <returns>A double-precision floating point number greater than or equal to 0.0, /// and less than 1.0.</returns> public double NextDouble() { return genrand_real2(); } /// <summary> /// Returns a random number greater than or equal to zero, and either strictly /// less than one, or less than or equal to one, depending on the value of the /// given boolean parameter. /// </summary> /// <param name="includeOne"> /// If <c>true</c>, the random number returned will be /// less than or equal to one; otherwise, the random number returned will /// be strictly less than one. /// </param> /// <returns> /// If <c>includeOne</c> is <c>true</c>, this method returns a /// single-precision random number greater than or equal to zero, and less /// than or equal to one. If <c>includeOne</c> is <c>false</c>, this method /// returns a single-precision random number greater than or equal to zero and /// strictly less than one. /// </returns> public double NextDouble( bool includeOne ) { if ( includeOne ) { return genrand_real1(); } return genrand_real2(); } /// <summary> /// Returns a random number greater than 0.0 and less than 1.0. /// </summary> /// <returns>A random number greater than 0.0 and less than 1.0.</returns> public double NextDoublePositive() { return genrand_real3(); } /// <summary> /// Generates a random number on <c>[0,1)</c> with 53-bit resolution. /// </summary> /// <returns>A random number on <c>[0,1)</c> with 53-bit resolution</returns> public double Next53BitRes() { return genrand_res53(); } /// <summary> /// Reinitializes the random number generator using the time of day in /// milliseconds as the seed. /// </summary> public void Initialize() { init_genrand( (uint)DateTime.Now.Millisecond ); } /// <summary> /// Reinitializes the random number generator with the given seed. /// </summary> /// <param name="seed">The seed.</param> public void Initialize( int seed ) { init_genrand( (uint)seed ); } /// <summary> /// Reinitializes the random number generator with the given array. /// </summary> /// <param name="init">The array for initializing keys.</param> public void Initialize( int[] init ) { uint[] initArray = new uint[init.Length]; for ( int i = 0; i < init.Length; ++i ) initArray[i] = (uint)init[i]; init_by_array( initArray, (uint)initArray.Length ); } #region Methods ported from C ------------------------------------------- // initializes mt[N] with a seed private void init_genrand( uint s) { mt[0]= s & 0xffffffffU; for (mti=1; mti<N; mti++) { mt[mti] = (uint)(1812433253U * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); // See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. // In the previous versions, MSBs of the seed affect // only MSBs of the array mt[]. // 2002/01/09 modified by Makoto Matsumoto mt[mti] &= 0xffffffffU; // for >32 bit machines } } // initialize by an array with array-length // init_key is the array for initializing keys // key_length is its length private void init_by_array(uint[] init_key, uint key_length) { int i, j, k; init_genrand(19650218U); i=1; j=0; k = (int)(N>key_length ? N : key_length); for (; k>0; k--) { mt[i] = (uint)((uint)(mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525U)) + init_key[j] + j); /* non linear */ mt[i] &= 0xffffffffU; // for WORDSIZE > 32 machines i++; j++; if (i>=N) { mt[0] = mt[N-1]; i=1; } if (j>=key_length) j=0; } for (k=N-1; k>0; k--) { mt[i] = (uint)((uint)(mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941U))- i); /* non linear */ mt[i] &= 0xffffffffU; // for WORDSIZE > 32 machines i++; if (i>=N) { mt[0] = mt[N-1]; i=1; } } mt[0] = 0x80000000U; // MSB is 1; assuring non-zero initial array } // generates a random number on [0,0xffffffff]-interval uint genrand_int32() { uint y; if (mti >= N) { /* generate N words at one time */ int kk; if (mti == N+1) /* if init_genrand() has not been called, */ init_genrand(5489U); /* a default initial seed is used */ for (kk=0;kk<N-M;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1U]; } for (;kk<N-1;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1U]; } y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1U]; mti = 0; } y = mt[mti++]; // Tempering y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680U; y ^= (y << 15) & 0xefc60000U; y ^= (y >> 18); return y; } // generates a random number on [0,0x7fffffff]-interval private int genrand_int31() { return (int)(genrand_int32()>>1); } // generates a random number on [0,1]-real-interval double genrand_real1() { return genrand_int32()*(1.0/4294967295.0); // divided by 2^32-1 } // generates a random number on [0,1)-real-interval double genrand_real2() { return genrand_int32()*(1.0/4294967296.0); // divided by 2^32 } // generates a random number on (0,1)-real-interval double genrand_real3() { return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0); // divided by 2^32 } // generates a random number on [0,1) with 53-bit resolution double genrand_res53() { uint a=genrand_int32()>>5, b=genrand_int32()>>6; return(a*67108864.0+b)*(1.0/9007199254740992.0); } // These real versions are due to Isaku Wada, 2002/01/09 added #endregion Methods ported from C #endregion Member Functions } }
using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; namespace Orleans.Runtime.Messaging { internal abstract class ConnectionListener { private readonly IConnectionListenerFactory listenerFactory; private readonly ConnectionManager connectionManager; protected readonly ConcurrentDictionary<Connection, Task> connections = new ConcurrentDictionary<Connection, Task>(ReferenceEqualsComparer.Instance); private readonly ConnectionCommon connectionShared; private TaskCompletionSource<object> acceptLoopTcs; private IConnectionListener listener; private ConnectionDelegate connectionDelegate; protected ConnectionListener( IConnectionListenerFactory listenerFactory, IOptions<ConnectionOptions> connectionOptions, ConnectionManager connectionManager, ConnectionCommon connectionShared) { this.listenerFactory = listenerFactory; this.connectionManager = connectionManager; this.ConnectionOptions = connectionOptions.Value; this.connectionShared = connectionShared; } public abstract EndPoint Endpoint { get; } protected IServiceProvider ServiceProvider => this.connectionShared.ServiceProvider; protected NetworkingTrace NetworkingTrace => this.connectionShared.NetworkingTrace; public int ConnectionCount => this.connections.Count; protected ConnectionOptions ConnectionOptions { get; } protected abstract Connection CreateConnection(ConnectionContext context); protected ConnectionDelegate ConnectionDelegate { get { if (this.connectionDelegate != null) return this.connectionDelegate; lock (this) { if (this.connectionDelegate != null) return this.connectionDelegate; // Configure the connection builder using the user-defined options. var connectionBuilder = new ConnectionBuilder(this.ServiceProvider); this.ConfigureConnectionBuilder(connectionBuilder); Connection.ConfigureBuilder(connectionBuilder); return this.connectionDelegate = connectionBuilder.Build(); } } } protected virtual void ConfigureConnectionBuilder(IConnectionBuilder connectionBuilder) { } public async Task BindAsync(CancellationToken cancellationToken) { this.listener = await this.listenerFactory.BindAsync(this.Endpoint, cancellationToken); } public void Start() { if (this.listener is null) throw new InvalidOperationException("Listener is not bound"); this.acceptLoopTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); ThreadPool.UnsafeQueueUserWorkItem(this.StartAcceptingConnections, this.acceptLoopTcs); } private void StartAcceptingConnections(object completionObj) { _ = RunAcceptLoop((TaskCompletionSource<object>)completionObj); async Task RunAcceptLoop(TaskCompletionSource<object> completion) { try { while (true) { var context = await this.listener.AcceptAsync(); if (context == null) break; var connection = this.CreateConnection(context); this.StartConnection(connection); } } catch (Exception exception) { this.NetworkingTrace.LogCritical("Exception in AcceptAsync: {Exception}", exception); } finally { completion.TrySetResult(null); } } } public async Task StopAsync(CancellationToken cancellationToken) { try { if (this.acceptLoopTcs is object) { await Task.WhenAll( this.listener.UnbindAsync(cancellationToken).AsTask(), this.acceptLoopTcs.Task); } else { await this.listener.UnbindAsync(cancellationToken); } var cycles = 0; while (this.ConnectionCount > 0) { foreach (var connection in this.connections.Keys.ToImmutableList()) { try { connection.Close(); } catch { } } await Task.Delay(10); if (cancellationToken.IsCancellationRequested) break; if (++cycles > 100 && cycles % 500 == 0 && this.ConnectionCount > 0) { this.NetworkingTrace.LogWarning("Waiting for {NumRemaining} connections to terminate", this.ConnectionCount); } } await this.connectionManager.Closed; if (this.listener != null) { await this.listener.DisposeAsync(); } } catch (Exception exception) { this.NetworkingTrace.LogWarning("Exception during shutdown: {Exception}", exception); } } private void StartConnection(Connection connection) { ThreadPool.UnsafeQueueUserWorkItem(this.StartConnectionCore, connection); } private void StartConnectionCore(object state) { var connection = (Connection)state; _ = this.RunConnectionAsync(connection); } private async Task RunConnectionAsync(Connection connection) { await Task.Yield(); using (this.BeginConnectionScope(connection)) { try { var connectionTask = connection.Run(); this.connections.TryAdd(connection, connectionTask); await connectionTask; this.NetworkingTrace.LogInformation("Connection {Connection} terminated", connection); } catch (Exception exception) { this.NetworkingTrace.LogInformation(exception, "Connection {Connection} terminated with an exception", connection); } finally { this.connections.TryRemove(connection, out _); } } } private IDisposable BeginConnectionScope(Connection connection) { if (this.NetworkingTrace.IsEnabled(LogLevel.Critical)) { return this.NetworkingTrace.BeginScope(new ConnectionLogScope(connection)); } return null; } } }
namespace Nancy.Tests.Unit.ModelBinding { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Xml.Serialization; using FakeItEasy; using Nancy.Configuration; using Nancy.IO; using Nancy.Json; using Nancy.ModelBinding; using Nancy.ModelBinding.DefaultBodyDeserializers; using Nancy.ModelBinding.DefaultConverters; using Nancy.Responses.Negotiation; using Nancy.Tests.Fakes; using Nancy.Tests.Unit.ModelBinding.DefaultBodyDeserializers; using Xunit; public class DefaultBinderFixture { private readonly IFieldNameConverter passthroughNameConverter; private readonly BindingDefaults emptyDefaults; private readonly JavaScriptSerializer serializer; private readonly BindingDefaults bindingDefaults; public DefaultBinderFixture() { var environment = new DefaultNancyEnvironment(); environment.AddValue(JsonConfiguration.Default); environment.AddValue(GlobalizationConfiguration.Default); this.passthroughNameConverter = A.Fake<IFieldNameConverter>(); A.CallTo(() => this.passthroughNameConverter.Convert(null)).WithAnyArguments() .ReturnsLazily(f => (string)f.Arguments[0]); this.serializer = new JavaScriptSerializer(); this.serializer.RegisterConverters(JsonConfiguration.Default.Converters); this.bindingDefaults = new BindingDefaults(environment); this.emptyDefaults = A.Fake<BindingDefaults>(options => options.WithArgumentsForConstructor(new[] { environment })); A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(ArrayCache.Empty<IBodyDeserializer>()); A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(ArrayCache.Empty<ITypeConverter>()); } [Fact] public void Should_throw_if_type_converters_is_null() { // Given, When var result = Record.Exception(() => new DefaultBinder(null, ArrayCache.Empty<IBodyDeserializer>(), A.Fake<IFieldNameConverter>(), this.bindingDefaults)); // Then result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_if_body_deserializers_is_null() { // Given, When var result = Record.Exception(() => new DefaultBinder(ArrayCache.Empty<ITypeConverter>(), null, A.Fake<IFieldNameConverter>(), this.bindingDefaults)); // Then result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_if_body_deserializer_fails_and_IgnoreErrors_is_false() { // Given var deserializer = new ThrowingBodyDeserializer<FormatException>(); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); var config = new BindingConfig { IgnoreErrors = false }; // When var result = Record.Exception(() => binder.Bind(context, this.GetType(), null, config)); // Then result.ShouldBeOfType<ModelBindingException>(); result.InnerException.ShouldBeOfType<FormatException>(); } [Fact] public void Should_not_throw_if_body_deserializer_fails_and_IgnoreErrors_is_true() { // Given var deserializer = new ThrowingBodyDeserializer<FormatException>(); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); var config = new BindingConfig { IgnoreErrors = true }; // When, Then binder.Bind(context, this.GetType(), null, config); } [Fact] public void Should_throw_if_field_name_converter_is_null() { // Given, When var result = Record.Exception(() => new DefaultBinder(ArrayCache.Empty<ITypeConverter>(), ArrayCache.Empty<IBodyDeserializer>(), null, this.bindingDefaults)); // Then result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_if_defaults_is_null() { // Given, When var result = Record.Exception(() => new DefaultBinder(ArrayCache.Empty<ITypeConverter>(), ArrayCache.Empty<IBodyDeserializer>(), A.Fake<IFieldNameConverter>(), null)); // Then result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_call_body_deserializer_if_one_matches() { // Given var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_not_call_body_deserializer_if_doesnt_match() { // Given var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(false); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments() .MustNotHaveHappened(); } [Fact] public void Should_pass_request_content_type_to_can_deserialize() { // Then var deserializer = A.Fake<IBodyDeserializer>(); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>.That.Matches(x => x.Matches("application/xml")), A<BindingContext>._)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_pass_binding_context_to_can_deserialize() { // Then var deserializer = A.Fake<IBodyDeserializer>(); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>.That.Matches(x => x.Matches("application/xml")), A<BindingContext>.That.Not.IsNull())) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_use_object_from_deserializer_if_one_returned() { // Given var modelObject = new TestModel { StringProperty = "Hello!" }; var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.ShouldBeOfType<TestModel>(); ((TestModel)result).StringProperty.ShouldEqual("Hello!"); } [Fact] public void Should_use_object_from_deserializer_if_one_returned_and_overwrite_when_allowed() { // Given var modelObject = new TestModel { StringPropertyWithDefaultValue = "Hello!" }; var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.ShouldBeOfType<TestModel>(); ((TestModel)result).StringPropertyWithDefaultValue.ShouldEqual("Hello!"); } [Fact] public void Should_use_object_from_deserializer_if_one_returned_and_not_overwrite_when_not_allowed() { // Given var modelObject = new TestModel() { StringPropertyWithDefaultValue = "Hello!", StringFieldWithDefaultValue = "World!", }; var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject); var binder = this.GetBinder(bodyDeserializers: new[] { deserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.NoOverwrite); // Then result.ShouldBeOfType<TestModel>(); ((TestModel)result).StringPropertyWithDefaultValue.ShouldEqual("Default Property Value"); ((TestModel)result).StringFieldWithDefaultValue.ShouldEqual("Default Field Value"); } [Fact] public void Should_see_if_a_type_converter_is_available_for_each_property_on_the_model_where_incoming_value_exists() { // Given var typeConverter = A.Fake<ITypeConverter>(); A.CallTo(() => typeConverter.CanConvertTo(null, null)).WithAnyArguments().Returns(false); var binder = this.GetBinder(typeConverters: new[] { typeConverter }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "12"; // When binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then A.CallTo(() => typeConverter.CanConvertTo(null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Times(2)); } [Fact] public void Should_call_convert_on_type_converter_if_available() { // Given var typeConverter = A.Fake<ITypeConverter>(); A.CallTo(() => typeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true); A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null); var binder = this.GetBinder(typeConverters: new[] { typeConverter }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; // When binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_ignore_properties_that_cannot_be_converted() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "12"; context.Request.Form["DateProperty"] = "Broken"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(12); result.DateProperty.ShouldEqual(default(DateTime)); } [Fact] public void Should_throw_ModelBindingException_if_convertion_of_a_property_fails() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["IntProperty"] = "badint"; context.Request.Form["AnotherIntProperty"] = "morebad"; // Then Type modelType = typeof(TestModel); Assert.Throws<ModelBindingException>(() => binder.Bind(context, modelType, null, BindingConfig.Default)) .ShouldMatch(exception => exception.BoundType == modelType && exception.PropertyBindingExceptions.Any(pe => pe.PropertyName == "IntProperty" && pe.AttemptedValue == "badint") && exception.PropertyBindingExceptions.Any(pe => pe.PropertyName == "AnotherIntProperty" && pe.AttemptedValue == "morebad") && exception.PropertyBindingExceptions.All(pe => pe.InnerException.Message.Contains(pe.AttemptedValue) && pe.InnerException.Message.Contains(modelType.GetProperty(pe.PropertyName).PropertyType.Name))); } [Fact] public void Should_not_throw_ModelBindingException_if_convertion_of_property_fails_and_ignore_error_is_true() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["IntProperty"] = "badint"; context.Request.Form["AnotherIntProperty"] = "morebad"; var config = new BindingConfig {IgnoreErrors = true}; // When // Then Record.Exception(() => binder.Bind(context, typeof(TestModel), null, config)).ShouldBeNull(); } [Fact] public void Should_set_remaining_properties_when_one_fails_and_ignore_error_is_enabled() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["IntProperty"] = "badint"; context.Request.Form["AnotherIntProperty"] = 10; var config = new BindingConfig { IgnoreErrors = true }; // When var model = binder.Bind(context, typeof(TestModel), null, config) as TestModel; // Then model.AnotherIntProperty.ShouldEqual(10); } [Fact] public void Should_ignore_indexer_properties() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); var validProperties = 0; var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>._, A<BindingContext>._)).Returns(true); A.CallTo(() => deserializer.Deserialize(A<MediaRange>._, A<Stream>.Ignored, A<BindingContext>.Ignored)) .Invokes(f => { validProperties = f.Arguments.Get<BindingContext>(2).ValidModelBindingMembers.Count(); }) .Returns(new TestModel()); A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer }); // When binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then validProperties.ShouldEqual(22); } [Fact] public void Should_pass_binding_context_to_default_deserializer() { // Given var deserializer = A.Fake<IBodyDeserializer>(); var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>.That.Matches(x => x.Matches("application/xml")), A<BindingContext>.That.Not.IsNull())) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_use_field_name_converter_for_each_field() { // Given var binder = this.GetBinder(); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "12"; // When binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then A.CallTo(() => this.passthroughNameConverter.Convert(null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Times(2)); } [Fact] public void Should_not_bind_anything_on_blacklist() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "12"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default, "IntProperty"); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(0); } [Fact] public void Should_not_bind_anything_on_blacklist_when_the_blacklist_is_specified_by_expressions() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "12"; var fakeModule = A.Fake<INancyModule>(); var fakeModelBinderLocator = A.Fake<IModelBinderLocator>(); A.CallTo(() => fakeModule.Context).Returns(context); A.CallTo(() => fakeModule.ModelBinderLocator).Returns(fakeModelBinderLocator); A.CallTo(() => fakeModelBinderLocator.GetBinderForType(typeof (TestModel), context)).Returns(binder); // When var result = fakeModule.Bind<TestModel>(tm => tm.IntProperty); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(0); } [Fact] public void Should_use_default_body_deserializer_if_one_found() { // Given var deserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer }); var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_use_default_type_converter_if_one_found() { // Given var typeConverter = A.Fake<ITypeConverter>(); A.CallTo(() => typeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true); A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null); A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new[] { typeConverter }); var binder = this.GetBinder(ArrayCache.Empty<ITypeConverter>()); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; // When binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void User_body_serializer_should_take_precedence_over_default_one() { // Given var userDeserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => userDeserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); var defaultDeserializer = A.Fake<IBodyDeserializer>(); A.CallTo(() => defaultDeserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true); A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { defaultDeserializer }); var binder = this.GetBinder(bodyDeserializers: new[] { userDeserializer }); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When binder.Bind(context, this.GetType(), null, BindingConfig.Default); // Then A.CallTo(() => userDeserializer.Deserialize(null, null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => defaultDeserializer.Deserialize(null, null, null)).WithAnyArguments() .MustNotHaveHappened(); } [Fact] public void User_type_converter_should_take_precedence_over_default_one() { // Given var userTypeConverter = A.Fake<ITypeConverter>(); A.CallTo(() => userTypeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true); A.CallTo(() => userTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null); var defaultTypeConverter = A.Fake<ITypeConverter>(); A.CallTo(() => defaultTypeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true); A.CallTo(() => defaultTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null); A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new[] { defaultTypeConverter }); var binder = this.GetBinder(new[] { userTypeConverter }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["StringProperty"] = "Test"; // When binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then A.CallTo(() => userTypeConverter.Convert(null, null, null)).WithAnyArguments() .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => defaultTypeConverter.Convert(null, null, null)).WithAnyArguments() .MustNotHaveHappened(); } [Fact] public void Should_bind_model_from_request() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Query["StringProperty"] = "Test"; context.Request.Query["IntProperty"] = "3"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(3); } [Fact] public void Should_bind_inherited_model_from_request() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Query["StringProperty"] = "Test"; context.Request.Query["IntProperty"] = "3"; context.Request.Query["AnotherProperty"] = "Hello"; // When var result = (InheritedTestModel)binder.Bind(context, typeof(InheritedTestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(3); result.AnotherProperty.ShouldEqual("Hello"); } [Fact] public void Should_bind_model_from_context_parameters() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Parameters["StringProperty"] = "Test"; context.Parameters["IntProperty"] = "3"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(3); } [Fact] public void Form_properties_should_take_precendence_over_request_properties() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "3"; context.Request.Query["StringProperty"] = "Test2"; context.Request.Query["IntProperty"] = "1"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(3); } [Fact] public void Should_bind_multiple_Form_properties_to_list() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["StringProperty_0"] = "Test"; context.Request.Form["IntProperty_0"] = "1"; context.Request.Form["StringProperty_1"] = "Test2"; context.Request.Form["IntProperty_1"] = "2"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.First().StringProperty.ShouldEqual("Test"); result.First().IntProperty.ShouldEqual(1); result.Last().StringProperty.ShouldEqual("Test2"); result.Last().IntProperty.ShouldEqual(2); } [Fact] public void Should_bind_more_than_10_multiple_Form_properties_to_list() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntProperty_0"] = "1"; context.Request.Form["IntProperty_01"] = "2"; context.Request.Form["IntProperty_02"] = "3"; context.Request.Form["IntProperty_03"] = "4"; context.Request.Form["IntProperty_04"] = "5"; context.Request.Form["IntProperty_05"] = "6"; context.Request.Form["IntProperty_06"] = "7"; context.Request.Form["IntProperty_07"] = "8"; context.Request.Form["IntProperty_08"] = "9"; context.Request.Form["IntProperty_09"] = "10"; context.Request.Form["IntProperty_10"] = "11"; context.Request.Form["IntProperty_11"] = "12"; context.Request.Form["IntProperty_12"] = "13"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.First().IntProperty.ShouldEqual(1); result.ElementAt(1).IntProperty.ShouldEqual(2); result.Last().IntProperty.ShouldEqual(13); } [Fact] public void Should_bind_more_than_10_multiple_Form_properties_to_list_should_work_with_padded_zeros() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntProperty_00"] = "1"; context.Request.Form["IntProperty_01"] = "2"; context.Request.Form["IntProperty_02"] = "3"; context.Request.Form["IntProperty_03"] = "4"; context.Request.Form["IntProperty_04"] = "5"; context.Request.Form["IntProperty_05"] = "6"; context.Request.Form["IntProperty_06"] = "7"; context.Request.Form["IntProperty_07"] = "8"; context.Request.Form["IntProperty_08"] = "9"; context.Request.Form["IntProperty_09"] = "10"; context.Request.Form["IntProperty_10"] = "11"; context.Request.Form["IntProperty_11"] = "12"; context.Request.Form["IntProperty_12"] = "13"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.First().IntProperty.ShouldEqual(1); result.Last().IntProperty.ShouldEqual(13); } [Fact] public void Should_bind_more_than_10_multiple_Form_properties_to_list_starting_counting_from_1() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntProperty_01"] = "1"; context.Request.Form["IntProperty_02"] = "2"; context.Request.Form["IntProperty_03"] = "3"; context.Request.Form["IntProperty_04"] = "4"; context.Request.Form["IntProperty_05"] = "5"; context.Request.Form["IntProperty_06"] = "6"; context.Request.Form["IntProperty_07"] = "7"; context.Request.Form["IntProperty_08"] = "8"; context.Request.Form["IntProperty_09"] = "9"; context.Request.Form["IntProperty_10"] = "10"; context.Request.Form["IntProperty_11"] = "11"; context.Request.Form["IntProperty_12"] = "12"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.First().IntProperty.ShouldEqual(1); result.Last().IntProperty.ShouldEqual(12); } [Fact] public void Should_be_able_to_bind_more_than_once_should_ignore_non_list_properties_when_binding_to_a_list() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "3"; context.Request.Form["NestedIntProperty[0]"] = "1"; context.Request.Form["NestedIntField[0]"] = "2"; context.Request.Form["NestedStringProperty[0]"] = "one"; context.Request.Form["NestedStringField[0]"] = "two"; context.Request.Form["NestedIntProperty[1]"] = "3"; context.Request.Form["NestedIntField[1]"] = "4"; context.Request.Form["NestedStringProperty[1]"] = "three"; context.Request.Form["NestedStringField[1]"] = "four"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); var result2 = (List<AnotherTestModel>)binder.Bind(context, typeof(List<AnotherTestModel>), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(3); result2.ShouldHaveCount(2); result2.First().NestedIntProperty.ShouldEqual(1); result2.First().NestedIntField.ShouldEqual(2); result2.First().NestedStringProperty.ShouldEqual("one"); result2.First().NestedStringField.ShouldEqual("two"); result2.Last().NestedIntProperty.ShouldEqual(3); result2.Last().NestedIntField.ShouldEqual(4); result2.Last().NestedStringProperty.ShouldEqual("three"); result2.Last().NestedStringField.ShouldEqual("four"); } [Fact] public void Should_bind_more_than_10_multiple_Form_properties_to_list_starting_with_jagged_ids() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntProperty_01"] = "1"; context.Request.Form["IntProperty_04"] = "2"; context.Request.Form["IntProperty_05"] = "3"; context.Request.Form["IntProperty_06"] = "4"; context.Request.Form["IntProperty_09"] = "5"; context.Request.Form["IntProperty_11"] = "6"; context.Request.Form["IntProperty_57"] = "7"; context.Request.Form["IntProperty_199"] = "8"; context.Request.Form["IntProperty_1599"] = "9"; context.Request.Form["StringProperty_1599"] = "nine"; context.Request.Form["IntProperty_233"] = "10"; context.Request.Form["IntProperty_14"] = "11"; context.Request.Form["IntProperty_12"] = "12"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.First().IntProperty.ShouldEqual(1); result.Last().IntProperty.ShouldEqual(9); result.Last().StringProperty.ShouldEqual("nine"); } [Fact] public void Should_bind_to_IEnumerable_from_Form() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntValuesProperty"] = "1,2,3,4"; context.Request.Form["IntValuesField"] = "5,6,7,8"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.IntValuesProperty.ShouldHaveCount(4); result.IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 }); result.IntValuesField.ShouldHaveCount(4); result.IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 }); } [Fact] public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntValuesProperty_0"] = "1,2,3,4"; context.Request.Form["IntValuesField_0"] = "5,6,7,8"; context.Request.Form["IntValuesProperty_1"] = "9,10,11,12"; context.Request.Form["IntValuesField_1"] = "13,14,15,16"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.ShouldHaveCount(2); result.First().IntValuesProperty.ShouldHaveCount(4); result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 }); result.First().IntValuesField.ShouldHaveCount(4); result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 }); result.Last().IntValuesProperty.ShouldHaveCount(4); result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 }); result.Last().IntValuesField.ShouldHaveCount(4); result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 }); } [Fact] public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs_using_brackets_and_specifying_an_instance() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntValuesProperty[0]"] = "1,2,3,4"; context.Request.Form["IntValuesField[0]"] = "5,6,7,8"; context.Request.Form["IntValuesProperty[1]"] = "9,10,11,12"; context.Request.Form["IntValuesField[1]"] = "13,14,15,16"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), new List<TestModel> { new TestModel {AnotherStringProperty = "Test"} }, new BindingConfig { Overwrite = false}); // Then result.ShouldHaveCount(2); result.First().AnotherStringProperty.ShouldEqual("Test"); result.First().IntValuesProperty.ShouldHaveCount(4); result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 }); result.First().IntValuesField.ShouldHaveCount(4); result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 }); result.Last().AnotherStringProperty.ShouldBeNull(); result.Last().IntValuesProperty.ShouldHaveCount(4); result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 }); result.Last().IntValuesField.ShouldHaveCount(4); result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 }); } [Fact] public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs_using_brackets() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["IntValuesProperty[0]"] = "1,2,3,4"; context.Request.Form["IntValuesField[0]"] = "5,6,7,8"; context.Request.Form["IntValuesProperty[1]"] = "9,10,11,12"; context.Request.Form["IntValuesField[1]"] = "13,14,15,16"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.ShouldHaveCount(2); result.First().IntValuesProperty.ShouldHaveCount(4); result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 }); result.First().IntValuesField.ShouldHaveCount(4); result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 }); result.Last().IntValuesProperty.ShouldHaveCount(4); result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 }); result.Last().IntValuesField.ShouldHaveCount(4); result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 }); } [Fact] public void Should_bind_collections_regardless_of_case() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" }); context.Request.Form["lowercaseintproperty[0]"] = "1"; context.Request.Form["lowercaseintproperty[1]"] = "2"; context.Request.Form["lowercaseIntproperty[2]"] = "3"; context.Request.Form["lowercaseIntproperty[3]"] = "4"; context.Request.Form["Lowercaseintproperty[4]"] = "5"; context.Request.Form["Lowercaseintproperty[5]"] = "6"; context.Request.Form["LowercaseIntproperty[6]"] = "7"; context.Request.Form["LowercaseIntproperty[7]"] = "8"; context.Request.Form["lowercaseintfield[0]"] = "9"; context.Request.Form["lowercaseintfield[1]"] = "10"; context.Request.Form["lowercaseIntfield[2]"] = "11"; context.Request.Form["lowercaseIntfield[3]"] = "12"; context.Request.Form["Lowercaseintfield[4]"] = "13"; context.Request.Form["Lowercaseintfield[5]"] = "14"; context.Request.Form["LowercaseIntfield[6]"] = "15"; context.Request.Form["LowercaseIntfield[7]"] = "16"; // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.ShouldHaveCount(8); result.First().lowercaseintproperty.ShouldEqual(1); result.Last().lowercaseintproperty.ShouldEqual(8); result.First().lowercaseintfield.ShouldEqual(9); result.Last().lowercaseintfield.ShouldEqual(16); } [Fact] public void Form_properties_should_take_precendence_over_request_properties_and_context_properties() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Form["StringProperty"] = "Test"; context.Request.Form["IntProperty"] = "3"; context.Request.Query["StringProperty"] = "Test2"; context.Request.Query["IntProperty"] = "1"; context.Parameters["StringProperty"] = "Test3"; context.Parameters["IntProperty"] = "2"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(3); } [Fact] public void Request_properties_should_take_precendence_over_context_properties() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Query["StringProperty"] = "Test"; context.Request.Query["IntProperty"] = "12"; context.Parameters["StringProperty"] = "Test2"; context.Parameters["IntProperty"] = "13"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(12); } [Fact] public void Should_be_able_to_bind_from_form_and_request_simultaneously() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Form["StringProperty"] = "Test"; context.Request.Query["IntProperty"] = "12"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(12); } [Theory] [InlineData("de-DE", 4.50)] [InlineData("en-GB", 450)] [InlineData("en-US", 450)] [InlineData("sv-SE", 4.50)] [InlineData("ru-RU", 4.50)] [InlineData("zh-TW", 450)] public void Should_be_able_to_bind_culturally_aware_form_properties_if_numeric(string culture, double expected) { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Culture = new CultureInfo(culture); context.Request.Form["DoubleProperty"] = "4,50"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.DoubleProperty.ShouldEqual(expected); } [Theory] [InlineData("12/25/2012", 12, 25, 2012, "en-US")] [InlineData("12/12/2012", 12, 12, 2012, "en-US")] [InlineData("25/12/2012", 12, 25, 2012, "en-GB")] [InlineData("12/12/2012", 12, 12, 2012, "en-GB")] [InlineData("12/12/2012", 12, 12, 2012, "ru-RU")] [InlineData("25/12/2012", 12, 25, 2012, "ru-RU")] [InlineData("2012-12-25", 12, 25, 2012, "zh-TW")] [InlineData("2012-12-12", 12, 12, 2012, "zh-TW")] public void Should_be_able_to_bind_culturally_aware_form_properties_if_datetime(string date, int month, int day, int year, string culture) { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Culture = new CultureInfo(culture); context.Request.Form["DateProperty"] = date; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.DateProperty.Date.Month.ShouldEqual(month); result.DateProperty.Date.Day.ShouldEqual(day); result.DateProperty.Date.Year.ShouldEqual(year); } [Fact] public void Should_be_able_to_bind_from_request_and_context_simultaneously() { // Given var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Query["StringProperty"] = "Test"; context.Parameters["IntProperty"] = "12"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(12); } [Fact] public void Should_not_overwrite_nullable_property_if_already_set_and_overwriting_is_not_allowed() { // Given var binder = this.GetBinder(); var existing = new TestModel { StringProperty = "Existing Value" }; var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Query["StringProperty"] = "Test"; context.Request.Query["IntProperty"] = "12"; context.Parameters["StringProperty"] = "Test2"; context.Parameters["IntProperty"] = "1"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.NoOverwrite); // Then result.StringProperty.ShouldEqual("Existing Value"); result.IntProperty.ShouldEqual(12); } [Fact] public void Should_not_overwrite_non_nullable_property_if_already_set_and_overwriting_is_not_allowed() { // Given var binder = this.GetBinder(); var existing = new TestModel { IntProperty = 27 }; var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Query["StringProperty"] = "Test"; context.Request.Query["IntProperty"] = "12"; context.Parameters["StringProperty"] = "Test2"; context.Parameters["IntProperty"] = "1"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.NoOverwrite); // Then result.StringProperty.ShouldEqual("Test"); result.IntProperty.ShouldEqual(27); } [Fact] public void Should_overwrite_nullable_property_if_already_set_and_overwriting_is_allowed() { // Given var binder = this.GetBinder(); var existing = new TestModel { StringProperty = "Existing Value" }; var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Parameters["StringProperty"] = "Test2"; context.Parameters["IntProperty"] = "1"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test2"); result.IntProperty.ShouldEqual(1); } [Fact] public void Should_overwrite_non_nullable_property_if_already_set_and_overwriting_is_allowed() { // Given var binder = this.GetBinder(); var existing = new TestModel { IntProperty = 27 }; var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Parameters["StringProperty"] = "Test2"; context.Parameters["IntProperty"] = "1"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("Test2"); result.IntProperty.ShouldEqual(1); } [Fact] public void Should_bind_list_model_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() }); var body = XmlBodyDeserializerFixture.ToXmlString(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } })); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body); // When var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default); // Then result.First().StringProperty.ShouldEqual("Test"); result.Last().StringProperty.ShouldEqual("AnotherTest"); } [Fact] public void Should_bind_array_model_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() }); var body = XmlBodyDeserializerFixture.ToXmlString(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } })); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body); // When var result = (TestModel[])binder.Bind(context, typeof(TestModel[]), null, BindingConfig.Default); // Then result.First().StringProperty.ShouldEqual("Test"); result.Last().StringProperty.ShouldEqual("AnotherTest"); } [Fact] public void Should_bind_string_array_model_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize(new[] { "Test","AnotherTest"}); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); // When var result = (string[])binder.Bind(context, typeof(string[]), null, BindingConfig.Default); // Then result.First().ShouldEqual("Test"); result.Last().ShouldEqual("AnotherTest"); } [Fact] public void Should_bind_ienumerable_model_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } })); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); // When var result = (IEnumerable<TestModel>)binder.Bind(context, typeof(IEnumerable<TestModel>), null, BindingConfig.Default); // Then result.First().StringProperty.ShouldEqual("Test"); result.Last().StringProperty.ShouldEqual("AnotherTest"); } [Fact] public void Should_bind_ienumerable_model_with_instance_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } })); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); var then = DateTime.Now; var instance = new List<TestModel> { new TestModel{ DateProperty = then }, new TestModel { IntProperty = 9, AnotherStringProperty = "Bananas" } }; // When var result = (IEnumerable<TestModel>)binder.Bind(context, typeof(IEnumerable<TestModel>), instance, new BindingConfig{Overwrite = false}); // Then result.First().StringProperty.ShouldEqual("Test"); result.First().DateProperty.ShouldEqual(then); result.Last().StringProperty.ShouldEqual("AnotherTest"); result.Last().IntProperty.ShouldEqual(9); result.Last().AnotherStringProperty.ShouldEqual("Bananas"); } [Fact] public void Should_bind_model_with_instance_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() }); var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { StringProperty = "Test" }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body); var then = DateTime.Now; var instance = new TestModel { DateProperty = then, IntProperty = 6, AnotherStringProperty = "Beers" }; // Wham var result = (TestModel)binder.Bind(context, typeof(TestModel), instance, new BindingConfig { Overwrite = false }); // Then result.StringProperty.ShouldEqual("Test"); result.DateProperty.ShouldEqual(then); result.IntProperty.ShouldEqual(6); result.AnotherStringProperty.ShouldEqual("Beers"); } [Fact] public void Should_bind_model_from_body_that_contains_an_array() { //Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = this.GetBinder(typeConverters, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize( new TestModel { StringProperty = "Test", SomeStringsProperty = new[] { "E", "A", "D", "G", "B", "E" }, SomeStringsField = new[] { "G", "D", "A", "E" }, }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.SomeStringsProperty.ShouldHaveCount(6); result.SomeStringsProperty.ShouldEqualSequence(new[] { "E", "A", "D", "G", "B", "E" }); result.SomeStringsField.ShouldHaveCount(4); result.SomeStringsField.ShouldEqualSequence(new[] { "G", "D", "A", "E" }); } [Fact] public void Should_bind_array_model_from_body_that_contains_an_array() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize(new[] { new TestModel() { StringProperty = "Test", SomeStringsProperty = new[] {"E", "A", "D", "G", "B", "E"}, SomeStringsField = new[] { "G", "D", "A", "E" }, }, new TestModel() { StringProperty = "AnotherTest", SomeStringsProperty = new[] {"E", "A", "D", "G", "B", "E"}, SomeStringsField = new[] { "G", "D", "A", "E" }, } }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); // When var result = (TestModel[])binder.Bind(context, typeof(TestModel[]), null, BindingConfig.Default, "SomeStringsProperty", "SomeStringsField"); // Then result.ShouldHaveCount(2); result.First().SomeStringsProperty.ShouldBeNull(); result.First().SomeStringsField.ShouldBeNull(); result.Last().SomeStringsProperty.ShouldBeNull(); result.Last().SomeStringsField.ShouldBeNull(); } [Fact] public void Form_request_and_context_properties_should_take_precedence_over_body_properties() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var bodyDeserializers = new IBodyDeserializer[] { new XmlBodyDeserializer() }; var binder = this.GetBinder(typeConverters, bodyDeserializers); var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { IntProperty = 0, StringProperty = "From body" }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body); context.Request.Form["StringProperty"] = "From form"; context.Request.Query["IntProperty"] = "1"; context.Parameters["AnotherStringProperty"] = "From context"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("From form"); result.AnotherStringProperty.ShouldEqual("From context"); result.IntProperty.ShouldEqual(1); } [Fact] public void Form_request_and_context_properties_should_be_ignored_in_body_only_mode_when_there_is_a_body() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var bodyDeserializers = new IBodyDeserializer[] { new XmlBodyDeserializer() }; var binder = GetBinder(typeConverters, bodyDeserializers); var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { IntProperty = 2, StringProperty = "From body" }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body); context.Request.Form["StringProperty"] = "From form"; context.Request.Query["IntProperty"] = "1"; context.Parameters["AnotherStringProperty"] = "From context"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, new BindingConfig { BodyOnly = true }); // Then result.StringProperty.ShouldEqual("From body"); result.AnotherStringProperty.ShouldBeNull(); // not in body, so default value result.IntProperty.ShouldEqual(2); } [Fact] public void Form_request_and_context_properties_should_NOT_be_used_in_body_only_mode_if_there_is_no_body() { // Given var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() }; var binder = GetBinder(typeConverters); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); context.Request.Form["StringProperty"] = "From form"; context.Request.Query["IntProperty"] = "1"; context.Parameters["AnotherStringProperty"] = "From context"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, new BindingConfig { BodyOnly = true }); // Then result.StringProperty.ShouldEqual(null); result.AnotherStringProperty.ShouldEqual(null); result.IntProperty.ShouldEqual(0); } [Fact] public void Should_be_able_to_bind_body_request_form_and_context_properties() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() }); var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { DateProperty = new DateTime(2012, 8, 16) }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body); context.Request.Form["IntProperty"] = "0"; context.Request.Query["StringProperty"] = "From Query"; context.Parameters["AnotherStringProperty"] = "From Context"; // When var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default); // Then result.StringProperty.ShouldEqual("From Query"); result.IntProperty.ShouldEqual(0); result.DateProperty.ShouldEqual(new DateTime(2012, 8, 16)); result.AnotherStringProperty.ShouldEqual("From Context"); } [Fact] public void Should_ignore_existing_instance_if_type_doesnt_match() { //Given var binder = this.GetBinder(); var existing = new object(); var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" }); // When var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default); // Then result.ShouldNotBeSameAs(existing); } [Fact] public void Should_bind_to_valuetype_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize(1); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); // When var result = (int)binder.Bind(context, typeof(int), null, BindingConfig.Default); // Then result.ShouldEqual(1); } [Fact] public void Should_bind_ienumerable_model__of_valuetype_from_body() { //Given var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) }); var body = serializer.Serialize(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }); var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body); // When var result = (IEnumerable<int>)binder.Bind(context, typeof(IEnumerable<int>), null, BindingConfig.Default); // Then result.ShouldEqualSequence(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }); } [Fact] public void Should_bind_to_model_with_non_public_default_constructor() { var binder = this.GetBinder(); var context = CreateContextWithHeader("Content-Type", new[] { "application/json" }); context.Request.Form["IntProperty"] = "10"; var result = (TestModelWithHiddenDefaultConstructor)binder.Bind(context, typeof (TestModelWithHiddenDefaultConstructor), null, BindingConfig.Default); result.ShouldNotBeNull(); result.IntProperty.ShouldEqual(10); } private IBinder GetBinder(IEnumerable<ITypeConverter> typeConverters = null, IEnumerable<IBodyDeserializer> bodyDeserializers = null, IFieldNameConverter nameConverter = null, BindingDefaults bindingDefaults = null) { var converters = typeConverters ?? new ITypeConverter[] { new DateTimeConverter(), new NumericConverter(), new FallbackConverter() }; var deserializers = bodyDeserializers ?? ArrayCache.Empty<IBodyDeserializer>(); var converter = nameConverter ?? this.passthroughNameConverter; var defaults = bindingDefaults ?? this.emptyDefaults; return new DefaultBinder(converters, deserializers, converter, defaults); } private static NancyContext CreateContextWithHeader(string name, IEnumerable<string> values) { var header = new Dictionary<string, IEnumerable<string>> { { name, values } }; return new NancyContext { Request = new FakeRequest("GET", "/", header), Parameters = DynamicDictionary.Empty }; } private static NancyContext CreateContextWithHeaderAndBody(string name, IEnumerable<string> values, string body) { var header = new Dictionary<string, IEnumerable<string>> { { name, values } }; byte[] byteArray = Encoding.UTF8.GetBytes(body); var bodyStream = RequestStream.FromStream(new MemoryStream(byteArray)); return new NancyContext { Request = new FakeRequest("GET", "/", header, bodyStream, "http", string.Empty), Parameters = DynamicDictionary.Empty }; } private static INancyEnvironment GetTestingEnvironment() { var envionment = new DefaultNancyEnvironment(); envionment.AddValue(JsonConfiguration.Default); envionment.AddValue(GlobalizationConfiguration.Default); return envionment; } public class TestModel { public TestModel() { this.StringPropertyWithDefaultValue = "Default Property Value"; this.StringFieldWithDefaultValue = "Default Field Value"; } public string StringProperty { get; set; } public string AnotherStringProperty { get; set; } public string StringField; public string AnotherStringField; public int IntProperty { get; set; } public int AnotherIntProperty { get; set; } public int IntField; public int AnotherIntField; public int lowercaseintproperty { get; set; } public int lowercaseintfield; public DateTime DateProperty { get; set; } public DateTime DateField; public string StringPropertyWithDefaultValue { get; set; } public string StringFieldWithDefaultValue; public double DoubleProperty { get; set; } public double DoubleField; [XmlIgnore] public IEnumerable<int> IntValuesProperty { get; set; } [XmlIgnore] public IEnumerable<int> IntValuesField; public string[] SomeStringsProperty { get; set; } public string[] SomeStringsField; public int this[int index] { get { return 0; } set { } } public List<AnotherTestModel> ModelsProperty { get; set; } public List<AnotherTestModel> ModelsField; } public class InheritedTestModel : TestModel { public string AnotherProperty { get; set; } } public class AnotherTestModel { public string NestedStringProperty { get; set; } public int NestedIntProperty { get; set; } public double NestedDoubleProperty { get; set; } public string NestedStringField; public int NestedIntField; public double NestedDoubleField; } private class ThrowingBodyDeserializer<T> : IBodyDeserializer where T : Exception, new() { public bool CanDeserialize(MediaRange mediaRange, BindingContext context) { return true; } public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context) { throw new T(); } } public class TestModelWithHiddenDefaultConstructor { public int IntProperty { get; private set; } private TestModelWithHiddenDefaultConstructor() { } } } public class BindingConfigFixture { [Fact] public void Should_allow_overwrite_on_new_instance() { // Given // When var instance = new BindingConfig(); // Then instance.Overwrite.ShouldBeTrue(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementUInt160() { var test = new VectorGetAndWithElement__GetAndWithElementUInt160(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt160 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); UInt16[] values = new UInt16[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt16(); } Vector64<UInt16> value = Vector64.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { UInt16 result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<UInt16.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt16 insertedValue = TestLibrary.Generator.GetUInt16(); try { Vector64<UInt16> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<UInt16.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); UInt16[] values = new UInt16[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt16(); } Vector64<UInt16> value = Vector64.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector64) .GetMethod(nameof(Vector64.GetElement)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((UInt16)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<UInt16.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt16 insertedValue = TestLibrary.Generator.GetUInt16(); try { object result2 = typeof(Vector64) .GetMethod(nameof(Vector64.WithElement)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector64<UInt16>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<UInt16.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(UInt16 result, UInt16[] values, [CallerMemberName] string method = "") { if (result != values[0]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector64<UInt16.GetElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector64<UInt16> result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "") { UInt16[] resultElements = new UInt16[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(UInt16[] result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 0) && (result[i] != values[i])) { succeeded = false; break; } } if (result[0] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<UInt16.WithElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.InteropServices; using FluentAssertions; using Microsoft.DotNet.Configurer; using Microsoft.DotNet.Tools.MSBuild; using Microsoft.DotNet.Tools.Test.Utilities; using NuGet.Protocol; using Xunit; using Xunit.Abstractions; using MSBuildCommand = Microsoft.DotNet.Tools.Test.Utilities.MSBuildCommand; namespace Microsoft.DotNet.Cli.MSBuild.Tests { public class GivenDotnetMSBuildBuildsProjects : TestBase { private readonly ITestOutputHelper _output; public GivenDotnetMSBuildBuildsProjects(ITestOutputHelper output) { _output = output; } [Fact] public void ItRunsSpecifiedTargetsWithPropertiesCorrectly() { var testInstance = TestAssets.Get("MSBuildBareBonesProject") .CreateInstance() .WithSourceFiles(); var testProjectDirectory = testInstance.Root; new MSBuildCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput("/t:SayHello") .Should() .Pass() .And .HaveStdOutContaining("Hello, from MSBuild!"); new MSBuildCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput("/t:SayGoodbye") .Should() .Pass() .And .HaveStdOutContaining("Goodbye, from MSBuild. :'("); new MSBuildCommand() .WithWorkingDirectory(testProjectDirectory) .ExecuteWithCapturedOutput("/t:SayThis /p:This=GreatScott") .Should() .Pass() .And .HaveStdOutContaining("You want me to say 'GreatScott'"); } [Theory(Skip="New parser feature needed")] [InlineData("build")] [InlineData("clean")] [InlineData("pack")] [InlineData("publish")] [InlineData("restore")] public void When_help_is_invoked_Then_MSBuild_extra_options_text_is_included_in_output(string commandName) { const string MSBuildHelpText = " Any extra options that should be passed to MSBuild. See 'dotnet msbuild -h' for available options."; var projectDirectory = TestAssets.CreateTestDirectory(commandName); var result = new TestCommand("dotnet") .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"{commandName} --help"); result.ExitCode.Should().Be(0); result.StdOut.Should().Contain(MSBuildHelpText); } [Fact] public void WhenRestoreSourcesStartsWithUnixPathThenHttpsSourceIsParsedCorrectly() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return; } // this is a workaround for https://github.com/Microsoft/msbuild/issues/1622 var testInstance = TestAssets.Get("LibraryWithUnresolvablePackageReference") .CreateInstance() .WithSourceFiles(); var root = testInstance.Root; var somePathThatExists = "/usr/local/bin"; var result = new DotnetCommand() .WithWorkingDirectory(root) .Execute($"msbuild /p:RestoreSources={somePathThatExists};https://api.nuget.org/v3/index.json /t:restore LibraryWithUnresolvablePackageReference.csproj"); _output.WriteLine($"[STDOUT]\n{result.StdOut}\n[STDERR]\n{result.StdErr}"); result.Should().Fail(); result.StdOut.Should() .ContainVisuallySameFragment( @"Feeds used: /usr/local/bin https://api.nuget.org/v3/index.json"); } [Fact] public void WhenDotnetRunHelpIsInvokedAppArgumentsTextIsIncludedInOutput() { const string AppArgumentsText = "Arguments passed to the application that is being run."; var projectDirectory = TestAssets.CreateTestDirectory("RunContainsAppArgumentsText"); var result = new TestCommand("dotnet") .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput("run --help"); result.ExitCode.Should().Be(0); result.StdOut.Should().Contain(AppArgumentsText); } [Fact] public void WhenTelemetryIsEnabledTheLoggerIsAddedToTheCommandLine() { Telemetry telemetry; string[] allArgs = GetArgsForMSBuild(() => true, out telemetry); // telemetry will still be disabled if environmental variable is set if (telemetry.Enabled) { allArgs.Should().NotBeNull(); allArgs.Should().Contain( value => value.IndexOf("/Logger", StringComparison.OrdinalIgnoreCase) >= 0, "The MSBuild logger argument should be specified when telemetry is enabled."); } } [Fact] public void WhenTelemetryIsDisabledTheLoggerIsNotAddedToTheCommandLine() { string[] allArgs = GetArgsForMSBuild(() => false); allArgs.Should().NotBeNull(); allArgs.Should().NotContain( value => value.IndexOf("/Logger", StringComparison.OrdinalIgnoreCase) >= 0, $"The MSBuild logger argument should not be specified when telemetry is disabled."); } private string[] GetArgsForMSBuild(Func<bool> sentinelExists) { Telemetry telemetry; return GetArgsForMSBuild(sentinelExists, out telemetry); } private string[] GetArgsForMSBuild(Func<bool> sentinelExists, out Telemetry telemetry) { telemetry = new Telemetry(new MockNuGetCacheSentinel(sentinelExists)); MSBuildForwardingApp msBuildForwardingApp = new MSBuildForwardingApp(Enumerable.Empty<string>()); FieldInfo forwardingAppFieldInfo = msBuildForwardingApp .GetType() .GetField("_forwardingApp", BindingFlags.Instance | BindingFlags.NonPublic); ForwardingApp forwardingApp = forwardingAppFieldInfo?.GetValue(msBuildForwardingApp) as ForwardingApp; FieldInfo allArgsFieldinfo = forwardingApp? .GetType() .GetField("_allArgs", BindingFlags.Instance | BindingFlags.NonPublic); return allArgsFieldinfo?.GetValue(forwardingApp) as string[]; } } public sealed class MockNuGetCacheSentinel : INuGetCacheSentinel { private readonly Func<bool> _exists; public MockNuGetCacheSentinel(Func<bool> exists = null) { _exists = exists ?? (() => true); } public void Dispose() { } public bool InProgressSentinelAlreadyExists() => false; public bool Exists() => _exists(); public void CreateIfNotExists() { } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using Google.Protobuf.TestProtos; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; namespace Google.Protobuf.Reflection { /// <summary> /// Tests for descriptors. (Not in its own namespace or broken up into individual classes as the /// size doesn't warrant it. On the other hand, this makes me feel a bit dirty...) /// </summary> public class DescriptorsTest { [Test] public void FileDescriptor_GeneratedCode() { TestFileDescriptor( UnittestProto3Reflection.Descriptor, UnittestImportProto3Reflection.Descriptor, UnittestImportPublicProto3Reflection.Descriptor); } [Test] public void FileDescriptor_BuildFromByteStrings() { // The descriptors have to be supplied in an order such that all the // dependencies come before the descriptors depending on them. var descriptorData = new List<ByteString> { UnittestImportPublicProto3Reflection.Descriptor.SerializedData, UnittestImportProto3Reflection.Descriptor.SerializedData, UnittestProto3Reflection.Descriptor.SerializedData }; var converted = FileDescriptor.BuildFromByteStrings(descriptorData); Assert.AreEqual(3, converted.Count); TestFileDescriptor(converted[2], converted[1], converted[0]); } private void TestFileDescriptor(FileDescriptor file, FileDescriptor importedFile, FileDescriptor importedPublicFile) { Assert.AreEqual("unittest_proto3.proto", file.Name); Assert.AreEqual("protobuf_unittest3", file.Package); Assert.AreEqual("UnittestProto", file.Proto.Options.JavaOuterClassname); Assert.AreEqual("unittest_proto3.proto", file.Proto.Name); // unittest_proto3.proto doesn't have any public imports, but unittest_import_proto3.proto does. Assert.AreEqual(0, file.PublicDependencies.Count); Assert.AreEqual(1, importedFile.PublicDependencies.Count); Assert.AreEqual(importedPublicFile, importedFile.PublicDependencies[0]); Assert.AreEqual(1, file.Dependencies.Count); Assert.AreEqual(importedFile, file.Dependencies[0]); Assert.Null(file.FindTypeByName<MessageDescriptor>("NoSuchType")); Assert.Null(file.FindTypeByName<MessageDescriptor>("protobuf_unittest3.TestAllTypes")); for (int i = 0; i < file.MessageTypes.Count; i++) { Assert.AreEqual(i, file.MessageTypes[i].Index); } Assert.AreEqual(file.EnumTypes[0], file.FindTypeByName<EnumDescriptor>("ForeignEnum")); Assert.Null(file.FindTypeByName<EnumDescriptor>("NoSuchType")); Assert.Null(file.FindTypeByName<EnumDescriptor>("protobuf_unittest3.ForeignEnum")); Assert.AreEqual(1, importedFile.EnumTypes.Count); Assert.AreEqual("ImportEnum", importedFile.EnumTypes[0].Name); for (int i = 0; i < file.EnumTypes.Count; i++) { Assert.AreEqual(i, file.EnumTypes[i].Index); } Assert.AreEqual(10, file.SerializedData[0]); } [Test] public void FileDescriptor_NonRootPath() { // unittest_proto3.proto used to be in google/protobuf. Now it's in the C#-specific location, // let's test something that's still in a directory. FileDescriptor file = UnittestWellKnownTypesReflection.Descriptor; Assert.AreEqual("google/protobuf/unittest_well_known_types.proto", file.Name); Assert.AreEqual("protobuf_unittest", file.Package); } [Test] public void FileDescriptor_BuildFromByteStrings_MissingDependency() { var descriptorData = new List<ByteString> { UnittestImportProto3Reflection.Descriptor.SerializedData, UnittestProto3Reflection.Descriptor.SerializedData, }; // This will fail, because we're missing UnittestImportPublicProto3Reflection Assert.Throws<ArgumentException>(() => FileDescriptor.BuildFromByteStrings(descriptorData)); } [Test] public void FileDescriptor_BuildFromByteStrings_DuplicateNames() { var descriptorData = new List<ByteString> { UnittestImportPublicProto3Reflection.Descriptor.SerializedData, UnittestImportPublicProto3Reflection.Descriptor.SerializedData, }; // This will fail due to the same name being used twice Assert.Throws<ArgumentException>(() => FileDescriptor.BuildFromByteStrings(descriptorData)); } [Test] public void FileDescriptor_BuildFromByteStrings_IncorrectOrder() { var descriptorData = new List<ByteString> { UnittestProto3Reflection.Descriptor.SerializedData, UnittestImportPublicProto3Reflection.Descriptor.SerializedData, UnittestImportProto3Reflection.Descriptor.SerializedData }; // This will fail, because the dependencies should come first Assert.Throws<ArgumentException>(() => FileDescriptor.BuildFromByteStrings(descriptorData)); } [Test] public void MessageDescriptorFromGeneratedCodeFileDescriptor() { var file = UnittestProto3Reflection.Descriptor; MessageDescriptor messageType = TestAllTypes.Descriptor; Assert.AreSame(typeof(TestAllTypes), messageType.ClrType); Assert.AreSame(TestAllTypes.Parser, messageType.Parser); Assert.AreEqual(messageType, file.MessageTypes[0]); Assert.AreEqual(messageType, file.FindTypeByName<MessageDescriptor>("TestAllTypes")); } [Test] public void MessageDescriptor() { MessageDescriptor messageType = TestAllTypes.Descriptor; MessageDescriptor nestedType = TestAllTypes.Types.NestedMessage.Descriptor; Assert.AreEqual("TestAllTypes", messageType.Name); Assert.AreEqual("protobuf_unittest3.TestAllTypes", messageType.FullName); Assert.AreEqual(UnittestProto3Reflection.Descriptor, messageType.File); Assert.IsNull(messageType.ContainingType); Assert.IsNull(messageType.Proto.Options); Assert.AreEqual("TestAllTypes", messageType.Name); Assert.AreEqual("NestedMessage", nestedType.Name); Assert.AreEqual("protobuf_unittest3.TestAllTypes.NestedMessage", nestedType.FullName); Assert.AreEqual(UnittestProto3Reflection.Descriptor, nestedType.File); Assert.AreEqual(messageType, nestedType.ContainingType); FieldDescriptor field = messageType.Fields.InDeclarationOrder()[0]; Assert.AreEqual("single_int32", field.Name); Assert.AreEqual(field, messageType.FindDescriptor<FieldDescriptor>("single_int32")); Assert.Null(messageType.FindDescriptor<FieldDescriptor>("no_such_field")); Assert.AreEqual(field, messageType.FindFieldByNumber(1)); Assert.Null(messageType.FindFieldByNumber(571283)); var fieldsInDeclarationOrder = messageType.Fields.InDeclarationOrder(); for (int i = 0; i < fieldsInDeclarationOrder.Count; i++) { Assert.AreEqual(i, fieldsInDeclarationOrder[i].Index); } Assert.AreEqual(nestedType, messageType.NestedTypes[0]); Assert.AreEqual(nestedType, messageType.FindDescriptor<MessageDescriptor>("NestedMessage")); Assert.Null(messageType.FindDescriptor<MessageDescriptor>("NoSuchType")); for (int i = 0; i < messageType.NestedTypes.Count; i++) { Assert.AreEqual(i, messageType.NestedTypes[i].Index); } Assert.AreEqual(messageType.EnumTypes[0], messageType.FindDescriptor<EnumDescriptor>("NestedEnum")); Assert.Null(messageType.FindDescriptor<EnumDescriptor>("NoSuchType")); for (int i = 0; i < messageType.EnumTypes.Count; i++) { Assert.AreEqual(i, messageType.EnumTypes[i].Index); } } [Test] public void FieldDescriptor_GeneratedCode() { TestFieldDescriptor(UnittestProto3Reflection.Descriptor, TestAllTypes.Descriptor, ForeignMessage.Descriptor, ImportMessage.Descriptor); } [Test] public void FieldDescriptor_BuildFromByteStrings() { // The descriptors have to be supplied in an order such that all the // dependencies come before the descriptors depending on them. var descriptorData = new List<ByteString> { UnittestImportPublicProto3Reflection.Descriptor.SerializedData, UnittestImportProto3Reflection.Descriptor.SerializedData, UnittestProto3Reflection.Descriptor.SerializedData }; var converted = FileDescriptor.BuildFromByteStrings(descriptorData); TestFieldDescriptor( converted[2], converted[2].FindTypeByName<MessageDescriptor>("TestAllTypes"), converted[2].FindTypeByName<MessageDescriptor>("ForeignMessage"), converted[1].FindTypeByName<MessageDescriptor>("ImportMessage")); } public void TestFieldDescriptor( FileDescriptor unitTestProto3Descriptor, MessageDescriptor testAllTypesDescriptor, MessageDescriptor foreignMessageDescriptor, MessageDescriptor importMessageDescriptor) { FieldDescriptor primitiveField = testAllTypesDescriptor.FindDescriptor<FieldDescriptor>("single_int32"); FieldDescriptor enumField = testAllTypesDescriptor.FindDescriptor<FieldDescriptor>("single_nested_enum"); FieldDescriptor foreignMessageField = testAllTypesDescriptor.FindDescriptor<FieldDescriptor>("single_foreign_message"); FieldDescriptor importMessageField = testAllTypesDescriptor.FindDescriptor<FieldDescriptor>("single_import_message"); Assert.AreEqual("single_int32", primitiveField.Name); Assert.AreEqual("protobuf_unittest3.TestAllTypes.single_int32", primitiveField.FullName); Assert.AreEqual(1, primitiveField.FieldNumber); Assert.AreEqual(testAllTypesDescriptor, primitiveField.ContainingType); Assert.AreEqual(unitTestProto3Descriptor, primitiveField.File); Assert.AreEqual(FieldType.Int32, primitiveField.FieldType); Assert.IsNull(primitiveField.Proto.Options); Assert.AreEqual("single_nested_enum", enumField.Name); Assert.AreEqual(FieldType.Enum, enumField.FieldType); Assert.AreEqual(testAllTypesDescriptor.EnumTypes[0], enumField.EnumType); Assert.AreEqual("single_foreign_message", foreignMessageField.Name); Assert.AreEqual(FieldType.Message, foreignMessageField.FieldType); Assert.AreEqual(foreignMessageDescriptor, foreignMessageField.MessageType); Assert.AreEqual("single_import_message", importMessageField.Name); Assert.AreEqual(FieldType.Message, importMessageField.FieldType); Assert.AreEqual(importMessageDescriptor, importMessageField.MessageType); } [Test] public void FieldDescriptorLabel() { FieldDescriptor singleField = TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("single_int32"); FieldDescriptor repeatedField = TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_int32"); Assert.IsFalse(singleField.IsRepeated); Assert.IsTrue(repeatedField.IsRepeated); } [Test] public void EnumDescriptor() { // Note: this test is a bit different to the Java version because there's no static way of getting to the descriptor EnumDescriptor enumType = UnittestProto3Reflection.Descriptor.FindTypeByName<EnumDescriptor>("ForeignEnum"); EnumDescriptor nestedType = TestAllTypes.Descriptor.FindDescriptor<EnumDescriptor>("NestedEnum"); Assert.AreEqual("ForeignEnum", enumType.Name); Assert.AreEqual("protobuf_unittest3.ForeignEnum", enumType.FullName); Assert.AreEqual(UnittestProto3Reflection.Descriptor, enumType.File); Assert.Null(enumType.ContainingType); Assert.Null(enumType.Proto.Options); Assert.AreEqual("NestedEnum", nestedType.Name); Assert.AreEqual("protobuf_unittest3.TestAllTypes.NestedEnum", nestedType.FullName); Assert.AreEqual(UnittestProto3Reflection.Descriptor, nestedType.File); Assert.AreEqual(TestAllTypes.Descriptor, nestedType.ContainingType); EnumValueDescriptor value = enumType.FindValueByName("FOREIGN_FOO"); Assert.AreEqual(value, enumType.Values[1]); Assert.AreEqual("FOREIGN_FOO", value.Name); Assert.AreEqual(4, value.Number); Assert.AreEqual((int) ForeignEnum.ForeignFoo, value.Number); Assert.AreEqual(value, enumType.FindValueByNumber(4)); Assert.Null(enumType.FindValueByName("NO_SUCH_VALUE")); for (int i = 0; i < enumType.Values.Count; i++) { Assert.AreEqual(i, enumType.Values[i].Index); } } [Test] public void OneofDescriptor() { OneofDescriptor descriptor = TestAllTypes.Descriptor.FindDescriptor<OneofDescriptor>("oneof_field"); Assert.AreEqual("oneof_field", descriptor.Name); Assert.AreEqual("protobuf_unittest3.TestAllTypes.oneof_field", descriptor.FullName); var expectedFields = new[] { TestAllTypes.OneofBytesFieldNumber, TestAllTypes.OneofNestedMessageFieldNumber, TestAllTypes.OneofStringFieldNumber, TestAllTypes.OneofUint32FieldNumber } .Select(fieldNumber => TestAllTypes.Descriptor.FindFieldByNumber(fieldNumber)) .ToList(); foreach (var field in expectedFields) { Assert.AreSame(descriptor, field.ContainingOneof); } CollectionAssert.AreEquivalent(expectedFields, descriptor.Fields); } [Test] public void MapEntryMessageDescriptor() { var descriptor = MapWellKnownTypes.Descriptor.NestedTypes[0]; Assert.IsNull(descriptor.Parser); Assert.IsNull(descriptor.ClrType); Assert.IsNull(descriptor.Fields[1].Accessor); } // From TestFieldOrdering: // string my_string = 11; // int64 my_int = 1; // float my_float = 101; // NestedMessage single_nested_message = 200; [Test] public void FieldListOrderings() { var fields = TestFieldOrderings.Descriptor.Fields; Assert.AreEqual(new[] { 11, 1, 101, 200 }, fields.InDeclarationOrder().Select(x => x.FieldNumber)); Assert.AreEqual(new[] { 1, 11, 101, 200 }, fields.InFieldNumberOrder().Select(x => x.FieldNumber)); } [Test] public void DescriptorProtoFileDescriptor() { var descriptor = Google.Protobuf.Reflection.FileDescriptor.DescriptorProtoFileDescriptor; Assert.AreEqual("google/protobuf/descriptor.proto", descriptor.Name); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ using System.Collections.Generic; using System.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; using System.Xml; using System.IO; using MSS = Microsoft.SqlServer.Server; namespace System.Data.SqlClient { internal sealed class MetaType { internal readonly Type ClassType; // com+ type internal readonly Type SqlType; internal readonly int FixedLength; // fixed length size in bytes (-1 for variable) internal readonly bool IsFixed; // true if fixed length, note that sqlchar and sqlbinary are not considered fixed length internal readonly bool IsLong; // true if long internal readonly bool IsPlp; // Column is Partially Length Prefixed (MAX) internal readonly byte Precision; // maxium precision for numeric types internal readonly byte Scale; internal readonly byte TDSType; internal readonly byte NullableType; internal readonly string TypeName; // string name of this type internal readonly SqlDbType SqlDbType; internal readonly DbType DbType; // holds count of property bytes expected for a SQLVariant structure internal readonly byte PropBytes; // pre-computed fields internal readonly bool IsAnsiType; internal readonly bool IsBinType; internal readonly bool IsCharType; internal readonly bool IsNCharType; internal readonly bool IsSizeInCharacters; internal readonly bool IsNewKatmaiType; internal readonly bool IsVarTime; internal readonly bool Is70Supported; internal readonly bool Is80Supported; internal readonly bool Is90Supported; internal readonly bool Is100Supported; public MetaType(byte precision, byte scale, int fixedLength, bool isFixed, bool isLong, bool isPlp, byte tdsType, byte nullableTdsType, string typeName, Type classType, Type sqlType, SqlDbType sqldbType, DbType dbType, byte propBytes) { this.Precision = precision; this.Scale = scale; this.FixedLength = fixedLength; this.IsFixed = isFixed; this.IsLong = isLong; this.IsPlp = isPlp; // can we get rid of this (?just have a mapping?) this.TDSType = tdsType; this.NullableType = nullableTdsType; this.TypeName = typeName; this.SqlDbType = sqldbType; this.DbType = dbType; this.ClassType = classType; this.SqlType = sqlType; this.PropBytes = propBytes; IsAnsiType = _IsAnsiType(sqldbType); IsBinType = _IsBinType(sqldbType); IsCharType = _IsCharType(sqldbType); IsNCharType = _IsNCharType(sqldbType); IsSizeInCharacters = _IsSizeInCharacters(sqldbType); IsNewKatmaiType = _IsNewKatmaiType(sqldbType); IsVarTime = _IsVarTime(sqldbType); Is70Supported = _Is70Supported(SqlDbType); Is80Supported = _Is80Supported(SqlDbType); Is90Supported = _Is90Supported(SqlDbType); Is100Supported = _Is100Supported(SqlDbType); } // properties should be inlined so there should be no perf penalty for using these accessor functions public int TypeId { // partial length prefixed (xml, nvarchar(max),...) get { return 0; } } private static bool _IsAnsiType(SqlDbType type) { return (type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text); } // is this type size expressed as count of characters or bytes? private static bool _IsSizeInCharacters(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.Xml || type == SqlDbType.NText); } private static bool _IsCharType(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text || type == SqlDbType.Xml); } private static bool _IsNCharType(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Xml); } private static bool _IsBinType(SqlDbType type) { return (type == SqlDbType.Image || type == SqlDbType.Binary || type == SqlDbType.VarBinary || type == SqlDbType.Timestamp || type == SqlDbType.Udt || (int)type == 24 /*SqlSmallVarBinary*/); } private static bool _Is70Supported(SqlDbType type) { return ((type != SqlDbType.BigInt) && ((int)type > 0) && ((int)type <= (int)SqlDbType.VarChar)); } private static bool _Is80Supported(SqlDbType type) { return ((int)type >= 0 && ((int)type <= (int)SqlDbType.Variant)); } private static bool _Is90Supported(SqlDbType type) { return _Is80Supported(type) || SqlDbType.Xml == type || SqlDbType.Udt == type; } private static bool _Is100Supported(SqlDbType type) { return _Is90Supported(type) || SqlDbType.Date == type || SqlDbType.Time == type || SqlDbType.DateTime2 == type || SqlDbType.DateTimeOffset == type; } private static bool _IsNewKatmaiType(SqlDbType type) { return SqlDbType.Structured == type; } internal static bool _IsVarTime(SqlDbType type) { return (type == SqlDbType.Time || type == SqlDbType.DateTime2 || type == SqlDbType.DateTimeOffset); } // // map SqlDbType to MetaType class // internal static MetaType GetMetaTypeFromSqlDbType(SqlDbType target, bool isMultiValued) { // WebData 113289 switch (target) { case SqlDbType.BigInt: return s_metaBigInt; case SqlDbType.Binary: return s_metaBinary; case SqlDbType.Bit: return s_metaBit; case SqlDbType.Char: return s_metaChar; case SqlDbType.DateTime: return s_metaDateTime; case SqlDbType.Decimal: return MetaDecimal; case SqlDbType.Float: return s_metaFloat; case SqlDbType.Image: return MetaImage; case SqlDbType.Int: return s_metaInt; case SqlDbType.Money: return s_metaMoney; case SqlDbType.NChar: return s_metaNChar; case SqlDbType.NText: return MetaNText; case SqlDbType.NVarChar: return MetaNVarChar; case SqlDbType.Real: return s_metaReal; case SqlDbType.UniqueIdentifier: return s_metaUniqueId; case SqlDbType.SmallDateTime: return s_metaSmallDateTime; case SqlDbType.SmallInt: return s_metaSmallInt; case SqlDbType.SmallMoney: return s_metaSmallMoney; case SqlDbType.Text: return MetaText; case SqlDbType.Timestamp: return s_metaTimestamp; case SqlDbType.TinyInt: return s_metaTinyInt; case SqlDbType.VarBinary: return MetaVarBinary; case SqlDbType.VarChar: return s_metaVarChar; case SqlDbType.Variant: return s_metaVariant; case (SqlDbType)TdsEnums.SmallVarBinary: return s_metaSmallVarBinary; case SqlDbType.Xml: return MetaXml; case SqlDbType.Structured: if (isMultiValued) { return s_metaTable; } else { return s_metaSUDT; } case SqlDbType.Date: return s_metaDate; case SqlDbType.Time: return MetaTime; case SqlDbType.DateTime2: return s_metaDateTime2; case SqlDbType.DateTimeOffset: return MetaDateTimeOffset; default: throw SQL.InvalidSqlDbType(target); } } // // map DbType to MetaType class // internal static MetaType GetMetaTypeFromDbType(DbType target) { // if we can't map it, we need to throw switch (target) { case DbType.AnsiString: return s_metaVarChar; case DbType.AnsiStringFixedLength: return s_metaChar; case DbType.Binary: return MetaVarBinary; case DbType.Byte: return s_metaTinyInt; case DbType.Boolean: return s_metaBit; case DbType.Currency: return s_metaMoney; case DbType.Date: case DbType.DateTime: return s_metaDateTime; case DbType.Decimal: return MetaDecimal; case DbType.Double: return s_metaFloat; case DbType.Guid: return s_metaUniqueId; case DbType.Int16: return s_metaSmallInt; case DbType.Int32: return s_metaInt; case DbType.Int64: return s_metaBigInt; case DbType.Object: return s_metaVariant; case DbType.Single: return s_metaReal; case DbType.String: return MetaNVarChar; case DbType.StringFixedLength: return s_metaNChar; case DbType.Time: return s_metaDateTime; case DbType.Xml: return MetaXml; case DbType.DateTime2: return s_metaDateTime2; case DbType.DateTimeOffset: return MetaDateTimeOffset; case DbType.SByte: // unsupported case DbType.UInt16: case DbType.UInt32: case DbType.UInt64: case DbType.VarNumeric: default: throw ADP.DbTypeNotSupported(target, typeof(SqlDbType)); // no direct mapping, error out } } internal static MetaType GetMaxMetaTypeFromMetaType(MetaType mt) { // if we can't map it, we need to throw switch (mt.SqlDbType) { case SqlDbType.VarBinary: case SqlDbType.Binary: return MetaMaxVarBinary; case SqlDbType.VarChar: case SqlDbType.Char: return MetaMaxVarChar; case SqlDbType.NVarChar: case SqlDbType.NChar: return MetaMaxNVarChar; case SqlDbType.Udt: Debug.Assert(false, "UDT is not supported"); return mt; default: return mt; } } // // map COM+ Type to MetaType class // static internal MetaType GetMetaTypeFromType(Type dataType, bool streamAllowed = true) { if (dataType == typeof(System.Byte[])) return MetaVarBinary; else if (dataType == typeof(System.Guid)) return s_metaUniqueId; else if (dataType == typeof(System.Object)) return s_metaVariant; else if (dataType == typeof(SqlBinary)) return MetaVarBinary; else if (dataType == typeof(SqlBoolean)) return s_metaBit; else if (dataType == typeof(SqlByte)) return s_metaTinyInt; else if (dataType == typeof(SqlBytes)) return MetaVarBinary; else if (dataType == typeof(SqlChars)) return MetaNVarChar; else if (dataType == typeof(SqlDateTime)) return s_metaDateTime; else if (dataType == typeof(SqlDouble)) return s_metaFloat; else if (dataType == typeof(SqlGuid)) return s_metaUniqueId; else if (dataType == typeof(SqlInt16)) return s_metaSmallInt; else if (dataType == typeof(SqlInt32)) return s_metaInt; else if (dataType == typeof(SqlInt64)) return s_metaBigInt; else if (dataType == typeof(SqlMoney)) return s_metaMoney; else if (dataType == typeof(SqlDecimal)) return MetaDecimal; else if (dataType == typeof(SqlSingle)) return s_metaReal; else if (dataType == typeof(SqlXml)) return MetaXml; else if (dataType == typeof(SqlString)) return MetaNVarChar; else if (dataType == typeof(IEnumerable<DbDataRecord>)) return s_metaTable; else if (dataType == typeof(TimeSpan)) return MetaTime; else if (dataType == typeof(DateTimeOffset)) return MetaDateTimeOffset; else if (dataType == typeof(DBNull)) throw ADP.InvalidDataType("DBNull"); else if (dataType == typeof(Boolean)) return s_metaBit; else if (dataType == typeof(Char)) throw ADP.InvalidDataType("Char"); else if (dataType == typeof(SByte)) throw ADP.InvalidDataType("SByte"); else if (dataType == typeof(Byte)) return s_metaTinyInt; else if (dataType == typeof(Int16)) return s_metaSmallInt; else if (dataType == typeof(UInt16)) throw ADP.InvalidDataType("UInt16"); else if (dataType == typeof(Int32)) return s_metaInt; else if (dataType == typeof(UInt32)) throw ADP.InvalidDataType("UInt32"); else if (dataType == typeof(Int64)) return s_metaBigInt; else if (dataType == typeof(UInt64)) throw ADP.InvalidDataType("UInt64"); else if (dataType == typeof(Single)) return s_metaReal; else if (dataType == typeof(Double)) return s_metaFloat; else if (dataType == typeof(Decimal)) return MetaDecimal; else if (dataType == typeof(DateTime)) return s_metaDateTime; else if (dataType == typeof(String)) return MetaNVarChar; else throw ADP.UnknownDataType(dataType); } static internal MetaType GetMetaTypeFromValue(object value, bool inferLen = true, bool streamAllowed = true) { if (value == null) { throw ADP.InvalidDataType("null"); } else if (value is DBNull) { throw ADP.InvalidDataType(typeof(DBNull).Name); } else if (value is bool) { return s_metaBit; } else if (value is char) { throw ADP.InvalidDataType(typeof(char).Name); } else if (value is sbyte) { throw ADP.InvalidDataType(typeof(sbyte).Name); } else if (value is byte) { return s_metaTinyInt; } else if (value is short) { return s_metaSmallInt; } else if (value is ushort) { throw ADP.InvalidDataType(typeof(ushort).Name); } else if (value is int) { return s_metaInt; } else if (value is uint) { throw ADP.InvalidDataType(typeof(uint).Name); } else if (value is long) { return s_metaBigInt; } else if (value is ulong) { throw ADP.InvalidDataType(typeof(ulong).Name); } else if (value is float) { return s_metaReal; } else if (value is double) { return s_metaFloat; } else if (value is decimal) { return MetaDecimal; } else if (value is DateTime) { return s_metaDateTime; } else if (value is string) { return (inferLen ? PromoteStringType((string)value) : MetaNVarChar); } else if (value is byte[]) { if (!inferLen || ((byte[])value).Length <= TdsEnums.TYPE_SIZE_LIMIT) { return MetaVarBinary; } else { return MetaImage; } } else if (value is Guid) { return s_metaUniqueId; } else if (value is SqlBinary) return MetaVarBinary; else if (value is SqlBoolean) return s_metaBit; else if (value is SqlByte) return s_metaTinyInt; else if (value is SqlBytes) return MetaVarBinary; else if (value is SqlChars) return MetaNVarChar; else if (value is SqlDateTime) return s_metaDateTime; else if (value is SqlDouble) return s_metaFloat; else if (value is SqlGuid) return s_metaUniqueId; else if (value is SqlInt16) return s_metaSmallInt; else if (value is SqlInt32) return s_metaInt; else if (value is SqlInt64) return s_metaBigInt; else if (value is SqlMoney) return s_metaMoney; else if (value is SqlDecimal) return MetaDecimal; else if (value is SqlSingle) return s_metaReal; else if (value is SqlXml) return MetaXml; else if (value is SqlString) { return ((inferLen && !((SqlString)value).IsNull) ? PromoteStringType(((SqlString)value).Value) : MetaNVarChar); } else if (value is IEnumerable<DbDataRecord>) { return s_metaTable; } else if (value is TimeSpan) { return MetaTime; } else if (value is DateTimeOffset) { return MetaDateTimeOffset; } else if (streamAllowed) { // Derived from Stream ? if (value is Stream) { return MetaVarBinary; } // Derived from TextReader ? if (value is TextReader) { return MetaNVarChar; } // Derived from XmlReader ? if (value is XmlReader) { return MetaXml; } } throw ADP.UnknownDataType(value.GetType()); } internal static object GetNullSqlValue(Type sqlType) { if (sqlType == typeof(SqlSingle)) return SqlSingle.Null; else if (sqlType == typeof(SqlString)) return SqlString.Null; else if (sqlType == typeof(SqlDouble)) return SqlDouble.Null; else if (sqlType == typeof(SqlBinary)) return SqlBinary.Null; else if (sqlType == typeof(SqlGuid)) return SqlGuid.Null; else if (sqlType == typeof(SqlBoolean)) return SqlBoolean.Null; else if (sqlType == typeof(SqlByte)) return SqlByte.Null; else if (sqlType == typeof(SqlInt16)) return SqlInt16.Null; else if (sqlType == typeof(SqlInt32)) return SqlInt32.Null; else if (sqlType == typeof(SqlInt64)) return SqlInt64.Null; else if (sqlType == typeof(SqlDecimal)) return SqlDecimal.Null; else if (sqlType == typeof(SqlDateTime)) return SqlDateTime.Null; else if (sqlType == typeof(SqlMoney)) return SqlMoney.Null; else if (sqlType == typeof(SqlXml)) return SqlXml.Null; else if (sqlType == typeof(object)) return DBNull.Value; else if (sqlType == typeof(IEnumerable<DbDataRecord>)) return DBNull.Value; else if (sqlType == typeof(DateTime)) return DBNull.Value; else if (sqlType == typeof(TimeSpan)) return DBNull.Value; else if (sqlType == typeof(DateTimeOffset)) return DBNull.Value; else { Debug.Assert(false, "Unknown SqlType!"); return DBNull.Value; } } internal static MetaType PromoteStringType(string s) { int len = s.Length; if ((len << 1) > TdsEnums.TYPE_SIZE_LIMIT) { return s_metaVarChar; // try as var char since we can send a 8K characters } return MetaNVarChar; // send 4k chars, but send as unicode } internal static object GetComValueFromSqlVariant(object sqlVal) { object comVal = null; if (ADP.IsNull(sqlVal)) return comVal; if (sqlVal is SqlSingle) comVal = ((SqlSingle)sqlVal).Value; else if (sqlVal is SqlString) comVal = ((SqlString)sqlVal).Value; else if (sqlVal is SqlDouble) comVal = ((SqlDouble)sqlVal).Value; else if (sqlVal is SqlBinary) comVal = ((SqlBinary)sqlVal).Value; else if (sqlVal is SqlGuid) comVal = ((SqlGuid)sqlVal).Value; else if (sqlVal is SqlBoolean) comVal = ((SqlBoolean)sqlVal).Value; else if (sqlVal is SqlByte) comVal = ((SqlByte)sqlVal).Value; else if (sqlVal is SqlInt16) comVal = ((SqlInt16)sqlVal).Value; else if (sqlVal is SqlInt32) comVal = ((SqlInt32)sqlVal).Value; else if (sqlVal is SqlInt64) comVal = ((SqlInt64)sqlVal).Value; else if (sqlVal is SqlDecimal) comVal = ((SqlDecimal)sqlVal).Value; else if (sqlVal is SqlDateTime) comVal = ((SqlDateTime)sqlVal).Value; else if (sqlVal is SqlMoney) comVal = ((SqlMoney)sqlVal).Value; else if (sqlVal is SqlXml) comVal = ((SqlXml)sqlVal).Value; else { Debug.Assert(false, "unknown SqlType class stored in sqlVal"); } return comVal; } // devnote: This method should not be used with SqlDbType.Date and SqlDbType.DateTime2. // With these types the values should be used directly as CLR types instead of being converted to a SqlValue internal static object GetSqlValueFromComVariant(object comVal) { object sqlVal = null; if ((null != comVal) && (DBNull.Value != comVal)) { if (comVal is float) sqlVal = new SqlSingle((float)comVal); else if (comVal is string) sqlVal = new SqlString((string)comVal); else if (comVal is double) sqlVal = new SqlDouble((double)comVal); else if (comVal is System.Byte[]) sqlVal = new SqlBinary((byte[])comVal); else if (comVal is System.Char) sqlVal = new SqlString(((char)comVal).ToString()); else if (comVal is System.Char[]) sqlVal = new SqlChars((System.Char[])comVal); else if (comVal is System.Guid) sqlVal = new SqlGuid((Guid)comVal); else if (comVal is bool) sqlVal = new SqlBoolean((bool)comVal); else if (comVal is byte) sqlVal = new SqlByte((byte)comVal); else if (comVal is Int16) sqlVal = new SqlInt16((Int16)comVal); else if (comVal is Int32) sqlVal = new SqlInt32((Int32)comVal); else if (comVal is Int64) sqlVal = new SqlInt64((Int64)comVal); else if (comVal is Decimal) sqlVal = new SqlDecimal((Decimal)comVal); else if (comVal is DateTime) { // devnote: Do not use with SqlDbType.Date and SqlDbType.DateTime2. See comment at top of method. sqlVal = new SqlDateTime((DateTime)comVal); } else if (comVal is XmlReader) sqlVal = new SqlXml((XmlReader)comVal); else if (comVal is TimeSpan || comVal is DateTimeOffset) sqlVal = comVal; #if DEBUG else Debug.Assert(false, "unknown SqlType class stored in sqlVal"); #endif } return sqlVal; } internal static MetaType GetSqlDataType(int tdsType, UInt32 userType, int length) { switch (tdsType) { case TdsEnums.SQLMONEYN: return ((4 == length) ? s_metaSmallMoney : s_metaMoney); case TdsEnums.SQLDATETIMN: return ((4 == length) ? s_metaSmallDateTime : s_metaDateTime); case TdsEnums.SQLINTN: return ((4 <= length) ? ((4 == length) ? s_metaInt : s_metaBigInt) : ((2 == length) ? s_metaSmallInt : s_metaTinyInt)); case TdsEnums.SQLFLTN: return ((4 == length) ? s_metaReal : s_metaFloat); case TdsEnums.SQLTEXT: return MetaText; case TdsEnums.SQLVARBINARY: return s_metaSmallVarBinary; case TdsEnums.SQLBIGVARBINARY: return MetaVarBinary; case TdsEnums.SQLVARCHAR: //goto TdsEnums.SQLBIGVARCHAR; case TdsEnums.SQLBIGVARCHAR: return s_metaVarChar; case TdsEnums.SQLBINARY: //goto TdsEnums.SQLBIGBINARY; case TdsEnums.SQLBIGBINARY: return ((TdsEnums.SQLTIMESTAMP == userType) ? s_metaTimestamp : s_metaBinary); case TdsEnums.SQLIMAGE: return MetaImage; case TdsEnums.SQLCHAR: //goto TdsEnums.SQLBIGCHAR; case TdsEnums.SQLBIGCHAR: return s_metaChar; case TdsEnums.SQLINT1: return s_metaTinyInt; case TdsEnums.SQLBIT: //goto TdsEnums.SQLBITN; case TdsEnums.SQLBITN: return s_metaBit; case TdsEnums.SQLINT2: return s_metaSmallInt; case TdsEnums.SQLINT4: return s_metaInt; case TdsEnums.SQLINT8: return s_metaBigInt; case TdsEnums.SQLMONEY: return s_metaMoney; case TdsEnums.SQLDATETIME: return s_metaDateTime; case TdsEnums.SQLFLT8: return s_metaFloat; case TdsEnums.SQLFLT4: return s_metaReal; case TdsEnums.SQLMONEY4: return s_metaSmallMoney; case TdsEnums.SQLDATETIM4: return s_metaSmallDateTime; case TdsEnums.SQLDECIMALN: //goto TdsEnums.SQLNUMERICN; case TdsEnums.SQLNUMERICN: return MetaDecimal; case TdsEnums.SQLUNIQUEID: return s_metaUniqueId; case TdsEnums.SQLNCHAR: return s_metaNChar; case TdsEnums.SQLNVARCHAR: return MetaNVarChar; case TdsEnums.SQLNTEXT: return MetaNText; case TdsEnums.SQLVARIANT: return s_metaVariant; case TdsEnums.SQLXMLTYPE: return MetaXml; case TdsEnums.SQLTABLE: return s_metaTable; case TdsEnums.SQLDATE: return s_metaDate; case TdsEnums.SQLTIME: return MetaTime; case TdsEnums.SQLDATETIME2: return s_metaDateTime2; case TdsEnums.SQLDATETIMEOFFSET: return MetaDateTimeOffset; case TdsEnums.SQLVOID: default: Debug.Assert(false, "Unknown type " + tdsType.ToString(CultureInfo.InvariantCulture)); throw SQL.InvalidSqlDbType((SqlDbType)tdsType); }// case } internal static MetaType GetDefaultMetaType() { return MetaNVarChar; } // Converts an XmlReader into String internal static String GetStringFromXml(XmlReader xmlreader) { SqlXml sxml = new SqlXml(xmlreader); return sxml.Value; } private static readonly MetaType s_metaBigInt = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLINT8, TdsEnums.SQLINTN, MetaTypeName.BIGINT, typeof(System.Int64), typeof(SqlInt64), SqlDbType.BigInt, DbType.Int64, 0); private static readonly MetaType s_metaFloat = new MetaType (15, 255, 8, true, false, false, TdsEnums.SQLFLT8, TdsEnums.SQLFLTN, MetaTypeName.FLOAT, typeof(System.Double), typeof(SqlDouble), SqlDbType.Float, DbType.Double, 0); private static readonly MetaType s_metaReal = new MetaType (7, 255, 4, true, false, false, TdsEnums.SQLFLT4, TdsEnums.SQLFLTN, MetaTypeName.REAL, typeof(System.Single), typeof(SqlSingle), SqlDbType.Real, DbType.Single, 0); // MetaBinary has two bytes of properties for binary and varbinary // 2 byte maxlen private static readonly MetaType s_metaBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.BINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Binary, DbType.Binary, 2); // syntatic sugar for the user...timestamps are 8-byte fixed length binary columns private static readonly MetaType s_metaTimestamp = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.TIMESTAMP, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Timestamp, DbType.Binary, 2); internal static readonly MetaType MetaVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); internal static readonly MetaType MetaMaxVarBinary = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); // HACK!!! We have an internal type for smallvarbinarys stored on TdsEnums. We // store on TdsEnums instead of SqlDbType because we do not want to expose // this type to the user! private static readonly MetaType s_metaSmallVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVARBINARY, TdsEnums.SQLBIGBINARY, ADP.StrEmpty, typeof(System.Byte[]), typeof(SqlBinary), TdsEnums.SmallVarBinary, DbType.Binary, 2); internal static readonly MetaType MetaImage = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLIMAGE, TdsEnums.SQLIMAGE, MetaTypeName.IMAGE, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Image, DbType.Binary, 0); private static readonly MetaType s_metaBit = new MetaType (255, 255, 1, true, false, false, TdsEnums.SQLBIT, TdsEnums.SQLBITN, MetaTypeName.BIT, typeof(System.Boolean), typeof(SqlBoolean), SqlDbType.Bit, DbType.Boolean, 0); private static readonly MetaType s_metaTinyInt = new MetaType (3, 255, 1, true, false, false, TdsEnums.SQLINT1, TdsEnums.SQLINTN, MetaTypeName.TINYINT, typeof(System.Byte), typeof(SqlByte), SqlDbType.TinyInt, DbType.Byte, 0); private static readonly MetaType s_metaSmallInt = new MetaType (5, 255, 2, true, false, false, TdsEnums.SQLINT2, TdsEnums.SQLINTN, MetaTypeName.SMALLINT, typeof(System.Int16), typeof(SqlInt16), SqlDbType.SmallInt, DbType.Int16, 0); private static readonly MetaType s_metaInt = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLINT4, TdsEnums.SQLINTN, MetaTypeName.INT, typeof(System.Int32), typeof(SqlInt32), SqlDbType.Int, DbType.Int32, 0); // MetaVariant has seven bytes of properties for MetaChar and MetaVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType s_metaChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGCHAR, TdsEnums.SQLBIGCHAR, MetaTypeName.CHAR, typeof(System.String), typeof(SqlString), SqlDbType.Char, DbType.AnsiStringFixedLength, 7); private static readonly MetaType s_metaVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaMaxVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLTEXT, TdsEnums.SQLTEXT, MetaTypeName.TEXT, typeof(System.String), typeof(SqlString), SqlDbType.Text, DbType.AnsiString, 0); // MetaVariant has seven bytes of properties for MetaNChar and MetaNVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType s_metaNChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNCHAR, TdsEnums.SQLNCHAR, MetaTypeName.NCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NChar, DbType.StringFixedLength, 7); internal static readonly MetaType MetaNVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaMaxNVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaNText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLNTEXT, TdsEnums.SQLNTEXT, MetaTypeName.NTEXT, typeof(System.String), typeof(SqlString), SqlDbType.NText, DbType.String, 7); // MetaVariant has two bytes of properties for numeric/decimal types // 1 byte precision // 1 byte scale internal static readonly MetaType MetaDecimal = new MetaType (38, 4, 17, true, false, false, TdsEnums.SQLNUMERICN, TdsEnums.SQLNUMERICN, MetaTypeName.DECIMAL, typeof(System.Decimal), typeof(SqlDecimal), SqlDbType.Decimal, DbType.Decimal, 2); internal static readonly MetaType MetaXml = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLXMLTYPE, TdsEnums.SQLXMLTYPE, MetaTypeName.XML, typeof(System.String), typeof(SqlXml), SqlDbType.Xml, DbType.Xml, 0); private static readonly MetaType s_metaDateTime = new MetaType (23, 3, 8, true, false, false, TdsEnums.SQLDATETIME, TdsEnums.SQLDATETIMN, MetaTypeName.DATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.DateTime, DbType.DateTime, 0); private static readonly MetaType s_metaSmallDateTime = new MetaType (16, 0, 4, true, false, false, TdsEnums.SQLDATETIM4, TdsEnums.SQLDATETIMN, MetaTypeName.SMALLDATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.SmallDateTime, DbType.DateTime, 0); private static readonly MetaType s_metaMoney = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLMONEY, TdsEnums.SQLMONEYN, MetaTypeName.MONEY, typeof(System.Decimal), typeof(SqlMoney), SqlDbType.Money, DbType.Currency, 0); private static readonly MetaType s_metaSmallMoney = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLMONEY4, TdsEnums.SQLMONEYN, MetaTypeName.SMALLMONEY, typeof(System.Decimal), typeof(SqlMoney), SqlDbType.SmallMoney, DbType.Currency, 0); private static readonly MetaType s_metaUniqueId = new MetaType (255, 255, 16, true, false, false, TdsEnums.SQLUNIQUEID, TdsEnums.SQLUNIQUEID, MetaTypeName.ROWGUID, typeof(System.Guid), typeof(SqlGuid), SqlDbType.UniqueIdentifier, DbType.Guid, 0); private static readonly MetaType s_metaVariant = new MetaType (255, 255, -1, true, false, false, TdsEnums.SQLVARIANT, TdsEnums.SQLVARIANT, MetaTypeName.VARIANT, typeof(System.Object), typeof(System.Object), SqlDbType.Variant, DbType.Object, 0); private static readonly MetaType s_metaTable = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLTABLE, TdsEnums.SQLTABLE, MetaTypeName.TABLE, typeof(IEnumerable<DbDataRecord>), typeof(IEnumerable<DbDataRecord>), SqlDbType.Structured, DbType.Object, 0); private static readonly MetaType s_metaSUDT = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVOID, TdsEnums.SQLVOID, "", typeof(MSS.SqlDataRecord), typeof(MSS.SqlDataRecord), SqlDbType.Structured, DbType.Object, 0); private static readonly MetaType s_metaDate = new MetaType (255, 255, 3, true, false, false, TdsEnums.SQLDATE, TdsEnums.SQLDATE, MetaTypeName.DATE, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.Date, DbType.Date, 0); internal static readonly MetaType MetaTime = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLTIME, TdsEnums.SQLTIME, MetaTypeName.TIME, typeof(System.TimeSpan), typeof(System.TimeSpan), SqlDbType.Time, DbType.Time, 1); private static readonly MetaType s_metaDateTime2 = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIME2, TdsEnums.SQLDATETIME2, MetaTypeName.DATETIME2, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.DateTime2, DbType.DateTime2, 1); internal static readonly MetaType MetaDateTimeOffset = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIMEOFFSET, TdsEnums.SQLDATETIMEOFFSET, MetaTypeName.DATETIMEOFFSET, typeof(System.DateTimeOffset), typeof(System.DateTimeOffset), SqlDbType.DateTimeOffset, DbType.DateTimeOffset, 1); public static TdsDateTime FromDateTime(DateTime dateTime, byte cb) { SqlDateTime sqlDateTime; TdsDateTime tdsDateTime = new TdsDateTime(); Debug.Assert(cb == 8 || cb == 4, "Invalid date time size!"); if (cb == 8) { sqlDateTime = new SqlDateTime(dateTime); tdsDateTime.time = sqlDateTime.TimeTicks; } else { // note that smalldatetime is days&minutes. // Adding 30 seconds ensures proper roundup if the seconds are >= 30 // The AddSeconds function handles eventual carryover sqlDateTime = new SqlDateTime(dateTime.AddSeconds(30)); tdsDateTime.time = sqlDateTime.TimeTicks / SqlDateTime.SQLTicksPerMinute; } tdsDateTime.days = sqlDateTime.DayTicks; return tdsDateTime; } public static DateTime ToDateTime(int sqlDays, int sqlTime, int length) { if (length == 4) { return new SqlDateTime(sqlDays, sqlTime * SqlDateTime.SQLTicksPerMinute).Value; } else { Debug.Assert(length == 8, "invalid length for DateTime"); return new SqlDateTime(sqlDays, sqlTime).Value; } } internal static int GetTimeSizeFromScale(byte scale) { if (scale <= 2) return 3; if (scale <= 4) return 4; return 5; } // // please leave string sorted alphabetically // note that these names should only be used in the context of parameters. We always send over BIG* and nullable types for SQL Server // private static class MetaTypeName { public const string BIGINT = "bigint"; public const string BINARY = "binary"; public const string BIT = "bit"; public const string CHAR = "char"; public const string DATETIME = "datetime"; public const string DECIMAL = "decimal"; public const string FLOAT = "float"; public const string IMAGE = "image"; public const string INT = "int"; public const string MONEY = "money"; public const string NCHAR = "nchar"; public const string NTEXT = "ntext"; public const string NVARCHAR = "nvarchar"; public const string REAL = "real"; public const string ROWGUID = "uniqueidentifier"; public const string SMALLDATETIME = "smalldatetime"; public const string SMALLINT = "smallint"; public const string SMALLMONEY = "smallmoney"; public const string TEXT = "text"; public const string TIMESTAMP = "timestamp"; public const string TINYINT = "tinyint"; public const string UDT = "udt"; public const string VARBINARY = "varbinary"; public const string VARCHAR = "varchar"; public const string VARIANT = "sql_variant"; public const string XML = "xml"; public const string TABLE = "table"; public const string DATE = "date"; public const string TIME = "time"; public const string DATETIME2 = "datetime2"; public const string DATETIMEOFFSET = "datetimeoffset"; } } // // note: it is the client's responsibility to know what size date time he is working with // internal struct TdsDateTime { public int days; // offset in days from 1/1/1900 // private UInt32 time; // if smalldatetime, this is # of minutes since midnight // otherwise: # of 1/300th of a second since midnight public int time; } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using Windows.Devices.PointOfService; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace SDKTemplate { public sealed partial class Scenario4_SymbologyAttributes : Page { MainPage rootPage = MainPage.Current; BarcodeScanner scanner = null; ClaimedBarcodeScanner claimedScanner = null; ObservableCollection<SymbologyListEntry> listOfSymbologies = null; BarcodeSymbologyAttributes symbologyAttributes = null; public Scenario4_SymbologyAttributes() { this.InitializeComponent(); listOfSymbologies = new ObservableCollection<SymbologyListEntry>(); SymbologyListSource.Source = listOfSymbologies; } protected override void OnNavigatedTo(NavigationEventArgs e) { ResetTheScenarioState(); } protected override void OnNavigatedFrom(NavigationEventArgs e) { ResetTheScenarioState(); } /// <summary> /// Event Handler for Start Scan Button Click. /// Sets up the barcode scanner to be ready to receive the data events from the scan. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ScenarioStartScanButton_Click(object sender, RoutedEventArgs e) { ScenarioStartScanButton.IsEnabled = false; rootPage.NotifyUser("Acquiring barcode scanner object.", NotifyType.StatusMessage); // create the barcode scanner. scanner = await DeviceHelpers.GetFirstBarcodeScannerAsync(); if (scanner != null) { // after successful creation, list supported symbologies IReadOnlyList<uint> supportedSymbologies = await scanner.GetSupportedSymbologiesAsync(); foreach (uint symbology in supportedSymbologies) { listOfSymbologies.Add(new SymbologyListEntry(symbology)); } // claim the scanner for exclusive use and enable it so that data received events are received. claimedScanner = await scanner.ClaimScannerAsync(); if (claimedScanner != null) { // It is always a good idea to have a release device requested event handler. If this event is not handled, there are chances of another app can // claim ownership of the barcode scanner. claimedScanner.ReleaseDeviceRequested += claimedScanner_ReleaseDeviceRequested; // after successfully claiming, attach the datareceived event handler. claimedScanner.DataReceived += claimedScanner_DataReceived; // Ask the API to decode the data by default. By setting this, API will decode the raw data from the barcode scanner and // send the ScanDataLabel and ScanDataType in the DataReceived event claimedScanner.IsDecodeDataEnabled = true; // enable the scanner. // Note: If the scanner is not enabled (i.e. EnableAsync not called), attaching the event handler will not be any useful because the API will not fire the event // if the claimedScanner has not been Enabled await claimedScanner.EnableAsync(); // reset the button state ScenarioEndScanButton.IsEnabled = true; rootPage.NotifyUser("Ready to scan. Device ID: " + claimedScanner.DeviceId, NotifyType.StatusMessage); } else { scanner.Dispose(); scanner = null; ScenarioStartScanButton.IsEnabled = true; rootPage.NotifyUser("Claim barcode scanner failed.", NotifyType.ErrorMessage); } } else { ScenarioStartScanButton.IsEnabled = true; rootPage.NotifyUser("Barcode scanner not found. Please connect a barcode scanner.", NotifyType.ErrorMessage); } } /// <summary> /// Event handler for the Release Device Requested event fired when barcode scanner receives Claim request from another application /// </summary> /// <param name="sender"></param> /// <param name="args"> Contains the ClamiedBarcodeScanner that is sending this request</param> void claimedScanner_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e) { // always retain the device e.RetainDevice(); rootPage.NotifyUser("Event ReleaseDeviceRequested received. Retaining the barcode scanner.", NotifyType.StatusMessage); } /// <summary> /// Event handler for the DataReceived event fired when a barcode is scanned by the barcode scanner /// </summary> /// <param name="sender"></param> /// <param name="args"> Contains the BarcodeScannerReport which contains the data obtained in the scan</param> async void claimedScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args) { // need to update the UI data on the dispatcher thread. // update the UI with the data received from the scan. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // read the data from the buffer and convert to string. ScenarioOutputScanDataLabel.Text = DataHelpers.GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType); ScenarioOutputScanData.Text = DataHelpers.GetDataString(args.Report.ScanData); ScenarioOutputScanDataType.Text = BarcodeSymbologies.GetName(args.Report.ScanDataType); }); } /// <summary> /// Reset the Scenario state /// </summary> private void ResetTheScenarioState() { if (claimedScanner != null) { // Detach the event handlers claimedScanner.DataReceived -= claimedScanner_DataReceived; claimedScanner.ReleaseDeviceRequested -= claimedScanner_ReleaseDeviceRequested; // Release the Barcode Scanner and set to null claimedScanner.Dispose(); claimedScanner = null; } if (scanner != null) { scanner.Dispose(); scanner = null; } symbologyAttributes = null; // Reset the strings in the UI rootPage.NotifyUser("Click the start scanning button to begin.", NotifyType.StatusMessage); this.ScenarioOutputScanData.Text = "No data"; this.ScenarioOutputScanDataLabel.Text = "No data"; this.ScenarioOutputScanDataType.Text = "No data"; // reset the button state ScenarioEndScanButton.IsEnabled = false; ScenarioStartScanButton.IsEnabled = true; SetSymbologyAttributesButton.IsEnabled = false; EnableCheckDigit.IsEnabled = false; TransmitCheckDigit.IsEnabled = false; SetDecodeRangeLimits.IsEnabled = false; // reset symbology list listOfSymbologies.Clear(); } /// <summary> /// Event handler for End Scan Button Click. /// Releases the Barcode Scanner and resets the text in the UI /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ScenarioEndScanButton_Click(object sender, RoutedEventArgs e) { // reset the scenario state this.ResetTheScenarioState(); } /// <summary> /// Event handler for Symbology listbox selection changed. /// Get symbology attributes and populate attribute UI components /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private async void SymbologySelection_Changed(object sender, SelectionChangedEventArgs args) { if (claimedScanner != null) { SymbologyListEntry symbologyListEntry = (SymbologyListEntry)SymbologyListBox.SelectedItem; if (symbologyListEntry != null) { SetSymbologyAttributesButton.IsEnabled = false; try { symbologyAttributes = await claimedScanner.GetSymbologyAttributesAsync(symbologyListEntry.Id); } catch (Exception) { symbologyAttributes = null; } if (symbologyAttributes != null) { SetSymbologyAttributesButton.IsEnabled = true; // initialize attributes UIs EnableCheckDigit.IsEnabled = symbologyAttributes.IsCheckDigitValidationSupported; EnableCheckDigit.IsChecked = symbologyAttributes.IsCheckDigitValidationEnabled; TransmitCheckDigit.IsEnabled = symbologyAttributes.IsCheckDigitTransmissionSupported; TransmitCheckDigit.IsChecked = symbologyAttributes.IsCheckDigitTransmissionEnabled; SetDecodeRangeLimits.IsEnabled = symbologyAttributes.IsDecodeLengthSupported; bool decodeLengthEnabled = (symbologyAttributes.DecodeLengthKind == BarcodeSymbologyDecodeLengthKind.Range); SetDecodeRangeLimits.IsChecked = decodeLengthEnabled; if (decodeLengthEnabled) { MinimumDecodeLength.Value = Math.Min(symbologyAttributes.DecodeLength1, symbologyAttributes.DecodeLength2); MaximumDecodeLength.Value = Math.Max(symbologyAttributes.DecodeLength1, symbologyAttributes.DecodeLength2); } } else { rootPage.NotifyUser("Symbology attributes are not available.", NotifyType.ErrorMessage); EnableCheckDigit.IsEnabled = false; TransmitCheckDigit.IsEnabled = false; SetDecodeRangeLimits.IsEnabled = false; } } } } private async void SetSymbologyAttributes_Click(object sender, RoutedEventArgs e) { if ((claimedScanner != null) && (symbologyAttributes != null)) { // populate attributes if (symbologyAttributes.IsCheckDigitValidationSupported) { symbologyAttributes.IsCheckDigitValidationEnabled = EnableCheckDigit.IsChecked.Value; } if (symbologyAttributes.IsCheckDigitTransmissionSupported) { symbologyAttributes.IsCheckDigitTransmissionEnabled = TransmitCheckDigit.IsChecked.Value; } if (symbologyAttributes.IsDecodeLengthSupported) { if (SetDecodeRangeLimits.IsChecked.Value) { symbologyAttributes.DecodeLengthKind = BarcodeSymbologyDecodeLengthKind.Range; symbologyAttributes.DecodeLength1 = (uint)MinimumDecodeLength.Value; symbologyAttributes.DecodeLength2 = (uint)MaximumDecodeLength.Value; } else { symbologyAttributes.DecodeLengthKind = BarcodeSymbologyDecodeLengthKind.AnyLength; } } SymbologyListEntry symbologyListEntry = (SymbologyListEntry)SymbologyListBox.SelectedItem; if (symbologyListEntry != null) { bool attributesSet = false; try { attributesSet = await claimedScanner.SetSymbologyAttributesAsync(symbologyListEntry.Id, symbologyAttributes); } catch (Exception) { // Scanner could not set the attributes. } if (attributesSet) { rootPage.NotifyUser("Attributes set for symbology '" + symbologyListEntry.Name + "'", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Attributes could not be set for symbology '" + symbologyListEntry.Name + "'.", NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("Select a symbology from the list.", NotifyType.ErrorMessage); } } } } }
#region BSD License /* Copyright (c) 2004 - 2008 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com), C.J. Adams-Collier (cjac@colliertech.org), Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * 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. */ #endregion using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Prebuild.Core.Attributes; using Prebuild.Core.Interfaces; using Prebuild.Core.Nodes; using Prebuild.Core.Utilities; namespace Prebuild.Core.Targets { /// <summary> /// /// </summary> [Target("nant")] public class NAntTarget : ITarget { #region Fields private Kernel m_Kernel; #endregion #region Private Methods private static string PrependPath(string path) { string tmpPath = Helper.NormalizePath(path, '/'); Regex regex = new Regex(@"(\w):/(\w+)"); Match match = regex.Match(tmpPath); //if(match.Success || tmpPath[0] == '.' || tmpPath[0] == '/') //{ tmpPath = Helper.NormalizePath(tmpPath); //} // else // { // tmpPath = Helper.NormalizePath("./" + tmpPath); // } return tmpPath; } private static string BuildReference(SolutionNode solution, ProjectNode currentProject, ReferenceNode refr) { if (!String.IsNullOrEmpty(refr.Path)) { return refr.Path; } if (solution.ProjectsTable.ContainsKey(refr.Name)) { ProjectNode projectRef = (ProjectNode) solution.ProjectsTable[refr.Name]; string finalPath = Helper.NormalizePath(refr.Name + GetProjectExtension(projectRef), '/'); return finalPath; } ProjectNode project = (ProjectNode) refr.Parent; // Do we have an explicit file reference? string fileRef = FindFileReference(refr.Name, project); if (fileRef != null) { return fileRef; } // Is there an explicit path in the project ref? if (refr.Path != null) { return Helper.NormalizePath(refr.Path + "/" + refr.Name + GetProjectExtension(project), '/'); } // No, it's an extensionless GAC ref, but nant needs the .dll extension anyway return refr.Name + ".dll"; } public static string GetRefFileName(string refName) { if (ExtensionSpecified(refName)) { return refName; } else { return refName + ".dll"; } } private static bool ExtensionSpecified(string refName) { return refName.EndsWith(".dll") || refName.EndsWith(".exe"); } private static string GetProjectExtension(ProjectNode project) { string extension = ".dll"; if (project.Type == ProjectType.Exe || project.Type == ProjectType.WinExe) { extension = ".exe"; } return extension; } private static string FindFileReference(string refName, ProjectNode project) { foreach (ReferencePathNode refPath in project.ReferencePaths) { string fullPath = Helper.MakeFilePath(refPath.Path, refName); if (File.Exists(fullPath)) { return fullPath; } fullPath = Helper.MakeFilePath(refPath.Path, refName, "dll"); if (File.Exists(fullPath)) { return fullPath; } fullPath = Helper.MakeFilePath(refPath.Path, refName, "exe"); if (File.Exists(fullPath)) { return fullPath; } } return null; } /// <summary> /// Gets the XML doc file. /// </summary> /// <param name="project">The project.</param> /// <param name="conf">The conf.</param> /// <returns></returns> public static string GetXmlDocFile(ProjectNode project, ConfigurationNode conf) { if (conf == null) { throw new ArgumentNullException("conf"); } if (project == null) { throw new ArgumentNullException("project"); } string docFile = (string)conf.Options["XmlDocFile"]; // if(docFile != null && docFile.Length == 0)//default to assembly name if not specified // { // return Path.GetFileNameWithoutExtension(project.AssemblyName) + ".xml"; // } return docFile; } private void WriteProject(SolutionNode solution, ProjectNode project) { string projFile = Helper.MakeFilePath(project.FullPath, project.Name + GetProjectExtension(project), "build"); StreamWriter ss = new StreamWriter(projFile); m_Kernel.CurrentWorkingDirectory.Push(); Helper.SetCurrentDir(Path.GetDirectoryName(projFile)); bool hasDoc = false; using (ss) { ss.WriteLine("<?xml version=\"1.0\" ?>"); ss.WriteLine("<project name=\"{0}\" default=\"build\">", project.Name); ss.WriteLine(" <target name=\"{0}\">", "build"); ss.WriteLine(" <echo message=\"Build Directory is ${project::get-base-directory()}/${build.dir}\" />"); ss.WriteLine(" <mkdir dir=\"${project::get-base-directory()}/${build.dir}\" />"); ss.WriteLine(" <copy todir=\"${project::get-base-directory()}/${build.dir}\" flatten=\"true\">"); ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}\">"); foreach (ReferenceNode refr in project.References) { if (refr.LocalCopy) { ss.WriteLine(" <include name=\"{0}", Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReference(solution, project, refr)) + "\" />", '/')); } } ss.WriteLine(" </fileset>"); ss.WriteLine(" </copy>"); if (project.ConfigFile != null && project.ConfigFile.Length!=0) { ss.Write(" <copy file=\"" + project.ConfigFile + "\" tofile=\"${project::get-base-directory()}/${build.dir}/${project::get-name()}"); if (project.Type == ProjectType.Library) { ss.Write(".dll.config\""); } else { ss.Write(".exe.config\""); } ss.WriteLine(" />"); } // Add the content files to just be copied ss.WriteLine(" {0}", "<copy todir=\"${project::get-base-directory()}/${build.dir}\">"); ss.WriteLine(" {0}", "<fileset basedir=\".\">"); foreach (string file in project.Files) { // Ignore if we aren't content if (project.Files.GetBuildAction(file) != BuildAction.Content) continue; // Create a include tag ss.WriteLine(" {0}", "<include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />"); } ss.WriteLine(" {0}", "</fileset>"); ss.WriteLine(" {0}", "</copy>"); ss.Write(" <csc "); ss.Write(" target=\"{0}\"", project.Type.ToString().ToLower()); ss.Write(" debug=\"{0}\"", "${build.debug}"); ss.Write(" platform=\"${build.platform}\""); foreach (ConfigurationNode conf in project.Configurations) { if (conf.Options.KeyFile != "") { ss.Write(" keyfile=\"{0}\"", conf.Options.KeyFile); break; } } foreach (ConfigurationNode conf in project.Configurations) { ss.Write(" unsafe=\"{0}\"", conf.Options.AllowUnsafe); break; } foreach (ConfigurationNode conf in project.Configurations) { ss.Write(" warnaserror=\"{0}\"", conf.Options.WarningsAsErrors); break; } foreach (ConfigurationNode conf in project.Configurations) { ss.Write(" define=\"{0}\"", conf.Options.CompilerDefines); break; } foreach (ConfigurationNode conf in project.Configurations) { ss.Write(" nostdlib=\"{0}\"", conf.Options["NoStdLib"]); break; } ss.Write(" main=\"{0}\"", project.StartupObject); foreach (ConfigurationNode conf in project.Configurations) { if (GetXmlDocFile(project, conf) != "") { ss.Write(" doc=\"{0}\"", "${project::get-base-directory()}/${build.dir}/" + GetXmlDocFile(project, conf)); hasDoc = true; } break; } ss.Write(" output=\"{0}", "${project::get-base-directory()}/${build.dir}/${project::get-name()}"); if (project.Type == ProjectType.Library) { ss.Write(".dll\""); } else { ss.Write(".exe\""); } if (project.AppIcon != null && project.AppIcon.Length != 0) { ss.Write(" win32icon=\"{0}\"", Helper.NormalizePath(project.AppIcon, '/')); } // This disables a very different behavior between VS and NAnt. With Nant, // If you have using System.Xml; it will ensure System.Xml.dll is referenced, // but not in VS. This will force the behaviors to match, so when it works // in nant, it will work in VS. ss.Write(" noconfig=\"true\""); ss.WriteLine(">"); ss.WriteLine(" <resources prefix=\"{0}\" dynamicprefix=\"true\" >", project.RootNamespace); foreach (string file in project.Files) { switch (project.Files.GetBuildAction(file)) { case BuildAction.EmbeddedResource: ss.WriteLine(" {0}", "<include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />"); break; default: if (project.Files.GetSubType(file) != SubType.Code && project.Files.GetSubType(file) != SubType.Settings) { ss.WriteLine(" <include name=\"{0}\" />", file.Substring(0, file.LastIndexOf('.')) + ".resx"); } break; } } //if (project.Files.GetSubType(file).ToString() != "Code") //{ // ps.WriteLine(" <EmbeddedResource Include=\"{0}\">", file.Substring(0, file.LastIndexOf('.')) + ".resx"); ss.WriteLine(" </resources>"); ss.WriteLine(" <sources failonempty=\"true\">"); foreach (string file in project.Files) { switch (project.Files.GetBuildAction(file)) { case BuildAction.Compile: ss.WriteLine(" <include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />"); break; default: break; } } ss.WriteLine(" </sources>"); ss.WriteLine(" <references basedir=\"${project::get-base-directory()}\">"); ss.WriteLine(" <lib>"); ss.WriteLine(" <include name=\"${project::get-base-directory()}\" />"); foreach(ReferencePathNode refPath in project.ReferencePaths) { ss.WriteLine(" <include name=\"${project::get-base-directory()}/" + refPath.Path.TrimEnd('/', '\\') + "\" />"); } ss.WriteLine(" </lib>"); foreach (ReferenceNode refr in project.References) { string path = Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReference(solution, project, refr)), '/'); if (refr.Path != null) { if (ExtensionSpecified(refr.Name)) { ss.WriteLine (" <include name=\"" + path + refr.Name + "\"/>"); } else { ss.WriteLine (" <include name=\"" + path + refr.Name + ".dll\"/>"); } } else { ss.WriteLine (" <include name=\"" + path + "\" />"); } } ss.WriteLine(" </references>"); ss.WriteLine(" </csc>"); foreach (ConfigurationNode conf in project.Configurations) { if (!String.IsNullOrEmpty(conf.Options.OutputPath)) { string targetDir = Helper.NormalizePath(conf.Options.OutputPath, '/'); ss.WriteLine(" <echo message=\"Copying from [${project::get-base-directory()}/${build.dir}/] to [${project::get-base-directory()}/" + targetDir + "\" />"); ss.WriteLine(" <mkdir dir=\"${project::get-base-directory()}/" + targetDir + "\"/>"); ss.WriteLine(" <copy todir=\"${project::get-base-directory()}/" + targetDir + "\">"); ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}/${build.dir}/\" >"); ss.WriteLine(" <include name=\"*.dll\"/>"); ss.WriteLine(" <include name=\"*.exe\"/>"); ss.WriteLine(" <include name=\"*.mdb\" if='${build.debug}'/>"); ss.WriteLine(" <include name=\"*.pdb\" if='${build.debug}'/>"); ss.WriteLine(" </fileset>"); ss.WriteLine(" </copy>"); break; } } ss.WriteLine(" </target>"); ss.WriteLine(" <target name=\"clean\">"); ss.WriteLine(" <delete dir=\"${bin.dir}\" failonerror=\"false\" />"); ss.WriteLine(" <delete dir=\"${obj.dir}\" failonerror=\"false\" />"); ss.WriteLine(" </target>"); ss.WriteLine(" <target name=\"doc\" description=\"Creates documentation.\">"); if (hasDoc) { ss.WriteLine(" <property name=\"doc.target\" value=\"\" />"); ss.WriteLine(" <if test=\"${platform::is-unix()}\">"); ss.WriteLine(" <property name=\"doc.target\" value=\"Web\" />"); ss.WriteLine(" </if>"); ss.WriteLine(" <ndoc failonerror=\"false\" verbose=\"true\">"); ss.WriteLine(" <assemblies basedir=\"${project::get-base-directory()}\">"); ss.Write(" <include name=\"${build.dir}/${project::get-name()}"); if (project.Type == ProjectType.Library) { ss.WriteLine(".dll\" />"); } else { ss.WriteLine(".exe\" />"); } ss.WriteLine(" </assemblies>"); ss.WriteLine(" <summaries basedir=\"${project::get-base-directory()}\">"); ss.WriteLine(" <include name=\"${build.dir}/${project::get-name()}.xml\"/>"); ss.WriteLine(" </summaries>"); ss.WriteLine(" <referencepaths basedir=\"${project::get-base-directory()}\">"); ss.WriteLine(" <include name=\"${build.dir}\" />"); // foreach(ReferenceNode refr in project.References) // { // string path = Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReferencePath(solution, refr)), '/'); // if (path != "") // { // ss.WriteLine(" <include name=\"{0}\" />", path); // } // } ss.WriteLine(" </referencepaths>"); ss.WriteLine(" <documenters>"); ss.WriteLine(" <documenter name=\"MSDN\">"); ss.WriteLine(" <property name=\"OutputDirectory\" value=\"${project::get-base-directory()}/${build.dir}/doc/${project::get-name()}\" />"); ss.WriteLine(" <property name=\"OutputTarget\" value=\"${doc.target}\" />"); ss.WriteLine(" <property name=\"HtmlHelpName\" value=\"${project::get-name()}\" />"); ss.WriteLine(" <property name=\"IncludeFavorites\" value=\"False\" />"); ss.WriteLine(" <property name=\"Title\" value=\"${project::get-name()} SDK Documentation\" />"); ss.WriteLine(" <property name=\"SplitTOCs\" value=\"False\" />"); ss.WriteLine(" <property name=\"DefaulTOC\" value=\"\" />"); ss.WriteLine(" <property name=\"ShowVisualBasic\" value=\"True\" />"); ss.WriteLine(" <property name=\"AutoDocumentConstructors\" value=\"True\" />"); ss.WriteLine(" <property name=\"ShowMissingSummaries\" value=\"${build.debug}\" />"); ss.WriteLine(" <property name=\"ShowMissingRemarks\" value=\"${build.debug}\" />"); ss.WriteLine(" <property name=\"ShowMissingParams\" value=\"${build.debug}\" />"); ss.WriteLine(" <property name=\"ShowMissingReturns\" value=\"${build.debug}\" />"); ss.WriteLine(" <property name=\"ShowMissingValues\" value=\"${build.debug}\" />"); ss.WriteLine(" <property name=\"DocumentInternals\" value=\"False\" />"); ss.WriteLine(" <property name=\"DocumentPrivates\" value=\"False\" />"); ss.WriteLine(" <property name=\"DocumentProtected\" value=\"True\" />"); ss.WriteLine(" <property name=\"DocumentEmptyNamespaces\" value=\"${build.debug}\" />"); ss.WriteLine(" <property name=\"IncludeAssemblyVersion\" value=\"True\" />"); ss.WriteLine(" </documenter>"); ss.WriteLine(" </documenters>"); ss.WriteLine(" </ndoc>"); } ss.WriteLine(" </target>"); ss.WriteLine("</project>"); } m_Kernel.CurrentWorkingDirectory.Pop(); } private void WriteCombine(SolutionNode solution) { m_Kernel.Log.Write("Creating NAnt build files"); foreach (ProjectNode project in solution.Projects) { if (m_Kernel.AllowProject(project.FilterGroups)) { m_Kernel.Log.Write("...Creating project: {0}", project.Name); WriteProject(solution, project); } } m_Kernel.Log.Write(""); string combFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "build"); StreamWriter ss = new StreamWriter(combFile); m_Kernel.CurrentWorkingDirectory.Push(); Helper.SetCurrentDir(Path.GetDirectoryName(combFile)); using (ss) { ss.WriteLine("<?xml version=\"1.0\" ?>"); ss.WriteLine("<project name=\"{0}\" default=\"build\">", solution.Name); ss.WriteLine(" <echo message=\"Using '${nant.settings.currentframework}' Framework\"/>"); ss.WriteLine(); //ss.WriteLine(" <property name=\"dist.dir\" value=\"dist\" />"); //ss.WriteLine(" <property name=\"source.dir\" value=\"source\" />"); ss.WriteLine(" <property name=\"bin.dir\" value=\"bin\" />"); ss.WriteLine(" <property name=\"obj.dir\" value=\"obj\" />"); ss.WriteLine(" <property name=\"doc.dir\" value=\"doc\" />"); ss.WriteLine(" <property name=\"project.main.dir\" value=\"${project::get-base-directory()}\" />"); // Use the active configuration, which is the first configuration name in the prebuild file. Dictionary<string,string> emittedConfigurations = new Dictionary<string, string>(); ss.WriteLine(" <property name=\"project.config\" value=\"{0}\" />", solution.ActiveConfig); ss.WriteLine(); foreach (ConfigurationNode conf in solution.Configurations) { // If the name isn't in the emitted configurations, we give a high level target to the // platform specific on. This lets "Debug" point to "Debug-AnyCPU". if (!emittedConfigurations.ContainsKey(conf.Name)) { // Add it to the dictionary so we only emit one. emittedConfigurations.Add(conf.Name, conf.Platform); // Write out the target block. ss.WriteLine(" <target name=\"{0}\" description=\"{0}|{1}\" depends=\"{0}-{1}\">", conf.Name, conf.Platform); ss.WriteLine(" </target>"); ss.WriteLine(); } // Write out the target for the configuration. ss.WriteLine(" <target name=\"{0}-{1}\" description=\"{0}|{1}\">", conf.Name, conf.Platform); ss.WriteLine(" <property name=\"project.config\" value=\"{0}\" />", conf.Name); ss.WriteLine(" <property name=\"build.debug\" value=\"{0}\" />", conf.Options["DebugInformation"].ToString().ToLower()); ss.WriteLine("\t\t <property name=\"build.platform\" value=\"{0}\" />", conf.Platform); ss.WriteLine(" </target>"); ss.WriteLine(); } ss.WriteLine(" <target name=\"net-1.1\" description=\"Sets framework to .NET 1.1\">"); ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-1.1\" />"); ss.WriteLine(" </target>"); ss.WriteLine(); ss.WriteLine(" <target name=\"net-2.0\" description=\"Sets framework to .NET 2.0\">"); ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-2.0\" />"); ss.WriteLine(" </target>"); ss.WriteLine(); ss.WriteLine(" <target name=\"net-3.5\" description=\"Sets framework to .NET 3.5\">"); ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-3.5\" />"); ss.WriteLine(" </target>"); ss.WriteLine(); ss.WriteLine(" <target name=\"mono-1.0\" description=\"Sets framework to mono 1.0\">"); ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-1.0\" />"); ss.WriteLine(" </target>"); ss.WriteLine(); ss.WriteLine(" <target name=\"mono-2.0\" description=\"Sets framework to mono 2.0\">"); ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-2.0\" />"); ss.WriteLine(" </target>"); ss.WriteLine(); ss.WriteLine(" <target name=\"mono-3.5\" description=\"Sets framework to mono 3.5\">"); ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-3.5\" />"); ss.WriteLine(" </target>"); ss.WriteLine(); ss.WriteLine(" <target name=\"init\" description=\"\">"); ss.WriteLine(" <call target=\"${project.config}\" />"); ss.WriteLine(" <property name=\"sys.os.platform\""); ss.WriteLine(" value=\"${platform::get-name()}\""); ss.WriteLine(" />"); ss.WriteLine(" <echo message=\"Platform ${sys.os.platform}\" />"); ss.WriteLine(" <property name=\"build.dir\" value=\"${bin.dir}/${project.config}\" />"); ss.WriteLine(" </target>"); ss.WriteLine(); // sdague - ok, this is an ugly hack, but what it lets // us do is native include of files into the nant // created files from all .nant/*include files. This // lets us keep using prebuild, but allows for // extended nant targets to do build and the like. try { Regex re = new Regex(".include$"); DirectoryInfo nantdir = new DirectoryInfo(".nant"); foreach (FileSystemInfo item in nantdir.GetFileSystemInfos()) { if (item is DirectoryInfo) { } else if (item is FileInfo) { if (re.Match(item.FullName) != System.Text.RegularExpressions.Match.Empty) { Console.WriteLine("Including file: " + item.FullName); using (FileStream fs = new FileStream(item.FullName, FileMode.Open, FileAccess.Read, FileShare.None)) { using (StreamReader sr = new StreamReader(fs)) { ss.WriteLine("<!-- included from {0} -->", (item).FullName); while (sr.Peek() != -1) { ss.WriteLine(sr.ReadLine()); } ss.WriteLine(); } } } } } } catch { } // ss.WriteLine(" <include buildfile=\".nant/local.include\" />"); // ss.WriteLine(" <target name=\"zip\" description=\"\">"); // ss.WriteLine(" <zip zipfile=\"{0}-{1}.zip\">", solution.Name, solution.Version); // ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}\">"); // ss.WriteLine(" <include name=\"${project::get-base-directory()}/**/*.cs\" />"); // // ss.WriteLine(" <include name=\"${project.main.dir}/**/*\" />"); // ss.WriteLine(" </fileset>"); // ss.WriteLine(" </zip>"); // ss.WriteLine(" <echo message=\"Building zip target\" />"); // ss.WriteLine(" </target>"); ss.WriteLine(); ss.WriteLine(" <target name=\"clean\" description=\"\">"); ss.WriteLine(" <echo message=\"Deleting all builds from all configurations\" />"); //ss.WriteLine(" <delete dir=\"${dist.dir}\" failonerror=\"false\" />"); // justincc: FIXME FIXME FIXME - A temporary OpenSim hack to clean up files when "nant clean" is executed. // Should be replaced with extreme prejudice once anybody finds out if the CleanFiles stuff works or there is // another working mechanism for specifying this stuff ss.WriteLine(" <delete failonerror=\"false\">"); ss.WriteLine(" <fileset basedir=\"${bin.dir}\">"); ss.WriteLine(" <include name=\"OpenSim*.dll\"/>"); ss.WriteLine(" <include name=\"OpenSim*.exe\"/>"); ss.WriteLine(" <include name=\"ScriptEngines/*\"/>"); ss.WriteLine(" <include name=\"Physics/*\"/>"); ss.WriteLine(" <exclude name=\"OpenSim.32BitLaunch.exe\"/>"); ss.WriteLine(" <exclude name=\"ScriptEngines/Default.lsl\"/>"); ss.WriteLine(" </fileset>"); ss.WriteLine(" </delete>"); if (solution.Cleanup != null && solution.Cleanup.CleanFiles.Count > 0) { foreach (CleanFilesNode cleanFile in solution.Cleanup.CleanFiles) { ss.WriteLine(" <delete failonerror=\"false\">"); ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}\">"); ss.WriteLine(" <include name=\"{0}/*\"/>", cleanFile.Pattern); ss.WriteLine(" <include name=\"{0}\"/>", cleanFile.Pattern); ss.WriteLine(" </fileset>"); ss.WriteLine(" </delete>"); } } ss.WriteLine(" <delete dir=\"${obj.dir}\" failonerror=\"false\" />"); foreach (ProjectNode project in solution.Projects) { string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath); ss.Write(" <nant buildfile=\"{0}\"", Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/')); ss.WriteLine(" target=\"clean\" />"); } ss.WriteLine(" </target>"); ss.WriteLine(); ss.WriteLine(" <target name=\"build\" depends=\"init\" description=\"\">"); foreach (ProjectNode project in solution.ProjectsTableOrder) { string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath); ss.Write(" <nant buildfile=\"{0}\"", Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/')); ss.WriteLine(" target=\"build\" />"); } ss.WriteLine(" </target>"); ss.WriteLine(); ss.WriteLine(" <target name=\"build-release\" depends=\"Release, init, build\" description=\"Builds in Release mode\" />"); ss.WriteLine(); ss.WriteLine(" <target name=\"build-debug\" depends=\"Debug, init, build\" description=\"Builds in Debug mode\" />"); ss.WriteLine(); //ss.WriteLine(" <target name=\"package\" depends=\"clean, doc, copyfiles, zip\" description=\"Builds in Release mode\" />"); ss.WriteLine(" <target name=\"package\" depends=\"clean, doc\" description=\"Builds all\" />"); ss.WriteLine(); ss.WriteLine(" <target name=\"doc\" depends=\"build-release\">"); ss.WriteLine(" <echo message=\"Generating all documentation from all builds\" />"); foreach (ProjectNode project in solution.Projects) { string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath); ss.Write(" <nant buildfile=\"{0}\"", Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/')); ss.WriteLine(" target=\"doc\" />"); } ss.WriteLine(" </target>"); ss.WriteLine(); ss.WriteLine("</project>"); } m_Kernel.CurrentWorkingDirectory.Pop(); } private void CleanProject(ProjectNode project) { m_Kernel.Log.Write("...Cleaning project: {0}", project.Name); string projectFile = Helper.MakeFilePath(project.FullPath, project.Name + GetProjectExtension(project), "build"); Helper.DeleteIfExists(projectFile); } private void CleanSolution(SolutionNode solution) { m_Kernel.Log.Write("Cleaning NAnt build files for", solution.Name); string slnFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "build"); Helper.DeleteIfExists(slnFile); foreach (ProjectNode project in solution.Projects) { CleanProject(project); } m_Kernel.Log.Write(""); } #endregion #region ITarget Members /// <summary> /// Writes the specified kern. /// </summary> /// <param name="kern">The kern.</param> public void Write(Kernel kern) { if (kern == null) { throw new ArgumentNullException("kern"); } m_Kernel = kern; foreach (SolutionNode solution in kern.Solutions) { WriteCombine(solution); } m_Kernel = null; } /// <summary> /// Cleans the specified kern. /// </summary> /// <param name="kern">The kern.</param> public virtual void Clean(Kernel kern) { if (kern == null) { throw new ArgumentNullException("kern"); } m_Kernel = kern; foreach (SolutionNode sol in kern.Solutions) { CleanSolution(sol); } m_Kernel = null; } /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name { get { return "nant"; } } #endregion } }
using System.ComponentModel; using System.Drawing; using Microsoft.Win32; using Skybound.ComponentModel; namespace Skybound.VisualTips.Rendering { [System.ComponentModel.TypeConverter(typeof(Skybound.VisualTips.Rendering.VisualTipOfficePreset.TypeConverter))] public class VisualTipOfficePreset { internal class TypeConverter : Skybound.ComponentModel.StandardValueConverter { public TypeConverter() : base(typeof(Skybound.VisualTips.Rendering.VisualTipOfficePreset)) { } } // class TypeConverter internal System.Drawing.Color BackColor; internal System.Drawing.Color BackColorGradient; internal System.Drawing.Color BorderColor; internal System.Drawing.Color TextColor; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _AutoSelect; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _Brown; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _Control; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _Cyan; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _DeepBlue; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _Hazel; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _Midnight; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _Pink; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _Red; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _Smoke; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _ToolTip; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _Violet; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _XPBlue; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _XPGreen; private static Skybound.VisualTips.Rendering.VisualTipOfficePreset _XPSilver; [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset AutoSelect { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._AutoSelect; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset Brown { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._Brown; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset Control { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._Control; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset Cyan { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._Cyan; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset DeepBlue { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._DeepBlue; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset Hazel { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._Hazel; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset Midnight { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._Midnight; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset Pink { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._Pink; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset Red { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._Red; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset Smoke { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._Smoke; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset ToolTip { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._ToolTip; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset Violet { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._Violet; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset XPBlue { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._XPBlue; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset XPGreen { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._XPGreen; } } [Skybound.ComponentModel.StandardValue] public static Skybound.VisualTips.Rendering.VisualTipOfficePreset XPSilver { get { return Skybound.VisualTips.Rendering.VisualTipOfficePreset._XPSilver; } } private VisualTipOfficePreset() { } private VisualTipOfficePreset(System.Drawing.Color backColor, System.Drawing.Color backColorGradient, System.Drawing.Color borderColor, System.Drawing.Color textColor) { BackColor = backColor; BackColorGradient = backColorGradient; BorderColor = borderColor; TextColor = textColor; } static VisualTipOfficePreset() { Skybound.VisualTips.Rendering.VisualTipOfficePreset._XPBlue = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.Color.FromArgb(255, 255, 255), System.Drawing.Color.FromArgb(201, 217, 239), System.Drawing.Color.FromArgb(111, 121, 133), System.Drawing.Color.FromArgb(64, 64, 64)); Skybound.VisualTips.Rendering.VisualTipOfficePreset._XPGreen = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.Color.FromArgb(245, 255, 215), System.Drawing.Color.FromArgb(197, 210, 155), System.Drawing.Color.FromArgb(123, 140, 119), System.Drawing.Color.FromArgb(64, 64, 64)); Skybound.VisualTips.Rendering.VisualTipOfficePreset._XPSilver = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.Color.FromArgb(251, 251, 251), System.Drawing.Color.FromArgb(220, 220, 220), System.Drawing.Color.FromArgb(128, 128, 128), System.Drawing.Color.FromArgb(64, 64, 64)); Skybound.VisualTips.Rendering.VisualTipOfficePreset._Control = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.SystemColors.ControlLightLight, System.Drawing.SystemColors.Control, System.Drawing.SystemColors.ControlDark, System.Drawing.SystemColors.ControlText); Skybound.VisualTips.Rendering.VisualTipOfficePreset._Brown = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.Color.FromArgb(255, 249, 249), System.Drawing.Color.FromArgb(233, 222, 208), System.Drawing.Color.FromArgb(138, 128, 118), System.Drawing.Color.FromArgb(64, 64, 64)); Skybound.VisualTips.Rendering.VisualTipOfficePreset._Hazel = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.Color.FromArgb(255, 252, 249), System.Drawing.Color.FromArgb(232, 233, 208), System.Drawing.Color.FromArgb(140, 140, 119), System.Drawing.Color.FromArgb(64, 64, 64)); Skybound.VisualTips.Rendering.VisualTipOfficePreset._Cyan = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.Color.FromArgb(248, 254, 251), System.Drawing.Color.FromArgb(208, 228, 233), System.Drawing.Color.FromArgb(118, 135, 138), System.Drawing.Color.FromArgb(64, 64, 64)); Skybound.VisualTips.Rendering.VisualTipOfficePreset._Pink = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.Color.FromArgb(254, 248, 253), System.Drawing.Color.FromArgb(233, 208, 212), System.Drawing.Color.FromArgb(138, 118, 123), System.Drawing.Color.FromArgb(64, 64, 64)); Skybound.VisualTips.Rendering.VisualTipOfficePreset._Violet = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.Color.FromArgb(248, 248, 254), System.Drawing.Color.FromArgb(227, 208, 233), System.Drawing.Color.FromArgb(132, 118, 138), System.Drawing.Color.FromArgb(64, 64, 64)); Skybound.VisualTips.Rendering.VisualTipOfficePreset._Red = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.Color.FromArgb(243, 217, 207), System.Drawing.Color.IndianRed, System.Drawing.Color.FromArgb(132, 96, 96), System.Drawing.Color.FromArgb(48, 32, 32)); Skybound.VisualTips.Rendering.VisualTipOfficePreset._ToolTip = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.SystemColors.Info, System.Drawing.SystemColors.Info, System.Drawing.SystemColors.WindowFrame, System.Drawing.SystemColors.InfoText); Skybound.VisualTips.Rendering.VisualTipOfficePreset._DeepBlue = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.Color.FromArgb(221, 236, 254), System.Drawing.Color.FromArgb(129, 169, 226), System.Drawing.Color.FromArgb(59, 97, 156), System.Drawing.Color.FromArgb(0, 0, 0)); Skybound.VisualTips.Rendering.VisualTipOfficePreset._Smoke = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.Color.FromArgb(240, 240, 240), System.Drawing.Color.FromArgb(224, 224, 224), System.Drawing.Color.FromArgb(128, 128, 128), System.Drawing.Color.FromArgb(0, 0, 0)); Skybound.VisualTips.Rendering.VisualTipOfficePreset._Midnight = new Skybound.VisualTips.Rendering.VisualTipOfficePreset(System.Drawing.Color.Gray, System.Drawing.Color.Black, System.Drawing.Color.Silver, System.Drawing.Color.White); Microsoft.Win32.SystemEvents.UserPreferenceChanged += new Microsoft.Win32.UserPreferenceChangedEventHandler(Skybound.VisualTips.Rendering.VisualTipOfficePreset.SystemEvents_UserPreferenceChanged); Skybound.VisualTips.Rendering.VisualTipOfficePreset.UpdateAutoSelect(); } private static void SystemEvents_UserPreferenceChanged(object sender, Microsoft.Win32.UserPreferenceChangedEventArgs e) { if (e.Category == Microsoft.Win32.UserPreferenceCategory.Color) Skybound.VisualTips.Rendering.VisualTipOfficePreset.UpdateAutoSelect(); } private static void UpdateAutoSelect() { Skybound.VisualTips.Rendering.VisualTipOfficePreset visualTipOfficePreset; System.Drawing.Color color1 = System.Drawing.SystemColors.ActiveCaption; float f = color1.GetHue(); if ((f >= 200.0F) && (f <= 250.0F)) { visualTipOfficePreset = Skybound.VisualTips.Rendering.VisualTipOfficePreset.XPBlue; } else if ((f >= 70.0F) && (f <= 120.0F)) { visualTipOfficePreset = Skybound.VisualTips.Rendering.VisualTipOfficePreset.XPGreen; } else { if (f != 0.0F) { System.Drawing.Color color2 = System.Drawing.SystemColors.ActiveCaption; if (color2.GetSaturation() >= 0.1F) goto label_1; } visualTipOfficePreset = Skybound.VisualTips.Rendering.VisualTipOfficePreset.XPSilver; goto label_2; label_1: visualTipOfficePreset = Skybound.VisualTips.Rendering.VisualTipOfficePreset.Control; } label_2: Skybound.VisualTips.Rendering.VisualTipOfficePreset._AutoSelect = (Skybound.VisualTips.Rendering.VisualTipOfficePreset)visualTipOfficePreset.MemberwiseClone(); } } // class VisualTipOfficePreset }
#region Namespaces using System; using System.ComponentModel; using System.Data; using System.Xml; using Epi; #endregion //Namespaces namespace Epi.Fields { /// <summary> /// Mirror Field. /// </summary> public class MirrorField : FieldWithSeparatePrompt, IDependentField { #region Private Members /// <summary> /// The Xml view element of the MirrorField. /// </summary> private XmlElement viewElement; /// <summary> /// Xml Node representation of ImageField. /// </summary> private XmlNode fieldNode; /// <summary> /// sourceFieldId - the field Id of control being mirrored. /// </summary> private int sourceFieldId; /// <summary> /// IDataField - the field being mirrored. /// </summary> private IDataField sourceField; private BackgroundWorker _updater; private BackgroundWorker _inserter; #endregion Private Members #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="page">The page this field belongs to</param> public MirrorField(Page page) : base(page) { } /// <summary> /// Constructor /// </summary> /// <param name="view">View</param> public MirrorField(View view) : base(view) { } /// <summary> /// Constructor /// </summary> /// <param name="page">Page</param> /// <param name="viewElement">Xml view element</param> public MirrorField(Page page, XmlElement viewElement) : base(page) { this.viewElement = viewElement; this.Page = page; } /// <summary> /// Constructor /// </summary> /// <param name="view">View</param> /// <param name="fieldNode">Xml field node</param> public MirrorField(View view, XmlNode fieldNode) : base(view) { this.fieldNode = fieldNode; this.view.Project.Metadata.GetFieldData(this, this.fieldNode); } /// <summary> /// Load from row /// </summary> /// <param name="row">Row</param> public override void LoadFromRow(DataRow row) { base.LoadFromRow(row); if (!string.IsNullOrEmpty(row["SourceFieldId"].ToString())) { sourceFieldId = int.Parse(row["SourceFieldId"].ToString()); } } public MirrorField Clone() { MirrorField clone = (MirrorField)this.MemberwiseClone(); base.AssignMembers(clone); return clone; } #endregion Constructors #region Public Properties /// <summary> /// Returns field type /// </summary> public override MetaFieldType FieldType { get { return MetaFieldType.Mirror; } } /// <summary> /// Source Field Id /// </summary> public int SourceFieldId // Implements IDependentField.SourceFieldId { get { return sourceFieldId; } set { sourceFieldId = value; } } /// <summary> /// Source Field /// </summary> public IDataField SourceField // Implements IDependentField.SourceField { get { View view = Page.GetView(); if ((sourceField == null) && (this.SourceFieldId > 0)) { Field field = view.GetFieldById(this.SourceFieldId); if (field is IDataField) { sourceField = (IDataField)field; } } return (sourceField) ; } } #endregion Public Properties #region Protected Properties #endregion Protected Properties #region Public Methods /// <summary> /// Deletes the field /// </summary> public override void Delete() { GetMetadata().DeleteField(this); view.MustRefreshFieldCollection = true; } #endregion Public Methods #region protected Methods /// <summary> /// Inserts the field to the database /// </summary> protected override void InsertField() { this.Id = GetMetadata().CreateField(this); base.OnFieldAdded(); } /// <summary> /// Update the field to the database /// </summary> protected override void UpdateField() { GetMetadata().UpdateField(this); } ///// <summary> ///// Inserts the field to the database ///// </summary> //protected override void InsertField() //{ // insertStarted = true; // _inserter = new BackgroundWorker(); // _inserter.DoWork += new DoWorkEventHandler(inserter_DoWork); // _inserter.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_inserter_RunWorkerCompleted); // _inserter.RunWorkerAsync(); //} //void _inserter_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) //{ // OnFieldInserted(this); //} //void inserter_DoWork(object sender, DoWorkEventArgs e) //{ // fieldsWaitingToUpdate++; // lock (view.FieldLockToken) // { // this.Id = GetMetadata().CreateField(this); // base.OnFieldAdded(); // fieldsWaitingToUpdate--; // } //} ///// <summary> ///// Update the field to the database ///// </summary> //protected override void UpdateField() //{ // _updater = new BackgroundWorker(); // _updater.DoWork += new DoWorkEventHandler(DoWork); // _updater.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_updater_RunWorkerCompleted); // _updater.RunWorkerAsync(); //} //void _updater_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) //{ // OnFieldUpdated(this); //} //private void DoWork(object sender, DoWorkEventArgs e) //{ // fieldsWaitingToUpdate++; // lock (view.FieldLockToken) // { // GetMetadata().UpdateField(this); // fieldsWaitingToUpdate--; // } //} #endregion protected Methods #region Event Handlers #endregion Event Handlers /// <summary> /// The view element of the field /// </summary> public XmlElement ViewElement { get { return viewElement; } set { viewElement = value; } } } }
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this 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, or any other, from this software. // // // ==--== namespace Microsoft.JScript { using Microsoft.JScript.Vsa; using System; using System.Reflection; using System.Collections; public sealed class LenientGlobalObject : GlobalObject{ // properties public new Object Infinity; private Object MathField; public new Object NaN; public new Object undefined; // backing fields for constructor properties private Object ActiveXObjectField; private Object ArrayField; private Object BooleanField; private Object DateField; private Object EnumeratorField; private Object ErrorField; private Object EvalErrorField; private Object FunctionField; private Object NumberField; private Object ObjectField; private Object RangeErrorField; private Object ReferenceErrorField; private Object RegExpField; private Object StringField; private Object SyntaxErrorField; private Object TypeErrorField; private Object VBArrayField; private Object URIErrorField; // function properties public new Object decodeURI; public new Object decodeURIComponent; public new Object encodeURI; public new Object encodeURIComponent; [NotRecommended ("escape")] public new Object escape; public new Object eval; public new Object isNaN; public new Object isFinite; public new Object parseInt; public new Object parseFloat; public new Object GetObject; public new Object ScriptEngine; public new Object ScriptEngineBuildVersion; public new Object ScriptEngineMajorVersion; public new Object ScriptEngineMinorVersion; [NotRecommended ("unescape")] public new Object unescape; // built-in types public new Object boolean; public new Object @byte; public new Object @char; public new Object @decimal; public new Object @double; public new Object @float; public new Object @int; public new Object @long; public new Object @sbyte; public new Object @short; public new Object @void; public new Object @uint; public new Object @ulong; public new Object @ushort; //backing fields for private properties used to initialize orignalXXX properties private LenientArrayPrototype arrayPrototypeField; private LenientFunctionPrototype functionPrototypeField; private LenientObjectPrototype objectPrototypeField; private VsaEngine engine; internal LenientGlobalObject(VsaEngine engine){ this.engine = engine; this.Infinity = Double.PositiveInfinity; this.NaN = Double.NaN; this.undefined = null; this.ActiveXObjectField = Missing.Value; this.ArrayField = Missing.Value; this.BooleanField = Missing.Value; this.DateField = Missing.Value; this.EnumeratorField = Missing.Value; this.ErrorField = Missing.Value; this.EvalErrorField = Missing.Value; this.FunctionField = Missing.Value; this.MathField = Missing.Value; this.NumberField = Missing.Value; this.ObjectField = Missing.Value; this.RangeErrorField = Missing.Value; this.ReferenceErrorField = Missing.Value; this.RegExpField = Missing.Value; this.StringField = Missing.Value; this.SyntaxErrorField = Missing.Value; this.TypeErrorField = Missing.Value; this.VBArrayField = Missing.Value; this.URIErrorField = Missing.Value; Type super = typeof(GlobalObject); LenientFunctionPrototype fprot = this.functionPrototype; this.decodeURI = new BuiltinFunction("decodeURI", this, super.GetMethod("decodeURI"), fprot); this.decodeURIComponent = new BuiltinFunction("decodeURIComponent", this, super.GetMethod("decodeURIComponent"), fprot); this.encodeURI = new BuiltinFunction("encodeURI", this, super.GetMethod("encodeURI"), fprot); this.encodeURIComponent = new BuiltinFunction("encodeURIComponent", this, super.GetMethod("encodeURIComponent"), fprot); this.escape = new BuiltinFunction("escape", this, super.GetMethod("escape"), fprot); this.eval = new BuiltinFunction("eval", this, super.GetMethod("eval"), fprot); this.isNaN = new BuiltinFunction("isNaN", this, super.GetMethod("isNaN"), fprot); this.isFinite = new BuiltinFunction("isFinite", this, super.GetMethod("isFinite"), fprot); this.parseInt = new BuiltinFunction("parseInt", this, super.GetMethod("parseInt"), fprot); this.GetObject = new BuiltinFunction("GetObject", this, super.GetMethod("GetObject"), fprot); this.parseFloat = new BuiltinFunction("parseFloat", this, super.GetMethod("parseFloat"), fprot); this.ScriptEngine = new BuiltinFunction("ScriptEngine", this, super.GetMethod("ScriptEngine"), fprot); this.ScriptEngineBuildVersion = new BuiltinFunction("ScriptEngineBuildVersion", this, super.GetMethod("ScriptEngineBuildVersion"), fprot); this.ScriptEngineMajorVersion = new BuiltinFunction("ScriptEngineMajorVersion", this, super.GetMethod("ScriptEngineMajorVersion"), fprot); this.ScriptEngineMinorVersion = new BuiltinFunction("ScriptEngineMinorVersion", this, super.GetMethod("ScriptEngineMinorVersion"), fprot); this.unescape = new BuiltinFunction("unescape", this, super.GetMethod("unescape"), fprot); this.boolean = Typeob.Boolean; this.@byte = Typeob.Byte; this.@char = Typeob.Char; this.@decimal = Typeob.Decimal; this.@double = Typeob.Double; this.@float = Typeob.Single; this.@int = Typeob.Int32; this.@long = Typeob.Int64; this.@sbyte = Typeob.SByte; this.@short = Typeob.Int16; this.@void = Typeob.Void; this.@uint = Typeob.UInt32; this.@ulong = Typeob.UInt64; this.@ushort = Typeob.UInt16; } private LenientArrayPrototype arrayPrototype{ get{ if (this.arrayPrototypeField == null) this.arrayPrototypeField = new LenientArrayPrototype(this.functionPrototype, this.objectPrototype); return this.arrayPrototypeField; } } private LenientFunctionPrototype functionPrototype{ get{ if (this.functionPrototypeField == null){ Object junk = this.objectPrototype; //initialize functionPrototypeField indiretly because of circularity } return this.functionPrototypeField; } } private LenientObjectPrototype objectPrototype{ get{ if (this.objectPrototypeField == null){ LenientObjectPrototype prototype = this.objectPrototypeField = new LenientObjectPrototype(this.engine); LenientFunctionPrototype fprot = this.functionPrototypeField = new LenientFunctionPrototype(prototype); prototype.Initialize(fprot); JSObject prot = new JSObject(prototype, false); prot.AddField("constructor").SetValue(prot, fprot); fprot.proto = prot; } return this.objectPrototypeField; } } internal override ActiveXObjectConstructor originalActiveXObject{ get{ if (this.originalActiveXObjectField == null) this.originalActiveXObjectField = new ActiveXObjectConstructor(this.functionPrototype); return this.originalActiveXObjectField; } } internal override ArrayConstructor originalArray{ get{ if (this.originalArrayField == null) this.originalArrayField = new ArrayConstructor(this.functionPrototype, this.arrayPrototype); return this.originalArrayField; } } internal override BooleanConstructor originalBoolean{ get{ if (this.originalBooleanField == null) this.originalBooleanField = new BooleanConstructor(this.functionPrototype, new LenientBooleanPrototype(this.functionPrototype, this.objectPrototype)); return this.originalBooleanField; } } internal override DateConstructor originalDate{ get{ if (this.originalDateField == null) this.originalDateField = new LenientDateConstructor(this.functionPrototype, new LenientDatePrototype(this.functionPrototype, this.objectPrototype)); return this.originalDateField; } } internal override ErrorConstructor originalError{ get{ if (this.originalErrorField == null) this.originalErrorField = new ErrorConstructor(this.functionPrototype, new LenientErrorPrototype(this.functionPrototype, this.objectPrototype, "Error"), this); return this.originalErrorField; } } internal override EnumeratorConstructor originalEnumerator{ get{ if (this.originalEnumeratorField == null) this.originalEnumeratorField = new EnumeratorConstructor(this.functionPrototype, new LenientEnumeratorPrototype(this.functionPrototype, this.objectPrototype)); return this.originalEnumeratorField; } } internal override ErrorConstructor originalEvalError{ get{ if (this.originalEvalErrorField == null) this.originalEvalErrorField = new ErrorConstructor("EvalError", ErrorType.EvalError, this.originalError, this); return this.originalEvalErrorField; } } internal override FunctionConstructor originalFunction{ get{ if (this.originalFunctionField == null) this.originalFunctionField = new FunctionConstructor(this.functionPrototype); return this.originalFunctionField; } } internal override NumberConstructor originalNumber{ get{ if (this.originalNumberField == null) this.originalNumberField = new NumberConstructor(this.functionPrototype, new LenientNumberPrototype(this.functionPrototype, this.objectPrototype)); return this.originalNumberField; } } internal override ObjectConstructor originalObject{ get{ if (this.originalObjectField == null) this.originalObjectField = new ObjectConstructor(this.functionPrototype, this.objectPrototype); return this.originalObjectField; } } internal override ObjectPrototype originalObjectPrototype{ get{ if (this.originalObjectPrototypeField == null) this.originalObjectPrototypeField = ObjectPrototype.ob; return this.originalObjectPrototypeField; } } internal override ErrorConstructor originalRangeError{ get{ if (this.originalRangeErrorField == null) this.originalRangeErrorField = new ErrorConstructor("RangeError", ErrorType.RangeError, this.originalError, this); return this.originalRangeErrorField; } } internal override ErrorConstructor originalReferenceError{ get{ if (this.originalReferenceErrorField == null) this.originalReferenceErrorField = new ErrorConstructor("ReferenceError", ErrorType.ReferenceError, this.originalError, this); return this.originalReferenceErrorField; } } internal override RegExpConstructor originalRegExp{ get{ if (this.originalRegExpField == null) this.originalRegExpField = new RegExpConstructor(this.functionPrototype, new LenientRegExpPrototype(this.functionPrototype, this.objectPrototype), this.arrayPrototype); return this.originalRegExpField; } } internal override StringConstructor originalString{ get{ if (this.originalStringField == null) this.originalStringField = new LenientStringConstructor(this.functionPrototype, new LenientStringPrototype(this.functionPrototype, this.objectPrototype)); return this.originalStringField; } } internal override ErrorConstructor originalSyntaxError{ get{ if (this.originalSyntaxErrorField == null) this.originalSyntaxErrorField = new ErrorConstructor("SyntaxError", ErrorType.SyntaxError, this.originalError, this); return this.originalSyntaxErrorField; } } internal override ErrorConstructor originalTypeError{ get{ if (this.originalTypeErrorField == null) this.originalTypeErrorField = new ErrorConstructor("TypeError", ErrorType.TypeError, this.originalError, this); return this.originalTypeErrorField; } } internal override ErrorConstructor originalURIError{ get{ if (this.originalURIErrorField == null) this.originalURIErrorField = new ErrorConstructor("URIError", ErrorType.URIError, this.originalError, this); return this.originalURIErrorField; } } internal override VBArrayConstructor originalVBArray{ get{ if (this.originalVBArrayField == null) this.originalVBArrayField = new VBArrayConstructor(this.functionPrototype, new LenientVBArrayPrototype(this.functionPrototype, this.objectPrototype)); return this.originalVBArrayField; } } new public Object ActiveXObject{ get{ if (this.ActiveXObjectField is Missing) this.ActiveXObjectField = this.originalActiveXObject; return this.ActiveXObjectField; } set{ this.ActiveXObjectField = value; } } new public Object Array{ get{ if (this.ArrayField is Missing) this.ArrayField = this.originalArray; return this.ArrayField; } set{ this.ArrayField = value; } } new public Object Boolean{ get{ if (this.BooleanField is Missing) this.BooleanField = this.originalBoolean; return this.BooleanField; } set{ this.BooleanField = value; } } new public Object Date{ get{ if (this.DateField is Missing) this.DateField = this.originalDate; return this.DateField; } set{ this.DateField = value; } } new public Object Enumerator{ get{ if (this.EnumeratorField is Missing) this.EnumeratorField = this.originalEnumerator; return this.EnumeratorField; } set{ this.EnumeratorField = value; } } new public Object Error{ get{ if (this.ErrorField is Missing) this.ErrorField = this.originalError; return this.ErrorField; } set{ this.ErrorField = value; } } new public Object EvalError{ get{ if (this.EvalErrorField is Missing) this.EvalErrorField = this.originalEvalError; return this.EvalErrorField; } set{ this.EvalErrorField = value; } } new public Object Function{ get{ if (this.FunctionField is Missing) this.FunctionField = this.originalFunction; return this.FunctionField; } set{ this.FunctionField = value; } } new public Object Math{ get{ if (this.MathField is Missing) this.MathField = new LenientMathObject(this.objectPrototype, this.functionPrototype); return this.MathField; } set{ this.MathField = value; } } new public Object Number{ get{ if (this.NumberField is Missing) this.NumberField = this.originalNumber; return this.NumberField; } set{ this.NumberField = value; } } new public Object Object{ get{ if (this.ObjectField is Missing) this.ObjectField = this.originalObject; return this.ObjectField; } set{ this.ObjectField = value; } } new public Object RangeError{ get{ if (this.RangeErrorField is Missing) this.RangeErrorField = this.originalRangeError; return this.RangeErrorField; } set{ this.RangeErrorField = value; } } new public Object ReferenceError{ get{ if (this.ReferenceErrorField is Missing) this.ReferenceErrorField = this.originalReferenceError; return this.ReferenceErrorField; } set{ this.ReferenceErrorField = value; } } new public Object RegExp{ get{ if (this.RegExpField is Missing) this.RegExpField = this.originalRegExp; return this.RegExpField; } set{ this.RegExpField = value; } } new public Object String{ get{ if (this.StringField is Missing) this.StringField = this.originalString; return this.StringField; } set{ this.StringField = value; } } new public Object SyntaxError{ get{ if (this.SyntaxErrorField is Missing) this.SyntaxErrorField = this.originalSyntaxError; return this.SyntaxErrorField; } set{ this.SyntaxErrorField = value; } } new public Object TypeError{ get{ if (this.TypeErrorField is Missing) this.TypeErrorField = this.originalTypeError; return this.TypeErrorField; } set{ this.TypeErrorField = value; } } new public Object URIError{ get{ if (this.URIErrorField is Missing) this.URIErrorField = this.originalURIError; return this.URIErrorField; } set{ this.URIErrorField = value; } } new public Object VBArray{ get{ if (this.VBArrayField is Missing) this.VBArrayField = this.originalVBArray; return this.VBArrayField; } set{ this.VBArrayField = value; } } } }
namespace RRLab.PhysiologyData.GUI { partial class CellAndRecordingInfoPanel { /// <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 Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.label3 = new System.Windows.Forms.Label(); this.RPipetteTextBox = new System.Windows.Forms.TextBox(); this.CellsBindingSource = new System.Windows.Forms.BindingSource(this.components); this.RSealTextBox = new System.Windows.Forms.TextBox(); this.CellCapacTextBox = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.CreatedDateTimePicker = new System.Windows.Forms.DateTimePicker(); this.BreakInDateTimePicker = new System.Windows.Forms.DateTimePicker(); this.label8 = new System.Windows.Forms.Label(); this.RMembraneTextBox = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.VMembraneTextBox = new System.Windows.Forms.TextBox(); this.UserComboBox = new System.Windows.Forms.ComboBox(); this.UsersBindingSource = new System.Windows.Forms.BindingSource(this.components); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.RSeriesTextBox = new System.Windows.Forms.TextBox(); this.label11 = new System.Windows.Forms.Label(); this.RecordedDateTimePicker = new System.Windows.Forms.DateTimePicker(); this.RecordingsBindingSource = new System.Windows.Forms.BindingSource(this.components); this.label12 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.label15 = new System.Windows.Forms.Label(); this.label16 = new System.Windows.Forms.Label(); this.label17 = new System.Windows.Forms.Label(); this.VHoldTextBox = new System.Windows.Forms.TextBox(); this.BathComboBox = new System.Windows.Forms.ComboBox(); this.PipetteComboBox = new System.Windows.Forms.ComboBox(); this.label18 = new System.Windows.Forms.Label(); this.label19 = new System.Windows.Forms.Label(); this.RecordingDescriptionTextBox = new System.Windows.Forms.TextBox(); this.CellDescriptionTextBox = new System.Windows.Forms.TextBox(); this.GenotypesComboBox = new System.Windows.Forms.ComboBox(); this.GenotypesBindingSource = new System.Windows.Forms.BindingSource(this.components); this.RoughnessTrackBar = new System.Windows.Forms.TrackBar(); this.LengthTrackBar = new System.Windows.Forms.TrackBar(); this.ShapeTrackBar = new System.Windows.Forms.TrackBar(); this.RecordingTitleLabel = new System.Windows.Forms.Label(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.CellsBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.UsersBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.RecordingsBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.GenotypesBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.RoughnessTrackBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.LengthTrackBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ShapeTrackBar)).BeginInit(); this.SuspendLayout(); // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 6; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); this.tableLayoutPanel1.Controls.Add(this.label3, 0, 0); this.tableLayoutPanel1.Controls.Add(this.RPipetteTextBox, 1, 1); this.tableLayoutPanel1.Controls.Add(this.RSealTextBox, 1, 2); this.tableLayoutPanel1.Controls.Add(this.CellCapacTextBox, 1, 3); this.tableLayoutPanel1.Controls.Add(this.label4, 0, 1); this.tableLayoutPanel1.Controls.Add(this.label5, 0, 2); this.tableLayoutPanel1.Controls.Add(this.label6, 4, 0); this.tableLayoutPanel1.Controls.Add(this.label7, 4, 1); this.tableLayoutPanel1.Controls.Add(this.CreatedDateTimePicker, 5, 0); this.tableLayoutPanel1.Controls.Add(this.BreakInDateTimePicker, 5, 1); this.tableLayoutPanel1.Controls.Add(this.label8, 2, 1); this.tableLayoutPanel1.Controls.Add(this.RMembraneTextBox, 3, 1); this.tableLayoutPanel1.Controls.Add(this.label9, 0, 3); this.tableLayoutPanel1.Controls.Add(this.label10, 2, 3); this.tableLayoutPanel1.Controls.Add(this.VMembraneTextBox, 3, 3); this.tableLayoutPanel1.Controls.Add(this.UserComboBox, 3, 0); this.tableLayoutPanel1.Controls.Add(this.label1, 2, 0); this.tableLayoutPanel1.Controls.Add(this.label2, 2, 2); this.tableLayoutPanel1.Controls.Add(this.RSeriesTextBox, 3, 2); this.tableLayoutPanel1.Controls.Add(this.label11, 4, 2); this.tableLayoutPanel1.Controls.Add(this.RecordedDateTimePicker, 5, 2); this.tableLayoutPanel1.Controls.Add(this.label12, 4, 3); this.tableLayoutPanel1.Controls.Add(this.label13, 4, 4); this.tableLayoutPanel1.Controls.Add(this.label14, 4, 5); this.tableLayoutPanel1.Controls.Add(this.label15, 0, 4); this.tableLayoutPanel1.Controls.Add(this.label16, 2, 4); this.tableLayoutPanel1.Controls.Add(this.label17, 2, 5); this.tableLayoutPanel1.Controls.Add(this.VHoldTextBox, 1, 4); this.tableLayoutPanel1.Controls.Add(this.BathComboBox, 3, 4); this.tableLayoutPanel1.Controls.Add(this.PipetteComboBox, 3, 5); this.tableLayoutPanel1.Controls.Add(this.label18, 0, 6); this.tableLayoutPanel1.Controls.Add(this.label19, 3, 6); this.tableLayoutPanel1.Controls.Add(this.RecordingDescriptionTextBox, 0, 7); this.tableLayoutPanel1.Controls.Add(this.CellDescriptionTextBox, 3, 7); this.tableLayoutPanel1.Controls.Add(this.GenotypesComboBox, 1, 0); this.tableLayoutPanel1.Controls.Add(this.RoughnessTrackBar, 5, 3); this.tableLayoutPanel1.Controls.Add(this.LengthTrackBar, 5, 4); this.tableLayoutPanel1.Controls.Add(this.ShapeTrackBar, 5, 5); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 20); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 8; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(536, 244); this.tableLayoutPanel1.TabIndex = 0; // // label3 // this.label3.AutoSize = true; this.label3.Dock = System.Windows.Forms.DockStyle.Fill; this.label3.Location = new System.Drawing.Point(3, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(88, 27); this.label3.TabIndex = 2; this.label3.Text = "Genotype"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // RPipetteTextBox // this.RPipetteTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.CellsBindingSource, "PipetteResistance", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "N2")); this.RPipetteTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.RPipetteTextBox.Location = new System.Drawing.Point(97, 30); this.RPipetteTextBox.Name = "RPipetteTextBox"; this.RPipetteTextBox.Size = new System.Drawing.Size(82, 20); this.RPipetteTextBox.TabIndex = 4; // // CellsBindingSource // this.CellsBindingSource.DataMember = "Cells"; this.CellsBindingSource.DataSource = typeof(RRLab.PhysiologyWorkbench.Data.PhysiologyDataSet); // // RSealTextBox // this.RSealTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.CellsBindingSource, "SealResistance", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "N3")); this.RSealTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.RSealTextBox.Location = new System.Drawing.Point(97, 56); this.RSealTextBox.Name = "RSealTextBox"; this.RSealTextBox.Size = new System.Drawing.Size(82, 20); this.RSealTextBox.TabIndex = 5; // // CellCapacTextBox // this.CellCapacTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.CellsBindingSource, "CellCapacitance", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "N2")); this.CellCapacTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.CellCapacTextBox.Location = new System.Drawing.Point(97, 82); this.CellCapacTextBox.Name = "CellCapacTextBox"; this.CellCapacTextBox.Size = new System.Drawing.Size(82, 20); this.CellCapacTextBox.TabIndex = 6; // // label4 // this.label4.AutoSize = true; this.label4.Dock = System.Windows.Forms.DockStyle.Fill; this.label4.Location = new System.Drawing.Point(3, 27); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(88, 26); this.label4.TabIndex = 7; this.label4.Text = "RPipette (MOhm)"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label5 // this.label5.AutoSize = true; this.label5.Dock = System.Windows.Forms.DockStyle.Fill; this.label5.Location = new System.Drawing.Point(3, 53); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(88, 26); this.label5.TabIndex = 8; this.label5.Text = "RSeal (GOhm)"; this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label6 // this.label6.AutoSize = true; this.label6.Dock = System.Windows.Forms.DockStyle.Fill; this.label6.Location = new System.Drawing.Point(384, 0); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(61, 27); this.label6.TabIndex = 9; this.label6.Text = "Created"; this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label7 // this.label7.AutoSize = true; this.label7.Dock = System.Windows.Forms.DockStyle.Fill; this.label7.Location = new System.Drawing.Point(384, 27); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(61, 26); this.label7.TabIndex = 10; this.label7.Text = "Break In"; this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // CreatedDateTimePicker // this.CreatedDateTimePicker.CustomFormat = "MM/dd/yy hh:mm"; this.CreatedDateTimePicker.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.CellsBindingSource, "Created", true)); this.CreatedDateTimePicker.Dock = System.Windows.Forms.DockStyle.Fill; this.CreatedDateTimePicker.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.CreatedDateTimePicker.Location = new System.Drawing.Point(451, 3); this.CreatedDateTimePicker.Name = "CreatedDateTimePicker"; this.CreatedDateTimePicker.Size = new System.Drawing.Size(82, 20); this.CreatedDateTimePicker.TabIndex = 11; // // BreakInDateTimePicker // this.BreakInDateTimePicker.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.CellsBindingSource, "BreakInTime", true)); this.BreakInDateTimePicker.Dock = System.Windows.Forms.DockStyle.Fill; this.BreakInDateTimePicker.Format = System.Windows.Forms.DateTimePickerFormat.Time; this.BreakInDateTimePicker.Location = new System.Drawing.Point(451, 30); this.BreakInDateTimePicker.Name = "BreakInDateTimePicker"; this.BreakInDateTimePicker.Size = new System.Drawing.Size(82, 20); this.BreakInDateTimePicker.TabIndex = 12; // // label8 // this.label8.AutoSize = true; this.label8.Dock = System.Windows.Forms.DockStyle.Fill; this.label8.Location = new System.Drawing.Point(185, 27); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(105, 26); this.label8.TabIndex = 13; this.label8.Text = "RMembrane (MOhm)"; this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // RMembraneTextBox // this.RMembraneTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.CellsBindingSource, "MembraneResistance", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "N2")); this.RMembraneTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.RMembraneTextBox.Location = new System.Drawing.Point(296, 30); this.RMembraneTextBox.Name = "RMembraneTextBox"; this.RMembraneTextBox.Size = new System.Drawing.Size(82, 20); this.RMembraneTextBox.TabIndex = 14; // // label9 // this.label9.AutoSize = true; this.label9.Dock = System.Windows.Forms.DockStyle.Fill; this.label9.Location = new System.Drawing.Point(3, 79); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(88, 31); this.label9.TabIndex = 15; this.label9.Text = "Cell Capac (pF)"; this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label10 // this.label10.AutoSize = true; this.label10.Dock = System.Windows.Forms.DockStyle.Fill; this.label10.Location = new System.Drawing.Point(185, 79); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(105, 31); this.label10.TabIndex = 16; this.label10.Text = "VMembrane (mV)"; this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // VMembraneTextBox // this.VMembraneTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.CellsBindingSource, "MembranePotential", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "N2")); this.VMembraneTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.VMembraneTextBox.Location = new System.Drawing.Point(296, 82); this.VMembraneTextBox.Name = "VMembraneTextBox"; this.VMembraneTextBox.Size = new System.Drawing.Size(82, 20); this.VMembraneTextBox.TabIndex = 17; // // UserComboBox // this.UserComboBox.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.CellsBindingSource, "UserID", true)); this.UserComboBox.DataSource = this.UsersBindingSource; this.UserComboBox.DisplayMember = "Name"; this.UserComboBox.Dock = System.Windows.Forms.DockStyle.Fill; this.UserComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.UserComboBox.FormattingEnabled = true; this.UserComboBox.Location = new System.Drawing.Point(296, 3); this.UserComboBox.Name = "UserComboBox"; this.UserComboBox.Size = new System.Drawing.Size(82, 21); this.UserComboBox.TabIndex = 18; this.UserComboBox.ValueMember = "UserID"; // // UsersBindingSource // this.UsersBindingSource.DataMember = "Users"; this.UsersBindingSource.DataSource = typeof(RRLab.PhysiologyWorkbench.Data.PhysiologyDataSet); // // label1 // this.label1.AutoSize = true; this.label1.Dock = System.Windows.Forms.DockStyle.Fill; this.label1.Location = new System.Drawing.Point(185, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(105, 27); this.label1.TabIndex = 19; this.label1.Text = "Experimenter"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label2 // this.label2.AutoSize = true; this.label2.Dock = System.Windows.Forms.DockStyle.Fill; this.label2.Location = new System.Drawing.Point(185, 53); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(105, 26); this.label2.TabIndex = 20; this.label2.Text = "RSeries (MOhm)"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // RSeriesTextBox // this.RSeriesTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.CellsBindingSource, "SeriesResistance", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "N2")); this.RSeriesTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.RSeriesTextBox.Location = new System.Drawing.Point(296, 56); this.RSeriesTextBox.Name = "RSeriesTextBox"; this.RSeriesTextBox.Size = new System.Drawing.Size(82, 20); this.RSeriesTextBox.TabIndex = 21; // // label11 // this.label11.AutoSize = true; this.label11.Dock = System.Windows.Forms.DockStyle.Fill; this.label11.Location = new System.Drawing.Point(384, 53); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(61, 26); this.label11.TabIndex = 22; this.label11.Text = "Recorded"; this.label11.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // RecordedDateTimePicker // this.RecordedDateTimePicker.CustomFormat = ""; this.RecordedDateTimePicker.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.RecordingsBindingSource, "Recorded", true)); this.RecordedDateTimePicker.Dock = System.Windows.Forms.DockStyle.Fill; this.RecordedDateTimePicker.Format = System.Windows.Forms.DateTimePickerFormat.Time; this.RecordedDateTimePicker.Location = new System.Drawing.Point(451, 56); this.RecordedDateTimePicker.Name = "RecordedDateTimePicker"; this.RecordedDateTimePicker.Size = new System.Drawing.Size(82, 20); this.RecordedDateTimePicker.TabIndex = 23; // // RecordingsBindingSource // this.RecordingsBindingSource.DataMember = "FK_Cells_Recordings"; this.RecordingsBindingSource.DataSource = this.CellsBindingSource; // // label12 // this.label12.AutoSize = true; this.label12.Dock = System.Windows.Forms.DockStyle.Fill; this.label12.Location = new System.Drawing.Point(384, 79); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(61, 31); this.label12.TabIndex = 24; this.label12.Text = "Roughness"; this.label12.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label13 // this.label13.AutoSize = true; this.label13.Dock = System.Windows.Forms.DockStyle.Fill; this.label13.Location = new System.Drawing.Point(384, 110); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(61, 31); this.label13.TabIndex = 25; this.label13.Text = "Length"; this.label13.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label14 // this.label14.AutoSize = true; this.label14.Dock = System.Windows.Forms.DockStyle.Fill; this.label14.Location = new System.Drawing.Point(384, 141); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(61, 31); this.label14.TabIndex = 26; this.label14.Text = "Shape"; this.label14.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label15 // this.label15.AutoSize = true; this.label15.Dock = System.Windows.Forms.DockStyle.Fill; this.label15.Location = new System.Drawing.Point(3, 110); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(88, 31); this.label15.TabIndex = 30; this.label15.Text = "VHold (mV)"; this.label15.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label16 // this.label16.AutoSize = true; this.label16.Dock = System.Windows.Forms.DockStyle.Fill; this.label16.Location = new System.Drawing.Point(185, 110); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(105, 31); this.label16.TabIndex = 31; this.label16.Text = "Bath Soln"; this.label16.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label17 // this.label17.AutoSize = true; this.label17.Dock = System.Windows.Forms.DockStyle.Fill; this.label17.Location = new System.Drawing.Point(185, 141); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(105, 31); this.label17.TabIndex = 32; this.label17.Text = "Pipette Soln"; this.label17.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // VHoldTextBox // this.VHoldTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.RecordingsBindingSource, "HoldingPotential", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "N0")); this.VHoldTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.VHoldTextBox.Location = new System.Drawing.Point(97, 113); this.VHoldTextBox.Name = "VHoldTextBox"; this.VHoldTextBox.Size = new System.Drawing.Size(82, 20); this.VHoldTextBox.TabIndex = 33; // // BathComboBox // this.BathComboBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.RecordingsBindingSource, "BathSolution", true)); this.BathComboBox.Dock = System.Windows.Forms.DockStyle.Fill; this.BathComboBox.FormattingEnabled = true; this.BathComboBox.Items.AddRange(new object[] { "1 mM CaCl2, 120 mM NaCl, 5 mM KCl, 10 mM HEPES, 4 mM MgCl2, 24 mM proline, 5 mM a" + "lanine pH 7.15", "0 mM CaCl2, 120 mM NaCl, 5 mM KCl, 10 mM HEPES, 4 mM MgCl2, 24 mM proline, 5 mM a" + "lanine pH 7.15"}); this.BathComboBox.Location = new System.Drawing.Point(296, 113); this.BathComboBox.Name = "BathComboBox"; this.BathComboBox.Size = new System.Drawing.Size(82, 21); this.BathComboBox.TabIndex = 34; // // PipetteComboBox // this.PipetteComboBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.RecordingsBindingSource, "PipetteSolution", true)); this.PipetteComboBox.Dock = System.Windows.Forms.DockStyle.Fill; this.PipetteComboBox.FormattingEnabled = true; this.PipetteComboBox.Items.AddRange(new object[] { "95 mM K-Gluconate, 40 mM KCl, 10 mM HEPES, 2 mM MgCl2, 4 mM MgATP, 0.5 mM NaGTP, " + "1 mM NAD+ pH 7.15"}); this.PipetteComboBox.Location = new System.Drawing.Point(296, 144); this.PipetteComboBox.Name = "PipetteComboBox"; this.PipetteComboBox.Size = new System.Drawing.Size(82, 21); this.PipetteComboBox.TabIndex = 35; // // label18 // this.label18.AutoSize = true; this.tableLayoutPanel1.SetColumnSpan(this.label18, 3); this.label18.Dock = System.Windows.Forms.DockStyle.Fill; this.label18.Location = new System.Drawing.Point(3, 172); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(287, 13); this.label18.TabIndex = 36; this.label18.Text = "Recording Description"; this.label18.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label19 // this.label19.AutoSize = true; this.tableLayoutPanel1.SetColumnSpan(this.label19, 3); this.label19.Dock = System.Windows.Forms.DockStyle.Fill; this.label19.Location = new System.Drawing.Point(296, 172); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(237, 13); this.label19.TabIndex = 37; this.label19.Text = "Cell Description"; this.label19.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // RecordingDescriptionTextBox // this.tableLayoutPanel1.SetColumnSpan(this.RecordingDescriptionTextBox, 3); this.RecordingDescriptionTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.RecordingsBindingSource, "Description", true)); this.RecordingDescriptionTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.RecordingDescriptionTextBox.Location = new System.Drawing.Point(3, 188); this.RecordingDescriptionTextBox.Multiline = true; this.RecordingDescriptionTextBox.Name = "RecordingDescriptionTextBox"; this.RecordingDescriptionTextBox.Size = new System.Drawing.Size(287, 53); this.RecordingDescriptionTextBox.TabIndex = 38; // // CellDescriptionTextBox // this.tableLayoutPanel1.SetColumnSpan(this.CellDescriptionTextBox, 3); this.CellDescriptionTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.CellsBindingSource, "Description", true)); this.CellDescriptionTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.CellDescriptionTextBox.Location = new System.Drawing.Point(296, 188); this.CellDescriptionTextBox.Multiline = true; this.CellDescriptionTextBox.Name = "CellDescriptionTextBox"; this.CellDescriptionTextBox.Size = new System.Drawing.Size(237, 53); this.CellDescriptionTextBox.TabIndex = 39; // // GenotypesComboBox // this.GenotypesComboBox.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.CellsBindingSource, "FlyStockID", true)); this.GenotypesComboBox.DataSource = this.GenotypesBindingSource; this.GenotypesComboBox.DisplayMember = "Genotype"; this.GenotypesComboBox.Dock = System.Windows.Forms.DockStyle.Fill; this.GenotypesComboBox.FormattingEnabled = true; this.GenotypesComboBox.Location = new System.Drawing.Point(97, 3); this.GenotypesComboBox.Name = "GenotypesComboBox"; this.GenotypesComboBox.Size = new System.Drawing.Size(82, 21); this.GenotypesComboBox.TabIndex = 40; this.GenotypesComboBox.ValueMember = "FlyStockID"; // // GenotypesBindingSource // this.GenotypesBindingSource.DataMember = "Genotypes"; this.GenotypesBindingSource.DataSource = typeof(RRLab.PhysiologyWorkbench.Data.PhysiologyDataSet); // // RoughnessTrackBar // this.RoughnessTrackBar.AutoSize = false; this.RoughnessTrackBar.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.CellsBindingSource, "RoughAppearanceRating", true)); this.RoughnessTrackBar.Dock = System.Windows.Forms.DockStyle.Fill; this.RoughnessTrackBar.LargeChange = 1; this.RoughnessTrackBar.Location = new System.Drawing.Point(451, 82); this.RoughnessTrackBar.Maximum = 5; this.RoughnessTrackBar.Name = "RoughnessTrackBar"; this.RoughnessTrackBar.Size = new System.Drawing.Size(82, 25); this.RoughnessTrackBar.TabIndex = 41; this.RoughnessTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; // // LengthTrackBar // this.LengthTrackBar.AutoSize = false; this.LengthTrackBar.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.CellsBindingSource, "LengthAppearanceRating", true)); this.LengthTrackBar.Dock = System.Windows.Forms.DockStyle.Fill; this.LengthTrackBar.LargeChange = 1; this.LengthTrackBar.Location = new System.Drawing.Point(451, 113); this.LengthTrackBar.Maximum = 5; this.LengthTrackBar.Name = "LengthTrackBar"; this.LengthTrackBar.Size = new System.Drawing.Size(82, 25); this.LengthTrackBar.TabIndex = 42; this.LengthTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; // // ShapeTrackBar // this.ShapeTrackBar.AutoSize = false; this.ShapeTrackBar.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.CellsBindingSource, "ShapeAppearanceRating", true)); this.ShapeTrackBar.Dock = System.Windows.Forms.DockStyle.Fill; this.ShapeTrackBar.LargeChange = 1; this.ShapeTrackBar.Location = new System.Drawing.Point(451, 144); this.ShapeTrackBar.Maximum = 5; this.ShapeTrackBar.Name = "ShapeTrackBar"; this.ShapeTrackBar.Size = new System.Drawing.Size(82, 25); this.ShapeTrackBar.TabIndex = 43; this.ShapeTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; // // RecordingTitleLabel // this.RecordingTitleLabel.AutoSize = true; this.RecordingTitleLabel.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.RecordingsBindingSource, "Title", true)); this.RecordingTitleLabel.Dock = System.Windows.Forms.DockStyle.Top; this.RecordingTitleLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.RecordingTitleLabel.Location = new System.Drawing.Point(0, 0); this.RecordingTitleLabel.Name = "RecordingTitleLabel"; this.RecordingTitleLabel.Size = new System.Drawing.Size(130, 20); this.RecordingTitleLabel.TabIndex = 1; this.RecordingTitleLabel.Text = "Recording Title"; // // CellAndRecordingInfoPanel // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.tableLayoutPanel1); this.Controls.Add(this.RecordingTitleLabel); this.MinimumSize = new System.Drawing.Size(535, 235); this.Name = "CellAndRecordingInfoPanel"; this.Size = new System.Drawing.Size(536, 264); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.CellsBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.UsersBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.RecordingsBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.GenotypesBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.RoughnessTrackBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.LengthTrackBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ShapeTrackBar)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox RPipetteTextBox; private System.Windows.Forms.TextBox RSealTextBox; private System.Windows.Forms.TextBox CellCapacTextBox; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.DateTimePicker CreatedDateTimePicker; private System.Windows.Forms.DateTimePicker BreakInDateTimePicker; private System.Windows.Forms.Label label8; private System.Windows.Forms.TextBox RMembraneTextBox; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox VMembraneTextBox; private System.Windows.Forms.ComboBox UserComboBox; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox RSeriesTextBox; private System.Windows.Forms.Label label11; private System.Windows.Forms.DateTimePicker RecordedDateTimePicker; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label label15; private System.Windows.Forms.Label label16; private System.Windows.Forms.Label label17; private System.Windows.Forms.TextBox VHoldTextBox; private System.Windows.Forms.ComboBox BathComboBox; private System.Windows.Forms.ComboBox PipetteComboBox; private System.Windows.Forms.Label label18; private System.Windows.Forms.Label label19; private System.Windows.Forms.TextBox RecordingDescriptionTextBox; private System.Windows.Forms.TextBox CellDescriptionTextBox; private System.Windows.Forms.ComboBox GenotypesComboBox; private System.Windows.Forms.Label RecordingTitleLabel; private System.Windows.Forms.BindingSource RecordingsBindingSource; private System.Windows.Forms.BindingSource CellsBindingSource; private System.Windows.Forms.BindingSource UsersBindingSource; private System.Windows.Forms.BindingSource GenotypesBindingSource; private System.Windows.Forms.TrackBar RoughnessTrackBar; private System.Windows.Forms.TrackBar LengthTrackBar; private System.Windows.Forms.TrackBar ShapeTrackBar; } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Reflection; using System.Diagnostics.Contracts; namespace System { [Immutable] public class Type { #if SILVERLIGHT_3_0 || SILVERLIGHT_4_0 || SILVERLIGHT_4_0_WP internal #else protected #endif Type() { } extern public virtual string Namespace { get; } #if !SILVERLIGHT extern public virtual bool IsMarshalByRef { get; } #endif #if false extern public ConstructorInfo TypeInitializer { get; } #endif #if NETFRAMEWORK_4_0 || SILVERLIGHT_5_0 [Pure] #if NETFRAMEWORK_4_0 public #else internal #endif virtual bool IsEquivalentTo(Type other) { return default(bool); } #endif #if !SILVERLIGHT extern public virtual bool IsExplicitLayout { get; } #endif public virtual bool IsGenericType { get { Contract.Ensures(!Contract.Result<bool>() || this.GetGenericArguments().Length > 0); return default(bool); } } public virtual bool IsGenericTypeDefinition { get { Contract.Ensures(!Contract.Result<bool>() || this.GetGenericArguments().Length > 0); return default(bool); } } extern public virtual bool IsGenericParameter { get; } extern public virtual bool IsValueType { get; } extern public virtual bool IsAutoClass { get; } extern public virtual bool IsNestedPrivate { get; } #if !SILVERLIGHT extern public virtual bool IsSerializable { get; } #endif public virtual Assembly Assembly { get { Contract.Ensures(Contract.Result< Assembly>() != null); return default( Assembly); } } extern public virtual bool IsNestedAssembly { get; } extern public virtual bool IsNotPublic { get; } extern public virtual bool IsSealed { get; } #if false extern public Guid GUID { get; } #endif #if !SILVERLIGHT extern public virtual bool IsLayoutSequential { get; } #endif extern public virtual bool IsNestedFamily { get; } extern public virtual bool IsNestedFamORAssem { get; } public virtual string FullName { get { Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>())); return default(string); } } // // Summary: // Returns a System.Type object representing a one-dimensional array of the // current type, with a lower bound of zero. // // Returns: // A System.Type object representing a one-dimensional array of the current // type, with a lower bound of zero. [Pure] public virtual Type MakeArrayType() { Contract.Ensures(Contract.Result<Type>() != null); return default(Type); } // // Summary: // Returns a System.Type object representing an array of the current type, with // the specified number of dimensions. // // Parameters: // rank: // The number of dimensions for the array. // // Returns: // A System.Type object representing an array of the current type, with the // specified number of dimensions. // // Exceptions: // System.IndexOutOfRangeException: // rank is invalid. For example, 0 or negative. // // System.NotSupportedException: // The invoked method is not supported in the base class. [Pure] public virtual Type MakeArrayType(int rank) { Contract.Requires(0 < rank); Contract.Ensures(Contract.Result<Type>() != null); return default(Type); } // // Summary: // Returns a System.Type object that represents the current type when passed // as a ref parameter (ByRef parameter in Visual Basic). // // Returns: // A System.Type object that represents the current type when passed as a ref // parameter (ByRef parameter in Visual Basic). // // Exceptions: // System.NotSupportedException: // The invoked method is not supported in the base class. [Pure] public virtual Type MakeByRefType() { Contract.Ensures(Contract.Result<Type>() != null); return default(Type); } // // Summary: // Substitutes the elements of an array of types for the type parameters of // the current generic type definition and returns a System.Type object representing // the resulting constructed type. // // Parameters: // typeArguments: // An array of types to be substituted for the type parameters of the current // generic type. // // Returns: // A System.Type representing the constructed type formed by substituting the // elements of typeArguments for the type parameters of the current generic // type. // // Exceptions: // System.InvalidOperationException: // The current type does not represent a generic type definition. That is, System.Type.IsGenericTypeDefinition // returns false. // // System.ArgumentNullException: // typeArguments is null. -or- Any element of typeArguments is null. // // System.ArgumentException: // The number of elements in typeArguments is not the same as the number of // type parameters in the current generic type definition. -or- Any element // of typeArguments does not satisfy the constraints specified for the corresponding // type parameter of the current generic type. // // System.NotSupportedException: // The invoked method is not supported in the base class. Derived classes must // provide an implementation. [Pure] public virtual Type MakeGenericType(params Type[] typeArguments) { Contract.Requires(this.IsGenericTypeDefinition); Contract.Requires(typeArguments != null); Contract.Requires(typeArguments.Length == this.GetGenericArguments().Length); Contract.Ensures(Contract.Result<Type>() != null); return default(Type); } // // Summary: // Returns a System.Type object that represents a pointer to the current type. // // Returns: // A System.Type object that represents a pointer to the current type. // // Exceptions: // System.NotSupportedException: // The invoked method is not supported in the base class. [Pure] public virtual Type MakePointerType() { Contract.Ensures(Contract.Result<Type>() != null); return default(Type); } #if false extern public MemberTypes MemberType { get; } #endif extern public virtual string AssemblyQualifiedName { get; } extern public virtual Type BaseType { get; } extern public virtual RuntimeTypeHandle TypeHandle { get; } extern public virtual bool IsInterface { get; } extern public virtual bool IsAnsiClass { get; } extern public virtual bool IsAutoLayout { get; } extern public virtual bool IsPointer { get; } extern public virtual bool IsEnum { get; } // public override Type ReflectedType #if false extern public TypeAttributes Attributes { get; } #endif extern public virtual Type DeclaringType { get; } extern public virtual bool IsNestedFamANDAssem { get; } #if !SILVERLIGHT extern public virtual bool IsContextful { get; } #endif extern public virtual bool IsClass { get; } extern public virtual bool IsPublic { get; } extern public virtual bool IsAbstract { get; } // // Summary: // Indicates the type provided by the common language runtime that represents // this type. // // Returns: // The underlying system type for the System.Type. public virtual Type UnderlyingSystemType { get { Contract.Ensures(Contract.Result<Type>() != null); return default(Type); } } extern public virtual bool IsPrimitive { get; } public virtual Module Module { get { Contract.Ensures(Contract.Result< Module>() != null); return default( Module); } } extern public virtual bool IsImport { get; } extern public virtual bool IsArray { get; } extern public virtual bool IsNestedPublic { get; } extern public virtual bool IsByRef { get; } extern public virtual bool IsSpecialName { get; } extern public virtual bool IsUnicodeClass { get; } #if false extern public static Binder DefaultBinder { get; } #endif extern public virtual bool HasElementType { get; } extern public virtual bool IsCOMObject { get; } #if false public InterfaceMapping GetInterfaceMap(Type interfaceType) { return default( InterfaceMapping); } #endif [Pure] public virtual bool Equals(Type o) { return default(bool); } #if !SILVERLIGHT [Pure] public static Type[] GetTypeArray(Object[] args) { Contract.Requires(args != null); Contract.Ensures(Contract.Result<Type[]>() != null); return default(Type[]); } #endif [Pure] public virtual bool IsAssignableFrom(Type c) { return default(bool); } [Pure] public virtual bool IsInstanceOfType(object o) { return default(bool); } [Pure] public virtual bool IsSubclassOf(Type c) { return default(bool); } [Pure] public virtual Type GetElementType() { return default(Type); } //public MemberInfo[] FindMembers( MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria) //{ // return default( MemberInfo[]); //} // // Summary: // Searches for the members defined for the current System.Type whose DefaultMemberAttribute // is set. // // Returns: // An array of MemberInfo objects representing all default // members of the current System.Type.-or- An empty array of type MemberInfo, // if the current System.Type does not have default members. [Pure] public virtual MemberInfo[] GetDefaultMembers() { Contract.Ensures(Contract.Result< MemberInfo[]>() != null); return default( MemberInfo[]); } [Pure] public virtual MemberInfo[] GetMembers(BindingFlags arg0) { Contract.Ensures(Contract.Result<MemberInfo[]>() != null); return default( MemberInfo[]); } // // Summary: // Returns all the public members of the current System.Type. // // Returns: // An array of System.Reflection.MemberInfo objects representing all the public // members of the current System.Type.-or- An empty array of type System.Reflection.MemberInfo, // if the current System.Type does not have public members. [Pure] public virtual MemberInfo[] GetMembers() { Contract.Ensures(Contract.Result<MemberInfo[]>() != null); return default( MemberInfo[]); } [Pure] public virtual MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { Contract.Ensures(Contract.Result<MemberInfo[]>() != null); return default( MemberInfo[]); } [Pure] public virtual MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { Contract.Ensures(Contract.Result<MemberInfo[]>() != null); return default( MemberInfo[]); } [Pure] public virtual MemberInfo[] GetMember(string name) { Contract.Ensures(Contract.Result<MemberInfo[]>() != null); return default(MemberInfo[]); } [Pure] public virtual Type GetNestedType(string arg0, BindingFlags arg1) { return default(Type); } #if !SILVERLIGHT [Pure] public virtual Type GetNestedType(string name) { return default(Type); } #endif [Pure] public virtual Type[] GetNestedTypes( BindingFlags arg0) { Contract.Ensures(Contract.Result<Type[]>() != null); return default(Type[]); } #if !SILVERLIGHT // // Summary: // Returns the public types nested in the current System.Type. // // Returns: // An array of System.Type objects representing the public types nested in the // current System.Type (the search is not recursive), or an empty array of type // System.Type if no public types are nested in the current System.Type. [Pure] public virtual Type[] GetNestedTypes() { Contract.Ensures(Contract.Result<Type[]>() != null); return default(Type[]); } #endif // // Summary: // Returns all the public properties of the current System.Type. // // Returns: // An array of System.Reflection.PropertyInfo objects representing all public // properties of the current System.Type.-or- An empty array of type System.Reflection.PropertyInfo, // if the current System.Type does not have public properties. [Pure] public virtual PropertyInfo[] GetProperties() { Contract.Ensures(Contract.Result<PropertyInfo[]>() != null); Contract.Ensures(Contract.ForAll(Contract.Result<PropertyInfo[]>(), el => el != null)); return default( PropertyInfo[]); } // // Summary: // When overridden in a derived class, searches for the properties of the current // System.Type, using the specified binding constraints. // // Parameters: // bindingAttr: // A bitmask comprised of one or more System.Reflection.BindingFlags that specify // how the search is conducted.-or- Zero, to return null. // // Returns: // An array of System.Reflection.PropertyInfo objects representing all properties // of the current System.Type that match the specified binding constraints.-or- // An empty array of type System.Reflection.PropertyInfo, if the current System.Type // does not have properties, or if none of the properties match the binding // constraints. [Pure] public virtual PropertyInfo[] GetProperties(BindingFlags arg0) { Contract.Ensures(Contract.Result<PropertyInfo[]>() != null); return default(PropertyInfo[]); } [Pure] public virtual PropertyInfo GetProperty(string name) { Contract.Requires(name != null); return default( PropertyInfo); } [Pure] public virtual PropertyInfo GetProperty(string name, Type returnType) { Contract.Requires(name != null); Contract.Requires(returnType != null); return default( PropertyInfo); } #if !SILVERLIGHT [Pure] public virtual PropertyInfo GetProperty(string name, Type[] types) { Contract.Requires(name != null); Contract.Requires(types != null); return default( PropertyInfo); } #endif [Pure] public virtual PropertyInfo GetProperty(string name, Type returnType, Type[] types) { Contract.Requires(name != null); Contract.Requires(types != null); return default( PropertyInfo); } [Pure] public virtual PropertyInfo GetProperty(string name, BindingFlags bindingAttr) { Contract.Requires(name != null); return default( PropertyInfo); } //public PropertyInfo GetProperty(string name, Type returnType, Type[] types, ParameterModifier[] modifiers) //{ // Contract.Requires(name != null); // Contract.Requires(types != null); // return default( PropertyInfo); //} //public PropertyInfo GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) //{ // Contract.Requires(name != null); // Contract.Requires(types != null); // return default( PropertyInfo); //} [Pure] public virtual EventInfo[] GetEvents(BindingFlags arg0) { Contract.Ensures(Contract.Result<EventInfo[]>() != null); return default( EventInfo[]); } // // Summary: // Returns all the public events that are declared or inherited by the current // System.Type. // // Returns: // An array of EventInfo objects representing all the public // events which are declared or inherited by the current System.Type.-or- An // empty array of type EventInfo, if the current System.Type [Pure] public virtual EventInfo[] GetEvents() { Contract.Ensures(Contract.Result< EventInfo[]>() != null); Contract.Ensures(Contract.ForAll(Contract.Result<EventInfo[]>(), el => el != null)); return default( EventInfo[]); } [Pure] public virtual EventInfo GetEvent(string arg0, BindingFlags arg1) { return default( EventInfo); } [Pure] public virtual EventInfo GetEvent(string name) { return default( EventInfo); } #if !SILVERLIGHT [Pure] public virtual Type[] FindInterfaces( TypeFilter filter, object filterCriteria) { Contract.Requires(filter != null); Contract.Ensures(Contract.Result<Type[]>() != null); return default(Type[]); } #endif // // Summary: // When overridden in a derived class, gets all the interfaces implemented or // inherited by the current System.Type. // // Returns: // An array of System.Type objects representing all the interfaces implemented // or inherited by the current System.Type.-or- An empty array of type System.Type, // if no interfaces are implemented or inherited by the current System.Type. // // Exceptions: // System.Reflection.TargetInvocationException: // A static initializer is invoked and throws an exception. [Pure] public virtual Type[] GetInterfaces() { Contract.Ensures(Contract.Result<Type[]>() != null); Contract.Ensures(Contract.ForAll(Contract.Result<Type[]>(), el => el != null)); return default(Type[]); } [Pure] public virtual Type GetInterface(string arg0, bool arg1) { return default(Type); } #if !SILVERLIGHT [Pure] public virtual Type GetInterface(string name) { return default(Type); } #endif // // Summary: // Returns all the public fields of the current System.Type. // // Returns: // An array of System.Reflection.FieldInfo objects representing all the public // fields defined for the current System.Type.-or- An empty array of type System.Reflection.FieldInfo, // if no public fields are defined for the current System.Type. [Pure] public virtual FieldInfo[] GetFields( BindingFlags arg0) { Contract.Ensures(Contract.Result<FieldInfo[]>() != null); return default( FieldInfo[]); } // // Summary: // Returns all the public fields of the current System.Type. // // Returns: // An array of System.Reflection.FieldInfo objects representing all the public // fields defined for the current System.Type.-or- An empty array of type System.Reflection.FieldInfo, // if no public fields are defined for the current System.Type. [Pure] public virtual FieldInfo[] GetFields() { Contract.Ensures(Contract.Result<FieldInfo[]>() != null); Contract.Ensures(Contract.ForAll(Contract.Result<FieldInfo[]>(), el => el != null)); return default( FieldInfo[]); } [Pure] public virtual FieldInfo GetField(string name) { return default( FieldInfo); } [Pure] public virtual FieldInfo GetField(string arg0, BindingFlags arg1) { return default( FieldInfo); } // // Summary: // Returns an array of System.Type objects that represent the type arguments // of a generic type or the type parameters of a generic type definition. // // Returns: // An array of System.Type objects that represent the type arguments of a generic // type. Returns an empty array if the current type is not a generic type. [Pure] public virtual Type[] GetGenericArguments() { // Removed as of Brian request // Contract.Ensures(Contract.Result<Type[]>() != null); // weaker form that should be okay Contract.Ensures(!this.IsGenericTypeDefinition || Contract.Result<Type[]>() != null); return default(Type[]); } [Pure] public virtual Type GetGenericTypeDefinition() { Contract.Requires(this.IsGenericType); Contract.Ensures(Contract.Result<Type>().IsGenericTypeDefinition); Contract.Ensures(Contract.Result<Type>().GetGenericArguments().Length == this.GetGenericArguments().Length); return default(Type); } [Pure] public virtual Type[] GetGenericParameterConstraints() { Contract.Requires(this.IsGenericParameter); Contract.Ensures(Contract.Result<Type[]>() != null); return default(Type[]); } [Pure] public virtual MethodInfo[] GetMethods(BindingFlags arg0) { Contract.Ensures(Contract.Result<MethodInfo[]>() != null); Contract.Ensures(Contract.ForAll(Contract.Result<MethodInfo[]>(), el => el != null)); return default(MethodInfo[]); } // // Summary: // Returns all the public methods of the current System.Type. // // Returns: // An array of System.Reflection.MethodInfo objects representing all the public // methods defined for the current System.Type.-or- An empty array of type System.Reflection.MethodInfo, // if no public methods are defined for the current System.Type. [Pure] public virtual MethodInfo[] GetMethods() { Contract.Ensures(Contract.Result<MethodInfo[]>() != null); Contract.Ensures(Contract.ForAll(Contract.Result<MethodInfo[]>(), el => el != null)); return default(MethodInfo[]); } [Pure] public virtual MethodInfo GetMethod(string name) { Contract.Requires(name != null); return default(MethodInfo); } [Pure] public virtual MethodInfo GetMethod(string name, BindingFlags bindingAttr) { Contract.Requires(name != null); return default(MethodInfo); } [Pure] public virtual MethodInfo GetMethod(string name, Type[] types) { Contract.Requires(name != null); Contract.Requires(types != null); return default(MethodInfo); } //public MethodInfo GetMethod(string name, Type[] types, ParameterModifier[] modifiers) //{ // Contract.Requires(name != null); // Contract.Requires(types != null); // return default( MethodInfo); //} //public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) //{ // Contract.Requires(name != null); // Contract.Requires(types != null); // return default( MethodInfo); //} //public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) //{ // Contract.Requires(name != null); // Contract.Requires(types != null); // return default( MethodInfo); //} [Pure] public virtual ConstructorInfo[] GetConstructors(BindingFlags arg0) { Contract.Ensures(Contract.Result< ConstructorInfo[]>() != null); return default(ConstructorInfo[]); } [Pure] public virtual ConstructorInfo[] GetConstructors() { Contract.Ensures(Contract.Result< ConstructorInfo[]>() != null); Contract.Ensures(Contract.ForAll(Contract.Result<ConstructorInfo[]>(), el => el != null)); return default(ConstructorInfo[]); } [Pure] public virtual ConstructorInfo GetConstructor(Type[] types) { return default(ConstructorInfo); } #if false [Pure] public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) { Contract.Requires(types != null); return default( ConstructorInfo); } [Pure] public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { Contract.Requires(types != null); return default(ConstructorInfo); } #endif [Pure] public virtual int GetArrayRank() { return default(int); } [Pure] public static Type GetTypeFromHandle(RuntimeTypeHandle handle) { Contract.Ensures(Contract.Result<Type>() != null); return default(Type); } #if !SILVERLIGHT [Pure] public static RuntimeTypeHandle GetTypeHandle(object o) { Contract.Requires(o != null); return default(RuntimeTypeHandle); } #endif #if false public object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, Object[] args) { return default(object); } public object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, Object[] args, System.Globalization.CultureInfo culture) { return default(object); } public object InvokeMember(string arg0, BindingFlags arg1, Binder arg2, object arg3, Object[] arg4, ParameterModifier[] arg5, System.Globalization.CultureInfo arg6, String[] arg7) { return default(object); } #endif [Pure] public static TypeCode GetTypeCode(Type type) { return default(TypeCode); } #if false public static Type GetTypeFromCLSID(Guid clsid, string server, bool throwOnError) { return default(Type); } public static Type GetTypeFromCLSID(Guid clsid, string server) { return default(Type); } public static Type GetTypeFromCLSID(Guid clsid, bool throwOnError) { return default(Type); } public static Type GetTypeFromCLSID(Guid clsid) { return default(Type); } #endif #if !SILVERLIGHT [Pure] public static Type GetTypeFromProgID(string progID, string server, bool throwOnError) { Contract.Ensures(!throwOnError || Contract.Result<Type>() != null); return default(Type); } [Pure] public static Type GetTypeFromProgID(string progID, string server) { return default(Type); } [Pure] public static Type GetTypeFromProgID(string progID, bool throwOnError) { Contract.Ensures(!throwOnError || Contract.Result<Type>() != null); return default(Type); } [Pure] public static Type GetTypeFromProgID(string progID) { return default(Type); } #endif // // Summary: // Object.GetType is not virtual and some types new it. // [Pure] new public virtual Type GetType() { Contract.Ensures(Contract.Result<Type>() != null); return default(Type); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static Type GetType(string typeName) { return default(Type); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static Type GetType(string typeName, bool throwOnError) { Contract.Ensures(!throwOnError || Contract.Result<Type>() != null); return default(Type); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static Type GetType(string typeName, bool throwOnError, bool ignoreCase) { Contract.Ensures(!throwOnError || Contract.Result<Type>() != null); return default(Type); } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace Model { /// <summary> /// /// </summary> [DataContract] public class ImageProperties : IEquatable<ImageProperties> { /// <summary> /// Initializes a new instance of the <see cref="ImageProperties" /> class. /// </summary> public ImageProperties() { this.CpuHotPlug = false; this.CpuHotUnplug = false; this.RamHotPlug = false; this.RamHotUnplug = false; this.NicHotPlug = false; this.NicHotUnplug = false; this.DiscVirtioHotPlug = false; this.DiscVirtioHotUnplug = false; this.DiscScsiHotPlug = false; this.DiscScsiHotUnplug = false; this.Public = false; } /// <summary> /// A name of that resource /// </summary> /// <value>A name of that resource</value> [DataMember(Name = "name", EmitDefaultValue = false)] public string Name { get; set; } /// <summary> /// Human readable description /// </summary> /// <value>Human readable description</value> [DataMember(Name = "description", EmitDefaultValue = false)] public string Description { get; set; } /// <summary> /// Location of that image/snapshot. /// </summary> /// <value>Location of that image/snapshot.</value> [DataMember(Name = "location", EmitDefaultValue = false)] public string Location { get; set; } /// <summary> /// The size of the image in GB /// </summary> /// <value>The size of the image in GB</value> [DataMember(Name = "size", EmitDefaultValue = false)] public double? Size { get; set; } /// <summary> /// Is capable of CPU hot plug (no reboot required) /// </summary> /// <value>Is capable of CPU hot plug (no reboot required)</value> [DataMember(Name = "cpuHotPlug", EmitDefaultValue = false)] public bool? CpuHotPlug { get; set; } /// <summary> /// Is capable of CPU hot unplug (no reboot required) /// </summary> /// <value>Is capable of CPU hot unplug (no reboot required)</value> [DataMember(Name = "cpuHotUnplug", EmitDefaultValue = false)] public bool? CpuHotUnplug { get; set; } /// <summary> /// Is capable of memory hot plug (no reboot required) /// </summary> /// <value>Is capable of memory hot plug (no reboot required)</value> [DataMember(Name = "ramHotPlug", EmitDefaultValue = false)] public bool? RamHotPlug { get; set; } /// <summary> /// Is capable of memory hot unplug (no reboot required) /// </summary> /// <value>Is capable of memory hot unplug (no reboot required)</value> [DataMember(Name = "ramHotUnplug", EmitDefaultValue = false)] public bool? RamHotUnplug { get; set; } /// <summary> /// Is capable of nic hot plug (no reboot required) /// </summary> /// <value>Is capable of nic hot plug (no reboot required)</value> [DataMember(Name = "nicHotPlug", EmitDefaultValue = false)] public bool? NicHotPlug { get; set; } /// <summary> /// Is capable of nic hot unplug (no reboot required) /// </summary> /// <value>Is capable of nic hot unplug (no reboot required)</value> [DataMember(Name = "nicHotUnplug", EmitDefaultValue = false)] public bool? NicHotUnplug { get; set; } /// <summary> /// Is capable of Virt-IO drive hot plug (no reboot required) /// </summary> /// <value>Is capable of Virt-IO drive hot plug (no reboot required)</value> [DataMember(Name = "discVirtioHotPlug", EmitDefaultValue = false)] public bool? DiscVirtioHotPlug { get; set; } /// <summary> /// Is capable of Virt-IO drive hot unplug (no reboot required) /// </summary> /// <value>Is capable of Virt-IO drive hot unplug (no reboot required)</value> [DataMember(Name = "discVirtioHotUnplug", EmitDefaultValue = false)] public bool? DiscVirtioHotUnplug { get; set; } /// <summary> /// Is capable of SCSI drive hot plug (no reboot required) /// </summary> /// <value>Is capable of SCSI drive hot plug (no reboot required)</value> [DataMember(Name = "discScsiHotPlug", EmitDefaultValue = false)] public bool? DiscScsiHotPlug { get; set; } /// <summary> /// Is capable of SCSI drive hot unplug (no reboot required) /// </summary> /// <value>Is capable of SCSI drive hot unplug (no reboot required)</value> [DataMember(Name = "discScsiHotUnplug", EmitDefaultValue = false)] public bool? DiscScsiHotUnplug { get; set; } /// <summary> /// OS type of this Image /// </summary> /// <value>OS type of this Image</value> [DataMember(Name = "licenceType", EmitDefaultValue = false)] public string LicenceType { get; set; } /// <summary> /// This indicates the type of image /// </summary> /// <value>This indicates the type of image</value> [DataMember(Name = "imageType", EmitDefaultValue = false)] public string ImageType { get; set; } /// <summary> /// Indicates if the image is part of the public repository or not /// </summary> /// <value>Indicates if the image is part of the public repository or not</value> [DataMember(Name = "public", EmitDefaultValue = false)] public bool? Public { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ImageProperties {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" Location: ").Append(Location).Append("\n"); sb.Append(" Size: ").Append(Size).Append("\n"); sb.Append(" CpuHotPlug: ").Append(CpuHotPlug).Append("\n"); sb.Append(" CpuHotUnplug: ").Append(CpuHotUnplug).Append("\n"); sb.Append(" RamHotPlug: ").Append(RamHotPlug).Append("\n"); sb.Append(" RamHotUnplug: ").Append(RamHotUnplug).Append("\n"); sb.Append(" NicHotPlug: ").Append(NicHotPlug).Append("\n"); sb.Append(" NicHotUnplug: ").Append(NicHotUnplug).Append("\n"); sb.Append(" DiscVirtioHotPlug: ").Append(DiscVirtioHotPlug).Append("\n"); sb.Append(" DiscVirtioHotUnplug: ").Append(DiscVirtioHotUnplug).Append("\n"); sb.Append(" DiscScsiHotPlug: ").Append(DiscScsiHotPlug).Append("\n"); sb.Append(" DiscScsiHotUnplug: ").Append(DiscScsiHotUnplug).Append("\n"); sb.Append(" LicenceType: ").Append(LicenceType).Append("\n"); sb.Append(" ImageType: ").Append(ImageType).Append("\n"); sb.Append(" Public: ").Append(Public).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as ImageProperties); } /// <summary> /// Returns true if ImageProperties instances are equal /// </summary> /// <param name="other">Instance of ImageProperties to be compared</param> /// <returns>Boolean</returns> public bool Equals(ImageProperties other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Description == other.Description || this.Description != null && this.Description.Equals(other.Description) ) && ( this.Location == other.Location || this.Location != null && this.Location.Equals(other.Location) ) && ( this.Size == other.Size || this.Size != null && this.Size.Equals(other.Size) ) && ( this.CpuHotPlug == other.CpuHotPlug || this.CpuHotPlug != null && this.CpuHotPlug.Equals(other.CpuHotPlug) ) && ( this.CpuHotUnplug == other.CpuHotUnplug || this.CpuHotUnplug != null && this.CpuHotUnplug.Equals(other.CpuHotUnplug) ) && ( this.RamHotPlug == other.RamHotPlug || this.RamHotPlug != null && this.RamHotPlug.Equals(other.RamHotPlug) ) && ( this.RamHotUnplug == other.RamHotUnplug || this.RamHotUnplug != null && this.RamHotUnplug.Equals(other.RamHotUnplug) ) && ( this.NicHotPlug == other.NicHotPlug || this.NicHotPlug != null && this.NicHotPlug.Equals(other.NicHotPlug) ) && ( this.NicHotUnplug == other.NicHotUnplug || this.NicHotUnplug != null && this.NicHotUnplug.Equals(other.NicHotUnplug) ) && ( this.DiscVirtioHotPlug == other.DiscVirtioHotPlug || this.DiscVirtioHotPlug != null && this.DiscVirtioHotPlug.Equals(other.DiscVirtioHotPlug) ) && ( this.DiscVirtioHotUnplug == other.DiscVirtioHotUnplug || this.DiscVirtioHotUnplug != null && this.DiscVirtioHotUnplug.Equals(other.DiscVirtioHotUnplug) ) && ( this.DiscScsiHotPlug == other.DiscScsiHotPlug || this.DiscScsiHotPlug != null && this.DiscScsiHotPlug.Equals(other.DiscScsiHotPlug) ) && ( this.DiscScsiHotUnplug == other.DiscScsiHotUnplug || this.DiscScsiHotUnplug != null && this.DiscScsiHotUnplug.Equals(other.DiscScsiHotUnplug) ) && ( this.LicenceType == other.LicenceType || this.LicenceType != null && this.LicenceType.Equals(other.LicenceType) ) && ( this.ImageType == other.ImageType || this.ImageType != null && this.ImageType.Equals(other.ImageType) ) && ( this.Public == other.Public || this.Public != null && this.Public.Equals(other.Public) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.Description != null) hash = hash * 59 + this.Description.GetHashCode(); if (this.Location != null) hash = hash * 59 + this.Location.GetHashCode(); if (this.Size != null) hash = hash * 59 + this.Size.GetHashCode(); if (this.CpuHotPlug != null) hash = hash * 59 + this.CpuHotPlug.GetHashCode(); if (this.CpuHotUnplug != null) hash = hash * 59 + this.CpuHotUnplug.GetHashCode(); if (this.RamHotPlug != null) hash = hash * 59 + this.RamHotPlug.GetHashCode(); if (this.RamHotUnplug != null) hash = hash * 59 + this.RamHotUnplug.GetHashCode(); if (this.NicHotPlug != null) hash = hash * 59 + this.NicHotPlug.GetHashCode(); if (this.NicHotUnplug != null) hash = hash * 59 + this.NicHotUnplug.GetHashCode(); if (this.DiscVirtioHotPlug != null) hash = hash * 59 + this.DiscVirtioHotPlug.GetHashCode(); if (this.DiscVirtioHotUnplug != null) hash = hash * 59 + this.DiscVirtioHotUnplug.GetHashCode(); if (this.DiscScsiHotPlug != null) hash = hash * 59 + this.DiscScsiHotPlug.GetHashCode(); if (this.DiscScsiHotUnplug != null) hash = hash * 59 + this.DiscScsiHotUnplug.GetHashCode(); if (this.LicenceType != null) hash = hash * 59 + this.LicenceType.GetHashCode(); if (this.ImageType != null) hash = hash * 59 + this.ImageType.GetHashCode(); if (this.Public != null) hash = hash * 59 + this.Public.GetHashCode(); return hash; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Elasticsearch.Net.Connection.Configuration; using Elasticsearch.Net.Connection.Thrift.Protocol; using Elasticsearch.Net.Connection.Thrift.Transport; namespace Elasticsearch.Net.Connection.Thrift { public class ThriftConnection : IConnection, IDisposable { public TransportAddressScheme? AddressScheme { get { return Elasticsearch.Net.Connection.TransportAddressScheme.Thrift; } } private readonly ConcurrentDictionary<Uri, ConcurrentQueue<Rest.Client>> _clients = new ConcurrentDictionary<Uri, ConcurrentQueue<Rest.Client>>(); private readonly Semaphore _resourceLock; private readonly int _timeout; private readonly int _poolSize; private bool _disposed; private readonly IConnectionConfigurationValues _connectionSettings; private readonly TProtocolFactory _protocolFactory; private readonly int _maximumConnections; public ThriftConnection(IConnectionConfigurationValues connectionSettings, TProtocolFactory protocolFactory = null) { this._connectionSettings = connectionSettings; this._protocolFactory = protocolFactory; this._timeout = connectionSettings.Timeout; this._maximumConnections = this._connectionSettings.MaximumAsyncConnections; if (this._maximumConnections > 0) this._resourceLock = new Semaphore(this._maximumConnections, this._maximumConnections); } #region IConnection Members public Task<ElasticsearchResponse<Stream>> Get(Uri uri, IRequestConfiguration requestConfiguration = null) { var restRequest = new RestRequest(); restRequest.Method = Method.GET; restRequest.Uri = uri; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() => { return this.Execute(restRequest, requestConfiguration); }); } public Task<ElasticsearchResponse<Stream>> Head(Uri uri, IRequestConfiguration requestConfiguration = null) { var restRequest = new RestRequest(); restRequest.Method = Method.HEAD; restRequest.Uri = uri; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() => { return this.Execute(restRequest, requestConfiguration); }); } public ElasticsearchResponse<Stream> GetSync(Uri uri, IRequestConfiguration requestConfiguration = null) { var restRequest = new RestRequest(); restRequest.Method = Method.GET; restRequest.Uri = uri; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return this.Execute(restRequest, requestConfiguration); } public ElasticsearchResponse<Stream> HeadSync(Uri uri, IRequestConfiguration requestConfiguration = null) { var restRequest = new RestRequest(); restRequest.Method = Method.HEAD; restRequest.Uri = uri; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return this.Execute(restRequest, requestConfiguration); } public Task<ElasticsearchResponse<Stream>> Post(Uri uri, byte[] data, IRequestConfiguration requestConfiguration = null) { var restRequest = new RestRequest(); restRequest.Method = Method.POST; restRequest.Uri = uri; restRequest.Body = data; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() => { return this.Execute(restRequest, requestConfiguration); }); } public Task<ElasticsearchResponse<Stream>> Put(Uri uri, byte[] data, IRequestConfiguration requestConfiguration = null) { var restRequest = new RestRequest(); restRequest.Method = Method.PUT; restRequest.Uri = uri; restRequest.Body = data; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() => { return this.Execute(restRequest, requestConfiguration); }); } public Task<ElasticsearchResponse<Stream>> Delete(Uri uri, byte[] data, IRequestConfiguration requestConfiguration = null) { var restRequest = new RestRequest(); restRequest.Method = Method.DELETE; restRequest.Uri = uri; restRequest.Body = data; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() => { return this.Execute(restRequest, requestConfiguration); }); } public ElasticsearchResponse<Stream> PostSync(Uri uri, byte[] data, IRequestConfiguration requestConfiguration = null) { var restRequest = new RestRequest(); restRequest.Method = Method.POST; restRequest.Uri = uri; restRequest.Body = data; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return this.Execute(restRequest, requestConfiguration); } public ElasticsearchResponse<Stream> PutSync(Uri uri, byte[] data, IRequestConfiguration requestConfiguration = null) { var restRequest = new RestRequest(); restRequest.Method = Method.PUT; restRequest.Uri = uri; restRequest.Body = data; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return this.Execute(restRequest, requestConfiguration); } public Task<ElasticsearchResponse<Stream>> Delete(Uri uri, IRequestConfiguration requestConfiguration = null) { var restRequest = new RestRequest(); restRequest.Method = Method.DELETE; restRequest.Uri = uri; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() => { return this.Execute(restRequest, requestConfiguration); }); } public ElasticsearchResponse<Stream> DeleteSync(Uri uri, IRequestConfiguration requestConfiguration = null) { var restRequest = new RestRequest(); restRequest.Method = Method.DELETE; restRequest.Uri = uri; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return this.Execute(restRequest, requestConfiguration); } public ElasticsearchResponse<Stream> DeleteSync(Uri uri, byte[] data, IRequestConfiguration requestConfiguration = null) { var restRequest = new RestRequest(); restRequest.Method = Method.DELETE; restRequest.Uri = uri; restRequest.Body = data; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return this.Execute(restRequest, requestConfiguration); } #endregion #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); } #endregion /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_disposed) return; foreach (var c in this._clients.SelectMany(c => c.Value)) { if (c != null && c.InputProtocol != null && c.InputProtocol.Transport != null && c.InputProtocol.Transport.IsOpen) c.InputProtocol.Transport.Close(); } _disposed = true; } /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="HttpConnection"/> is reclaimed by garbage collection. /// </summary> ~ThriftConnection() { Dispose(false); } private Rest.Client CreateClient(Uri uri, ConcurrentQueue<Rest.Client> queue) { var host = uri.Host; var port = uri.Port; var tsocket = new TSocket(host, port, this._connectionSettings.Timeout); var transport = new TBufferedTransport(tsocket, 1024); var protocol = _protocolFactory == null ? new TBinaryProtocol(transport) : _protocolFactory.GetProtocol(transport); var client = new Rest.Client(protocol); tsocket.ConnectTimeout = this._connectionSettings.ConnectTimeout.GetValueOrDefault(200); tsocket.Timeout = this._connectionSettings.Timeout; tsocket.TcpClient.SendTimeout = this._connectionSettings.Timeout; tsocket.TcpClient.ReceiveTimeout = this._connectionSettings.Timeout; tsocket.TcpClient.NoDelay = true; queue.Enqueue(client); return client; } private Uri GetBaseBaseUri(Uri uri) { var path = uri.ToString(); var baseUri = new Uri(string.Format("{0}://{1}:{2}", uri.Scheme, uri.Host, uri.Port)); return baseUri; } private void EnqueueClient(Uri baseUri, Rest.Client connection) { ConcurrentQueue<Rest.Client> queue; if (!this._clients.TryGetValue(baseUri, out queue)) return; queue.Enqueue(connection); } private object _additionLock = new object(); private Rest.Client GetClientForUri(Uri baseUri, out string errorMessage) { errorMessage = null; ConcurrentQueue<Rest.Client> queue; Rest.Client client; if (!this._clients.TryGetValue(baseUri, out queue)) { //lock because multiple threads might evaluate to true lock (_additionLock) { if (!this._clients.TryGetValue(baseUri, out queue)) { //unknown endpoint lets set up some closed connections queue = new ConcurrentQueue<Rest.Client>(); var max = Math.Max(10, this._maximumConnections); for (var i = 0; i < max; i++) CreateClient(baseUri, queue); this._clients.TryAdd(baseUri, queue); } } } if (!queue.TryDequeue(out client)) errorMessage = string.Format("Could not dequeue connection for {0}", baseUri); return client; } private ElasticsearchResponse<Stream> Execute(RestRequest restRequest, object requestConfiguration) { var method = Enum.GetName(typeof(Method), restRequest.Method); var requestData = restRequest.Body; var uri = restRequest.Uri; var path = uri.ToString(); if (this._resourceLock != null && !this._resourceLock.WaitOne(this._timeout)) { var m = "Could not start the thrift operation before the timeout of " + this._timeout + "ms completed while waiting for the semaphore"; return ElasticsearchResponse<Stream>.CreateError(this._connectionSettings, new TimeoutException(m), method, path, requestData); } try { var baseUri = this.GetBaseBaseUri(uri); string errorMessage; var client = this.GetClientForUri(baseUri, out errorMessage); if (client == null) return ElasticsearchResponse<Stream>.CreateError( this._connectionSettings, new Exception(errorMessage), method, path, requestData); try { if (!client.InputProtocol.Transport.IsOpen) client.InputProtocol.Transport.Open(); var result = client.execute(restRequest); if (result.Status == Status.OK || result.Status == Status.CREATED || result.Status == Status.ACCEPTED) { var response = ElasticsearchResponse<Stream>.Create( this._connectionSettings, (int)result.Status, method, path, requestData, new MemoryStream(result.Body ?? new byte[0])); return response; } else { var response = ElasticsearchResponse<Stream>.Create( this._connectionSettings, (int)result.Status, method, path, requestData, new MemoryStream(result.Body ?? new byte[0])); return response; } } catch (SocketException) { client.InputProtocol.Transport.Close(); throw; } catch (IOException) { client.InputProtocol.Transport.Close(); throw; } catch (TTransportException) { client.InputProtocol.Transport.Close(); throw; } finally { this.EnqueueClient(baseUri, client); } } catch (Exception e) { return ElasticsearchResponse<Stream>.CreateError(this._connectionSettings, e, method, path, requestData); } finally { if (this._resourceLock != null) this._resourceLock.Release(); } } public string DecodeStr(byte[] bytes) { if (bytes != null && bytes.Length > 0) { return Encoding.UTF8.GetString(bytes); } return string.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; using Test.Cryptography; namespace System.Security.Cryptography.Pkcs.Tests { public static class Pkcs9AttributeTests { [Fact] public static void Pkcs9AttributeObjectNullaryCtor() { Pkcs9AttributeObject p = new Pkcs9AttributeObject(); Assert.Null(p.Oid); Assert.Null(p.RawData); } [Fact] public static void Pkcs9AttributeAsnEncodedDataCtorNullOid() { AsnEncodedData a = new AsnEncodedData(new byte[3]); object ign; Assert.Throws<ArgumentNullException>(() => ign = new Pkcs9AttributeObject(a)); } [Fact] public static void InputDateTimeAsWindowsFileTimeBefore1601() { DateTime dt = new DateTime(1600, 12, 31, 11, 59, 59, DateTimeKind.Utc); AssertExtensions.Throws<CryptographicException, ArgumentOutOfRangeException>(() => new Pkcs9SigningTime(dt)); } [Fact] public static void Pkcs9SigningTime_DateTimeMinValue() { AssertExtensions.Throws<CryptographicException, ArgumentOutOfRangeException>(() => new Pkcs9SigningTime(DateTime.MinValue)); } [Fact] public static void InputDateTimeAsX509TimeBefore1950_Utc() { DateTime dt = new DateTime(1949, 12, 31, 23, 59, 59, DateTimeKind.Utc); Assert.ThrowsAny<CryptographicException>(() => new Pkcs9SigningTime(dt)); } [Fact] public static void InputDateTimeAsX509TimeBefore1950_Unspecified() { DateTime dt = new DateTime(1949, 12, 30); Assert.ThrowsAny<CryptographicException>(() => new Pkcs9SigningTime(dt)); } [Fact] public static void InputDateTimeAsX509TimeBefore1950_Local() { DateTime dt = new DateTime(1949, 12, 30, 00, 00, 00, DateTimeKind.Local); Assert.ThrowsAny<CryptographicException>(() => new Pkcs9SigningTime(dt)); } [Fact] public static void InputDateTimeAsX509TimeAfter2049_Utc() { DateTime dt = new DateTime(2050, 01, 01, 00, 00, 00, DateTimeKind.Utc); Assert.ThrowsAny<CryptographicException>(() => new Pkcs9SigningTime(dt)); } [Fact] public static void InputDateTimeAsX509TimeAfter2049_Unspecified() { DateTime dt = new DateTime(2050, 01, 02); Assert.ThrowsAny<CryptographicException>(() => new Pkcs9SigningTime(dt)); } [Fact] public static void InputDateTimeAsX509TimeAfter2049_Local() { DateTime dt = new DateTime(2050, 01, 02, 00, 00, 00, DateTimeKind.Local); Assert.ThrowsAny<CryptographicException>(() => new Pkcs9SigningTime(dt)); } [Fact] public static void InputDateTimeAsX509TimeBetween1950And2049_Utc() { var exception = Record.Exception(() => { DateTime dt = new DateTime(1950, 1, 1, 00, 00, 00, DateTimeKind.Utc); Pkcs9SigningTime st = new Pkcs9SigningTime(dt); dt = new DateTime(2049, 12, 31, 23, 59, 59, DateTimeKind.Utc); st = new Pkcs9SigningTime(dt); dt = new DateTime(1950, 1, 2); st = new Pkcs9SigningTime(dt); dt = new DateTime(2049, 12, 30); st = new Pkcs9SigningTime(dt); dt = new DateTime(1950, 1, 2, 00, 00, 00, DateTimeKind.Local); st = new Pkcs9SigningTime(dt); dt = new DateTime(2049, 12, 30, 23, 59, 59, DateTimeKind.Local); st = new Pkcs9SigningTime(dt); }); Assert.Null(exception); } [Fact] public static void Pkcs9AttributeAsnEncodedDataCtorNullOidValue() { Oid oid = new Oid(Oids.Aes128); oid.Value = null; AsnEncodedData a = new AsnEncodedData(oid, new byte[3]); object ign; Assert.Throws<ArgumentNullException>(() => ign = new Pkcs9AttributeObject(a)); } [Fact] public static void Pkcs9AttributeAsnEncodedDataCtorEmptyOidValue() { Oid oid = new Oid(Oids.Aes128); oid.Value = string.Empty; AsnEncodedData a = new AsnEncodedData(oid, new byte[3]); object ign; AssertExtensions.Throws<ArgumentException>("oid.Value", () => ign = new Pkcs9AttributeObject(a)); } [Fact] public static void Pkcs9AttributeCopyFromNullAsn() { Pkcs9AttributeObject p = new Pkcs9AttributeObject(); Assert.Throws<ArgumentNullException>(() => p.CopyFrom(null)); } [Fact] public static void Pkcs9AttributeCopyFromAsnNotAPkcs9Attribute() { // Pkcs9AttributeObject.CopyFrom(AsnEncodedData) refuses to accept any AsnEncodedData that isn't a Pkcs9AttributeObject-derived class. Pkcs9AttributeObject p = new Pkcs9AttributeObject(); byte[] rawData = "041e4d00790020004400650073006300720069007000740069006f006e000000".HexToByteArray(); AsnEncodedData a = new AsnEncodedData(Oids.DocumentName, rawData); AssertExtensions.Throws<ArgumentException>(null, () => p.CopyFrom(a)); } [Fact] public static void DocumentDescriptionNullary() { Pkcs9DocumentDescription p = new Pkcs9DocumentDescription(); Assert.Null(p.RawData); Assert.Null(p.DocumentDescription); string oid = p.Oid.Value; Assert.Equal(s_OidDocumentDescription, oid); } [Fact] public static void DocumentDescriptionFromRawData() { byte[] rawData = "041e4d00790020004400650073006300720069007000740069006f006e000000".HexToByteArray(); Pkcs9DocumentDescription p = new Pkcs9DocumentDescription(rawData); Assert.Equal(rawData, p.RawData); string cookedData = p.DocumentDescription; Assert.Equal("My Description", cookedData); string oid = p.Oid.Value; Assert.Equal(s_OidDocumentDescription, oid); } [Fact] public static void DocumentDescriptionFromCookedData() { Pkcs9DocumentDescription p = new Pkcs9DocumentDescription("My Description"); string oid = p.Oid.Value; Assert.Equal(s_OidDocumentDescription, oid); Pkcs9DocumentDescription p2 = new Pkcs9DocumentDescription(p.RawData); string cookedData = p2.DocumentDescription; Assert.Equal("My Description", cookedData); } [Fact] public static void DocumentDescriptionNullValue() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new Pkcs9DocumentDescription((string)null)); } [Fact] public static void DocumentNameNullary() { Pkcs9DocumentName p = new Pkcs9DocumentName(); Assert.Null(p.RawData); Assert.Null(p.DocumentName); string oid = p.Oid.Value; Assert.Equal(s_OidDocumentName, oid); } [Fact] public static void DocumentNameFromRawData() { byte[] rawData = "04104d00790020004e0061006d0065000000".HexToByteArray(); Pkcs9DocumentName p = new Pkcs9DocumentName(rawData); Assert.Equal(rawData, p.RawData); string cookedData = p.DocumentName; Assert.Equal("My Name", cookedData); string oid = p.Oid.Value; Assert.Equal(s_OidDocumentName, oid); } [Fact] public static void DocumentNameFromCookedData() { Pkcs9DocumentName p = new Pkcs9DocumentName("My Name"); string oid = p.Oid.Value; Assert.Equal(s_OidDocumentName, oid); Pkcs9DocumentName p2 = new Pkcs9DocumentName(p.RawData); string cookedData = p2.DocumentName; Assert.Equal("My Name", cookedData); } [Fact] public static void DocumentNamenNullValue() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new Pkcs9DocumentName((string)null)); } [Fact] public static void SigningTimeNullary() { Pkcs9SigningTime p = new Pkcs9SigningTime(); // the default constructor initializes with DateTime.Now. Assert.NotNull(p.RawData); Assert.Equal(DateTimeKind.Local, p.SigningTime.Kind); string oid = p.Oid.Value; Assert.Equal(s_OidSigningTime, oid); } [Fact] public static void SigningTimeFromRawData() { DateTime dateTime = new DateTime(2015, 4, 1); byte[] rawData = "170d3135303430313030303030305a".HexToByteArray(); Pkcs9SigningTime p = new Pkcs9SigningTime(rawData); Assert.Equal(rawData, p.RawData); DateTime cookedData = p.SigningTime; Assert.Equal(DateTimeKind.Utc, cookedData.Kind); Assert.Equal(dateTime, cookedData); string oid = p.Oid.Value; Assert.Equal(s_OidSigningTime, oid); } [Fact] public static void SigningTimeFromCookedData_Unspecified() { DateTime dateTime = new DateTime(2015, 4, 1); Pkcs9SigningTime p = new Pkcs9SigningTime(dateTime); string oid = p.Oid.Value; Assert.Equal(s_OidSigningTime, oid); Pkcs9SigningTime p2 = new Pkcs9SigningTime(p.RawData); DateTime cookedData = p2.SigningTime; Assert.Equal(dateTime, cookedData); Assert.Equal(DateTimeKind.Utc, cookedData.Kind); } [Fact] public static void SigningTimeFromCookedData_Local() { DateTime dateTime = new DateTime(2015, 4, 1, 0, 0, 0, DateTimeKind.Local); Pkcs9SigningTime p = new Pkcs9SigningTime(dateTime); string oid = p.Oid.Value; Assert.Equal(s_OidSigningTime, oid); Pkcs9SigningTime p2 = new Pkcs9SigningTime(p.RawData); DateTime cookedData = p2.SigningTime; Assert.Equal(dateTime, cookedData.ToLocalTime()); Assert.Equal(DateTimeKind.Utc, cookedData.Kind); } [Fact] public static void SigningTimeFromCookedData_Utc() { DateTime dateTime = new DateTime(2015, 4, 1, 0, 0, 0, DateTimeKind.Utc); Pkcs9SigningTime p = new Pkcs9SigningTime(dateTime); string oid = p.Oid.Value; Assert.Equal(s_OidSigningTime, oid); Pkcs9SigningTime p2 = new Pkcs9SigningTime(p.RawData); DateTime cookedData = p2.SigningTime; Assert.Equal(dateTime, cookedData); Assert.Equal(DateTimeKind.Utc, cookedData.Kind); } [Fact] public static void ContentTypeNullary() { Pkcs9ContentType p = new Pkcs9ContentType(); Assert.Null(p.RawData); Assert.Null(p.ContentType); string oid = p.Oid.Value; Assert.Equal(s_OidContentType, oid); } [Fact] public static void ContentTypeFromRawData() { byte[] rawData = { ASN_TAG_OBJID, 0, 42, 0x9f, 0xa2, 0, 0x82, 0xf3, 0 }; rawData[1] = (byte)(rawData.Length - 2); Pkcs9ContentType p = CreatePkcs9ContentType(rawData); Assert.Equal(rawData, p.RawData); string cookedData = p.ContentType.Value; Assert.Equal("1.2.512256.47488", cookedData); string oid = p.Oid.Value; Assert.Equal(s_OidContentType, oid); } [Fact] public static void ContentTypeFromCookedData() { string contentType = "1.3.8473.23.4773.23"; byte[] encodedContentType = "06072bc21917a52517".HexToByteArray(); Pkcs9ContentType p = new Pkcs9ContentType(); Pkcs9AttributeObject pkcs9AttributeObject = new Pkcs9AttributeObject(p.Oid, encodedContentType); p.CopyFrom(pkcs9AttributeObject); string cookedData = p.ContentType.Value; Assert.Equal(contentType, cookedData); string oid = p.Oid.Value; Assert.Equal(s_OidContentType, oid); } [Fact] public static void ContentTypeFromRawDataMinimal() { byte[] rawData = { ASN_TAG_OBJID, 0 }; rawData[1] = (byte)(rawData.Length - 2); Pkcs9ContentType p = CreatePkcs9ContentType(rawData); Assert.Equal(rawData, p.RawData); string cookedData = p.ContentType.Value; Assert.Equal("", cookedData); string oid = p.Oid.Value; Assert.Equal(s_OidContentType, oid); } [Fact] public static void ContentTypeBadData() { Assert.ThrowsAny<CryptographicException>(() => CreatePkcs9ContentTypeAndExtractContentType(new byte[0])); // Too short Assert.ThrowsAny<CryptographicException>(() => CreatePkcs9ContentTypeAndExtractContentType(new byte[1])); // Too short Assert.ThrowsAny<CryptographicException>(() => CreatePkcs9ContentTypeAndExtractContentType(new byte[2])); // Does not start with ASN_TAG_OBJID. Assert.ThrowsAny<CryptographicException>(() => CreatePkcs9ContentTypeAndExtractContentType(new byte[] { ASN_TAG_OBJID, 1 })); // Bad length byte. } [Fact] public static void MessageDigestNullary() { Pkcs9MessageDigest p = new Pkcs9MessageDigest(); Assert.Null(p.RawData); Assert.Null(p.MessageDigest); string oid = p.Oid.Value; Assert.Equal(s_OidMessageDigest, oid); } [Fact] public static void MessageDigestFromRawData() { byte[] messageDigest = { 3, 45, 88, 128, 93 }; List<byte> encodedMessageDigestList = new List<byte>(messageDigest.Length + 2); encodedMessageDigestList.Add(4); encodedMessageDigestList.Add(checked((byte)(messageDigest.Length))); encodedMessageDigestList.AddRange(messageDigest); byte[] encodedMessageDigest = encodedMessageDigestList.ToArray(); Pkcs9MessageDigest p = new Pkcs9MessageDigest(); Pkcs9AttributeObject pAttribute = new Pkcs9AttributeObject(s_OidMessageDigest, encodedMessageDigest); p.CopyFrom(pAttribute); Assert.Equal<byte>(encodedMessageDigest, p.RawData); Assert.Equal<byte>(messageDigest, p.MessageDigest); string oid = p.Oid.Value; Assert.Equal(s_OidMessageDigest, oid); } private static void CreatePkcs9ContentTypeAndExtractContentType(byte[] rawData) { Oid contentType = CreatePkcs9ContentType(rawData).ContentType; } private static Pkcs9ContentType CreatePkcs9ContentType(byte[] rawData) { Pkcs9ContentType pkcs9ContentType = new Pkcs9ContentType(); Pkcs9AttributeObject pkcs9AttributeObject = new Pkcs9AttributeObject(pkcs9ContentType.Oid, rawData); pkcs9ContentType.CopyFrom(pkcs9AttributeObject); return pkcs9ContentType; } private const byte ASN_TAG_OBJID = 0x06; private const string s_OidDocumentDescription = "1.3.6.1.4.1.311.88.2.2"; private const string s_OidDocumentName = "1.3.6.1.4.1.311.88.2.1"; private const string s_OidSigningTime = "1.2.840.113549.1.9.5"; private const string s_OidContentType = "1.2.840.113549.1.9.3"; private const string s_OidMessageDigest = "1.2.840.113549.1.9.4"; } }
// // Copyright (c) 2016, Bianco Veigel // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Xfs { using System; using System.IO; using System.Collections.Generic; using DiscUtils.Streams; internal class Inode : IByteArraySerializable { public Inode(ulong number, Context context) { var sb = context.SuperBlock; RelativeInodeNumber = (uint) (number & sb.RelativeInodeMask); AllocationGroup = (uint) ((number & sb.AgInodeMask) >> (sb.AgBlocksLog2 + sb.InodesPerBlockLog2)); AgBlock = (uint) ((number >> context.SuperBlock.InodesPerBlockLog2) & XFS_INO_MASK(context.SuperBlock.AgBlocksLog2)); BlockOffset = (uint) (number & XFS_INO_MASK(sb.InodesPerBlockLog2)); } private static uint XFS_INO_MASK(int k) { return (1u << k) - 1; } public Inode(uint allocationGroup, uint relInode) { AllocationGroup = allocationGroup; RelativeInodeNumber = relInode; } public uint AllocationGroup { get; private set; } public uint RelativeInodeNumber { get; private set; } public uint AgBlock { get; private set; } public uint BlockOffset { get; private set; } public const ushort InodeMagic = 0x494e; /// <summary> /// The inode signature where these two bytes are 0x494e, or "IN" in ASCII. /// </summary> public ushort Magic { get; private set; } /// <summary> /// Specifies the mode access bits and type of file using the standard S_Ixxx values defined in stat.h. /// </summary> public ushort Mode { get; private set; } /// <summary> /// Specifies the inode version which currently can only be 1 or 2. The inode version specifies the /// usage of the di_onlink, di_nlink and di_projid values in the inode core.Initially, inodes /// are created as v1 but can be converted on the fly to v2 when required. /// </summary> public byte Version { get; private set; } /// <summary> /// Specifies the format of the data fork in conjunction with the di_mode type. This can be one of /// several values. For directories and links, it can be "local" where all metadata associated with the /// file is within the inode, "extents" where the inode contains an array of extents to other filesystem /// blocks which contain the associated metadata or data or "btree" where the inode contains a /// B+tree root node which points to filesystem blocks containing the metadata or data. Migration /// between the formats depends on the amount of metadata associated with the inode. "dev" is /// used for character and block devices while "uuid" is currently not used. /// </summary> public InodeFormat Format { get; private set; } /// <summary> /// In v1 inodes, this specifies the number of links to the inode from directories. When the number /// exceeds 65535, the inode is converted to v2 and the link count is stored in di_nlink. /// </summary> public ushort Onlink { get; private set; } /// <summary> /// Specifies the owner's UID of the inode. /// </summary> public uint UserId { get; private set; } /// <summary> /// Specifies the owner's GID of the inode. /// </summary> public uint GroupId { get; private set; } /// <summary> /// Specifies the number of links to the inode from directories. This is maintained for both inode /// versions for current versions of XFS.Old versions of XFS did not support v2 inodes, and /// therefore this value was never updated and was classed as reserved space (part of <see cref="Padding"/>). /// </summary> public uint Nlink { get; private set; } /// <summary> /// Specifies the owner's project ID in v2 inodes. An inode is converted to v2 if the project ID is set. /// This value must be zero for v1 inodes. /// </summary> public ushort ProjectId { get; private set; } /// <summary> /// Reserved, must be zero. /// </summary> public byte[] Padding { get; private set; } /// <summary> /// Incremented on flush. /// </summary> public ushort FlushIterator { get; private set; } /// <summary> /// Specifies the last access time of the files using UNIX time conventions the following structure. /// This value maybe undefined if the filesystem is mounted with the "noatime" option. /// </summary> public DateTime AccessTime { get; private set; } /// <summary> /// Specifies the last time the file was modified. /// </summary> public DateTime ModificationTime { get; private set; } /// <summary> /// Specifies when the inode's status was last changed. /// </summary> public DateTime CreationTime { get; private set; } /// <summary> /// Specifies the EOF of the inode in bytes. This can be larger or smaller than the extent space /// (therefore actual disk space) used for the inode.For regular files, this is the filesize in bytes, /// directories, the space taken by directory entries and for links, the length of the symlink. /// </summary> public ulong Length { get; private set; } /// <summary> /// Specifies the number of filesystem blocks used to store the inode's data including relevant /// metadata like B+trees.This does not include blocks used for extended attributes. /// </summary> public ulong BlockCount { get; private set; } /// <summary> /// Specifies the extent size for filesystems with real-time devices and an extent size hint for /// standard filesystems. For normal filesystems, and with directories, the /// XFS_DIFLAG_EXTSZINHERIT flag must be set in di_flags if this field is used.Inodes /// created in these directories will inherit the di_extsize value and have /// XFS_DIFLAG_EXTSIZE set in their di_flags. When a file is written to beyond allocated /// space, XFS will attempt to allocate additional disk space based on this value. /// </summary> public uint ExtentSize { get; private set; } /// <summary> /// Specifies the number of data extents associated with this inode. /// </summary> public uint Extents { get; private set; } /// <summary> /// Specifies the number of extended attribute extents associated with this inode. /// </summary> public ushort AttributeExtents { get; private set; } /// <summary> /// Specifies the offset into the inode's literal area where the extended attribute fork starts. This is /// an 8-bit value that is multiplied by 8 to determine the actual offset in bytes(ie.attribute data is /// 64-bit aligned). This also limits the maximum size of the inode to 2048 bytes.This value is /// initially zero until an extended attribute is created.When in attribute is added, the nature of /// di_forkoff depends on the XFS_SB_VERSION2_ATTR2BIT flag in the superblock. /// </summary> public byte Forkoff { get; private set; } /// <summary> /// Specifies the format of the attribute fork. This uses the same values as di_format, but /// restricted to "local", "extents" and "btree" formats for extended attribute data. /// </summary> public sbyte AttributeFormat { get; private set; } /// <summary> /// DMAPI event mask. /// </summary> public uint DmApiEventMask { get; private set; } /// <summary> /// DMAPI state. /// </summary> public ushort DmState { get; private set; } /// <summary> /// Specifies flags associated with the inode. /// </summary> public InodeFlags Flags { get; private set; } /// <summary> /// A generation number used for inode identification. This is used by tools that do inode scanning /// such as backup tools and xfsdump. An inode's generation number can change by unlinking and /// creating a new file that reuses the inode. /// </summary> public uint Generation { get; private set; } public UnixFileType FileType { get { return (UnixFileType) ((Mode >> 12) & 0xF); } } public byte[] DataFork { get; private set; } public int Size { get { return 96; } } public int ReadFrom(byte[] buffer, int offset) { Magic = EndianUtilities.ToUInt16BigEndian(buffer, offset); Mode = EndianUtilities.ToUInt16BigEndian(buffer, offset + 0x2); Version = buffer[offset + 0x4]; Format = (InodeFormat)buffer[offset + 0x5]; Onlink = EndianUtilities.ToUInt16BigEndian(buffer, offset + 0x6); UserId = EndianUtilities.ToUInt32BigEndian(buffer, offset + 0x8); GroupId = EndianUtilities.ToUInt32BigEndian(buffer, offset + 0xC); Nlink = EndianUtilities.ToUInt32BigEndian(buffer, offset + 0x10); ProjectId = EndianUtilities.ToUInt16BigEndian(buffer, offset + 0x14); Padding = EndianUtilities.ToByteArray(buffer, offset + 0x16, 8); FlushIterator = EndianUtilities.ToUInt16BigEndian(buffer, 0x1E); AccessTime = ReadTimestamp(buffer, offset + 0x20); ModificationTime = ReadTimestamp(buffer, offset + 0x28); CreationTime = ReadTimestamp(buffer, offset + 0x30); Length = EndianUtilities.ToUInt64BigEndian(buffer, offset + 0x38); BlockCount = EndianUtilities.ToUInt64BigEndian(buffer, offset + 0x40); ExtentSize = EndianUtilities.ToUInt32BigEndian(buffer, offset + 0x48); Extents = EndianUtilities.ToUInt32BigEndian(buffer, offset + 0x4C); AttributeExtents = EndianUtilities.ToUInt16BigEndian(buffer, offset + 0x50); Forkoff = buffer[offset + 0x52]; AttributeFormat = (sbyte) buffer[offset + 0x53]; DmApiEventMask = EndianUtilities.ToUInt32BigEndian(buffer, offset + 0x54); DmState = EndianUtilities.ToUInt16BigEndian(buffer, offset + 0x58); Flags = (InodeFlags) EndianUtilities.ToUInt16BigEndian(buffer, offset + 0x5A); Generation = EndianUtilities.ToUInt32BigEndian(buffer, offset + 0x5C); var dfLength = (Forkoff*8) - 0x64; if (dfLength < 0) { dfLength = buffer.Length - offset - 0x64; } DataFork = EndianUtilities.ToByteArray(buffer, offset + 0x64, dfLength); return Size; } private DateTime ReadTimestamp(byte[] buffer, int offset) { var seconds = EndianUtilities.ToUInt32BigEndian(buffer, offset); var nanoSeconds = EndianUtilities.ToUInt32BigEndian(buffer, offset + 0x4); return ((long)seconds).FromUnixTimeSeconds().AddTicks(nanoSeconds/100).LocalDateTime; } public void WriteTo(byte[] buffer, int offset) { throw new NotImplementedException(); } public Extent[] GetExtents() { var result = new Extent[Extents]; int offset = Forkoff; for (int i = 0; i < Extents; i++) { var extent = new Extent(); offset += extent.ReadFrom(DataFork, offset); result[i] = extent; } return result; } public IBuffer GetContentBuffer(Context context) { if (Format == InodeFormat.Local) { return new StreamBuffer(new MemoryStream(DataFork), Ownership.Dispose); } else if (Format == InodeFormat.Extents) { var extents = GetExtents(); return BufferFromExtentList(context, extents); } else if (Format == InodeFormat.Btree) { var tree = new BTreeExtentRoot(); tree.ReadFrom(DataFork, 0); tree.LoadBtree(context); var extents = tree.GetExtents(); return BufferFromExtentList(context, extents); } throw new NotImplementedException(); } public IBuffer BufferFromExtentList(Context context, IList<Extent> extents) { var builderExtents = new List<BuilderExtent>(extents.Count); foreach (var extent in extents) { var blockOffset = extent.GetOffset(context); var substream = new SubStream(context.RawStream, blockOffset, (long)extent.BlockCount*context.SuperBlock.Blocksize); builderExtents.Add(new BuilderSparseStreamExtent((long) extent.StartOffset * context.SuperBlock.Blocksize, substream)); } return new StreamBuffer(new ExtentStream((long) this.Length, builderExtents), Ownership.Dispose); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System { /// <summary> /// Extension methods for Span&lt;T&gt;. /// </summary> public static partial class SpanExtensions { /// <summary> /// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable&lt;T&gt;.Equals(T). /// </summary> /// <param name="span">The span to search.</param> /// <param name="value">The value to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this Span<T> span, T value) where T:struct, IEquatable<T> { return SpanHelpers.IndexOf<T>(ref span.DangerousGetPinnableReference(), value, span.Length); } /// <summary> /// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1. /// </summary> /// <param name="span">The span to search.</param> /// <param name="value">The value to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this Span<byte> span, byte value) { return SpanHelpers.IndexOf(ref span.DangerousGetPinnableReference(), value, span.Length); } /// <summary> /// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable&lt;T&gt;.Equals(T). /// </summary> /// <param name="span">The span to search.</param> /// <param name="value">The sequence to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : struct, IEquatable<T> { return SpanHelpers.IndexOf<T>(ref span.DangerousGetPinnableReference(), span.Length, ref value.DangerousGetPinnableReference(), value.Length); } /// <summary> /// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1. /// </summary> /// <param name="span">The span to search.</param> /// <param name="value">The sequence to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this Span<byte> span, ReadOnlySpan<byte> value) { return SpanHelpers.IndexOf(ref span.DangerousGetPinnableReference(), span.Length, ref value.DangerousGetPinnableReference(), value.Length); } /// <summary> /// Determines whether two sequences are equal by comparing the elements using IEquatable&lt;T&gt;.Equals(T). /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual<T>(this Span<T> first, ReadOnlySpan<T> second) where T:struct, IEquatable<T> { int length = first.Length; return length == second.Length && SpanHelpers.SequenceEqual(ref first.DangerousGetPinnableReference(), ref second.DangerousGetPinnableReference(), length); } /// <summary> /// Determines whether two sequences are equal by comparing the elements. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual(this Span<byte> first, ReadOnlySpan<byte> second) { int length = first.Length; return length == second.Length && SpanHelpers.SequenceEqual(ref first.DangerousGetPinnableReference(), ref second.DangerousGetPinnableReference(), length); } /// <summary> /// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable&lt;T&gt;.Equals(T). /// </summary> /// <param name="span">The span to search.</param> /// <param name="value">The value to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this ReadOnlySpan<T> span, T value) where T : struct, IEquatable<T> { return SpanHelpers.IndexOf<T>(ref span.DangerousGetPinnableReference(), value, span.Length); } /// <summary> /// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1. /// </summary> /// <param name="span">The span to search.</param> /// <param name="value">The value to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this ReadOnlySpan<byte> span, byte value) { return SpanHelpers.IndexOf(ref span.DangerousGetPinnableReference(), value, span.Length); } /// <summary> /// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable&lt;T&gt;.Equals(T). /// </summary> /// <param name="span">The span to search.</param> /// <param name="value">The sequence to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : struct, IEquatable<T> { return SpanHelpers.IndexOf<T>(ref span.DangerousGetPinnableReference(), span.Length, ref value.DangerousGetPinnableReference(), value.Length); } /// <summary> /// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1. /// </summary> /// <param name="span">The span to search.</param> /// <param name="value">The sequence to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this ReadOnlySpan<byte> span, ReadOnlySpan<byte> value) { return SpanHelpers.IndexOf(ref span.DangerousGetPinnableReference(), span.Length, ref value.DangerousGetPinnableReference(), value.Length); } /// <summary> /// Searches for the first index of any of the specified values similar to calling IndexOf several times with the logical OR operator. If not found, returns -1. /// </summary> /// <param name="span">The span to search.</param> /// <param name="value0">One of the values to search for.</param> /// <param name="value1">One of the values to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this Span<byte> span, byte value0, byte value1) { return SpanHelpers.IndexOfAny(ref span.DangerousGetPinnableReference(), value0, value1, span.Length); } /// <summary> /// Searches for the first index of any of the specified values similar to calling IndexOf several times with the logical OR operator. If not found, returns -1. /// </summary> /// <param name="span">The span to search.</param> /// <param name="value0">One of the values to search for.</param> /// <param name="value1">One of the values to search for.</param> /// <param name="value2">One of the values to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this Span<byte> span, byte value0, byte value1, byte value2) { return SpanHelpers.IndexOfAny(ref span.DangerousGetPinnableReference(), value0, value1, value2, span.Length); } /// <summary> /// Searches for the first index of any of the specified values similar to calling IndexOf several times with the logical OR operator. If not found, returns -1. /// </summary> /// <param name="span">The span to search.</param> /// <param name="values">The set of values to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this Span<byte> span, ReadOnlySpan<byte> values) { return SpanHelpers.IndexOfAny(ref span.DangerousGetPinnableReference(), span.Length, ref values.DangerousGetPinnableReference(), values.Length); } /// <summary> /// Searches for the first index of any of the specified values similar to calling IndexOf several times with the logical OR operator. If not found, returns -1. /// </summary> /// <param name="span">The span to search.</param> /// <param name="value0">One of the values to search for.</param> /// <param name="value1">One of the values to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this ReadOnlySpan<byte> span, byte value0, byte value1) { return SpanHelpers.IndexOfAny(ref span.DangerousGetPinnableReference(), value0, value1, span.Length); } /// <summary> /// Searches for the first index of any of the specified values similar to calling IndexOf several times with the logical OR operator. If not found, returns -1. /// </summary> /// <param name="span">The span to search.</param> /// <param name="value0">One of the values to search for.</param> /// <param name="value1">One of the values to search for.</param> /// <param name="value2">One of the values to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this ReadOnlySpan<byte> span, byte value0, byte value1, byte value2) { return SpanHelpers.IndexOfAny(ref span.DangerousGetPinnableReference(), value0, value1, value2, span.Length); } /// <summary> /// Searches for the first index of any of the specified values similar to calling IndexOf several times with the logical OR operator. If not found, returns -1. /// </summary> /// <param name="span">The span to search.</param> /// <param name="values">The set of values to search for.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this ReadOnlySpan<byte> span, ReadOnlySpan<byte> values) { return SpanHelpers.IndexOfAny(ref span.DangerousGetPinnableReference(), span.Length, ref values.DangerousGetPinnableReference(), values.Length); } /// <summary> /// Determines whether two sequences are equal by comparing the elements using IEquatable&lt;T&gt;.Equals(T). /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual<T>(this ReadOnlySpan<T> first, ReadOnlySpan<T> second) where T : struct, IEquatable<T> { int length = first.Length; return length == second.Length && SpanHelpers.SequenceEqual(ref first.DangerousGetPinnableReference(), ref second.DangerousGetPinnableReference(), length); } /// <summary> /// Determines whether two sequences are equal by comparing the elements. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual(this ReadOnlySpan<byte> first, ReadOnlySpan<byte> second) { int length = first.Length; return length == second.Length && SpanHelpers.SequenceEqual(ref first.DangerousGetPinnableReference(), ref second.DangerousGetPinnableReference(), length); } /// <summary> /// Determines whether the specified sequence appears at the start of the span. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith(this Span<byte> span, ReadOnlySpan<byte> value) { int valueLength = value.Length; return valueLength <= span.Length && SpanHelpers.SequenceEqual(ref span.DangerousGetPinnableReference(), ref value.DangerousGetPinnableReference(), valueLength); } /// <summary> /// Determines whether the specified sequence appears at the start of the span. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : struct, IEquatable<T> { int valueLength = value.Length; return valueLength <= span.Length && SpanHelpers.SequenceEqual(ref span.DangerousGetPinnableReference(), ref value.DangerousGetPinnableReference(), valueLength); } /// <summary> /// Determines whether the specified sequence appears at the start of the span. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith(this ReadOnlySpan<byte> span, ReadOnlySpan<byte> value) { int valueLength = value.Length; return valueLength <= span.Length && SpanHelpers.SequenceEqual(ref span.DangerousGetPinnableReference(), ref value.DangerousGetPinnableReference(), valueLength); } /// <summary> /// Determines whether the specified sequence appears at the start of the span. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : struct, IEquatable<T> { int valueLength = value.Length; return valueLength <= span.Length && SpanHelpers.SequenceEqual(ref span.DangerousGetPinnableReference(), ref value.DangerousGetPinnableReference(), valueLength); } /// <summary> /// Creates a new span over the portion of the target array. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this T[] array) { return new Span<T>(array); } /// <summary> /// Creates a new span over the portion of the target array segment. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> arraySegment) { return new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count); } /// <summary> /// Creates a new readonly span over the entire target array. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<T> AsReadOnlySpan<T>(this T[] array) { return new ReadOnlySpan<T>(array); } /// <summary> /// Creates a new readonly span over the target array segment. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<T> AsReadOnlySpan<T>(this ArraySegment<T> arraySegment) { return new ReadOnlySpan<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count); } /// <summary> /// Copies the contents of the array into the span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// ///<param name="array">The array to copy items from.</param> /// <param name="destination">The span to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination Span is shorter than the source array. /// </exception> /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo<T>(this T[] array, Span<T> destination) { new ReadOnlySpan<T>(array).CopyTo(destination); } } }
using System; using System.Collections.Generic; using Tibia.Packets; using System.Drawing; using Tibia.Util; namespace Tibia.Objects { /// <summary> /// Represents one stack of items. Can also represent a type of item (with no location in memory). /// </summary> public class Item { protected Client client; protected uint id; protected string name; protected byte count; protected ItemLocation location; #region Constructors /// <summary> /// Please use this constructor only for items list. /// </summary> /// <param name="id"></param> /// <param name="name"></param> public Item(uint id, string name) : this(null, id, 0, name) { } public Item(Client client, uint id) : this(client, id, 0) { } public Item(Client client, uint id, byte count) : this(client, id, count, "") { } public Item(Client client, uint id, byte count, string name) : this(client, id, count, name, null) { } public Item(Client client, uint id, byte count, string name, ItemLocation location) { this.client = client; this.id = id; this.count = count; this.name = name; this.location = location; } #endregion #region Packet Functions /// <summary> /// Opens a container in the same window. Only works if the item is a container. /// </summary> /// <param name="container">Which container window to open in.</param> /// <returns></returns> public bool OpenAsContainer(byte container) { return Packets.Outgoing.ItemUsePacket.Send(client, location.ToLocation(), (ushort)id, location.StackOrder, container); } /// <summary> /// Use the item (eg. eat food). /// </summary> /// <returns></returns> /// Use function should never send anything more than 0 for using food(but only for open containers.)(Klusbert) public bool Use() { return Packets.Outgoing.ItemUsePacket.Send(client, location.ToLocation(), (ushort)id, location.StackOrder, 0); } /// <summary> /// Use the item on a tile (eg. fish, rope, pick, shovel, etc). /// </summary> /// <param name="onTile"></param> /// <returns></returns> public bool Use(Objects.Tile onTile) { return Packets.Outgoing.ItemUseOnPacket.Send(client, location.ToLocation(), (ushort)id, 0, onTile.Location, (ushort)onTile.Ground.Id, 0); } /// <summary> /// Use an item on another item. /// Not tested. /// </summary> /// <param name="onItem"></param> /// <returns></returns> public bool Use(Objects.Item onItem) { return Packets.Outgoing.ItemUseOnPacket.Send(client, location.ToLocation(), (ushort)id, 0, onItem.Location.ToLocation(), (ushort)onItem.Id, 0); } /// <summary> /// Use an item on a creature. /// </summary> /// <param name="onCreature"></param> /// <returns></returns> public bool Use(Objects.Creature onCreature) { return Packets.Outgoing.ItemUseOnPacket.Send(client, location.ToLocation(), (ushort)id, location.ToBytes()[4], onCreature.Location, 0x63, 0); } /// <summary> /// Use the item on yourself /// </summary> /// <returns></returns> public bool UseOnSelf() { uint playerId = client.Player.Id; byte stack = 0; if (id == Constants.Items.Bottle.Vial.Id) stack = count; return Packets.Outgoing.ItemUseBattlelistPacket.Send(client, ItemLocation.FromHotkey().ToLocation(), (ushort)id, stack, playerId); } /// <summary> /// Move an item to a location (eg. move a blank rune to the right hand). /// </summary> /// <param name="toLocation"></param> /// <returns></returns> public bool Move(Objects.ItemLocation toLocation) { return Move(toLocation, this.count); } /// <summary> /// Move an item to a location (eg. move a blank rune to the right hand). /// </summary> /// <param name="toLocation"></param> /// <returns></returns> public bool Move(Objects.ItemLocation toLocation, byte count) { return Packets.Outgoing.ItemMovePacket.Send(client, location.ToLocation(), (ushort)id, location.ToBytes()[4], toLocation.ToLocation(), count); } /// <summary> /// Look at an item. /// </summary> /// <returns></returns> public bool Look() { return Packets.Outgoing.LookAtPacket.Send(client, location.ToLocation(), (ushort)id, location.StackOrder); } #endregion #region Get/Set Properties /// <summary> /// Gets the client associated with this item; /// </summary> public Client Client { get { return client; } set { client = value; } } /// <summary> /// Gets or sets the id of the item. /// </summary> public uint Id { get { return id; } set { id = value; } } /// <summary> /// Gets or sets the name of the item. /// </summary> public string Name { get { return name; } set { name = value; } } public ItemData Data { get { if (Constants.ItemLists.AllItems.ContainsKey(Id)) { Name = Constants.ItemLists.AllItems[Id].Name; return Constants.ItemDataLists.AllItems[Name]; } else { return null; } } } /// <summary> /// Gets or sets the amount stacked of this item. /// </summary> public byte Count { get { return count; } set { count = value; } } /// <summary> /// Gets the total number of items/objects in Tibia. /// </summary> public uint TotalItemCount { get { uint baseAddr = client.Memory.ReadUInt32(Addresses.Client.DatPointer); return client.Memory.ReadUInt32(baseAddr + 4); } } /// <summary> /// Gets or sets the location of this item. /// </summary> public ItemLocation Location { get { return location; } set { location = value; } } /// <summary> /// Gets the DatAddress of the item in the dat structure. /// </summary> public uint DatAddress { get { uint baseAddr = client.Memory.ReadUInt32(Addresses.Client.DatPointer); return client.Memory.ReadUInt32(baseAddr + 8) + Addresses.DatItem.StepItems * (id - 100); } } /// <summary> /// Gets or sets the visible width of the item. /// </summary> public int Width { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.Width); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.Width, value); } } /// <summary> /// Gets or sets the visible height of the item. /// </summary> public int Height { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.Height); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.Height, value); } } public int MaxSizeInPixels { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.MaxSizeInPixels); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.MaxSizeInPixels, value); } } public int Layers { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.Layers); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.Layers, value); } } public int PatternX { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.PatternX); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.PatternX, value); } } public int PatternY { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.PatternY); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.PatternY, value); } } public int PatternDepth { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.PatternDepth); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.PatternDepth, value); } } public int Phase { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.Phase); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.Phase, value); } } public int SpriteCount { get { return Width * Height * Layers * PatternX * PatternY * PatternDepth * Phase; } } public ushort[] SpriteIds { get { int count = SpriteCount; uint address = client.Memory.ReadUInt32(DatAddress + Addresses.DatItem.Sprite); ushort[] spriteIds = new ushort[count]; for (int i = 0; i < count; i++) { spriteIds[i] = client.Memory.ReadUInt16(address + i * 2); } return spriteIds; } set { int count = SpriteCount; if (value.Length != count) throw new ArgumentException("value.Length!=SpriteCount"); uint address = client.Memory.ReadUInt32(DatAddress + Addresses.DatItem.Sprite); for (int i = 0; i < count; i++) { client.Memory.WriteUInt16(address + i * 2, value[i]); } } } public Image[] Sprites { get { ushort[] spriteIds = SpriteIds; Image[] sprites = new Image[spriteIds.Length]; for (int i = 0; i < spriteIds.Length; i++) { try { sprites[i] = SpriteReader.GetSpriteImage(client, spriteIds[i]); } catch (ArgumentOutOfRangeException) { sprites[i] = null; } } return sprites; } } /// <summary> /// Gets or sets the flags of the item. /// </summary> public uint Flags { get { return client.Memory.ReadUInt32(DatAddress + Addresses.DatItem.Flags); } set { client.Memory.WriteUInt32(DatAddress + Addresses.DatItem.Flags, value); } } /// <summary> /// Gets or sets the walking speed of the item. (Walkable tiles) /// </summary> public int WalkSpeed { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.WalkSpeed); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.WalkSpeed, value); } } /// <summary> /// Gets or sets the text limit of the item. (Writable items) /// </summary> public int TextLimit { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.TextLimit); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.TextLimit, value); } } /// <summary> /// Gets or sets the light radius of the item. (Light items) /// </summary> public int LightRadius { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.LightRadius); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.LightRadius, value); } } /// <summary> /// Gets or sets the light color of the item. (Light items) /// </summary> public int LightColor { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.LightColor); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.LightColor, value); } } /// <summary> /// Gets or sets how many pixels the item is shifted horizontally from the lower /// right corner of the tile. /// </summary> public int ShiftX { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.ShiftX); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.ShiftX, value); } } /// <summary> /// Gets or sets how many pixels the item is shifted vertically from the lower /// right corner of the tile. /// </summary> public int ShiftY { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.ShiftY); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.ShiftY, value); } } /// <summary> /// Gets or sets the height created by the item when a character walks over. /// </summary> public int WalkHeight { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.WalkHeight); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.WalkHeight, value); } } /// <summary> /// Gets or sets the color shown by the item in the automap. /// </summary> public int AutomapColor { get { return client.Memory.ReadInt32(DatAddress + Addresses.DatItem.Automap); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.Automap, value); } } /// <summary> /// Gets or sets the help id for the item in Help mode. /// </summary> public Addresses.DatItem.Help LensHelp { get { return (Addresses.DatItem.Help)client.Memory.ReadInt32(DatAddress + Addresses.DatItem.LensHelp); } set { client.Memory.WriteInt32(DatAddress + Addresses.DatItem.LensHelp, (int)value); } } public byte TopOrder { get { if (GetFlag(Tibia.Addresses.DatItem.Flag.IsGround)) return 0; else if (GetFlag(Tibia.Addresses.DatItem.Flag.TopOrder1)) return 1; else if (GetFlag(Tibia.Addresses.DatItem.Flag.TopOrder2)) return 2; else if (GetFlag(Tibia.Addresses.DatItem.Flag.TopOrder3)) return 3; else return 5; } } #endregion #region Composite Properties /// <summary> /// Returns whether the item has an extra byte (count, fluid type, charges, etc). /// </summary> public bool HasExtraByte { get { return GetFlag(Tibia.Addresses.DatItem.Flag.IsStackable) || GetFlag(Tibia.Addresses.DatItem.Flag.IsRune) || // unused in 8.60, always returns false GetFlag(Tibia.Addresses.DatItem.Flag.IsSplash) || GetFlag(Tibia.Addresses.DatItem.Flag.IsFluidContainer); } } #endregion #region Flags public bool GetFlag(Addresses.DatItem.Flag flag) { return (Flags & Addresses.DatItem.GetFlagOffset(client.VersionNumber, flag)) != 0; } public void SetFlag(Addresses.DatItem.Flag flag, bool enable) { if (enable) Flags |= Addresses.DatItem.GetFlagOffset(client.VersionNumber, flag); else Flags &= ~Addresses.DatItem.GetFlagOffset(client.VersionNumber, flag); } #endregion /// <summary> /// Check whether or not this item is in a list (checks by ID only) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <returns>True if the item is in the list, false if not</returns> public bool IsInList<T>(IEnumerable<T> list) where T : Item { if (Id != 0) { foreach (T i in list) { if (Id == i.Id) return true; } } return false; } public override string ToString() { return Name; } } #region Special Item Types /// <summary> /// Represents a food item. Same as regular item but also stores regeneration time. /// </summary> public class Food : Item { public uint RegenerationTime; public Food(uint id, string name, uint regenerationTime) : base(null, id, 0, name) { RegenerationTime = regenerationTime; } public Food(Client client, uint id, string name, uint regenerationTime) : base(client, id, 0, name) { RegenerationTime = regenerationTime; } } /// <summary> /// Represents a rune item. Contains metadata relating specifically to runes. /// </summary> public class TransformingItem : Item { public Spell Spell; public uint SoulPoints; public Item OriginalItem; /// <summary> /// Default constructor. /// </summary> /// <param name="id">item id</param> /// <param name="name">item name</param> /// <param name="spell">spell used to create the item</param> /// <param name="soulPoints">amount of soul points needed to make the item</param> /// <param name="originalItem">the item that the spell words are used on to create this item</param> public TransformingItem(Client client, uint id, string name, Spell spell, uint soulPoints, Item originalItem) : base(client, id, 0, name) { Spell = spell; SoulPoints = soulPoints; OriginalItem = originalItem; } public TransformingItem(uint id, string name, Spell spell, uint soulPoints, Item originalItem) : base(null, id, 0, name) { Spell = spell; SoulPoints = soulPoints; OriginalItem = originalItem; } } /// <summary> /// Represents a rune item. Contains metadata relating specifically to runes. /// </summary> public class Rune : TransformingItem { /// <summary> /// Default rune constructor. /// </summary> /// <param name="id">item id</param> /// <param name="name">item name</param> /// <param name="spell">spell used to create the rune</param> /// <param name="soulPoints">amount of soul points needed to make the rune</param> public Rune(Client client, uint id, string name, Spell spell, uint soulPoints) : base(client, id, name, spell, soulPoints, Constants.Items.Rune.Blank) { } public Rune(uint id, string name, Spell spell, uint soulPoints) : base(null, id, name, spell, soulPoints, Constants.Items.Rune.Blank) { } } #endregion /// <summary> /// Represents an item's location in game/memory. Can be either a slot, an inventory location, or on the ground. /// </summary> public class ItemLocation { public Constants.ItemLocationType Type; public byte ContainerId; public byte ContainerSlot; public Location GroundLocation; public byte StackOrder; public Constants.SlotNumber Slot; public ItemLocation() { } public static ItemLocation FromSlot(Constants.SlotNumber slot) { ItemLocation loc = new ItemLocation(); loc.Type = Constants.ItemLocationType.Slot; loc.Slot = slot; return loc; } public static ItemLocation FromContainer(byte container, byte position) { ItemLocation loc = new ItemLocation(); loc.Type = Constants.ItemLocationType.Container; loc.ContainerId = container; loc.ContainerSlot = position; loc.StackOrder = position; return loc; } public static ItemLocation FromLocation(Location location, byte stack) { ItemLocation loc = new ItemLocation(); loc.Type = Constants.ItemLocationType.Ground; loc.GroundLocation = location; loc.StackOrder = stack; return loc; } public static ItemLocation FromLocation(Location location) { return FromLocation(location, 1); } public static ItemLocation FromItemLocation(ItemLocation location) { switch (location.Type) { case Tibia.Constants.ItemLocationType.Container: return ItemLocation.FromContainer(location.ContainerId, location.ContainerSlot); case Tibia.Constants.ItemLocationType.Ground: return ItemLocation.FromLocation(location.GroundLocation, location.StackOrder); case Tibia.Constants.ItemLocationType.Slot: return ItemLocation.FromSlot(location.Slot); default: return null; } } /// <summary> /// Return a blank item location for packets (FF FF 00 00 00) /// </summary> /// <returns></returns> public static ItemLocation FromHotkey() { return FromSlot(Constants.SlotNumber.None); } public byte[] ToBytes() { byte[] bytes = new byte[5]; switch (Type) { case Constants.ItemLocationType.Container: bytes[00] = 0xFF; bytes[01] = 0xFF; bytes[02] = (byte)(0x40 + ContainerId); bytes[03] = 0x00; bytes[04] = ContainerSlot; break; case Constants.ItemLocationType.Slot: bytes[00] = 0xFF; bytes[01] = 0xFF; bytes[02] = (byte)Slot; bytes[03] = 0x00; bytes[04] = 0x00; break; case Constants.ItemLocationType.Ground: bytes[00] = GroundLocation.X.Low(); bytes[01] = GroundLocation.X.High(); bytes[02] = GroundLocation.Y.Low(); bytes[03] = GroundLocation.Y.High(); bytes[04] = (byte)GroundLocation.Z; break; } return bytes; } public Location ToLocation() { Location newPos = new Location(); switch (Type) { case Constants.ItemLocationType.Container: newPos.X = 0xFFFF; newPos.Y = (int)BitConverter.ToUInt16(new byte[] { (byte)(0x40 + ContainerId), 0x00 }, 0); newPos.Z = (int)ContainerSlot; break; case Constants.ItemLocationType.Slot: newPos.X = 0xFFFF; newPos.Y = (int)BitConverter.ToUInt16(new byte[] { (byte)Slot, 0x00 }, 0); newPos.Z = 0; break; case Constants.ItemLocationType.Ground: newPos = GroundLocation; break; } return newPos; } } }
// 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; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Xml; using System.Security; namespace System.Runtime.Serialization { #if NET_NATIVE public class DataMember #else internal class DataMember #endif { [SecurityCritical] /// <SecurityNote> /// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization. /// Static fields are marked SecurityCritical or readonly to prevent /// data from being modified or leaked to other components in appdomain. /// </SecurityNote> private CriticalHelper _helper; /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> [SecuritySafeCritical] public DataMember() { _helper = new CriticalHelper(); } /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> [SecuritySafeCritical] internal DataMember(MemberInfo memberInfo) { _helper = new CriticalHelper(memberInfo); } /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> [SecuritySafeCritical] internal DataMember(DataContract memberTypeContract, string name, bool isNullable, bool isRequired, bool emitDefaultValue, int order) { _helper = new CriticalHelper(memberTypeContract, name, isNullable, isRequired, emitDefaultValue, order); } internal MemberInfo MemberInfo { [SecuritySafeCritical] get { return _helper.MemberInfo; } } public string Name { [SecuritySafeCritical] get { return _helper.Name; } [SecurityCritical] set { _helper.Name = value; } } public int Order { [SecuritySafeCritical] get { return _helper.Order; } [SecurityCritical] set { _helper.Order = value; } } public bool IsRequired { [SecuritySafeCritical] get { return _helper.IsRequired; } [SecurityCritical] set { _helper.IsRequired = value; } } public bool EmitDefaultValue { [SecuritySafeCritical] get { return _helper.EmitDefaultValue; } [SecurityCritical] set { _helper.EmitDefaultValue = value; } } public bool IsNullable { [SecuritySafeCritical] get { return _helper.IsNullable; } [SecurityCritical] set { _helper.IsNullable = value; } } public bool IsGetOnlyCollection { [SecuritySafeCritical] get { return _helper.IsGetOnlyCollection; } [SecurityCritical] set { _helper.IsGetOnlyCollection = value; } } internal Type MemberType { [SecuritySafeCritical] get { return _helper.MemberType; } } internal DataContract MemberTypeContract { [SecuritySafeCritical] get { return _helper.MemberTypeContract; } } public bool HasConflictingNameAndType { [SecuritySafeCritical] get { return _helper.HasConflictingNameAndType; } [SecurityCritical] set { _helper.HasConflictingNameAndType = value; } } internal DataMember ConflictingMember { [SecuritySafeCritical] get { return _helper.ConflictingMember; } [SecurityCritical] set { _helper.ConflictingMember = value; } } [SecurityCritical] /// <SecurityNote> /// Critical /// </SecurityNote> private class CriticalHelper { private DataContract _memberTypeContract; private string _name; private int _order; private bool _isRequired; private bool _emitDefaultValue; private bool _isNullable; private bool _isGetOnlyCollection = false; private MemberInfo _memberInfo; private bool _hasConflictingNameAndType; private DataMember _conflictingMember; internal CriticalHelper() { _emitDefaultValue = Globals.DefaultEmitDefaultValue; } internal CriticalHelper(MemberInfo memberInfo) { _emitDefaultValue = Globals.DefaultEmitDefaultValue; _memberInfo = memberInfo; } internal CriticalHelper(DataContract memberTypeContract, string name, bool isNullable, bool isRequired, bool emitDefaultValue, int order) { this.MemberTypeContract = memberTypeContract; this.Name = name; this.IsNullable = isNullable; this.IsRequired = isRequired; this.EmitDefaultValue = emitDefaultValue; this.Order = order; } internal MemberInfo MemberInfo { get { return _memberInfo; } } internal string Name { get { return _name; } set { _name = value; } } internal int Order { get { return _order; } set { _order = value; } } internal bool IsRequired { get { return _isRequired; } set { _isRequired = value; } } internal bool EmitDefaultValue { get { return _emitDefaultValue; } set { _emitDefaultValue = value; } } internal bool IsNullable { get { return _isNullable; } set { _isNullable = value; } } internal bool IsGetOnlyCollection { get { return _isGetOnlyCollection; } set { _isGetOnlyCollection = value; } } internal Type MemberType { get { FieldInfo field = MemberInfo as FieldInfo; if (field != null) return field.FieldType; return ((PropertyInfo)MemberInfo).PropertyType; } } internal DataContract MemberTypeContract { get { if (_memberTypeContract == null) { if (MemberInfo != null) { if (this.IsGetOnlyCollection) { _memberTypeContract = DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(MemberType.TypeHandle), MemberType.TypeHandle, MemberType, SerializationMode.SharedContract); } else { _memberTypeContract = DataContract.GetDataContract(MemberType); } } } return _memberTypeContract; } set { _memberTypeContract = value; } } internal bool HasConflictingNameAndType { get { return _hasConflictingNameAndType; } set { _hasConflictingNameAndType = value; } } internal DataMember ConflictingMember { get { return _conflictingMember; } set { _conflictingMember = value; } } } /// <SecurityNote> /// Review - checks member visibility to calculate if access to it requires MemberAccessPermission for serialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForGet(string[] serializationAssemblyPatterns) { MemberInfo memberInfo = MemberInfo; FieldInfo field = memberInfo as FieldInfo; if (field != null) { return DataContract.FieldRequiresMemberAccess(field, serializationAssemblyPatterns); } else { PropertyInfo property = (PropertyInfo)memberInfo; MethodInfo getMethod = property.GetMethod; if (getMethod != null) { return DataContract.MethodRequiresMemberAccess(getMethod, serializationAssemblyPatterns) || !DataContract.IsTypeVisible(property.PropertyType, serializationAssemblyPatterns); } } return false; } /// <SecurityNote> /// Review - checks member visibility to calculate if access to it requires MemberAccessPermission for deserialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForSet(string[] serializationAssemblyPatterns) { MemberInfo memberInfo = MemberInfo; FieldInfo field = memberInfo as FieldInfo; if (field != null) { return DataContract.FieldRequiresMemberAccess(field, serializationAssemblyPatterns); } else { PropertyInfo property = (PropertyInfo)memberInfo; MethodInfo setMethod = property.SetMethod; if (setMethod != null) { return DataContract.MethodRequiresMemberAccess(setMethod, serializationAssemblyPatterns) || !DataContract.IsTypeVisible(property.PropertyType, serializationAssemblyPatterns); } } return false; } } }
/* * Win32KeyProvider.cs - Implementation of the * "Microsoft.Win32.Win32KeyProvider" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace Microsoft.Win32 { #if CONFIG_WIN32_SPECIFICS using System; using System.Text; using System.Collections; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // This class implements registry functionality for Win32 systems. internal sealed class Win32KeyProvider : IRegistryKeyProvider { // Internal state. private String name; private IntPtr hKey; // Constructors. public Win32KeyProvider(String name, IntPtr hKey) { this.name = name; this.hKey = hKey; } // Destructor. ~Win32KeyProvider() { Close(false); } // Determine if we should use the Win32 registry. public static bool IsWin32() { return (Environment.OSVersion.Platform != PlatformID.Unix); } // Close a reference to this key and flush any modifications to disk. public void Close(bool writable) { lock(this) { if(hKey != IntPtr.Zero) { long key = hKey.ToInt64(); if(key < (long)(int)(RegistryHive.ClassesRoot) || key > (long)(int)(RegistryHive.DynData)) { RegCloseKey(hKey); } hKey = IntPtr.Zero; } } } // Create a subkey underneath this particular registry key. public IRegistryKeyProvider CreateSubKey(String subkey) { lock(this) { if(hKey != IntPtr.Zero) { IntPtr newKey; if(RegCreateKey(hKey, subkey, out newKey) == 0) { return new Win32KeyProvider (name + "\\" + subkey, newKey); } } } throw new ArgumentException(_("IO_RegistryKeyNotExist")); } // Returns true if we should delete subkeys from their parents. public bool DeleteFromParents { get { // Use "DeleteSubKey" and "DeleteSubKeyTree". return true; } } // Delete a subkey of this key entry. Returns false if not present. public bool DeleteSubKey(String name) { lock(this) { if(hKey != IntPtr.Zero) { // Make sure that we don't have any subkeys. // This is to work around an API discontinuity: // Win95 deletes subtrees, but WinNT doesn't. uint numSubKeys, numValues; RegQueryInfoKey(hKey, null, IntPtr.Zero, IntPtr.Zero, out numSubKeys, IntPtr.Zero, IntPtr.Zero, out numValues, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); if(numSubKeys != 0) { throw new InvalidOperationException (_("IO_RegistryHasSubKeys")); } return (RegDeleteKey(hKey, name) == 0); } else { return false; } } } // Delete this key entry. public void Delete() { // This version is not used under Win32. } // Internal recursive version of "DeleteSubKeyTree". private static bool DeleteSubKeyTree(IntPtr hKey, String name) { IntPtr subTree; // Open the subkey tree. if(RegOpenKeyEx(hKey, name, 0, KEY_ALL_ACCESS, out subTree) != 0) { return false; } // Collect up the names of all subkeys under "subTree". uint numSubKeys, numValues; RegQueryInfoKey(subTree, null, IntPtr.Zero, IntPtr.Zero, out numSubKeys, IntPtr.Zero, IntPtr.Zero, out numValues, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); String[] names = new String [numSubKeys]; uint index = 0; char[] nameBuf = new char [1024]; uint nameLen; long writeTime; while(index < numSubKeys) { nameBuf.Initialize(); nameLen = (uint)(name.Length); if(RegEnumKeyEx(subTree, index, nameBuf, ref nameLen, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, out writeTime) != 0) { break; } names[(int)(index++)] = ArrayToString(nameBuf); } // Recursively delete the subtrees. foreach(String n in names) { DeleteSubKeyTree(subTree, n); } // Close the subtree. RegCloseKey(subTree); // Delete the subkey that corresponds to the subtree. return (RegDeleteKey(hKey, name) == 0); } // Delete a subkey entry and all of its descendents. // Returns false if not present. public bool DeleteSubKeyTree(String name) { lock(this) { if(hKey != IntPtr.Zero) { return DeleteSubKeyTree(hKey, name); } else { return false; } } } // Delete this key entry and all of its descendents. public void DeleteTree() { // This version is not used under Win32. } // Delete a particular value underneath this registry key. // Returns false if the value is missing. public bool DeleteValue(String name) { lock(this) { if(hKey != IntPtr.Zero) { if(RegDeleteValue(hKey, name) == 0) { return true; } } return false; } } // Flush all modifications to this registry key. public void Flush() { lock(this) { if(hKey != IntPtr.Zero) { RegFlushKey(hKey); } } } // Convert a null-terminated "char[]" array into a "String". private static String ArrayToString(char[] array) { int index = 0; while(index < array.Length && array[index] != '\0') { ++index; } return new String(array, 0, index); } // Convert a null-terminated "byte[]" array into a "String", // where the array contains 16-bit character values. private static String ArrayToString(byte[] array, ref int index) { int len = 0; while((index + len + 1) < array.Length && (array[index + len] != 0 || array[index + len + 1] != 0)) { len += 2; } StringBuilder builder = new StringBuilder(len / 2); len = 0; while((index + len + 1) < array.Length && (array[index + len] != 0 || array[index + len + 1] != 0)) { builder.Append((char)(((int)array[index + len]) | (((int)array[index + len + 1]) << 8))); len += 2; } index += len + 2; return builder.ToString(); } private static String ArrayToString(byte[] array) { int index = 0; return ArrayToString(array, ref index); } // Convert a "byte[]" array into an array of "String" values. private static String[] ArrayToStringArray(byte[] array) { ArrayList list = new ArrayList(); String value; int index = 0; for(;;) { value = ArrayToString(array, ref index); if(value.Length == 0) { break; } list.Add(value); } return (String[])(list.ToArray(typeof(String))); } // Convert a "String" into a "byte[]" array. private static byte[] StringToArray(String value) { byte[] data = new byte [value.Length * 2]; int index; for(index = 0; index < value.Length; ++index) { data[index * 2] = (byte)(value[index]); data[index * 2 + 1] = (byte)(value[index] >> 8); } return data; } // Convert a "String[]" array into a "byte[]" array. private static byte[] StringArrayToArray(String[] value) { // Determine the total length of the "byte[]" array. int len = 0; int index, posn; String str; for(index = 0; index < value.Length; ++index) { str = value[index]; if(str != null) { len += str.Length * 2 + 2; } else { len += 2; } } len += 2; // Create the "byte[]" array. byte[] data = new byte [len]; // Write the strings into the "byte[]" array. len = 0; for(index = 0; index < value.Length; ++index) { str = value[index]; if(str != null) { for(posn = 0; posn < str.Length; ++posn) { data[len++] = (byte)(str[posn]); data[len++] = (byte)(str[posn] >> 8); } len += 2; } else { len += 2; } } // Return the final encoded array to the caller. return data; } // Get the names of all subkeys underneath this registry key. public String[] GetSubKeyNames() { lock(this) { if(hKey != IntPtr.Zero) { // Get the number of subkey names under the key. uint numSubKeys, numValues; RegQueryInfoKey(hKey, null, IntPtr.Zero, IntPtr.Zero, out numSubKeys, IntPtr.Zero, IntPtr.Zero, out numValues, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); // Create an array to hold the names. String[] names = new String [numSubKeys]; // Enumerate the names into the array. uint index = 0; char[] name = new char [1024]; uint nameLen; long writeTime; while(index < numSubKeys) { name.Initialize(); nameLen = (uint)(name.Length); if(RegEnumKeyEx(hKey, index, name, ref nameLen, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, out writeTime) != 0) { break; } names[(int)(index++)] = ArrayToString(name); } // Return the final name array to the caller. return names; } return new String [0]; } } // Get a value from underneath this registry key. public Object GetValue(String name, Object defaultValue) { uint type = REG_NONE; byte[] data = null; uint dataLen; // Query the value from the registry. lock(this) { if(hKey != IntPtr.Zero) { // Determine how big the buffer needs to be first. dataLen = 0; if(RegQueryValueEx(hKey, name, IntPtr.Zero, out type, IntPtr.Zero, ref dataLen) != 0) { return defaultValue; } // Allocate a buffer to hold the data. data = new byte [dataLen]; // Now query the actual value. if(RegQueryValueEx(hKey, name, IntPtr.Zero, out type, data, ref dataLen) != 0) { return defaultValue; } } else { return defaultValue; } } // Decode the value into something that we can return. switch(type) { case REG_BINARY: return data; case REG_DWORD_LITTLE_ENDIAN: { if(data.Length == 4) { return ((int)(data[0])) | (((int)(data[1])) << 8) | (((int)(data[2])) << 16) | (((int)(data[3])) << 24); } } break; case REG_DWORD_BIG_ENDIAN: { if(data.Length == 4) { return ((int)(data[3])) | (((int)(data[2])) << 8) | (((int)(data[1])) << 16) | (((int)(data[0])) << 24); } } break; case REG_SZ: case REG_EXPAND_SZ: { return ArrayToString(data); } // Not reached. case REG_MULTI_SZ: { return ArrayToStringArray(data); } // Not reached. case REG_QWORD_LITTLE_ENDIAN: { if(data.Length == 8) { return ((long)(data[0])) | (((long)(data[1])) << 8) | (((long)(data[2])) << 16) | (((long)(data[3])) << 24) | (((long)(data[4])) << 32) | (((long)(data[5])) << 40) | (((long)(data[6])) << 48) | (((long)(data[7])) << 56); } } break; default: break; } // If we get here, then we don't know how to decode the data. return defaultValue; } // Get the names of all values underneath this registry key. public String[] GetValueNames() { lock(this) { if(hKey != IntPtr.Zero) { // Get the number of value names under the key. uint numSubKeys, numValues; RegQueryInfoKey(hKey, null, IntPtr.Zero, IntPtr.Zero, out numSubKeys, IntPtr.Zero, IntPtr.Zero, out numValues, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); // Create an array to hold the names. String[] names = new String [numValues]; // Enumerate the names into the array. uint index = 0; char[] name = new char [1024]; uint nameLen; while(index < numValues) { name.Initialize(); nameLen = (uint)(name.Length); if(RegEnumValue(hKey, index, name, ref nameLen, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) != 0) { break; } names[(int)(index++)] = ArrayToString(name); } // Return the final name array to the caller. return names; } return new String [0]; } } // Open a subkey. public IRegistryKeyProvider OpenSubKey(String name, bool writable) { lock(this) { if(hKey != IntPtr.Zero) { IntPtr newKey; if(RegOpenKeyEx (hKey, name, 0, (writable ? KEY_ALL_ACCESS : KEY_READ), out newKey) != 0) { return null; } return new Win32KeyProvider (this.name + "\\" + name, newKey); } else { return null; } } } // Set a value under this registry key. public void SetValue(String name, Object value) { uint type; byte[] data; // Convert the value into a byte array and type. if(value is String) { // Convert a string. type = REG_SZ; data = StringToArray((String)value); } else if(value is int) { // Convert a signed integer. int ivalue = (int)value; type = REG_DWORD_LITTLE_ENDIAN; data = new byte [4]; data[0] = (byte)ivalue; data[1] = (byte)(ivalue >> 8); data[2] = (byte)(ivalue >> 16); data[3] = (byte)(ivalue >> 24); } else if(value is uint) { // Convert an unsigned integer. uint uivalue = (uint)value; type = REG_DWORD_LITTLE_ENDIAN; data = new byte [4]; data[0] = (byte)uivalue; data[1] = (byte)(uivalue >> 8); data[2] = (byte)(uivalue >> 16); data[3] = (byte)(uivalue >> 24); } else if(value is long) { // Convert a signed long integer. long lvalue = (long)value; type = REG_QWORD_LITTLE_ENDIAN; data = new byte [8]; data[0] = (byte)lvalue; data[1] = (byte)(lvalue >> 8); data[2] = (byte)(lvalue >> 16); data[3] = (byte)(lvalue >> 24); data[4] = (byte)(lvalue >> 32); data[5] = (byte)(lvalue >> 40); data[6] = (byte)(lvalue >> 48); data[7] = (byte)(lvalue >> 56); } else if(value is ulong) { // Convert an unsigned long integer. ulong ulvalue = (ulong)value; type = REG_QWORD_LITTLE_ENDIAN; data = new byte [8]; data[0] = (byte)ulvalue; data[1] = (byte)(ulvalue >> 8); data[2] = (byte)(ulvalue >> 16); data[3] = (byte)(ulvalue >> 24); data[4] = (byte)(ulvalue >> 32); data[5] = (byte)(ulvalue >> 40); data[6] = (byte)(ulvalue >> 48); data[7] = (byte)(ulvalue >> 56); } else if(value is byte[]) { // Convert a raw binary byte array. type = REG_BINARY; data = (byte[])value; } else if(value is String[]) { // Convert an array of strings. type = REG_MULTI_SZ; data = StringArrayToArray((String[])value); } else { // Last ditch attempt: use the string form of the value. type = REG_SZ; data = StringToArray(value.ToString()); } // Set the value within the registry. lock(this) { if(hKey != IntPtr.Zero) { RegSetValueEx(hKey, name, 0, type, data, (uint)(data.Length)); } } } // Get the name of this registry key provider. public String Name { get { return name; } } // Get the number of subkeys underneath this key. public int SubKeyCount { get { lock(this) { if(hKey != IntPtr.Zero) { uint numSubKeys, numValues; RegQueryInfoKey(hKey, null, IntPtr.Zero, IntPtr.Zero, out numSubKeys, IntPtr.Zero, IntPtr.Zero, out numValues, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); return (int)numSubKeys; } return 0; } } } // Get the number of values that are associated with this key. public int ValueCount { get { lock(this) { if(hKey != IntPtr.Zero) { uint numSubKeys, numValues; RegQueryInfoKey(hKey, null, IntPtr.Zero, IntPtr.Zero, out numSubKeys, IntPtr.Zero, IntPtr.Zero, out numValues, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); return (int)numValues; } return 0; } } } // Convert a hive value into a HKEY value. public static IntPtr HiveToHKey(RegistryHive hive) { return new IntPtr((int)hive); } // Import the Win32 registry functions from "advapi32.dll". [DllImport("advapi32.dll", CallingConvention=CallingConvention.Winapi)] [MethodImpl(MethodImplOptions.PreserveSig)] extern private static int RegCloseKey(IntPtr hKey); [DllImport("advapi32.dll", EntryPoint="RegConnectRegistryW", CallingConvention=CallingConvention.Winapi)] [MethodImpl(MethodImplOptions.PreserveSig)] extern public static int RegConnectRegistry ([MarshalAs(UnmanagedType.LPWStr)] String lpMachineName, IntPtr hKey, out IntPtr phkResult); [DllImport("advapi32.dll", EntryPoint="RegCreateKeyW", CallingConvention=CallingConvention.Winapi)] [MethodImpl(MethodImplOptions.PreserveSig)] extern private static int RegCreateKey (IntPtr hkey, [MarshalAs(UnmanagedType.LPWStr)] String lpSubKey, out IntPtr phkResult); [DllImport("advapi32.dll", EntryPoint="RegDeleteKeyW", CallingConvention=CallingConvention.Winapi)] [MethodImpl(MethodImplOptions.PreserveSig)] extern private static int RegDeleteKey (IntPtr hkey, [MarshalAs(UnmanagedType.LPWStr)] String lpSubKey); [DllImport("advapi32.dll", EntryPoint="RegDeleteValueW", CallingConvention=CallingConvention.Winapi)] [MethodImpl(MethodImplOptions.PreserveSig)] extern private static int RegDeleteValue (IntPtr hkey, [MarshalAs(UnmanagedType.LPWStr)] String lpValueName); [DllImport("advapi32.dll", EntryPoint="RegEnumKeyExW", CallingConvention=CallingConvention.Winapi)] [MethodImpl(MethodImplOptions.PreserveSig)] extern private static int RegEnumKeyEx (IntPtr hkey, uint index, char[] lpName, ref uint lpcbName, IntPtr reserved, IntPtr lpClass, IntPtr lpcbClass, out long lpftLastWriteTime); [DllImport("advapi32.dll", EntryPoint="RegEnumValueW", CallingConvention=CallingConvention.Winapi)] [MethodImpl(MethodImplOptions.PreserveSig)] extern private static int RegEnumValue (IntPtr hkey, uint index, char[] lpValueName, ref uint lpcbValueName, IntPtr reserved, IntPtr lpType, IntPtr lpData, IntPtr lpcbData); [DllImport("advapi32.dll", CallingConvention=CallingConvention.Winapi)] [MethodImpl(MethodImplOptions.PreserveSig)] extern private static int RegFlushKey(IntPtr hKey); [DllImport("advapi32.dll", EntryPoint="RegOpenKeyExW", CallingConvention=CallingConvention.Winapi)] [MethodImpl(MethodImplOptions.PreserveSig)] extern private static int RegOpenKeyEx (IntPtr hkey, [MarshalAs(UnmanagedType.LPWStr)] String lpSubKey, uint ulOptions, uint samDesired, out IntPtr phkResult); [DllImport("advapi32.dll", EntryPoint="RegQueryInfoKeyW", CallingConvention=CallingConvention.Winapi)] [MethodImpl(MethodImplOptions.PreserveSig)] extern private static int RegQueryInfoKey (IntPtr hkey, byte[] lpClass, IntPtr lpcbClass, IntPtr lpReserved, out uint lpcSubKeys, IntPtr lpcbMaxSubKeyLen, IntPtr lpcbMaxClassLen, out uint lpcValues, IntPtr lpcbMaxValueNameLen, IntPtr lpcbMaxValueLen, IntPtr lpcbSecurityDescriptor, IntPtr lpftLastWriteTime); [DllImport("advapi32.dll", EntryPoint="RegQueryValueExW", CallingConvention=CallingConvention.Winapi)] [MethodImpl(MethodImplOptions.PreserveSig)] extern private static int RegQueryValueEx (IntPtr hkey, [MarshalAs(UnmanagedType.LPWStr)] String lpValueName, IntPtr lpReserved, out uint lpType, byte[] lpData, ref uint lpcbData); [DllImport("advapi32.dll", EntryPoint="RegQueryValueExW", CallingConvention=CallingConvention.Winapi)] [MethodImpl(MethodImplOptions.PreserveSig)] extern private static int RegQueryValueEx (IntPtr hkey, [MarshalAs(UnmanagedType.LPWStr)] String lpValueName, IntPtr lpReserved, out uint lpType, IntPtr lpData, ref uint lpcbData); [DllImport("advapi32.dll", EntryPoint="RegSetValueExW", CallingConvention=CallingConvention.Winapi)] [MethodImpl(MethodImplOptions.PreserveSig)] extern private static int RegSetValueEx (IntPtr hkey, [MarshalAs(UnmanagedType.LPWStr)] String lpValueName, uint Reserved, uint dwType, byte[] lpData, uint cbData); // Type codes for values that can be stored in the registry. private const uint REG_NONE = 0; private const uint REG_SZ = 1; private const uint REG_EXPAND_SZ = 2; private const uint REG_BINARY = 3; private const uint REG_DWORD_LITTLE_ENDIAN = 4; private const uint REG_DWORD_BIG_ENDIAN = 5; private const uint REG_LINK = 6; private const uint REG_MULTI_SZ = 7; private const uint REG_RESOURCE_LIST = 8; private const uint REG_FULL_RESOURCE_DESCRIPTOR = 9; private const uint REG_RESOURCE_REQUIREMENTS_LIST = 10; private const uint REG_QWORD_LITTLE_ENDIAN = 11; // Access types for the "samDesired" parameter of "RegOpenKeyEx". private const uint KEY_QUERY_VALUE = 1; private const uint KEY_SET_VALUE = 2; private const uint KEY_CREATE_SUB_KEY = 4; private const uint KEY_ENUMERATE_SUB_KEYS = 8; private const uint KEY_NOTIFY = 16; private const uint KEY_CREATE_LINK = 32; private const uint KEY_WRITE = 0x20006; private const uint KEY_READ = 0x20019; private const uint KEY_ALL_ACCESS = 0xF003F; }; // class Win32KeyProvider #endif // CONFIG_WIN32_SPECIFICS }; // namespace Microsoft.Win32
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Mastersign.Expressions.Functions; using Mastersign.Expressions.Language; using Sprache; namespace Mastersign.Expressions { /// <summary> /// The evaluation context provides functions, constants and other contextual information /// for the evaluation of expressions. /// This class is the facade to the Mastersign.Expressions API. /// </summary> public class EvaluationContext { #region Static /// <summary> /// An evaluation context with all default packages loaded. /// </summary> public static EvaluationContext Default; static EvaluationContext() { Default = new EvaluationContext(); Default.LoadAllPackages(); } #endregion private readonly EvaluationContext parent; /// <summary> /// Initializes a new instance of <see cref="EvaluationContext"/> without a parent context. /// </summary> public EvaluationContext() { this.parent = null; InitializeLookupTables(); } /// <summary> /// Initializes a new instance of <see cref="EvaluationContext"/> /// with the context <paramref name="parent"/> as backup for looking up /// variables and functions. /// </summary> /// <param name="parent">The parent context.</param> public EvaluationContext(EvaluationContext parent) { this.parent = parent; InitializeLookupTables(); } private void InitializeLookupTables() { InitializeVariableLookupTable(); InitializeFunctionLookupTable(); InitializeParameterLookup(); } #region Variables private readonly List<KeyValuePair<string, Tuple<object, bool>>> variableList = new(); private Dictionary<string, Tuple<object, bool>> variableLookup; private void InitializeVariableLookupTable() { variableLookup = new Dictionary<string, Tuple<object, bool>>( Options.IgnoreVariableNameCase ? StringComparer.InvariantCultureIgnoreCase : StringComparer.InvariantCulture); foreach (var variable in variableList) { SetVariable(variable); } } /// <summary> /// Sets the value for a variable or constant. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="value">The value of the variable.</param> /// <param name="asConst">A value indicating if the variable is compiled by value or by reference. /// If this parameter is set to <c>true</c>, the varibale value is integrated into the /// expression as a constant. If set to <c>false</c>, the variable is compiled as a /// call to <see cref="ReadVariable"/>. /// </param> public void SetVariable(string name, object value, bool asConst = false) { if (Options.IsKeyword(name)) throw new ArgumentException("The given variable name is a language keyword."); var kvp = new KeyValuePair<string, Tuple<object, bool>>(name, Tuple.Create(value, asConst)); variableList.Add(kvp); SetVariable(kvp); } private void SetVariable(KeyValuePair<string, Tuple<object, bool>> variable) { variableLookup[variable.Key] = variable.Value; } /// <summary> /// Removes a variable or constant from the context. /// </summary> /// <remarks> /// The case of the variable name must be identical to the one /// used when calling <see cref="SetVariable(string, object, bool)"/>, /// regardless of the state of <see cref="IgnoreVariableNameCase"/>. /// </remarks> /// <param name="name">The name of the variable.</param> public void RemoveVariable(string name) { variableLookup.Remove(name); } /// <summary> /// Checks if a variable or a constant exists. /// </summary> /// <param name="name"></param> /// <returns><c>true</c>, if the variable or constant exists; otherwise <c>false</c>.</returns> public bool VariableExists(string name) { return variableLookup.ContainsKey(name) || (parent != null && parent.VariableExists(name)); } /// <summary> /// Returns the value of a variable or a constant. /// </summary> /// <param name="name">The name of the variable.</param> /// <returns>The value.</returns> public object ReadVariable(string name) { if (!VariableExists(name)) { throw new ArgumentException("Variable does not exists.", "name"); } Tuple<object, bool> variable; return variableLookup.TryGetValue(name, out variable) ? variable.Item1 : parent.ReadVariable(name); } /// <summary> /// Returns a value, indicating of the varibale is a constant value. /// </summary> /// <param name="name">The name of the variable.</param> /// <returns><c>true</c> if the variable will be compiled as constant and /// <c>false</c>, if the variable is compiled as call to <see cref="ReadVariable"/>.</returns> public bool IsVariableConstant(string name) { if (!VariableExists(name)) { throw new ArgumentException("Variable does not exists.", "name"); } Tuple<object, bool> variable; return variableLookup.TryGetValue(name, out variable) ? variable.Item2 : parent.IsVariableConstant(name); } #endregion #region Functions private readonly List<KeyValuePair<string, FunctionHandle>> functionList = new(); private Dictionary<string, FunctionGroup> functionGroupLookup; private void InitializeFunctionLookupTable() { functionGroupLookup = Options.IgnoreFunctionNameCase ? new Dictionary<string, FunctionGroup>(StringComparer.InvariantCultureIgnoreCase) : new Dictionary<string, FunctionGroup>(StringComparer.InvariantCulture); foreach (var function in functionList) { AddFunction(function); } } /// <summary> /// Adds a group of functions to the context. /// </summary> /// <param name="identifier">The function name.</param> /// <param name="functionGroup">The group of functions.</param> public void AddFunctionGroup(string identifier, FunctionGroup functionGroup) { foreach (var function in functionGroup) { AddFunction(new KeyValuePair<string, FunctionHandle>(identifier, function)); } } /// <summary> /// Adds a single function to the context. If there are functions allready registered under the given /// function name, the new function will be added to the function group. /// </summary> /// <param name="identifier">The function name.</param> /// <param name="function">The function.</param> public void AddFunction(string identifier, FunctionHandle function) { var kvp = new KeyValuePair<string, FunctionHandle>(identifier, function); functionList.Add(kvp); AddFunction(kvp); } private void AddFunction(KeyValuePair<string, FunctionHandle> function) { FunctionGroup group; if (!functionGroupLookup.TryGetValue(function.Key, out group)) { group = new FunctionGroup(); functionGroupLookup.Add(function.Key, group); } group.Add(function.Value); } /// <summary> /// Removes a complete function group from the context. /// </summary> /// <param name="identifier">The function name.</param> public void RemoveFunctionGroup(string identifier) { functionList.RemoveAll(kvp => string.Equals(kvp.Key, identifier, Options.IgnoreFunctionNameCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture)); functionGroupLookup.Remove(identifier); } /// <summary> /// Checks, if a function group with the given function name exists. /// </summary> /// <param name="identifier">The function name.</param> /// <returns><c>true</c>, if a function group is registered with the given name; otherwise <c>false</c>.</returns> public bool FunctionGroupExists(string identifier) { return functionGroupLookup.ContainsKey(identifier) || (parent != null && parent.FunctionGroupExists(identifier)); } /// <summary> /// Returns a function group for a given function name. /// </summary> /// <param name="identifier">The function name.</param> /// <returns>The function group or <c>null</c>, if no function group with the given name exists.</returns> public FunctionGroup GetFunctionGroup(string identifier) { FunctionGroup group; return functionGroupLookup.TryGetValue(identifier, out group) ? group : (parent != null ? parent.GetFunctionGroup(identifier) : null); } #endregion #region Parameters private ParameterInfo[] parameterList = new ParameterInfo[0]; private Dictionary<string, Tuple<ParameterInfo, int>> parameterLookup; private void InitializeParameterLookup() { parameterLookup = new Dictionary<string, Tuple<ParameterInfo, int>>( Options.IgnoreParameterNameCase ? StringComparer.InvariantCultureIgnoreCase : StringComparer.InvariantCulture); for (int i = 0; i < parameterList.Length; i++) { parameterLookup[parameterList[i].Name] = Tuple.Create(parameterList[i], i); } } /// <summary> /// Sets the parameter list for the evaluation. /// </summary> /// <param name="parameters">An enumerable with the parameters.</param> public void SetParameters(IEnumerable<ParameterInfo> parameters) { parameterList = parameters != null ? parameters.ToArray() : new ParameterInfo[0]; InitializeParameterLookup(); } /// <summary> /// Sets the parameter list for the evaluation. /// </summary> /// <param name="parameters">The parameters.</param> public void SetParameters(params ParameterInfo[] parameters) { parameterList = parameters ?? new ParameterInfo[0]; InitializeParameterLookup(); } /// <summary> /// Checks if a parameter labeled <paramref name="name"/> exists in this evaluation context. /// </summary> /// <remarks>Parameters are not derived from a parent context.</remarks> /// <param name="name">The name of the parameter.</param> /// <returns><c>true</c> if this context contains a parameter with the given name; /// otherwise <c>false</c>.</returns> public bool ParameterExists(string name) { return parameterLookup.ContainsKey(name); } /// <summary> /// Returns the <see cref="ParameterInfo"/> called <paramref name="name"/>. /// </summary> /// <param name="name">The name of the parameter.</param> /// <returns>The parameter description.</returns> /// <exception cref="KeyNotFoundException">Is thrown, /// if no parameter labeled <paramref name="name"/> exists.</exception> public ParameterInfo GetParameter(string name) { return parameterLookup.TryGetValue(name, out var t) ? t.Item1 : throw new KeyNotFoundException("The given parameter name does not exist."); } /// <summary> /// Returns the position of the parameter called <paramref name="name"/> /// in the parameter list. /// </summary> /// <param name="name">The name of the parameter.</param> /// <returns>The position of the parameter.</returns> /// <exception cref="InvalidOperationException">Is thrown, /// if no parameter labeled <paramref name="name"/> exists.</exception> public int GetParameterPosition(string name) { return parameterLookup.TryGetValue(name, out var t) ? t.Item2 : throw new KeyNotFoundException("The given parameter name does not exist."); } /// <summary> /// Creates a sequence of parameter expressions. /// </summary> private IEnumerable<ParameterExpression> ParameterExpressions { get { return from p in parameterList select p.Expression; } } #endregion #region Default Context /// <summary> /// Load all included packages into the context. /// </summary> public void LoadAllPackages() { LoadLogicPackage(); LoadMathPackage(); LoadConversionPackage(); LoadStringPackage(); LoadRegexPackage(); } /// <summary> /// Load the package with functions for boolean logic. /// </summary> public void LoadLogicPackage() { AddFunction("not", typeof(Logic).GetMethod("Not", new[] { typeof(bool) })); } /// <summary> /// The static dictionary for random instances: a random instances per thread. /// </summary> private static readonly Dictionary<Thread, Random> randoms = new Dictionary<Thread, Random>(); /// <summary> /// Returns the thread specific random object. /// </summary> private static Random Random { get { Random res; if (!randoms.TryGetValue(Thread.CurrentThread, out res)) { res = new Random(); randoms.Add(Thread.CurrentThread, res); } return res; } } /// <summary> /// Returns the next random value from <see cref="EvaluationContext.Random"/>. /// </summary> /// <returns>A pseudo random number.</returns> public static double NextRandomNumber() { return Random.NextDouble(); } /// <summary> /// Load the package with functions and constants for simple math. /// </summary> public void LoadMathPackage() { SetVariable("pi", Math.PI, true); SetVariable("e", Math.E, true); AddFunction("mod", typeof(Math2).GetMethod("Mod", new[] { typeof(Int32), typeof(Int32) })); AddFunction("mod", typeof(Math2).GetMethod("Mod", new[] { typeof(UInt32), typeof(UInt32) })); AddFunction("mod", typeof(Math2).GetMethod("Mod", new[] { typeof(Int64), typeof(Int64) })); AddFunction("mod", typeof(Math2).GetMethod("Mod", new[] { typeof(UInt64), typeof(UInt64) })); AddFunction("mod", typeof(Math2).GetMethod("Mod", new[] { typeof(Single), typeof(Single) })); AddFunction("mod", typeof(Math2).GetMethod("Mod", new[] { typeof(Double), typeof(Double) })); AddFunction("mod", typeof(Math2).GetMethod("Mod", new[] { typeof(Decimal), typeof(Decimal) })); AddFunction("abs", typeof(Math).GetMethod("Abs", new[] { typeof(SByte) })); AddFunction("abs", typeof(Math).GetMethod("Abs", new[] { typeof(Int16) })); AddFunction("abs", typeof(Math).GetMethod("Abs", new[] { typeof(Int32) })); AddFunction("abs", typeof(Math).GetMethod("Abs", new[] { typeof(Int64) })); AddFunction("abs", typeof(Math).GetMethod("Abs", new[] { typeof(Single) })); AddFunction("abs", typeof(Math).GetMethod("Abs", new[] { typeof(Double) })); AddFunction("abs", typeof(Math).GetMethod("Abs", new[] { typeof(Decimal) })); AddFunction("sign", typeof(Math).GetMethod("Sign", new[] { typeof(SByte) })); AddFunction("sign", typeof(Math).GetMethod("Sign", new[] { typeof(Int16) })); AddFunction("sign", typeof(Math).GetMethod("Sign", new[] { typeof(Int32) })); AddFunction("sign", typeof(Math).GetMethod("Sign", new[] { typeof(Int64) })); AddFunction("sign", typeof(Math).GetMethod("Sign", new[] { typeof(Single) })); AddFunction("sign", typeof(Math).GetMethod("Sign", new[] { typeof(Double) })); AddFunction("sign", typeof(Math).GetMethod("Sign", new[] { typeof(Decimal) })); AddFunction("floor", typeof(Math).GetMethod("Floor", new[] { typeof(Double) })); AddFunction("floor", typeof(Math).GetMethod("Floor", new[] { typeof(Decimal) })); AddFunction("round", typeof(Math).GetMethod("Round", new[] { typeof(Double) })); AddFunction("round", typeof(Math).GetMethod("Round", new[] { typeof(Decimal) })); AddFunction("round", typeof(Math).GetMethod("Round", new[] { typeof(Double), typeof(int) })); AddFunction("round", typeof(Math).GetMethod("Round", new[] { typeof(Decimal), typeof(int) })); AddFunction("ceil", typeof(Math).GetMethod("Ceiling", new[] { typeof(Double) })); AddFunction("ceil", typeof(Math).GetMethod("Ceiling", new[] { typeof(Decimal) })); AddFunction("trunc", typeof(Math).GetMethod("Truncate", new[] { typeof(Double) })); AddFunction("trunc", typeof(Math).GetMethod("Truncate", new[] { typeof(Decimal) })); AddFunction("sin", typeof(Math).GetMethod("Sin", new[] { typeof(double) })); AddFunction("cos", typeof(Math).GetMethod("Cos", new[] { typeof(double) })); AddFunction("tan", typeof(Math).GetMethod("Tan", new[] { typeof(double) })); AddFunction("asin", typeof(Math).GetMethod("Asin", new[] { typeof(double) })); AddFunction("acos", typeof(Math).GetMethod("Acos", new[] { typeof(double) })); AddFunction("atan", typeof(Math).GetMethod("Atan", new[] { typeof(double) })); AddFunction("atan2", typeof(Math).GetMethod("Atan2", new[] { typeof(double), typeof(double) })); AddFunction("sinh", typeof(Math).GetMethod("Sinh", new[] { typeof(double) })); AddFunction("cosh", typeof(Math).GetMethod("Cosh", new[] { typeof(double) })); AddFunction("tanh", typeof(Math).GetMethod("Tanh", new[] { typeof(double) })); AddFunction("exp", typeof(Math).GetMethod("Exp", new[] { typeof(double) })); AddFunction("log", typeof(Math).GetMethod("Log", new[] { typeof(double) })); AddFunction("log", typeof(Math).GetMethod("Log", new[] { typeof(double), typeof(double) })); AddFunction("log10", typeof(Math).GetMethod("Log10", new[] { typeof(double) })); AddFunction("sqrt", typeof(Math).GetMethod("Sqrt", new[] { typeof(double) })); AddFunction("rand", typeof(EvaluationContext).GetMethod("NextRandomNumber", new Type[0])); AddFunction("min", typeof(Math).GetMethod("Min", new[] { typeof(SByte), typeof(SByte) })); AddFunction("min", typeof(Math).GetMethod("Min", new[] { typeof(Byte), typeof(Byte) })); AddFunction("min", typeof(Math).GetMethod("Min", new[] { typeof(Int16), typeof(Int16) })); AddFunction("min", typeof(Math).GetMethod("Min", new[] { typeof(UInt16), typeof(UInt16) })); AddFunction("min", typeof(Math).GetMethod("Min", new[] { typeof(Int32), typeof(Int32) })); AddFunction("min", typeof(Math).GetMethod("Min", new[] { typeof(UInt32), typeof(UInt32) })); AddFunction("min", typeof(Math).GetMethod("Min", new[] { typeof(Int64), typeof(Int64) })); AddFunction("min", typeof(Math).GetMethod("Min", new[] { typeof(UInt64), typeof(UInt64) })); AddFunction("min", typeof(Math).GetMethod("Min", new[] { typeof(Single), typeof(Single) })); AddFunction("min", typeof(Math).GetMethod("Min", new[] { typeof(Double), typeof(Double) })); AddFunction("min", typeof(Math).GetMethod("Min", new[] { typeof(Decimal), typeof(Decimal) })); AddFunction("max", typeof(Math).GetMethod("Max", new[] { typeof(SByte), typeof(SByte) })); AddFunction("max", typeof(Math).GetMethod("Max", new[] { typeof(Byte), typeof(Byte) })); AddFunction("max", typeof(Math).GetMethod("Max", new[] { typeof(Int16), typeof(Int16) })); AddFunction("max", typeof(Math).GetMethod("Max", new[] { typeof(UInt16), typeof(UInt16) })); AddFunction("max", typeof(Math).GetMethod("Max", new[] { typeof(Int32), typeof(Int32) })); AddFunction("max", typeof(Math).GetMethod("Max", new[] { typeof(UInt32), typeof(UInt32) })); AddFunction("max", typeof(Math).GetMethod("Max", new[] { typeof(Int64), typeof(Int64) })); AddFunction("max", typeof(Math).GetMethod("Max", new[] { typeof(UInt64), typeof(UInt64) })); AddFunction("max", typeof(Math).GetMethod("Max", new[] { typeof(Single), typeof(Single) })); AddFunction("max", typeof(Math).GetMethod("Max", new[] { typeof(Double), typeof(Double) })); AddFunction("max", typeof(Math).GetMethod("Max", new[] { typeof(Decimal), typeof(Decimal) })); } /// <summary> /// Load a package for conversion between primitive types. /// </summary> public void LoadConversionPackage() { AddFunction("c_byte", typeof(Convert).GetMethod("ToByte", new[] { typeof(SByte) })); AddFunction("c_byte", typeof(Convert).GetMethod("ToByte", new[] { typeof(Byte) })); AddFunction("c_byte", typeof(Convert).GetMethod("ToByte", new[] { typeof(Int16) })); AddFunction("c_byte", typeof(Convert).GetMethod("ToByte", new[] { typeof(UInt16) })); AddFunction("c_byte", typeof(Convert).GetMethod("ToByte", new[] { typeof(Int32) })); AddFunction("c_byte", typeof(Convert).GetMethod("ToByte", new[] { typeof(UInt32) })); AddFunction("c_byte", typeof(Convert).GetMethod("ToByte", new[] { typeof(Int64) })); AddFunction("c_byte", typeof(Convert).GetMethod("ToByte", new[] { typeof(UInt64) })); AddFunction("c_byte", typeof(Convert).GetMethod("ToByte", new[] { typeof(Single) })); AddFunction("c_byte", typeof(Convert).GetMethod("ToByte", new[] { typeof(Double) })); AddFunction("c_byte", typeof(Convert).GetMethod("ToByte", new[] { typeof(Decimal) })); AddFunction("c_byte", typeof(Convert2).GetMethod("ParseByte", new[] { typeof(string) })); AddFunction("c_sbyte", typeof(Convert).GetMethod("ToSByte", new[] { typeof(SByte) })); AddFunction("c_sbyte", typeof(Convert).GetMethod("ToSByte", new[] { typeof(Byte) })); AddFunction("c_sbyte", typeof(Convert).GetMethod("ToSByte", new[] { typeof(Int16) })); AddFunction("c_sbyte", typeof(Convert).GetMethod("ToSByte", new[] { typeof(UInt16) })); AddFunction("c_sbyte", typeof(Convert).GetMethod("ToSByte", new[] { typeof(Int32) })); AddFunction("c_sbyte", typeof(Convert).GetMethod("ToSByte", new[] { typeof(UInt32) })); AddFunction("c_sbyte", typeof(Convert).GetMethod("ToSByte", new[] { typeof(Int64) })); AddFunction("c_sbyte", typeof(Convert).GetMethod("ToSByte", new[] { typeof(UInt64) })); AddFunction("c_sbyte", typeof(Convert).GetMethod("ToSByte", new[] { typeof(Single) })); AddFunction("c_sbyte", typeof(Convert).GetMethod("ToSByte", new[] { typeof(Double) })); AddFunction("c_sbyte", typeof(Convert).GetMethod("ToSByte", new[] { typeof(Decimal) })); AddFunction("c_sbyte", typeof(Convert2).GetMethod("ParseSByte", new[] { typeof(string) })); AddFunction("c_int16", typeof(Convert).GetMethod("ToInt16", new[] { typeof(SByte) })); AddFunction("c_int16", typeof(Convert).GetMethod("ToInt16", new[] { typeof(Byte) })); AddFunction("c_int16", typeof(Convert).GetMethod("ToInt16", new[] { typeof(Int16) })); AddFunction("c_int16", typeof(Convert).GetMethod("ToInt16", new[] { typeof(UInt16) })); AddFunction("c_int16", typeof(Convert).GetMethod("ToInt16", new[] { typeof(Int32) })); AddFunction("c_int16", typeof(Convert).GetMethod("ToInt16", new[] { typeof(UInt32) })); AddFunction("c_int16", typeof(Convert).GetMethod("ToInt16", new[] { typeof(Int64) })); AddFunction("c_int16", typeof(Convert).GetMethod("ToInt16", new[] { typeof(UInt64) })); AddFunction("c_int16", typeof(Convert).GetMethod("ToInt16", new[] { typeof(Single) })); AddFunction("c_int16", typeof(Convert).GetMethod("ToInt16", new[] { typeof(Double) })); AddFunction("c_int16", typeof(Convert).GetMethod("ToInt16", new[] { typeof(Decimal) })); AddFunction("c_int16", typeof(Convert2).GetMethod("ParseInt16", new[] { typeof(string) })); AddFunction("c_uint16", typeof(Convert).GetMethod("ToUInt16", new[] { typeof(SByte) })); AddFunction("c_uint16", typeof(Convert).GetMethod("ToUInt16", new[] { typeof(Byte) })); AddFunction("c_uint16", typeof(Convert).GetMethod("ToUInt16", new[] { typeof(Int16) })); AddFunction("c_uint16", typeof(Convert).GetMethod("ToUInt16", new[] { typeof(UInt16) })); AddFunction("c_uint16", typeof(Convert).GetMethod("ToUInt16", new[] { typeof(Int32) })); AddFunction("c_uint16", typeof(Convert).GetMethod("ToUInt16", new[] { typeof(UInt32) })); AddFunction("c_uint16", typeof(Convert).GetMethod("ToUInt16", new[] { typeof(Int64) })); AddFunction("c_uint16", typeof(Convert).GetMethod("ToUInt16", new[] { typeof(UInt64) })); AddFunction("c_uint16", typeof(Convert).GetMethod("ToUInt16", new[] { typeof(Single) })); AddFunction("c_uint16", typeof(Convert).GetMethod("ToUInt16", new[] { typeof(Double) })); AddFunction("c_uint16", typeof(Convert).GetMethod("ToUInt16", new[] { typeof(Decimal) })); AddFunction("c_uint16", typeof(Convert2).GetMethod("ParseUInt16", new[] { typeof(string) })); AddFunction("c_int32", typeof(Convert).GetMethod("ToInt32", new[] { typeof(SByte) })); AddFunction("c_int32", typeof(Convert).GetMethod("ToInt32", new[] { typeof(Byte) })); AddFunction("c_int32", typeof(Convert).GetMethod("ToInt32", new[] { typeof(Int16) })); AddFunction("c_int32", typeof(Convert).GetMethod("ToInt32", new[] { typeof(UInt16) })); AddFunction("c_int32", typeof(Convert).GetMethod("ToInt32", new[] { typeof(Int32) })); AddFunction("c_int32", typeof(Convert).GetMethod("ToInt32", new[] { typeof(UInt32) })); AddFunction("c_int32", typeof(Convert).GetMethod("ToInt32", new[] { typeof(Int64) })); AddFunction("c_int32", typeof(Convert).GetMethod("ToInt32", new[] { typeof(UInt64) })); AddFunction("c_int32", typeof(Convert).GetMethod("ToInt32", new[] { typeof(Single) })); AddFunction("c_int32", typeof(Convert).GetMethod("ToInt32", new[] { typeof(Double) })); AddFunction("c_int32", typeof(Convert).GetMethod("ToInt32", new[] { typeof(Decimal) })); AddFunction("c_int32", typeof(Convert2).GetMethod("ParseInt32", new[] { typeof(string) })); AddFunction("c_uint32", typeof(Convert).GetMethod("ToUInt32", new[] { typeof(SByte) })); AddFunction("c_uint32", typeof(Convert).GetMethod("ToUInt32", new[] { typeof(Byte) })); AddFunction("c_uint32", typeof(Convert).GetMethod("ToUInt32", new[] { typeof(Int16) })); AddFunction("c_uint32", typeof(Convert).GetMethod("ToUInt32", new[] { typeof(UInt16) })); AddFunction("c_uint32", typeof(Convert).GetMethod("ToUInt32", new[] { typeof(Int32) })); AddFunction("c_uint32", typeof(Convert).GetMethod("ToUInt32", new[] { typeof(UInt32) })); AddFunction("c_uint32", typeof(Convert).GetMethod("ToUInt32", new[] { typeof(Int64) })); AddFunction("c_uint32", typeof(Convert).GetMethod("ToUInt32", new[] { typeof(UInt64) })); AddFunction("c_uint32", typeof(Convert).GetMethod("ToUInt32", new[] { typeof(Single) })); AddFunction("c_uint32", typeof(Convert).GetMethod("ToUInt32", new[] { typeof(Double) })); AddFunction("c_uint32", typeof(Convert).GetMethod("ToUInt32", new[] { typeof(Decimal) })); AddFunction("c_uint32", typeof(Convert2).GetMethod("ParseUInt32", new[] { typeof(string) })); AddFunction("c_int64", typeof(Convert).GetMethod("ToInt64", new[] { typeof(SByte) })); AddFunction("c_int64", typeof(Convert).GetMethod("ToInt64", new[] { typeof(Byte) })); AddFunction("c_int64", typeof(Convert).GetMethod("ToInt64", new[] { typeof(Int16) })); AddFunction("c_int64", typeof(Convert).GetMethod("ToInt64", new[] { typeof(UInt16) })); AddFunction("c_int64", typeof(Convert).GetMethod("ToInt64", new[] { typeof(Int32) })); AddFunction("c_int64", typeof(Convert).GetMethod("ToInt64", new[] { typeof(UInt32) })); AddFunction("c_int64", typeof(Convert).GetMethod("ToInt64", new[] { typeof(Int64) })); AddFunction("c_int64", typeof(Convert).GetMethod("ToInt64", new[] { typeof(UInt64) })); AddFunction("c_int64", typeof(Convert).GetMethod("ToInt64", new[] { typeof(Single) })); AddFunction("c_int64", typeof(Convert).GetMethod("ToInt64", new[] { typeof(Double) })); AddFunction("c_int64", typeof(Convert).GetMethod("ToInt64", new[] { typeof(Decimal) })); AddFunction("c_int64", typeof(Convert2).GetMethod("ParseInt64", new[] { typeof(string) })); AddFunction("c_uint64", typeof(Convert).GetMethod("ToUInt64", new[] { typeof(SByte) })); AddFunction("c_uint64", typeof(Convert).GetMethod("ToUInt64", new[] { typeof(Byte) })); AddFunction("c_uint64", typeof(Convert).GetMethod("ToUInt64", new[] { typeof(Int16) })); AddFunction("c_uint64", typeof(Convert).GetMethod("ToUInt64", new[] { typeof(UInt16) })); AddFunction("c_uint64", typeof(Convert).GetMethod("ToUInt64", new[] { typeof(Int32) })); AddFunction("c_uint64", typeof(Convert).GetMethod("ToUInt64", new[] { typeof(UInt32) })); AddFunction("c_uint64", typeof(Convert).GetMethod("ToUInt64", new[] { typeof(Int64) })); AddFunction("c_uint64", typeof(Convert).GetMethod("ToUInt64", new[] { typeof(UInt64) })); AddFunction("c_uint64", typeof(Convert).GetMethod("ToUInt64", new[] { typeof(Single) })); AddFunction("c_uint64", typeof(Convert).GetMethod("ToUInt64", new[] { typeof(Double) })); AddFunction("c_uint64", typeof(Convert).GetMethod("ToUInt64", new[] { typeof(Decimal) })); AddFunction("c_uint64", typeof(Convert2).GetMethod("ParseUInt64", new[] { typeof(string) })); AddFunction("c_single", typeof(Convert).GetMethod("ToSingle", new[] { typeof(SByte) })); AddFunction("c_single", typeof(Convert).GetMethod("ToSingle", new[] { typeof(Byte) })); AddFunction("c_single", typeof(Convert).GetMethod("ToSingle", new[] { typeof(Int16) })); AddFunction("c_single", typeof(Convert).GetMethod("ToSingle", new[] { typeof(UInt16) })); AddFunction("c_single", typeof(Convert).GetMethod("ToSingle", new[] { typeof(Int32) })); AddFunction("c_single", typeof(Convert).GetMethod("ToSingle", new[] { typeof(UInt32) })); AddFunction("c_single", typeof(Convert).GetMethod("ToSingle", new[] { typeof(Int64) })); AddFunction("c_single", typeof(Convert).GetMethod("ToSingle", new[] { typeof(UInt64) })); AddFunction("c_single", typeof(Convert).GetMethod("ToSingle", new[] { typeof(Single) })); AddFunction("c_single", typeof(Convert).GetMethod("ToSingle", new[] { typeof(Double) })); AddFunction("c_single", typeof(Convert).GetMethod("ToSingle", new[] { typeof(Decimal) })); AddFunction("c_single", typeof(Convert2).GetMethod("ParseSingle", new[] { typeof(string) })); AddFunction("c_double", typeof(Convert).GetMethod("ToDouble", new[] { typeof(SByte) })); AddFunction("c_double", typeof(Convert).GetMethod("ToDouble", new[] { typeof(Byte) })); AddFunction("c_double", typeof(Convert).GetMethod("ToDouble", new[] { typeof(Int16) })); AddFunction("c_double", typeof(Convert).GetMethod("ToDouble", new[] { typeof(UInt16) })); AddFunction("c_double", typeof(Convert).GetMethod("ToDouble", new[] { typeof(Int32) })); AddFunction("c_double", typeof(Convert).GetMethod("ToDouble", new[] { typeof(UInt32) })); AddFunction("c_double", typeof(Convert).GetMethod("ToDouble", new[] { typeof(Int64) })); AddFunction("c_double", typeof(Convert).GetMethod("ToDouble", new[] { typeof(UInt64) })); AddFunction("c_double", typeof(Convert).GetMethod("ToDouble", new[] { typeof(Single) })); AddFunction("c_double", typeof(Convert).GetMethod("ToDouble", new[] { typeof(Double) })); AddFunction("c_double", typeof(Convert).GetMethod("ToDouble", new[] { typeof(Decimal) })); AddFunction("c_double", typeof(Convert2).GetMethod("ParseDouble", new[] { typeof(string) })); AddFunction("c_decimal", typeof(Convert).GetMethod("ToDecimal", new[] { typeof(SByte) })); AddFunction("c_decimal", typeof(Convert).GetMethod("ToDecimal", new[] { typeof(Byte) })); AddFunction("c_decimal", typeof(Convert).GetMethod("ToDecimal", new[] { typeof(Int16) })); AddFunction("c_decimal", typeof(Convert).GetMethod("ToDecimal", new[] { typeof(UInt16) })); AddFunction("c_decimal", typeof(Convert).GetMethod("ToDecimal", new[] { typeof(Int32) })); AddFunction("c_decimal", typeof(Convert).GetMethod("ToDecimal", new[] { typeof(UInt32) })); AddFunction("c_decimal", typeof(Convert).GetMethod("ToDecimal", new[] { typeof(Int64) })); AddFunction("c_decimal", typeof(Convert).GetMethod("ToDecimal", new[] { typeof(UInt64) })); AddFunction("c_decimal", typeof(Convert).GetMethod("ToDecimal", new[] { typeof(Single) })); AddFunction("c_decimal", typeof(Convert).GetMethod("ToDecimal", new[] { typeof(Double) })); AddFunction("c_decimal", typeof(Convert).GetMethod("ToDecimal", new[] { typeof(Decimal) })); AddFunction("c_decimal", typeof(Convert2).GetMethod("ParseDecimal", new[] { typeof(string) })); AddFunction("c_str", typeof(Convert2).GetMethod("SByteToString", new[] { typeof(SByte) })); AddFunction("c_str", typeof(Convert2).GetMethod("ByteToString", new[] { typeof(Byte) })); AddFunction("c_str", typeof(Convert2).GetMethod("Int16ToString", new[] { typeof(Int16) })); AddFunction("c_str", typeof(Convert2).GetMethod("UInt16ToString", new[] { typeof(UInt16) })); AddFunction("c_str", typeof(Convert2).GetMethod("Int32ToString", new[] { typeof(Int32) })); AddFunction("c_str", typeof(Convert2).GetMethod("UInt32ToString", new[] { typeof(UInt32) })); AddFunction("c_str", typeof(Convert2).GetMethod("Int64ToString", new[] { typeof(Int64) })); AddFunction("c_str", typeof(Convert2).GetMethod("UInt64ToString", new[] { typeof(UInt64) })); AddFunction("c_str", typeof(Convert2).GetMethod("SingleToString", new[] { typeof(Single) })); AddFunction("c_str", typeof(Convert2).GetMethod("DoubleToString", new[] { typeof(Double) })); AddFunction("c_str", typeof(Convert2).GetMethod("DecimalToString", new[] { typeof(Decimal) })); AddFunction("c_str", typeof(Convert2).GetMethod("BooleanToString", new[] { typeof(bool) })); AddFunction("c_str", typeof(Convert2).GetMethod("DateTimeToString", new[] { typeof(DateTime) })); AddFunction("c_str", typeof(Convert2).GetMethod("StringToString", new[] { typeof(string) })); AddFunction("c_str", typeof(Convert2).GetMethod("ObjectToString", new[] { typeof(object) })); } /// <summary> /// Load the package with functions for string manipulation. /// </summary> public void LoadStringPackage() { AddFunction("len", typeof(Strings).GetMethod("Length", new[] { typeof(string) })); AddFunction("to_lower", typeof(Strings).GetMethod("ToLower", new[] { typeof(string) })); AddFunction("to_upper", typeof(Strings).GetMethod("ToUpper", new[] { typeof(string) })); AddFunction("trim", typeof(Strings).GetMethod("Trim", new[] { typeof(string) })); AddFunction("trim_start", typeof(Strings).GetMethod("TrimStart", new[] { typeof(string) })); AddFunction("trim_end", typeof(Strings).GetMethod("TrimEnd", new[] { typeof(string) })); AddFunction("substr", typeof(Strings).GetMethod("Substr", new[] { typeof(string), typeof(int) })); AddFunction("substr", typeof(Strings).GetMethod("Substr", new[] { typeof(string), typeof(int), typeof(int) })); AddFunction("left", typeof(Strings).GetMethod("Left", new[] { typeof(string), typeof(int) })); AddFunction("right", typeof(Strings).GetMethod("Right", new[] { typeof(string), typeof(int) })); AddFunction("remove", typeof(Strings).GetMethod("Remove", new[] { typeof(string), typeof(int) })); AddFunction("remove", typeof(Strings).GetMethod("Remove", new[] { typeof(string), typeof(int), typeof(int) })); AddFunction("replace", typeof(Strings).GetMethod("Replace", new[] { typeof(string), typeof(string), typeof(string) })); AddFunction("find", typeof(Strings).GetMethod("Find", new[] { typeof(string), typeof(string) })); AddFunction("find", typeof(Strings).GetMethod("Find", new[] { typeof(string), typeof(string), typeof(int) })); AddFunction("find", typeof(Strings).GetMethod("Find", new[] { typeof(string), typeof(string), typeof(int), typeof(int) })); AddFunction("find_i", typeof(Strings).GetMethod("FindIgnoreCase", new[] { typeof(string), typeof(string) })); AddFunction("find_i", typeof(Strings).GetMethod("FindIgnoreCase", new[] { typeof(string), typeof(string), typeof(int) })); AddFunction("find_i", typeof(Strings).GetMethod("FindIgnoreCase", new[] { typeof(string), typeof(string), typeof(int), typeof(int) })); AddFunction("find_last", typeof(Strings).GetMethod("FindLast", new[] { typeof(string), typeof(string) })); AddFunction("find_last", typeof(Strings).GetMethod("FindLast", new[] { typeof(string), typeof(string), typeof(int) })); AddFunction("find_last", typeof(Strings).GetMethod("FindLast", new[] { typeof(string), typeof(string), typeof(int), typeof(int) })); AddFunction("find_last_i", typeof(Strings).GetMethod("FindLastIgnoreCase", new[] { typeof(string), typeof(string) })); AddFunction("find_last_i", typeof(Strings).GetMethod("FindLastIgnoreCase", new[] { typeof(string), typeof(string), typeof(int) })); AddFunction("find_last_i", typeof(Strings).GetMethod("FindLastIgnoreCase", new[] { typeof(string), typeof(string), typeof(int), typeof(int) })); AddFunction("contains", typeof(Strings).GetMethod("Contains", new[] { typeof(string), typeof(string) })); AddFunction("starts_with", typeof(Strings).GetMethod("StartsWith", new[] { typeof(string), typeof(string) })); AddFunction("ends_with", typeof(Strings).GetMethod("EndsWith", new[] { typeof(string), typeof(string) })); AddFunction("min", typeof(Strings).GetMethod("Min", new[] { typeof(string), typeof(string) })); AddFunction("max", typeof(Strings).GetMethod("Max", new[] { typeof(string), typeof(string) })); AddFunction("min_i", typeof(Strings).GetMethod("MinIgnoreCase", new[] { typeof(string), typeof(string) })); AddFunction("max_i", typeof(Strings).GetMethod("MaxIgnoreCase", new[] { typeof(string), typeof(string) })); } /// <summary> /// Load the package for regular expressions. /// </summary> public void LoadRegexPackage() { AddFunction("regex", typeof(Regex).GetMethod("IsMatch", new[] { typeof(string), typeof(string) })); AddFunction("regex_match", typeof(Strings).GetMethod("RegexMatch", new[] { typeof(string), typeof(string) })); AddFunction("regex_replace", typeof(Regex).GetMethod("Replace", new[] { typeof(string), typeof(string), typeof(string) })); } #endregion #region Parsing, Compiling, Evaluating private readonly Grammar grammar = new Grammar(); internal Grammar Grammar { get { return grammar; } } /// <summary> /// Gets and sets the language options. /// </summary> public LanguageOptions Options { get { return grammar.Options; } set { if (grammar.Options == value) return; grammar.Options = value; cachedParser = null; InitializeLookupTables(); } } private Parser<ExpressionElement> cachedParser; /// <summary> /// Parse the given expression string, build the abstract syntax tree /// (represented by the returned <see cref="ExpressionElement"/>) and check /// the tree for semantic errors. /// </summary> /// <param name="input">The expression string.</param> /// <returns>The root of the abstract syntax tree.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public ExpressionElement ParseAndCheckExpression(string input) { ExpressionElement element; if (cachedParser == null) { cachedParser = grammar.Expression.End(); } try { element = cachedParser.Parse(input); } catch (Exception ex) { throw new SyntaxErrorException("Syntax error.", ex); } var sb = new StringBuilder(); if (!element.CheckSemantic(this, sb)) { throw new SemanticErrorException(sb.ToString()); } return element; } private void CheckParameters(Type[] argTypes) { var parameters = ParameterExpressions.ToArray(); if (parameters.Length != argTypes.Length) { throw new SemanticErrorException("The number of parameters does not match the evaluation context."); } for (var i = 0; i < parameters.Length; i++) { if (parameters[i].Type != argTypes[i]) { throw new SemanticErrorException(string.Format("The type of parameter '{0}' does not match.", parameters[i].Name)); } } } /// <summary> /// Parses, checks and compiles an expression string to a lambda with <see cref="Object"/> as return type. /// </summary> /// <remarks>Calls <see cref="ParseAndCheckExpression"/> before compilation.</remarks> /// <param name="input">The expression string.</param> /// <returns>A lambda delegate of the compilation result.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public Func<object> CompileExpression(string input) { var model = ParseAndCheckExpression(input); CheckParameters(new Type[0]); var expr = model.GetExpression(this); try { if (expr.Type != typeof(object)) { expr = Expression.Convert(expr, typeof(object)); } var lambda = Expression.Lambda<Func<object>>(expr); return lambda.Compile(); } catch (Exception ex) { throw new SemanticErrorException("Error compiling the expression.", ex); } } /// <summary> /// Parses, checks and compiles an expression string with the return type <typeparamref name="TResult"/>. /// </summary> /// <remarks>Calls <see cref="ParseAndCheckExpression"/> before compilation.</remarks> /// <param name="input">The expression string.</param> /// <returns>A lambda delegate of the compilation result.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public Func<TResult> CompileExpression<TResult>(string input) { var model = ParseAndCheckExpression(input); CheckParameters(new Type[0]); var expr = model.GetExpression(this); try { if (expr.Type != typeof(TResult)) { expr = Expression.ConvertChecked(expr, typeof(TResult)); } var lambda = Expression.Lambda<Func<TResult>>(expr); return lambda.Compile(); } catch (Exception ex) { throw new SemanticErrorException("Error compiling the expression.", ex); } } /// <summary> /// Parses, checks and compiles an expression string with the return type <typeparamref name="TResult"/>. /// </summary> /// <remarks>Calls <see cref="ParseAndCheckExpression"/> before compilation.</remarks> /// <param name="input">The expression string.</param> /// <returns>A lambda delegate of the compilation result.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public Func<T1, TResult> CompileExpression<T1, TResult>(string input) { var model = ParseAndCheckExpression(input); CheckParameters(new[] { typeof(T1) }); var expr = model.GetExpression(this); try { if (expr.Type != typeof(TResult)) { expr = Expression.ConvertChecked(expr, typeof(TResult)); } var parameterExpressions = ParameterExpressions.ToArray(); var lambda = Expression.Lambda<Func<T1, TResult>>(expr, parameterExpressions); return lambda.Compile(); } catch (Exception ex) { throw new SemanticErrorException("Error compiling the expression.", ex); } } /// <summary> /// Parses, checks and compiles an expression string with the return type <typeparamref name="TResult"/>. /// </summary> /// <remarks>Calls <see cref="ParseAndCheckExpression"/> before compilation.</remarks> /// <param name="input">The expression string.</param> /// <returns>A lambda delegate of the compilation result.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public Func<T1, T2, TResult> CompileExpression<T1, T2, TResult>(string input) { var model = ParseAndCheckExpression(input); CheckParameters(new[] { typeof(T1), typeof(T2) }); var expr = model.GetExpression(this); try { if (expr.Type != typeof(TResult)) { expr = Expression.ConvertChecked(expr, typeof(TResult)); } var lambda = Expression.Lambda<Func<T1, T2, TResult>>(expr, ParameterExpressions); return lambda.Compile(); } catch (Exception ex) { throw new SemanticErrorException("Error compiling the expression.", ex); } } /// <summary> /// Parses, checks and compiles an expression string with the return type <typeparamref name="TResult"/>. /// </summary> /// <remarks>Calls <see cref="ParseAndCheckExpression"/> before compilation.</remarks> /// <param name="input">The expression string.</param> /// <returns>A lambda delegate of the compilation result.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public Func<T1, T2, T3, TResult> CompileExpression<T1, T2, T3, TResult>(string input) { var model = ParseAndCheckExpression(input); CheckParameters(new[] { typeof(T1), typeof(T2), typeof(T3) }); var expr = model.GetExpression(this); try { if (expr.Type != typeof(TResult)) { expr = Expression.ConvertChecked(expr, typeof(TResult)); } var lambda = Expression.Lambda<Func<T1, T2, T3, TResult>>(expr, ParameterExpressions); return lambda.Compile(); } catch (Exception ex) { throw new SemanticErrorException("Error compiling the expression.", ex); } } /// <summary> /// Parses, checks and compiles an expression string with the return type <typeparamref name="TResult"/>. /// </summary> /// <remarks>Calls <see cref="ParseAndCheckExpression"/> before compilation.</remarks> /// <param name="input">The expression string.</param> /// <returns>A lambda delegate of the compilation result.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public Func<T1, T2, T3, T4, TResult> CompileExpression<T1, T2, T3, T4, TResult>(string input) { var model = ParseAndCheckExpression(input); CheckParameters(new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }); var expr = model.GetExpression(this); try { if (expr.Type != typeof(TResult)) { expr = Expression.ConvertChecked(expr, typeof(TResult)); } var lambda = Expression.Lambda<Func<T1, T2, T3, T4, TResult>>(expr, ParameterExpressions); return lambda.Compile(); } catch (Exception ex) { throw new SemanticErrorException("Error compiling the expression.", ex); } } /// <summary> /// Parses, checks and compiles an expression string with the return type <typeparamref name="TResult"/>. /// </summary> /// <remarks>Calls <see cref="ParseAndCheckExpression"/> before compilation.</remarks> /// <param name="input">The expression string.</param> /// <returns>A lambda delegate of the compilation result.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public Func<T1, T2, T3, T4, T5, TResult> CompileExpression<T1, T2, T3, T4, T5, TResult>(string input) { var model = ParseAndCheckExpression(input); CheckParameters(new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }); var expr = model.GetExpression(this); try { if (expr.Type != typeof(TResult)) { expr = Expression.ConvertChecked(expr, typeof(TResult)); } var lambda = Expression.Lambda<Func<T1, T2, T3, T4, T5, TResult>>(expr, ParameterExpressions); return lambda.Compile(); } catch (Exception ex) { throw new SemanticErrorException("Error compiling the expression.", ex); } } /// <summary> /// Parses, checks and compiles an expression string with the return type <typeparamref name="TResult"/>. /// </summary> /// <remarks>Calls <see cref="ParseAndCheckExpression"/> before compilation.</remarks> /// <param name="input">The expression string.</param> /// <returns>A lambda delegate of the compilation result.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public Func<T1, T2, T3, T4, T5, T6, TResult> CompileExpression<T1, T2, T3, T4, T5, T6, TResult>(string input) { var model = ParseAndCheckExpression(input); CheckParameters(new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) }); var expr = model.GetExpression(this); try { if (expr.Type != typeof(TResult)) { expr = Expression.ConvertChecked(expr, typeof(TResult)); } var lambda = Expression.Lambda<Func<T1, T2, T3, T4, T5, T6, TResult>>(expr, ParameterExpressions); return lambda.Compile(); } catch (Exception ex) { throw new SemanticErrorException("Error compiling the expression.", ex); } } /// <summary> /// Parses, checks and compiles an expression string with the return type <typeparamref name="TResult"/>. /// </summary> /// <remarks>Calls <see cref="ParseAndCheckExpression"/> before compilation.</remarks> /// <param name="input">The expression string.</param> /// <returns>A lambda delegate of the compilation result.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public Func<T1, T2, T3, T4, T5, T6, T7, TResult> CompileExpression<T1, T2, T3, T4, T5, T6, T7, TResult>(string input) { var model = ParseAndCheckExpression(input); CheckParameters(new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7) }); var expr = model.GetExpression(this); try { if (expr.Type != typeof(TResult)) { expr = Expression.ConvertChecked(expr, typeof(TResult)); } var lambda = Expression.Lambda<Func<T1, T2, T3, T4, T5, T6, T7, TResult>>(expr, ParameterExpressions); return lambda.Compile(); } catch (Exception ex) { throw new SemanticErrorException("Error compiling the expression.", ex); } } /// <summary> /// Parses, checks and compiles an expression string with the return type <typeparamref name="TResult"/>. /// </summary> /// <remarks>Calls <see cref="ParseAndCheckExpression"/> before compilation.</remarks> /// <param name="input">The expression string.</param> /// <returns>A lambda delegate of the compilation result.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> CompileExpression<T1, T2, T3, T4, T5, T6, T7, T8, TResult>(string input) { var model = ParseAndCheckExpression(input); CheckParameters(new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8) }); var expr = model.GetExpression(this); try { if (expr.Type != typeof(TResult)) { expr = Expression.ConvertChecked(expr, typeof(TResult)); } var lambda = Expression.Lambda<Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult>>(expr, ParameterExpressions); return lambda.Compile(); } catch (Exception ex) { throw new SemanticErrorException("Error compiling the expression.", ex); } } /// <summary> /// Parses, checks, compiles and calls an expression string. /// </summary> /// <remarks>Calls <see cref="CompileExpression"/> before evaluating.</remarks> /// <param name="expression">The expression string.</param> /// <returns>The resulting value of the expression.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public object EvaluateExpression(string expression) { return CompileExpression(expression)(); } /// <summary> /// Parses, checks, compiles and calls an expression string. /// </summary> /// <remarks>Calls <see cref="CompileExpression"/> before evaluating.</remarks> /// <param name="expression">The expression string.</param> /// <param name="p1">The first parameter value for the evaluation.</param> /// <returns>The resulting value of the expression.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public object EvaluateExpression<T1>(string expression, T1 p1) { return CompileExpression<T1, object>(expression)(p1); } /// <summary> /// Parses, checks, compiles and calls an expression string. /// </summary> /// <remarks>Calls <see cref="CompileExpression"/> before evaluating.</remarks> /// <param name="expression">The expression string.</param> /// <param name="p1">The first parameter value for the evaluation.</param> /// <param name="p2">The second parameter value for the evaluation.</param> /// <returns>The resulting value of the expression.</returns> /// <exception cref="SyntaxErrorException">Is thrown, if the expression has syntax errors.</exception> /// <exception cref="SemanticErrorException">Is thrown, if the expression has semantic errors.</exception> public object EvaluateExpression<T1, T2>(string expression, T1 p1, T2 p2) { return CompileExpression<T1, T2, object>(expression)(p1, p2); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Microsoft.SharePoint; // ReSharper disable once CheckNamespace namespace SharepointCommon { /// <summary> /// Represents wrapper on a SharePoint list or library /// </summary> /// <typeparam name="T">Item or ContentType of list item</typeparam> public interface IQueryList<T> where T : Item, new() { /// <summary> /// Gets reference of parent <see cref="IQueryWeb" /> object /// </summary> IQueryWeb ParentWeb { get; } /// <summary> /// Gets underlying list instance /// </summary> SPList List { get; } /// <summary> /// Gets the SPList id. /// </summary> Guid Id { get; } /// <summary> /// Gets the SPWeb id. /// </summary> Guid WebId { get; } /// <summary> /// Gets the SPSite id. /// </summary> Guid SiteId { get; } /// <summary> /// Gets or sets the SPList title. /// </summary> /// <value> /// The title. /// </value> string Title { get; set; } /// <summary> /// Gets or sets a value indicating whether this list is versioning enabled. /// </summary> /// <value> /// <c>true</c> if this list is versioning enabled; otherwise, <c>false</c>. /// </value> bool IsVersioningEnabled { get; set; } /// <summary> /// Gets or sets a value indicating whether this list is folder creation allowed. /// </summary> /// <value> /// <c>true</c> if this list is folder creation allowed; otherwise, <c>false</c>. /// </value> bool IsFolderCreationAllowed { get; set; } /// <summary> /// Gets or sets a value indicating whether list allows to manage content types. /// </summary> /// <value> /// <c>true</c> if list allows manage content types; otherwise, <c>false</c>. /// </value> bool AllowManageContentTypes { get; set; } /// <summary> /// Gets the full url of list. Ex: http://server/lists/list1 /// </summary> string Url { get; } /// <summary> /// Gets the relative url of list. Ex: /lists/list1 /// </summary> string RelativeUrl { get; } /// <summary> /// Registers list event receiver /// </summary> /// <typeparam name="TEventReceiver">Type inherited from <see cref="ListEventReceiver{T}"/></typeparam> void AddEventReceiver<TEventReceiver>() where TEventReceiver : ListEventReceiver<T>; /// <summary> /// Removes list event receiver /// </summary> /// <typeparam name="TEventReceiver">Type inherited from <see cref="ListEventReceiver{T}"/></typeparam> void RemoveEventReceiver<TEventReceiver>() where TEventReceiver : ListEventReceiver<T>; /// <summary> /// Gets the url of specific list form /// </summary> /// <param name="pageType">Type of the page.</param> /// <param name="id">The id of item</param> /// <param name="isDlg">Add 'isDlg=1' to form url</param> /// <returns>Url of list form with item id</returns> string FormUrl(PageType pageType, int id = 0, bool isDlg = false); /// <summary> /// Adds new list item to the list /// </summary> /// <param name="entity">instance of entity that represents new item</param> void Add(T entity); /// <summary> /// Updates specified field of existing item by data of entity /// </summary> /// <param name="entity">The entity instance.</param> /// <param name="incrementVersion">if set to <c>true</c>increments item version.</param> /// <param name="selectors">Expressions used to enumerate fields been updated. Ex: e => e.Title</param> void Update(T entity, bool incrementVersion, params Expression<Func<T, object>>[] selectors); /// <summary> /// /// </summary> /// <param name="entity"></param> /// <param name="fieldSelector"></param> /// <param name="valueToSet"></param> /// <param name="incrementVersion"></param> void UpdateField(T entity, Expression<Func<T, object>> fieldSelector, object valueToSet, bool incrementVersion = true); /// <summary> /// Deletes the specified entity. /// </summary> /// <param name="entity">The entity.</param> /// <param name="recycle">if set to <c>true</c> to move in recycle bin.</param> void Delete(T entity, bool recycle); /// <summary> /// Deletes item by the specified id. /// </summary> /// <param name="id">The id.</param> /// <param name="recycle">if set to <c>true</c> to move recycle bin.</param> void Delete(int id, bool recycle); /// <summary> /// Gets item by specified id. /// </summary> /// <param name="id">The item id.</param> /// <returns>List item instance.</returns> T ById(int id); /// <summary> /// Gets item of specified content type by id /// </summary> /// <typeparam name="TCt">Type of entity, represents content type (marked with [ContentType])</typeparam> /// <param name="id">The item id.</param> /// <returns>List item instance.</returns> TCt ById<TCt>(int id) where TCt : Item, new(); /// <summary> /// Gets item by specified Guid (field 'GUID' not equals to 'UniqueId') /// </summary> /// <param name="id"></param> /// <returns>List item instance.</returns> T ByGuid(Guid id); /// <summary> /// Gets item by specified content type Guid (field 'GUID' not equals to 'UniqueId') /// </summary> /// <typeparam name="TCt">Type of entity, represents content type (marked with [ContentType])</typeparam> /// <param name="id">the item id.</param> /// <returns>List item instance.</returns> TCt ByGuid<TCt>(Guid id) where TCt : Item, new(); /// <summary> /// Gets items by value of specified field. /// </summary> /// <typeparam name="TR">type of value</typeparam> /// <param name="selector">Expression used to point needed field. Ex: e=>e.Title</param> /// <param name="value">value to filter items</param> /// <returns>items, which have specified value in specified field.</returns> IEnumerable<T> ByField<TR>(Expression<Func<T, TR>> selector, TR value); /// <summary> /// Gets items filtered by specified options /// </summary> /// <param name="option">The option used to filter items.</param> /// <returns>items by query</returns> IEnumerable<T> Items(CamlQuery option); /// <summary> /// Gets items of specified content type, filtered by specified options. /// </summary> /// <typeparam name="TCt">Type of entity, represents content type (marked with [ContentType])</typeparam> /// <param name="option">The option used to filter items.</param> /// <returns>items by query.</returns> IEnumerable<TCt> Items<TCt>(CamlQuery option) where TCt : Item, new(); IOrderedQueryable<T> Items(); /// <summary> /// Deletes the list. /// </summary> /// <param name="recycle">if set to <c>true</c> to recycle list.</param> void DeleteList(bool recycle); /// <summary> /// Check that all fields of '<typeparamref name="T"/>' are exists in list. /// If at least one of fields not exists, throw exception. /// </summary> /// <exception cref="SharepointCommonException"></exception> void CheckFields(); /// <summary> /// Check that all fields of '<typeparamref name="T"/>' are exists in list. /// If some of fields not exists in list, creates it. /// </summary> void EnsureFields(); /// <summary> /// Ensure field in list.(Skip if exists, Create if not exists) /// </summary> /// <param name="selector">Expression used to point needed field. Ex: e=>e.Title</param> void EnsureField(Expression<Func<T, object>> selector); /// <summary> /// Determines whether the specified field contains in list. /// </summary> /// <param name="selector">Expression used to point needed field. Ex: e=>e.Title</param> /// <returns> /// <c>true</c> if the specified selector contains field; otherwise, <c>false</c>. /// </returns> bool ContainsField(Expression<Func<T, object>> selector); /// <summary> /// Gets the wrapper for SPField. /// </summary> /// <param name="selector">Expression used to point needed field. Ex: e=>e.Title</param> /// <returns>field wrapper</returns> Field GetField(Expression<Func<T, object>> selector); /// <summary> /// Gets the wrapper collection for list fields. /// </summary> /// <param name="onlyCustom">if set to <c>true</c> only custom fields; otherwise all fields.</param> /// <returns></returns> IEnumerable<Field> GetFields(bool onlyCustom); /// <summary> /// Adds the specified content type to list. /// </summary> /// <typeparam name="TCt">Type of entity, represents content type (marked with [ContentType]).</typeparam> void AddContentType<TCt>() where TCt : Item, new(); /// <summary> /// Determines whether list contains specified content type. /// </summary> /// <typeparam name="TCt">Type of entity, represents content type (marked with [ContentType])</typeparam> /// <returns> /// <c>true</c> if [contains content type]; otherwise, <c>false</c>. /// </returns> bool ContainsContentType<TCt>() where TCt : Item, new(); /// <summary> /// Removes the specified content type from list. /// </summary> /// <typeparam name="TCt">Type of entity, represents content type (marked with [ContentType])</typeparam> void RemoveContentType<TCt>() where TCt : Item, new(); } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.IO; using System.Linq; using System.Reflection; using NLog.Common; /// <summary> /// Helpers for <see cref="Assembly"/>. /// </summary> internal static class AssemblyHelpers { #if !NETSTANDARD1_3 /// <summary> /// Load from url /// </summary> /// <param name="assemblyFileName">file or path, including .dll</param> /// <param name="baseDirectory">basepath, optional</param> /// <returns></returns> public static Assembly LoadFromPath(string assemblyFileName, string baseDirectory = null) { string fullFileName = baseDirectory is null ? assemblyFileName : Path.Combine(baseDirectory, assemblyFileName); InternalLogger.Info("Loading assembly file: {0}", fullFileName); #if NETSTANDARD1_5 try { var assemblyName = System.Runtime.Loader.AssemblyLoadContext.GetAssemblyName(fullFileName); return Assembly.Load(assemblyName); } catch (Exception ex) { // this doesn't usually work InternalLogger.Warn(ex, "Fallback to AssemblyLoadContext.Default.LoadFromAssemblyPath for file: {0}", fullFileName); return System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(fullFileName); } #else Assembly asm = Assembly.LoadFrom(fullFileName); return asm; #endif } #endif /// <summary> /// Load from url /// </summary> /// <param name="assemblyName">name without .dll</param> /// <returns></returns> public static Assembly LoadFromName(string assemblyName) { InternalLogger.Info("Loading assembly: {0}", assemblyName); #if !NETSTANDARD1_3 && !NETSTANDARD1_5 try { Assembly assembly = Assembly.Load(assemblyName); return assembly; } catch (FileNotFoundException) { var name = new AssemblyName(assemblyName); InternalLogger.Trace("Try find '{0}' in current domain", assemblyName); var loadedAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(domainAssembly => IsAssemblyMatch(name, domainAssembly.GetName())); if (loadedAssembly != null) { InternalLogger.Trace("Found '{0}' in current domain", assemblyName); return loadedAssembly; } InternalLogger.Trace("Haven't found' '{0}' in current domain", assemblyName); throw; } #else var name = new AssemblyName(assemblyName); return Assembly.Load(name); #endif } private static bool IsAssemblyMatch(AssemblyName expected, AssemblyName actual) { if (expected.Name != actual.Name) return false; if (expected.Version != null && expected.Version != actual.Version) return false; #if !NETSTANDARD1_3 && !NETSTANDARD1_5 if (expected.CultureInfo != null && expected.CultureInfo.Name != actual.CultureInfo.Name) return false; #endif var expectedKeyToken = expected.GetPublicKeyToken(); var correctToken = expectedKeyToken is null || expectedKeyToken.SequenceEqual(actual.GetPublicKeyToken()); return correctToken; } #if !NETSTANDARD1_3 public static string GetAssemblyFileLocation(Assembly assembly) { string fullName = string.Empty; try { if (assembly is null) { return string.Empty; } fullName = assembly.FullName; #if NETSTANDARD if (string.IsNullOrEmpty(assembly.Location)) { // Assembly with no actual location should be skipped (Avoid PlatformNotSupportedException) InternalLogger.Debug("Ignoring assembly location because location is empty: {0}", fullName); return string.Empty; } #endif Uri assemblyCodeBase; if (!Uri.TryCreate(assembly.CodeBase, UriKind.RelativeOrAbsolute, out assemblyCodeBase)) { InternalLogger.Debug("Ignoring assembly location because code base is unknown: '{0}' ({1})", assembly.CodeBase, fullName); return string.Empty; } var assemblyLocation = Path.GetDirectoryName(assemblyCodeBase.LocalPath); if (string.IsNullOrEmpty(assemblyLocation)) { InternalLogger.Debug("Ignoring assembly location because it is not a valid directory: '{0}' ({1})", assemblyCodeBase.LocalPath, fullName); return string.Empty; } DirectoryInfo directoryInfo = new DirectoryInfo(assemblyLocation); if (!directoryInfo.Exists) { InternalLogger.Debug("Ignoring assembly location because directory doesn't exists: '{0}' ({1})", assemblyLocation, fullName); return string.Empty; } InternalLogger.Debug("Found assembly location directory: '{0}' ({1})", directoryInfo.FullName, fullName); return directoryInfo.FullName; } catch (System.PlatformNotSupportedException ex) { InternalLogger.Warn(ex, "Ignoring assembly location because assembly lookup is not supported: {0}", fullName); if (ex.MustBeRethrown()) { throw; } return string.Empty; } catch (System.Security.SecurityException ex) { InternalLogger.Warn(ex, "Ignoring assembly location because assembly lookup is not allowed: {0}", fullName); if (ex.MustBeRethrown()) { throw; } return string.Empty; } catch (UnauthorizedAccessException ex) { InternalLogger.Warn(ex, "Ignoring assembly location because assembly lookup is not allowed: {0}", fullName); if (ex.MustBeRethrown()) { throw; } return string.Empty; } } #endif } }
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.SwaggerGen; using HETSAPI.Models; using HETSAPI.ViewModels; using HETSAPI.Services; using HETSAPI.Authorization; namespace HETSAPI.Controllers { /// <summary> /// User Controller /// </summary> [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public class UserController : Controller { private readonly IUserService _service; /// <summary> /// User Controller Constructor /// </summary> public UserController(IUserService service) { _service = service; } /// <summary> /// Create bulk users /// </summary> /// <param name="items"></param> /// <response code="200">User created</response> [HttpPost] [Route("/api/users/bulk")] [SwaggerOperation("UsersBulkPost")] [RequiresPermission(Permission.Admin)] public virtual IActionResult UsersBulkPost([FromBody]User[] items) { return _service.UsersBulkPostAsync(items); } /// <summary> /// Get all users /// </summary> /// <response code="200">OK</response> [HttpGet] [Route("/api/users")] [SwaggerOperation("UsersGet")] [SwaggerResponse(200, type: typeof(List<UserViewModel>))] [RequiresPermission(Permission.UserManagement)] public virtual IActionResult UsersGet() { return _service.UsersGetAsync(); } /// <summary> /// Delete user /// </summary> /// <param name="id">id of User to delete</param> /// <response code="200">OK</response> [HttpPost] [Route("/api/users/{id}/delete")] [SwaggerOperation("UsersIdDeletePost")] [RequiresPermission(Permission.UserManagement)] public virtual IActionResult UsersIdDeletePost([FromRoute]int id) { return _service.UsersIdDeletePostAsync(id); } /// <summary> /// Get user favorites /// </summary> /// <remarks>Returns a use favourites</remarks> /// <param name="id">id of User to fetch favorites for</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/users/{id}/favourites")] [SwaggerOperation("UsersIdFavouritesGet")] [SwaggerResponse(200, type: typeof(List<UserFavouriteViewModel>))] [RequiresPermission(Permission.UserManagement)] public virtual IActionResult UsersIdFavouritesGet([FromRoute]int id) { return _service.UsersIdFavouritesGetAsync(id); } /// <summary> /// Get user by id /// </summary> /// <param name="id">id of User to fetch</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/users/{id}")] [SwaggerOperation("UsersIdGet")] [SwaggerResponse(200, type: typeof(UserViewModel))] [RequiresPermission(Permission.UserManagement)] public virtual IActionResult UsersIdGet([FromRoute]int id) { return _service.UsersIdGetAsync(id); } /// <summary> /// Get permissions for a user /// </summary> /// <remarks>Returns the set of permissions for a user</remarks> /// <param name="id">id of User to fetch</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/users/{id}/permissions")] [SwaggerOperation("UsersIdPermissionsGet")] [SwaggerResponse(200, type: typeof(List<PermissionViewModel>))] [RequiresPermission(Permission.UserManagement)] public virtual IActionResult UsersIdPermissionsGet([FromRoute]int id) { return _service.UsersIdPermissionsGetAsync(id); } /// <summary> /// Update user /// </summary> /// <param name="id">id of User to update</param> /// <param name="item"></param> /// <response code="200">OK</response> [HttpPut] [Route("/api/users/{id}")] [SwaggerOperation("UsersIdPut")] [SwaggerResponse(200, type: typeof(UserViewModel))] [RequiresPermission(Permission.UserManagement)] public virtual IActionResult UsersIdPut([FromRoute]int id, [FromBody]UserViewModel item) { return _service.UsersIdPutAsync(id, item); } /// <summary> /// Get all roles for a user /// </summary> /// <remarks>Returns the roles for a user</remarks> /// <param name="id">id of User to fetch</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/users/{id}/roles")] [SwaggerOperation("UsersIdRolesGet")] [SwaggerResponse(200, type: typeof(List<UserRoleViewModel>))] [RequiresPermission(Permission.UserManagement)] public virtual IActionResult UsersIdRolesGet([FromRoute]int id) { return _service.UsersIdRolesGetAsync(id); } /// <summary> /// Adds a role to a user /// </summary> /// <remarks>Adds a role to a user</remarks> /// <param name="id">id of User to update</param> /// <param name="item"></param> /// <response code="200">Role created for user</response> [HttpPost] [Route("/api/users/{id}/roles")] [SwaggerOperation("UsersIdRolesPost")] [SwaggerResponse(200, type: typeof(UserRoleViewModel))] [RequiresPermission(Permission.UserManagement)] public virtual IActionResult UsersIdRolesPost([FromRoute]int id, [FromBody]UserRoleViewModel item) { return _service.UsersIdRolesPostAsync(id, item); } /// <summary> /// Add user to roles /// </summary> /// <remarks>Updates the roles for a user</remarks> /// <param name="id">id of User to update</param> /// <param name="items"></param> /// <response code="200">OK</response> [HttpPut] [Route("/api/users/{id}/roles")] [SwaggerOperation("UsersIdRolesPut")] [SwaggerResponse(200, type: typeof(List<UserRoleViewModel>))] [RequiresPermission(Permission.UserManagement)] public virtual IActionResult UsersIdRolesPut([FromRoute]int id, [FromBody]UserRoleViewModel[] items) { return _service.UsersIdRolesPutAsync(id, items); } /// <summary> /// Create user /// </summary> /// <param name="item"></param> /// <response code="200">User created</response> [HttpPost] [Route("/api/users")] [SwaggerOperation("UsersPost")] [SwaggerResponse(200, type: typeof(UserViewModel))] [RequiresPermission(Permission.UserManagement)] public virtual IActionResult UsersPost([FromBody]UserViewModel item) { return _service.UsersPostAsync(item); } /// <summary> /// Search for users /// </summary> /// <remarks>Used to search users.</remarks> /// <param name="districts">Districts (comma seperated list of id numbers)</param> /// <param name="surname"></param> /// <param name="includeInactive">True if Inactive users will be returned</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/users/search")] [SwaggerOperation("UsersSearchGet")] [SwaggerResponse(200, type: typeof(List<UserViewModel>))] [RequiresPermission(Permission.UserManagement)] public virtual IActionResult UsersSearchGet([FromQuery]string districts, [FromQuery]string surname, [FromQuery]bool? includeInactive) { return _service.UsersSearchGetAsync(districts, surname, includeInactive); } /// <summary> /// Get user districts /// </summary> /// <remarks>Returns a users districts</remarks> /// <param name="id">id of User to fetch districts for</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/users/{id}/districts")] [SwaggerOperation("UsersIdDistrictsGet")] [SwaggerResponse(200, type: typeof(List<UserDistrict>))] [RequiresPermission(Permission.UserManagement)] public virtual IActionResult UsersIdDistrictsGet([FromRoute]int id) { return _service.UsersIdDistrictsGetAsync(id); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; namespace Arango.fastJSON { /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// </summary> internal sealed class JsonParser { enum Token { None = -1, // Used to denote no Lookahead available Curly_Open, Curly_Close, Squared_Open, Squared_Close, Colon, Comma, String, Number, True, False, Null } readonly string json; readonly StringBuilder s = new StringBuilder(); Token lookAheadToken = Token.None; int index; bool _ignorecase = false; internal JsonParser(string json, bool ignorecase) { this.json = json;//.ToCharArray(); _ignorecase = ignorecase; } public object Decode() { return ParseValue(); } private Dictionary<string, object> ParseObject() { Dictionary<string, object> table = new Dictionary<string, object>(); ConsumeToken(); // { while (true) { switch (LookAhead()) { case Token.Comma: ConsumeToken(); break; case Token.Curly_Close: ConsumeToken(); return table; default: { // name string name = ParseString(); if (_ignorecase) name = name.ToLower(); // : if (NextToken() != Token.Colon) { throw new Exception("Expected colon at index " + index); } // value object value = ParseValue(); table[name] = value; } break; } } } private List<object> ParseArray() { List<object> array = new List<object>(); ConsumeToken(); // [ while (true) { switch (LookAhead()) { case Token.Comma: ConsumeToken(); break; case Token.Squared_Close: ConsumeToken(); return array; default: array.Add(ParseValue()); break; } } } private object ParseValue() { switch (LookAhead()) { case Token.Number: return ParseNumber(); case Token.String: return ParseString(); case Token.Curly_Open: return ParseObject(); case Token.Squared_Open: return ParseArray(); case Token.True: ConsumeToken(); return true; case Token.False: ConsumeToken(); return false; case Token.Null: ConsumeToken(); return null; } throw new Exception("Unrecognized token at index" + index); } private string ParseString() { ConsumeToken(); // " s.Length = 0; int runIndex = -1; while (index < json.Length) { var c = json[index++]; if (c == '"') { if (runIndex != -1) { if (s.Length == 0) return json.Substring(runIndex, index - runIndex - 1); s.Append(json, runIndex, index - runIndex - 1); } return s.ToString(); } if (c != '\\') { if (runIndex == -1) runIndex = index - 1; continue; } if (index == json.Length) break; if (runIndex != -1) { s.Append(json, runIndex, index - runIndex - 1); runIndex = -1; } switch (json[index++]) { case '"': s.Append('"'); break; case '\\': s.Append('\\'); break; case '/': s.Append('/'); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': { int remainingLength = json.Length - index; if (remainingLength < 4) break; // parse the 32 bit hex into an integer codepoint uint codePoint = ParseUnicode(json[index], json[index + 1], json[index + 2], json[index + 3]); s.Append((char)codePoint); // skip 4 chars index += 4; } break; } } throw new Exception("Unexpectedly reached end of string"); } private uint ParseSingleChar(char c1, uint multipliyer) { uint p1 = 0; if (c1 >= '0' && c1 <= '9') p1 = (uint)(c1 - '0') * multipliyer; else if (c1 >= 'A' && c1 <= 'F') p1 = (uint)((c1 - 'A') + 10) * multipliyer; else if (c1 >= 'a' && c1 <= 'f') p1 = (uint)((c1 - 'a') + 10) * multipliyer; return p1; } private uint ParseUnicode(char c1, char c2, char c3, char c4) { uint p1 = ParseSingleChar(c1, 0x1000); uint p2 = ParseSingleChar(c2, 0x100); uint p3 = ParseSingleChar(c3, 0x10); uint p4 = ParseSingleChar(c4, 1); return p1 + p2 + p3 + p4; } private long CreateLong(string s) { long num = 0; bool neg = false; foreach (char cc in s) { if (cc == '-') neg = true; else if (cc == '+') neg = false; else { num *= 10; num += (int)(cc - '0'); } } return neg ? -num : num; } private object ParseNumber() { ConsumeToken(); // Need to start back one place because the first digit is also a token and would have been consumed var startIndex = index - 1; bool dec = false; do { if (index == json.Length) break; var c = json[index]; if ((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E') { if (c == '.' || c == 'e' || c == 'E') dec = true; if (++index == json.Length) break;//throw new Exception("Unexpected end of string whilst parsing number"); continue; } break; } while (true); if (dec) { string s = json.Substring(startIndex, index - startIndex); return double.Parse(s, NumberFormatInfo.InvariantInfo); } long num; return JSON.CreateLong(out num, json, startIndex, index - startIndex); } private Token LookAhead() { if (lookAheadToken != Token.None) return lookAheadToken; return lookAheadToken = NextTokenCore(); } private void ConsumeToken() { lookAheadToken = Token.None; } private Token NextToken() { var result = lookAheadToken != Token.None ? lookAheadToken : NextTokenCore(); lookAheadToken = Token.None; return result; } private Token NextTokenCore() { char c; // Skip past whitespace do { c = json[index]; if (c > ' ') break; if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break; } while (++index < json.Length); if (index == json.Length) { throw new Exception("Reached end of string unexpectedly"); } c = json[index]; index++; switch (c) { case '{': return Token.Curly_Open; case '}': return Token.Curly_Close; case '[': return Token.Squared_Open; case ']': return Token.Squared_Close; case ',': return Token.Comma; case '"': return Token.String; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': case '+': case '.': return Token.Number; case ':': return Token.Colon; case 'f': if (json.Length - index >= 4 && json[index + 0] == 'a' && json[index + 1] == 'l' && json[index + 2] == 's' && json[index + 3] == 'e') { index += 4; return Token.False; } break; case 't': if (json.Length - index >= 3 && json[index + 0] == 'r' && json[index + 1] == 'u' && json[index + 2] == 'e') { index += 3; return Token.True; } break; case 'n': if (json.Length - index >= 3 && json[index + 0] == 'u' && json[index + 1] == 'l' && json[index + 2] == 'l') { index += 3; return Token.Null; } break; } throw new Exception("Could not find token at index " + --index); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Web.UI.WebControls; using ASPNET.StarterKit.BusinessLogicLayer; namespace ASPNET.StarterKit.DataAccessLayer { public class SQLDataAccess : DataAccess { /*** DELEGATE ***/ private delegate void TGenerateListFromReader<T>(SqlDataReader returnData, ref List<T> tempList); /***************************** BASE CLASS IMPLEMENTATION *****************************/ /*** CATEGORY ***/ private const string SP_CATEGORY_CREATE = "aspnet_starterkits_CreateNewCategory"; private const string SP_CATEGORY_DELETE = "aspnet_starterkits_DeleteCategory"; private const string SP_CATEGORY_GETALLCATEGORIES = "aspnet_starterkits_GetAllCategories"; private const string SP_CATEGORY_GETCATEGORYBYPROJECTID = "aspnet_starterkits_GetCategoriesByProjectId"; private const string SP_CATEGORY_GETCATEGORYBYID = "aspnet_starterkits_GetCategoryById"; private const string SP_CATEGORY_GETCATEGORYBYNAMEANDPROJECT = "aspnet_starterkits_GetCategoryByNameAndProjectId"; private const string SP_CATEGORY_UPDATE = "aspnet_starterkits_UpdateCategories"; public override int CreateNewCategory(Category newCategory) { if (newCategory == null) throw (new ArgumentNullException("newCategory")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null); AddParamToSQLCmd(sqlCmd, "@CategoryAbbreviation", SqlDbType.NText, 255, ParameterDirection.Input, newCategory.Abbreviation); AddParamToSQLCmd(sqlCmd, "@CategoryEstimateDuration", SqlDbType.Decimal, 0, ParameterDirection.Input, newCategory.EstimateDuration); AddParamToSQLCmd(sqlCmd, "@CategoryName", SqlDbType.NText, 255, ParameterDirection.Input, newCategory.Name); AddParamToSQLCmd(sqlCmd, "@ProjectId", SqlDbType.Int, 0, ParameterDirection.Input, newCategory.ProjectId); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_CREATE); ExecuteScalarCmd(sqlCmd); return ((int)sqlCmd.Parameters["@ReturnValue"].Value); } public override bool DeleteCategory(int categoryId) { if (categoryId <= DefaultValues.GetCategoryIdMinValue()) throw (new ArgumentOutOfRangeException("categoryId")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null); AddParamToSQLCmd(sqlCmd, "@CategoryIdToDelete", SqlDbType.Int, 0, ParameterDirection.Input, categoryId); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_DELETE); ExecuteScalarCmd(sqlCmd); int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value; return (returnValue == 0 ? true : false); } public override List<Category> GetAllCategories() { SqlCommand sqlCmd = new SqlCommand(); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_GETALLCATEGORIES); List<Category> categoryList = new List<Category>(); TExecuteReaderCmd<Category>(sqlCmd, TGenerateCategoryListFromReader<Category>, ref categoryList); return categoryList; } public override Category GetCategoryByCategoryId(int Id) { if (Id <= DefaultValues.GetCategoryIdMinValue()) throw (new ArgumentOutOfRangeException("Id")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@CategoryId", SqlDbType.Int, 0, ParameterDirection.Input, Id); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_GETCATEGORYBYID); List<Category> categoryList = new List<Category>(); TExecuteReaderCmd<Category>(sqlCmd, TGenerateCategoryListFromReader<Category>, ref categoryList); if (categoryList.Count > 0) return categoryList[0]; else return null; } public override Category GetCategoryByCategoryNameandProjectId(string categoryName, int projectId) { if (projectId <= DefaultValues.GetProjectIdMinValue()) throw (new ArgumentOutOfRangeException("Id")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ProjectId", SqlDbType.Int, 0, ParameterDirection.Input, projectId); AddParamToSQLCmd(sqlCmd, "@CategoryName", SqlDbType.NText, 255, ParameterDirection.Input, categoryName); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_GETCATEGORYBYNAMEANDPROJECT); List<Category> categoryList = new List<Category>(); TExecuteReaderCmd<Category>(sqlCmd, TGenerateCategoryListFromReader<Category>, ref categoryList); if (categoryList.Count > 0) return categoryList[0]; else return null; } public override List<Category> GetCategoriesByProjectId(int projectId) { if (projectId <= DefaultValues.GetProjectIdMinValue()) throw (new ArgumentOutOfRangeException("projectId")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ProjectId", SqlDbType.Int, 0, ParameterDirection.Input, projectId); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_GETCATEGORYBYPROJECTID); List<Category> categoryList = new List<Category>(); TExecuteReaderCmd<Category>(sqlCmd, TGenerateCategoryListFromReader<Category>, ref categoryList); return categoryList; } public override bool UpdateCategory(Category newCategory) { if (newCategory == null) throw (new ArgumentNullException("newCategory")); if (newCategory.Id <= DefaultValues.GetCategoryIdMinValue()) throw (new ArgumentOutOfRangeException("newCategory.Id")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null); AddParamToSQLCmd(sqlCmd, "@CategoryId", SqlDbType.Int, 0, ParameterDirection.Input, newCategory.Id); AddParamToSQLCmd(sqlCmd, "@CategoryAbbreviation", SqlDbType.NText, 255, ParameterDirection.Input, newCategory.Abbreviation); AddParamToSQLCmd(sqlCmd, "@CategoryEstimateDuration", SqlDbType.Decimal, 0, ParameterDirection.Input, newCategory.EstimateDuration); AddParamToSQLCmd(sqlCmd, "@CategoryName", SqlDbType.NText, 255, ParameterDirection.Input, newCategory.Name); AddParamToSQLCmd(sqlCmd, "@ProjectId", SqlDbType.Int, 0, ParameterDirection.Input, newCategory.ProjectId); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_CATEGORY_UPDATE); ExecuteScalarCmd(sqlCmd); int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value; return (returnValue == 0 ? true : false); } /*** PROJECT ***/ private const string SP_PROJECT_ADDUSERTOPROJECT = "aspnet_starterkits_AddUserToProject"; private const string SP_PROJECT_CREATE = "aspnet_starterkits_CreateNewProject"; private const string SP_PROJECT_DELETE = "aspnet_starterkits_DeleteProject"; private const string SP_PROJECT_GETALLPROJECTS = "aspnet_starterkits_GetAllProjects"; private const string SP_PROJECT_GETAPROJECTBYID = "aspnet_starterkits_GetProjectById"; private const string SP_PROJECT_GETAPROJECTSBYMANAGERUSERNAME = "aspnet_starterkits_GetProjectByManagerUserName"; private const string SP_PROJECT_GETPROJECTSBYYSERNAME = "aspnet_starterkits_GetProjectByUserName"; private const string SP_PROJECT_GETPROJECTMEMBERS = "aspnet_starterkits_GetProjectMember"; private const string SP_PROJECT_REMOVEUSERFROMPROJECT = "aspnet_starterkits_RemoveUserFromProject"; private const string SP_PROJECT_UPDATE = "aspnet_starterkits_UpdateProject"; public override bool AddUserToProject(int projectId, string userName) { if (userName == null || userName.Length == 0) throw (new ArgumentOutOfRangeException("userName")); if (projectId <= 0) throw (new ArgumentOutOfRangeException("projectId")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ResultValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null); AddParamToSQLCmd(sqlCmd, "@MemberUserName", SqlDbType.NText, 255, ParameterDirection.Input, userName); AddParamToSQLCmd(sqlCmd, "@ProjectId", SqlDbType.Int, 0, ParameterDirection.Input, projectId); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_ADDUSERTOPROJECT); ExecuteScalarCmd(sqlCmd); int resultValue = (int)sqlCmd.Parameters["@ResultValue"].Value; return (resultValue == 0 ? true : false); } public override int CreateNewProject(Project newProject) { if (newProject == null) throw (new ArgumentNullException("newProject")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null); AddParamToSQLCmd(sqlCmd, "@ProjectCreatorUserName", SqlDbType.NText, 255, ParameterDirection.Input, newProject.CreatorUserName); AddParamToSQLCmd(sqlCmd, "@ProjectCompletionDate", SqlDbType.DateTime, 0, ParameterDirection.Input, newProject.CompletionDate); AddParamToSQLCmd(sqlCmd, "@ProjectDescription", SqlDbType.NText, 1000, ParameterDirection.Input, newProject.Description); AddParamToSQLCmd(sqlCmd, "@ProjectEstimateDuration", SqlDbType.Decimal, 0, ParameterDirection.Input, newProject.EstimateDuration); AddParamToSQLCmd(sqlCmd, "@ProjectManagerUserName", SqlDbType.NText, 255, ParameterDirection.Input, newProject.ManagerUserName); AddParamToSQLCmd(sqlCmd, "@ProjectName", SqlDbType.NText, 255, ParameterDirection.Input, newProject.Name); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_CREATE); ExecuteScalarCmd(sqlCmd); return ((int)sqlCmd.Parameters["@ReturnValue"].Value); } public override bool DeleteProject(int projectID) { if (projectID <= 0) throw (new ArgumentOutOfRangeException("projectID")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null); AddParamToSQLCmd(sqlCmd, "@ProjectIdToDelete", SqlDbType.Int, 0, ParameterDirection.Input, projectID); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_DELETE); ExecuteScalarCmd(sqlCmd); int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value; return (returnValue == 0 ? true : false); } public override List<Project> GetAllProjects() { SqlCommand sqlCmd = new SqlCommand(); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_GETALLPROJECTS); List<Project> prjList = new List<Project>(); TExecuteReaderCmd<Project>(sqlCmd, TGenerateProjectListFromReader<Project>, ref prjList); return prjList; } public override Project GetProjectById(int projectId) { if (projectId <= 0) throw (new ArgumentOutOfRangeException("projectId")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ProjectId", SqlDbType.Int, 0, ParameterDirection.Input, projectId); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_GETAPROJECTBYID); List<Project> prjList = new List<Project>(); TExecuteReaderCmd<Project>(sqlCmd, TGenerateProjectListFromReader<Project>, ref prjList); if (prjList.Count > 0) return prjList[0]; else return null; } public override List<Project> GetProjectsByManagerUserName(string userName) { if (userName == null || userName.Length == 0) throw (new ArgumentOutOfRangeException("userName")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ProjectManagerUserName", SqlDbType.NText, 256, ParameterDirection.Input, userName); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_GETAPROJECTSBYMANAGERUSERNAME); List<Project> prjList = new List<Project>(); TExecuteReaderCmd<Project>(sqlCmd, TGenerateProjectListFromReader<Project>, ref prjList); return prjList; } public override List<string> GetProjectMembers(int Id) { if (Id <= 0) throw (new ArgumentOutOfRangeException("Id")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ProjectId", SqlDbType.Int, 0, ParameterDirection.Input, Id); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_GETPROJECTMEMBERS); List<string> userList = new List<string>(); TExecuteReaderCmd<string>(sqlCmd, TGenerateUsertListFromReader<string>, ref userList); return userList; } public override List<Project> GetProjectsByUserName(string userName) { if (userName == null || userName.Length == 0) throw (new ArgumentOutOfRangeException("userName")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@UserName", SqlDbType.NText, 256, ParameterDirection.Input, userName); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_GETPROJECTSBYYSERNAME); List<Project> prjList = new List<Project>(); TExecuteReaderCmd<Project>(sqlCmd, TGenerateProjectListFromReader<Project>, ref prjList); return prjList; // return (new List<Project>()); } public override bool RemoveUserFromProject(int projectId, string userName) { if (String.IsNullOrEmpty(userName)) throw (new ArgumentOutOfRangeException("userName")); if (projectId <= 0) throw (new ArgumentOutOfRangeException("projectId")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ResultValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null); AddParamToSQLCmd(sqlCmd, "@userName", SqlDbType.NVarChar, 0, ParameterDirection.Input, userName); AddParamToSQLCmd(sqlCmd, "@ProjectId", SqlDbType.Int, 0, ParameterDirection.Input, projectId); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_REMOVEUSERFROMPROJECT); ExecuteScalarCmd(sqlCmd); int resultValue = (int)sqlCmd.Parameters["@ResultValue"].Value; return (resultValue == 0 ? true : false); } public override bool UpdateProject(Project projectToUpdate) { // validate input if (projectToUpdate == null) throw (new ArgumentNullException("projectToUpdate")); // validate input if (projectToUpdate.Id <= 0) throw (new ArgumentOutOfRangeException("projectToUpdate")); SqlCommand sqlCmd = new SqlCommand(); // set the type of parameter to add a new project AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null); AddParamToSQLCmd(sqlCmd, "@ProjectId", SqlDbType.Int, 0, ParameterDirection.Input, projectToUpdate.Id); AddParamToSQLCmd(sqlCmd, "@ProjectCompletionDate", SqlDbType.DateTime, 0, ParameterDirection.Input, projectToUpdate.CompletionDate); AddParamToSQLCmd(sqlCmd, "@ProjectDescription", SqlDbType.NText, 1000, ParameterDirection.Input, projectToUpdate.Description); AddParamToSQLCmd(sqlCmd, "@ProjectEstimateDuration", SqlDbType.Decimal, 0, ParameterDirection.Input, projectToUpdate.EstimateDuration); AddParamToSQLCmd(sqlCmd, "@ProjectManagerUserName", SqlDbType.NText, 256, ParameterDirection.Input, projectToUpdate.ManagerUserName); AddParamToSQLCmd(sqlCmd, "@ProjectName", SqlDbType.NText, 256, ParameterDirection.Input, projectToUpdate.Name); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_PROJECT_UPDATE); ExecuteScalarCmd(sqlCmd); int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value; return (returnValue == 0 ? true : false); } /*** TIME ENTRY ***/ private string SP_TIMEENTRY_CREATE = "aspnet_starterkits_CreateNewTimeEntry"; private string SP_TIMEENTRY_DELETE = "aspnet_starterkits_DeleteTimeEntry"; private string SP_TIMEENTRY_GETALLTIMEENTRIES = "aspnet_starterkits_GetAllTimeEntries"; private string SP_TIMEENTRY_GETALLTIMEENTRIESBYPROJECTID_USER = "aspnet_starterkits_GetAllTimeEntriesByProjectIdandUser"; private string SP_TIMEENTRY_GETALLTIMEENTRIESBYUSERNAMEANDDATE = "aspnet_starterkits_GetAllTimeEntriesByProjectIdandUserAndDate"; private string SP_TIMEENTRY_UPDATE = "aspnet_starterkits_UpdateTimeEntry"; private string SP_TIMEENTRY_GETTIMEENTRYBYID = "aspnet_starterkits_GetTimeEntryById"; public override int CreateNewTimeEntry(TimeEntry newTimeEntry) { if (newTimeEntry == null) throw (new ArgumentNullException("newTimeEntry")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null); AddParamToSQLCmd(sqlCmd, "@CategoryId", SqlDbType.Int, 0, ParameterDirection.Input, newTimeEntry.CategoryId); AddParamToSQLCmd(sqlCmd, "@TimeEntryCreatorUserName", SqlDbType.NText, 255, ParameterDirection.Input, newTimeEntry.CreatorUserName); AddParamToSQLCmd(sqlCmd, "@TimeEntryDescription", SqlDbType.NText, 1000, ParameterDirection.Input, newTimeEntry.Description); AddParamToSQLCmd(sqlCmd, "@TimeEntryEstimateDuration", SqlDbType.Decimal, 0, ParameterDirection.Input, newTimeEntry.Duration); AddParamToSQLCmd(sqlCmd, "@TimeEntryEnteredDate", SqlDbType.DateTime, 0, ParameterDirection.Input, newTimeEntry.ReportedDate); AddParamToSQLCmd(sqlCmd, "@TimeEntryUserName", SqlDbType.NText, 255, ParameterDirection.Input, newTimeEntry.UserName); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_CREATE); ExecuteScalarCmd(sqlCmd); return ((int)sqlCmd.Parameters["@ReturnValue"].Value); } public override bool DeleteTimeEntry(int timeEntryId) { if (timeEntryId <= DefaultValues.GetTimeEntryIdMinValue()) throw (new ArgumentOutOfRangeException("timeEntryId")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null); AddParamToSQLCmd(sqlCmd, "@TimeEntryIdToDelete", SqlDbType.Int, 0, ParameterDirection.Input, timeEntryId); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_DELETE); ExecuteScalarCmd(sqlCmd); int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value; return (returnValue == 0 ? true : false); } public override List<TimeEntry> GetAllTimeEntries() { SqlCommand sqlCmd = new SqlCommand(); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETALLTIMEENTRIES); List<TimeEntry> timeEntryList = new List<TimeEntry>(); TExecuteReaderCmd<TimeEntry>(sqlCmd, TGenerateTimeEntryListFromReader<TimeEntry>, ref timeEntryList); return timeEntryList; } public override List<TimeEntry> GetTimeEntries(int projectId, string userName) { if (projectId <= DefaultValues.GetTimeEntryIdMinValue()) throw (new ArgumentOutOfRangeException("projectId")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null); AddParamToSQLCmd(sqlCmd, "@ProjectId", SqlDbType.Int, 0, ParameterDirection.Input, projectId); AddParamToSQLCmd(sqlCmd, "@TimeEntryUserName", SqlDbType.NText, 255, ParameterDirection.Input, userName); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETALLTIMEENTRIESBYPROJECTID_USER); List<TimeEntry> timeEntryList = new List<TimeEntry>(); TExecuteReaderCmd<TimeEntry>(sqlCmd, TGenerateTimeEntryListFromReader<TimeEntry>, ref timeEntryList); return timeEntryList; } public override TimeEntry GetTimeEntryById(int timeEntryId) { if (timeEntryId <= 0) throw (new ArgumentOutOfRangeException("timeEntryId")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@TimeEntryId", SqlDbType.Int, 0, ParameterDirection.Input, timeEntryId); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETTIMEENTRYBYID); List<TimeEntry> timeEntryList = new List<TimeEntry>(); TExecuteReaderCmd<TimeEntry>(sqlCmd, TGenerateTimeEntryListFromReader<TimeEntry>, ref timeEntryList); if (timeEntryList.Count > 0) return timeEntryList[0]; else return null; } public override List<TimeEntry> GetTimeEntriesByUserNameAndDates(string userName, DateTime startingDate, DateTime endDate) { SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null); AddParamToSQLCmd(sqlCmd, "@EndDate", SqlDbType.DateTime, 0, ParameterDirection.Input, endDate); AddParamToSQLCmd(sqlCmd, "@StartingDate", SqlDbType.DateTime, 0, ParameterDirection.Input, startingDate); AddParamToSQLCmd(sqlCmd, "@TimeEntryUserName", SqlDbType.NText, 255, ParameterDirection.Input, userName); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETALLTIMEENTRIESBYUSERNAMEANDDATE); List<TimeEntry> timeEntryList = new List<TimeEntry>(); TExecuteReaderCmd<TimeEntry>(sqlCmd, TGenerateTimeEntryListFromReader<TimeEntry>, ref timeEntryList); return timeEntryList; } public override bool UpdateTimeEntry(TimeEntry timeEntry) { if (timeEntry == null) throw (new ArgumentNullException("timeEntry")); SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null); AddParamToSQLCmd(sqlCmd, "@TimeEntryId", SqlDbType.Int, 0, ParameterDirection.Input, timeEntry.Id); AddParamToSQLCmd(sqlCmd, "@CategoryId", SqlDbType.Int, 0, ParameterDirection.Input, timeEntry.CategoryId); AddParamToSQLCmd(sqlCmd, "@TimeEntryDescription", SqlDbType.NText, 1000, ParameterDirection.Input, timeEntry.Description); AddParamToSQLCmd(sqlCmd, "@TimeEntryEstimateDuration", SqlDbType.Decimal, 0, ParameterDirection.Input, timeEntry.Duration); AddParamToSQLCmd(sqlCmd, "@TimeEntryEnteredDate", SqlDbType.DateTime, 0, ParameterDirection.Input, timeEntry.ReportedDate); AddParamToSQLCmd(sqlCmd, "@TimeEntryUserName", SqlDbType.NText, 1000, ParameterDirection.Input, timeEntry.UserName); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_UPDATE); ExecuteScalarCmd(sqlCmd); int resultValue = (int)sqlCmd.Parameters["@ReturnValue"].Value; return (resultValue == 0 ? true : false); } /*** USER REPORT ***/ private string SP_TIMEENTRY_GETUSERREPORT = "aspnet_starterkits_GetTimeEntryUserReport"; private string SP_TIMEENTRY_GETUSERREPORTBYCATEGORY = "aspnet_starterkits_GetTimeEntryUserReportByCategoryId"; public override List<UserReport> GetUserReportsByProjectId(int projectId) { SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@ProjectId", SqlDbType.Int, 0, ParameterDirection.Input, projectId); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETUSERREPORT); List<UserReport> userReport = new List<UserReport>(); TExecuteReaderCmd<UserReport>(sqlCmd, TGenerateUserReportListFromReader<UserReport>, ref userReport); return userReport; } public override List<UserReport> GetUserReportsByCategoryId(int categoryId) { SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@CategoryId", SqlDbType.Int, 0, ParameterDirection.Input, categoryId); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETUSERREPORTBYCATEGORY); List<UserReport> userReport = new List<UserReport>(); TExecuteReaderCmd<UserReport>(sqlCmd, TGenerateUserReportListFromReader<UserReport>, ref userReport); return userReport; } /*** USER TOTAL DURATION REPORT ***/ private string SP_TIMEENTRY_GETUSERREPORTBYUSER = "aspnet_starterkits_GetTimeEntryUserReportByUser"; public override List<UserTotalDurationReport> GetUserReportsByUserName(string userName) { SqlCommand sqlCmd = new SqlCommand(); AddParamToSQLCmd(sqlCmd, "@UserName", SqlDbType.NText, 256, ParameterDirection.Input, userName); SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_TIMEENTRY_GETUSERREPORTBYUSER); List<UserTotalDurationReport> userReport = new List<UserTotalDurationReport>(); TExecuteReaderCmd<UserTotalDurationReport>(sqlCmd, TGenerateUserReportListFromReader<UserTotalDurationReport>, ref userReport); return userReport; } /***************************** SQL HELPER METHODS *****************************/ private void AddParamToSQLCmd(SqlCommand sqlCmd, string paramId, SqlDbType sqlType, int paramSize, ParameterDirection paramDirection, object paramvalue) { if (sqlCmd == null) throw (new ArgumentNullException("sqlCmd")); if (paramId == string.Empty) throw (new ArgumentOutOfRangeException("paramId")); SqlParameter newSqlParam = new SqlParameter(); newSqlParam.ParameterName = paramId; newSqlParam.SqlDbType = sqlType; newSqlParam.Direction = paramDirection; if (paramSize > 0) newSqlParam.Size = paramSize; if (paramvalue != null) newSqlParam.Value = paramvalue; sqlCmd.Parameters.Add(newSqlParam); } private void ExecuteScalarCmd(SqlCommand sqlCmd) { if (ConnectionString == string.Empty) throw (new ArgumentOutOfRangeException("ConnectionString")); if (sqlCmd == null) throw (new ArgumentNullException("sqlCmd")); using (SqlConnection cn = new SqlConnection(this.ConnectionString)) { sqlCmd.Connection = cn; cn.Open(); sqlCmd.ExecuteScalar(); } } private void SetCommandType(SqlCommand sqlCmd, CommandType cmdType, string cmdText) { sqlCmd.CommandType = cmdType; sqlCmd.CommandText = cmdText; } private void TExecuteReaderCmd<T>(SqlCommand sqlCmd, TGenerateListFromReader<T> gcfr, ref List<T> List) { if (ConnectionString == string.Empty) throw (new ArgumentOutOfRangeException("ConnectionString")); if (sqlCmd == null) throw (new ArgumentNullException("sqlCmd")); using (SqlConnection cn = new SqlConnection(this.ConnectionString)) { sqlCmd.Connection = cn; cn.Open(); gcfr(sqlCmd.ExecuteReader(), ref List); } } /***************************** GENARATE List HELPER METHODS *****************************/ private void TGenerateProjectListFromReader<T>(SqlDataReader returnData, ref List<Project> prjList) { while (returnData.Read()) { decimal actualDuration = 0; if (returnData["ProjectActualDuration"] != DBNull.Value) actualDuration = Convert.ToDecimal(returnData["ProjectActualDuration"]); Project project = new Project(actualDuration, (string)returnData["ProjectCreatorDisplayName"], (DateTime)returnData["ProjectCompletionDate"], (DateTime)returnData["ProjectCreationDate"], (string)returnData["ProjectDescription"], (Decimal)returnData["ProjectEstimateDuration"], (int)returnData["ProjectId"], (string)returnData["ProjectManagerDisplayName"], (string)returnData["ProjectName"]); prjList.Add(project); } } private void TGenerateCategoryListFromReader<T>(SqlDataReader returnData, ref List<Category> categoryList) { while (returnData.Read()) { decimal actualDuration = 0; if (returnData["CategoryActualDuration"] != DBNull.Value) actualDuration = Convert.ToDecimal(returnData["CategoryActualDuration"]); Category category = new Category((string)returnData["CategoryAbbreviation"], actualDuration, (int)returnData["CategoryId"], (decimal)returnData["CategoryEstimateDuration"], (string)returnData["CategoryName"], (int)returnData["ProjectId"]); categoryList.Add(category); } } private void TGenerateTimeEntryListFromReader<T>(SqlDataReader returnData, ref List<TimeEntry> timeEntryList) { while (returnData.Read()) { TimeEntry timeEntry = new TimeEntry((string)returnData["TimeEntryCreatorDisplayName"], (int)returnData["CategoryId"], (DateTime)returnData["TimeEntryCreated"], (string)returnData["TimeEntryDescription"], (Decimal)returnData["TimeEntryDuration"], (int)returnData["TimeEntryId"], (DateTime)returnData["TimeEntryDate"], (string)returnData["TimeEntryUserName"]); timeEntryList.Add(timeEntry); } } private void TGenerateUsertListFromReader<T>(SqlDataReader returnData, ref List<string> userList) { while (returnData.Read()) { string userName = (string)returnData["UserName"]; userList.Add(userName); } } private void TGenerateUserReportListFromReader<T>(SqlDataReader returnData, ref List<UserReport> userReportList) { while (returnData.Read()) { UserReport userReport = new UserReport((decimal)returnData["duration"], (int)returnData["CategoryId"], (string)returnData["UserName"]); userReportList.Add(userReport); } } private void TGenerateUserReportListFromReader<T>(SqlDataReader returnData, ref List<UserTotalDurationReport> userReportList) { while (returnData.Read()) { decimal totalDuration = 0; if (returnData["TotalDuration"] != DBNull.Value) totalDuration = (decimal)returnData["TotalDuration"]; UserTotalDurationReport userReport = new UserTotalDurationReport(totalDuration, (string)returnData["UserName"]); userReportList.Add(userReport); } } } }
using System; using System.Windows.Forms; using System.Drawing; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { public delegate string GetPersistStringCallback(); public class DockContentHandler : IDisposable, IDockDragSource { public DockContentHandler(Form form) : this(form, null) { } public DockContentHandler(Form form, GetPersistStringCallback getPersistStringCallback) { if (!(form is IDockContent)) throw new ArgumentException(Strings.DockContent_Constructor_InvalidForm, nameof(form)); m_form = form; GetPersistStringCallback = getPersistStringCallback; Events = new EventHandlerList(); Form.Disposed += new EventHandler(Form_Disposed); Form.TextChanged += new EventHandler(Form_TextChanged); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { DockPanel = null; if (m_autoHideTab != null) m_autoHideTab.Dispose(); if (m_tab != null) m_tab.Dispose(); Form.Disposed -= new EventHandler(Form_Disposed); Form.TextChanged -= new EventHandler(Form_TextChanged); Events.Dispose(); } } private Form m_form; public Form Form { get { return m_form; } } public IDockContent Content { get { return Form as IDockContent; } } public IDockContent PreviousActive { get; internal set; } public IDockContent NextActive { get; internal set; } private EventHandlerList Events { get; } public bool AllowEndUserDocking { get; set; } = true; internal bool SuspendAutoHidePortionUpdates { get; set; } = false; private double m_autoHidePortion = 0.25; public double AutoHidePortion { get { return m_autoHidePortion; } set { if (value <= 0) throw (new ArgumentOutOfRangeException(Strings.DockContentHandler_AutoHidePortion_OutOfRange)); if (SuspendAutoHidePortionUpdates) return; if (Math.Abs(m_autoHidePortion - value) < double.Epsilon) return; m_autoHidePortion = value; if (DockPanel == null) return; if (DockPanel.ActiveAutoHideContent == Content) DockPanel.PerformLayout(); } } private bool m_closeButton = true; public bool CloseButton { get { return m_closeButton; } set { if (m_closeButton == value) return; m_closeButton = value; if (IsActiveContentHandler) Pane.RefreshChanges(); } } private bool m_closeButtonVisible = true; /// <summary> /// Determines whether the close button is visible on the content /// </summary> public bool CloseButtonVisible { get { return m_closeButtonVisible; } set { if (m_closeButtonVisible == value) return; m_closeButtonVisible = value; if (IsActiveContentHandler) Pane.RefreshChanges(); } } private bool IsActiveContentHandler { get { return Pane != null && Pane.ActiveContent != null && Pane.ActiveContent.DockHandler == this; } } private DockState DefaultDockState { get { if (ShowHint != DockState.Unknown && ShowHint != DockState.Hidden) return ShowHint; if ((DockAreas & DockAreas.Document) != 0) return DockState.Document; if ((DockAreas & DockAreas.DockRight) != 0) return DockState.DockRight; if ((DockAreas & DockAreas.DockLeft) != 0) return DockState.DockLeft; if ((DockAreas & DockAreas.DockBottom) != 0) return DockState.DockBottom; if ((DockAreas & DockAreas.DockTop) != 0) return DockState.DockTop; return DockState.Unknown; } } private DockState DefaultShowState { get { if (ShowHint != DockState.Unknown) return ShowHint; if ((DockAreas & DockAreas.Document) != 0) return DockState.Document; if ((DockAreas & DockAreas.DockRight) != 0) return DockState.DockRight; if ((DockAreas & DockAreas.DockLeft) != 0) return DockState.DockLeft; if ((DockAreas & DockAreas.DockBottom) != 0) return DockState.DockBottom; if ((DockAreas & DockAreas.DockTop) != 0) return DockState.DockTop; if ((DockAreas & DockAreas.Float) != 0) return DockState.Float; return DockState.Unknown; } } private DockAreas m_allowedAreas = DockAreas.DockLeft | DockAreas.DockRight | DockAreas.DockTop | DockAreas.DockBottom | DockAreas.Document | DockAreas.Float; public DockAreas DockAreas { get { return m_allowedAreas; } set { if (m_allowedAreas == value) return; if (!DockHelper.IsDockStateValid(DockState, value)) throw (new InvalidOperationException(Strings.DockContentHandler_DockAreas_InvalidValue)); m_allowedAreas = value; if (!DockHelper.IsDockStateValid(ShowHint, m_allowedAreas)) ShowHint = DockState.Unknown; } } private DockState m_dockState = DockState.Unknown; public DockState DockState { get { return m_dockState; } set { if (m_dockState == value) return; DockPanel.SuspendLayout(true); if (value == DockState.Hidden) IsHidden = true; else SetDockState(false, value, Pane); DockPanel.ResumeLayout(true, true); } } private DockPanel m_dockPanel = null; public DockPanel DockPanel { get { return m_dockPanel; } set { if (m_dockPanel == value) return; Pane = null; if (m_dockPanel != null) m_dockPanel.RemoveContent(Content); if (m_tab != null) { m_tab.Dispose(); m_tab = null; } if (m_autoHideTab != null) { m_autoHideTab.Dispose(); m_autoHideTab = null; } m_dockPanel = value; if (m_dockPanel != null) { m_dockPanel.AddContent(Content); Form.TopLevel = false; Form.FormBorderStyle = FormBorderStyle.None; Form.ShowInTaskbar = false; Form.WindowState = FormWindowState.Normal; Content.ApplyTheme(); if (Win32Helper.IsRunningOnMono) return; NativeMethods.SetWindowPos(Form.Handle, IntPtr.Zero, 0, 0, 0, 0, Win32.FlagsSetWindowPos.SWP_NOACTIVATE | Win32.FlagsSetWindowPos.SWP_NOMOVE | Win32.FlagsSetWindowPos.SWP_NOSIZE | Win32.FlagsSetWindowPos.SWP_NOZORDER | Win32.FlagsSetWindowPos.SWP_NOOWNERZORDER | Win32.FlagsSetWindowPos.SWP_FRAMECHANGED); } } } public Icon Icon { get { return Form.Icon; } } public DockPane Pane { get { return IsFloat ? FloatPane : PanelPane; } set { if (Pane == value) return; DockPanel.SuspendLayout(true); DockPane oldPane = Pane; SuspendSetDockState(); FloatPane = (value == null ? null : (value.IsFloat ? value : FloatPane)); PanelPane = (value == null ? null : (value.IsFloat ? PanelPane : value)); ResumeSetDockState(IsHidden, value != null ? value.DockState : DockState.Unknown, oldPane); DockPanel.ResumeLayout(true, true); } } private bool m_isHidden = true; public bool IsHidden { get { return m_isHidden; } set { if (m_isHidden == value) return; SetDockState(value, VisibleState, Pane); } } private string m_tabText = null; public string TabText { get { return m_tabText == null || m_tabText == "" ? Form.Text : m_tabText; } set { if (m_tabText == value) return; m_tabText = value; if (Pane != null) Pane.RefreshChanges(); } } private DockState m_visibleState = DockState.Unknown; public DockState VisibleState { get { return m_visibleState; } set { if (m_visibleState == value) return; SetDockState(IsHidden, value, Pane); } } private bool m_isFloat = false; public bool IsFloat { get { return m_isFloat; } set { if (m_isFloat == value) return; DockState visibleState = CheckDockState(value); if (visibleState == DockState.Unknown) throw new InvalidOperationException(Strings.DockContentHandler_IsFloat_InvalidValue); SetDockState(IsHidden, visibleState, Pane); if (PatchController.EnableFloatSplitterFix == true) { if (PanelPane != null && PanelPane.IsHidden) { PanelPane.NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(PanelPane); } } } } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public DockState CheckDockState(bool isFloat) { DockState dockState; if (isFloat) { if (!IsDockStateValid(DockState.Float)) dockState = DockState.Unknown; else dockState = DockState.Float; } else { dockState = (PanelPane != null) ? PanelPane.DockState : DefaultDockState; if (dockState != DockState.Unknown && !IsDockStateValid(dockState)) dockState = DockState.Unknown; } return dockState; } private DockPane m_panelPane = null; public DockPane PanelPane { get { return m_panelPane; } set { if (m_panelPane == value) return; if (value != null) { if (value.IsFloat || value.DockPanel != DockPanel) throw new InvalidOperationException(Strings.DockContentHandler_DockPane_InvalidValue); } DockPane oldPane = Pane; if (m_panelPane != null) RemoveFromPane(m_panelPane); m_panelPane = value; if (m_panelPane != null) { m_panelPane.AddContent(Content); SetDockState(IsHidden, IsFloat ? DockState.Float : m_panelPane.DockState, oldPane); } else SetDockState(IsHidden, DockState.Unknown, oldPane); } } private void RemoveFromPane(DockPane pane) { pane.RemoveContent(Content); SetPane(null); if (pane.Contents.Count == 0) pane.Dispose(); } private DockPane m_floatPane = null; public DockPane FloatPane { get { return m_floatPane; } set { if (m_floatPane == value) return; if (value != null) { if (!value.IsFloat || value.DockPanel != DockPanel) throw new InvalidOperationException(Strings.DockContentHandler_FloatPane_InvalidValue); } DockPane oldPane = Pane; if (m_floatPane != null) RemoveFromPane(m_floatPane); m_floatPane = value; if (m_floatPane != null) { m_floatPane.AddContent(Content); SetDockState(IsHidden, IsFloat ? DockState.Float : VisibleState, oldPane); } else SetDockState(IsHidden, DockState.Unknown, oldPane); } } private int m_countSetDockState = 0; private void SuspendSetDockState() { m_countSetDockState++; } private void ResumeSetDockState() { m_countSetDockState--; if (m_countSetDockState < 0) m_countSetDockState = 0; } internal bool IsSuspendSetDockState { get { return m_countSetDockState != 0; } } private void ResumeSetDockState(bool isHidden, DockState visibleState, DockPane oldPane) { ResumeSetDockState(); SetDockState(isHidden, visibleState, oldPane); } internal void SetDockState(bool isHidden, DockState visibleState, DockPane oldPane) { if (IsSuspendSetDockState) return; if (DockPanel == null && visibleState != DockState.Unknown) throw new InvalidOperationException(Strings.DockContentHandler_SetDockState_NullPanel); if (visibleState == DockState.Hidden || (visibleState != DockState.Unknown && !IsDockStateValid(visibleState))) throw new InvalidOperationException(Strings.DockContentHandler_SetDockState_InvalidState); DockPanel dockPanel = DockPanel; if (dockPanel != null) dockPanel.SuspendLayout(true); SuspendSetDockState(); DockState oldDockState = DockState; if (m_isHidden != isHidden || oldDockState == DockState.Unknown) { m_isHidden = isHidden; } m_visibleState = visibleState; m_dockState = isHidden ? DockState.Hidden : visibleState; //Remove hidden content (shown content is added last so removal is done first to invert the operation) bool hidingContent = (DockState == DockState.Hidden) || (DockState == DockState.Unknown) || DockHelper.IsDockStateAutoHide(DockState); if (PatchController.EnableContentOrderFix == true && oldDockState != DockState) { if (hidingContent) { if (!Win32Helper.IsRunningOnMono) DockPanel.ContentFocusManager.RemoveFromList(Content); } } if (visibleState == DockState.Unknown) Pane = null; else { m_isFloat = (m_visibleState == DockState.Float); if (Pane == null) Pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(Content, visibleState, true); else if (Pane.DockState != visibleState) { if (Pane.Contents.Count == 1) Pane.SetDockState(visibleState); else Pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(Content, visibleState, true); } } if (Form.ContainsFocus) { if (DockState == DockState.Hidden || DockState == DockState.Unknown) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.GiveUpFocus(Content); } } } SetPaneAndVisible(Pane); if (oldPane != null && !oldPane.IsDisposed && oldDockState == oldPane.DockState) RefreshDockPane(oldPane); if (Pane != null && DockState == Pane.DockState) { if ((Pane != oldPane) || (Pane == oldPane && oldDockState != oldPane.DockState)) { // Avoid early refresh of hidden AutoHide panes if ((Pane.DockWindow == null || Pane.DockWindow.Visible || Pane.IsHidden) && !Pane.IsAutoHide) { RefreshDockPane(Pane); } } } if (oldDockState != DockState) { if (PatchController.EnableContentOrderFix == true) { //Add content that is being shown if (!hidingContent) { if (!Win32Helper.IsRunningOnMono) DockPanel.ContentFocusManager.AddToList(Content); } } else { if (DockState == DockState.Hidden || DockState == DockState.Unknown || DockHelper.IsDockStateAutoHide(DockState)) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.RemoveFromList(Content); } } else if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.AddToList(Content); } } ResetAutoHidePortion(oldDockState, DockState); OnDockStateChanged(EventArgs.Empty); } ResumeSetDockState(); if (dockPanel != null) dockPanel.ResumeLayout(true, true); } private void ResetAutoHidePortion(DockState oldState, DockState newState) { if (oldState == newState || DockHelper.ToggleAutoHideState(oldState) == newState) return; switch (newState) { case DockState.DockTop: case DockState.DockTopAutoHide: AutoHidePortion = DockPanel.DockTopPortion; break; case DockState.DockLeft: case DockState.DockLeftAutoHide: AutoHidePortion = DockPanel.DockLeftPortion; break; case DockState.DockBottom: case DockState.DockBottomAutoHide: AutoHidePortion = DockPanel.DockBottomPortion; break; case DockState.DockRight: case DockState.DockRightAutoHide: AutoHidePortion = DockPanel.DockRightPortion; break; } } private static void RefreshDockPane(DockPane pane) { pane.RefreshChanges(); pane.ValidateActiveContent(); } internal string PersistString { get { return GetPersistStringCallback == null ? Form.GetType().ToString() : GetPersistStringCallback(); } } public GetPersistStringCallback GetPersistStringCallback { get; set; } public bool HideOnClose { get; set; } private DockState m_showHint = DockState.Unknown; public DockState ShowHint { get { return m_showHint; } set { if (!DockHelper.IsDockStateValid(value, DockAreas)) throw (new InvalidOperationException(Strings.DockContentHandler_ShowHint_InvalidValue)); if (m_showHint == value) return; m_showHint = value; } } private bool m_isActivated; public bool IsActivated { get { return m_isActivated; } internal set { if (m_isActivated == value) return; m_isActivated = value; } } public bool IsDockStateValid(DockState dockState) { if (DockPanel != null && dockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.SystemMdi) return false; else return DockHelper.IsDockStateValid(dockState, DockAreas); } public ContextMenu TabPageContextMenu { get; set; } public string ToolTipText { get; set; } public void Activate() { if (DockPanel == null) Form.Activate(); else if (Pane == null) Show(DockPanel); else { IsHidden = false; Pane.ActiveContent = Content; if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.SystemMdi) { Form.Activate(); return; } else if (DockHelper.IsDockStateAutoHide(DockState)) { if (DockPanel.ActiveAutoHideContent != Content) { DockPanel.ActiveAutoHideContent = null; return; } } if (Form.ContainsFocus) return; if (Win32Helper.IsRunningOnMono) return; DockPanel.ContentFocusManager.Activate(Content); } } public void GiveUpFocus() { if (!Win32Helper.IsRunningOnMono) DockPanel.ContentFocusManager.GiveUpFocus(Content); } private IntPtr m_activeWindowHandle = IntPtr.Zero; internal IntPtr ActiveWindowHandle { get { return m_activeWindowHandle; } set { m_activeWindowHandle = value; } } public void Hide() { IsHidden = true; } internal void SetPaneAndVisible(DockPane pane) { SetPane(pane); SetVisible(); } private void SetPane(DockPane pane) { if (pane != null && pane.DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) { if (Form.Parent is DockPane) SetParent(null); if (Form.MdiParent != DockPanel.ParentForm) { FlagClipWindow = true; // The content form should inherit the font of the dock panel, not the font of // the dock panel's parent form. However, the content form's font value should // not be overwritten if it has been explicitly set to a non-default value. if (PatchController.EnableFontInheritanceFix == true && Form.Font == Control.DefaultFont) { Form.MdiParent = DockPanel.ParentForm; Form.Font = DockPanel.Font; } else { Form.MdiParent = DockPanel.ParentForm; } } } else { FlagClipWindow = true; if (Form.MdiParent != null) Form.MdiParent = null; if (Form.TopLevel) Form.TopLevel = false; SetParent(pane); } } internal void SetVisible() { bool visible; if (IsHidden) visible = false; else if (Pane != null && Pane.DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) visible = true; else if (Pane != null && Pane.ActiveContent == Content) visible = true; else if (Pane != null && Pane.ActiveContent != Content) visible = false; else visible = Form.Visible; if (Form.Visible != visible) Form.Visible = visible; } private void SetParent(Control value) { if (Form.Parent == value) return; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! bool bRestoreFocus = false; if (Form.ContainsFocus) { // Suggested as a fix for a memory leak by bugreports if (value == null && !IsFloat) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.GiveUpFocus(this.Content); } } else { DockPanel.SaveFocus(); bRestoreFocus = true; } } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! var parentChanged = value != Form.Parent; Form.Parent = value; if (PatchController.EnableMainWindowFocusLostFix == true && parentChanged) { Form.Focus(); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (bRestoreFocus && !Win32Helper.IsRunningOnMono) Activate(); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } public void Show() { if (DockPanel == null) Form.Show(); else Show(DockPanel); } public void Show(DockPanel dockPanel) { if (dockPanel == null) throw (new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); if (DockState == DockState.Unknown) Show(dockPanel, DefaultShowState); else if (DockPanel != dockPanel) Show(dockPanel, DockState == DockState.Hidden ? m_visibleState : DockState); else Activate(); } public void Show(DockPanel dockPanel, DockState dockState) { if (dockPanel == null) throw (new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); if (dockState == DockState.Unknown || dockState == DockState.Hidden) throw (new ArgumentException(Strings.DockContentHandler_Show_InvalidDockState)); dockPanel.SuspendLayout(true); DockPanel = dockPanel; if (dockState == DockState.Float) { if (FloatPane == null) Pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(Content, DockState.Float, true); } else if (PanelPane == null) { DockPane paneExisting = null; foreach (DockPane pane in DockPanel.Panes) if (pane.DockState == dockState) { if (paneExisting == null || pane.IsActivated) paneExisting = pane; if (pane.IsActivated) break; } if (paneExisting == null) Pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(Content, dockState, true); else Pane = paneExisting; } DockState = dockState; dockPanel.ResumeLayout(true, true); //we'll resume the layout before activating to ensure that the position Activate(); //and size of the form are finally processed before the form is shown } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public void Show(DockPanel dockPanel, Rectangle floatWindowBounds) { if (dockPanel == null) throw (new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); dockPanel.SuspendLayout(true); DockPanel = dockPanel; if (FloatPane == null) { IsHidden = true; // to reduce the screen flicker FloatPane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(Content, DockState.Float, false); FloatPane.FloatWindow.StartPosition = FormStartPosition.Manual; } FloatPane.FloatWindow.Bounds = floatWindowBounds; Show(dockPanel, DockState.Float); Activate(); dockPanel.ResumeLayout(true, true); } public void Show(DockPane pane, IDockContent beforeContent) { if (pane == null) throw (new ArgumentNullException(Strings.DockContentHandler_Show_NullPane)); if (beforeContent != null && pane.Contents.IndexOf(beforeContent) == -1) throw (new ArgumentException(Strings.DockContentHandler_Show_InvalidBeforeContent)); pane.DockPanel.SuspendLayout(true); DockPanel = pane.DockPanel; Pane = pane; pane.SetContentIndex(Content, pane.Contents.IndexOf(beforeContent)); Show(); pane.DockPanel.ResumeLayout(true, true); } public void Show(DockPane previousPane, DockAlignment alignment, double proportion) { if (previousPane == null) throw (new ArgumentException(Strings.DockContentHandler_Show_InvalidPrevPane)); if (DockHelper.IsDockStateAutoHide(previousPane.DockState)) throw (new ArgumentException(Strings.DockContentHandler_Show_InvalidPrevPane)); previousPane.DockPanel.SuspendLayout(true); DockPanel = previousPane.DockPanel; DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(Content, previousPane, alignment, proportion, true); Show(); previousPane.DockPanel.ResumeLayout(true, true); } public void Close() { DockPanel dockPanel = DockPanel; if (dockPanel != null) dockPanel.SuspendLayout(true); Form.Close(); if (dockPanel != null) dockPanel.ResumeLayout(true, true); } private DockPaneStripBase.Tab m_tab = null; internal DockPaneStripBase.Tab GetTab(DockPaneStripBase dockPaneStrip) { if (m_tab == null) m_tab = dockPaneStrip.CreateTab(Content); return m_tab; } private IDisposable m_autoHideTab = null; internal IDisposable AutoHideTab { get { return m_autoHideTab; } set { m_autoHideTab = value; } } #region Events private static readonly object DockStateChangedEvent = new object(); public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } #endregion private void Form_Disposed(object sender, EventArgs e) { Dispose(); } private void Form_TextChanged(object sender, EventArgs e) { if (DockHelper.IsDockStateAutoHide(DockState)) DockPanel.RefreshAutoHideStrip(); else if (Pane != null) { if (Pane.FloatWindow != null) Pane.FloatWindow.SetText(); Pane.RefreshChanges(); } } private bool m_flagClipWindow = false; internal bool FlagClipWindow { get { return m_flagClipWindow; } set { if (m_flagClipWindow == value) return; m_flagClipWindow = value; if (m_flagClipWindow) Form.Region = new Region(Rectangle.Empty); else Form.Region = null; } } private ContextMenuStrip m_tabPageContextMenuStrip; public ContextMenuStrip TabPageContextMenuStrip { get { return m_tabPageContextMenuStrip; } set { if (value == m_tabPageContextMenuStrip) return; m_tabPageContextMenuStrip = value; ApplyTheme(); } } public void ApplyTheme() { if (m_tabPageContextMenuStrip != null && DockPanel != null) DockPanel.Theme.ApplyTo(m_tabPageContextMenuStrip); } #region IDockDragSource Members Control IDragSource.DragControl { get { return Form; } } bool IDockDragSource.CanDockTo(DockPane pane) { if (!IsDockStateValid(pane.DockState)) return false; if (Pane == pane && pane.DisplayingContents.Count == 1) return false; return true; } Rectangle IDockDragSource.BeginDrag(Point ptMouse) { Size size; DockPane floatPane = this.FloatPane; if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1) size = DockPanel.DefaultFloatWindowSize; else size = floatPane.FloatWindow.Size; Point location; Rectangle rectPane = Pane.ClientRectangle; if (DockState == DockState.Document) { if (Pane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) location = new Point(rectPane.Left, rectPane.Bottom - size.Height); else location = new Point(rectPane.Left, rectPane.Top); } else { location = new Point(rectPane.Left, rectPane.Bottom); location.Y -= size.Height; } location = Pane.PointToScreen(location); if (ptMouse.X > location.X + size.Width) location.X += ptMouse.X - (location.X + size.Width) + DockPanel.Theme.Measures.SplitterSize; return new Rectangle(location, size); } void IDockDragSource.EndDrag() { } public void FloatAt(Rectangle floatWindowBounds) { // TODO: where is the pane used? DockPane pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(Content, floatWindowBounds, true); } public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) { if (dockStyle == DockStyle.Fill) { bool samePane = (Pane == pane); if (!samePane) Pane = pane; int visiblePanes = 0; int convertedIndex = 0; while (visiblePanes <= contentIndex && convertedIndex < Pane.Contents.Count) { DockContent window = Pane.Contents[convertedIndex] as DockContent; if (window != null && !window.IsHidden) ++visiblePanes; ++convertedIndex; } contentIndex = Math.Min(Math.Max(0, convertedIndex - 1), Pane.Contents.Count - 1); if (contentIndex == -1 || !samePane) pane.SetContentIndex(Content, contentIndex); else { DockContentCollection contents = pane.Contents; int oldIndex = contents.IndexOf(Content); int newIndex = contentIndex; if (oldIndex < newIndex) { newIndex += 1; if (newIndex > contents.Count - 1) newIndex = -1; } pane.SetContentIndex(Content, newIndex); } } else { DockPane paneFrom = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(Content, pane.DockState, true); INestedPanesContainer container = pane.NestedPanesContainer; if (dockStyle == DockStyle.Left) paneFrom.DockTo(container, pane, DockAlignment.Left, 0.5); else if (dockStyle == DockStyle.Right) paneFrom.DockTo(container, pane, DockAlignment.Right, 0.5); else if (dockStyle == DockStyle.Top) paneFrom.DockTo(container, pane, DockAlignment.Top, 0.5); else if (dockStyle == DockStyle.Bottom) paneFrom.DockTo(container, pane, DockAlignment.Bottom, 0.5); paneFrom.DockState = pane.DockState; } if(PatchController.EnableActivateOnDockFix == true) Pane.ActiveContent = Content; } public void DockTo(DockPanel panel, DockStyle dockStyle) { if (panel != DockPanel) throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, nameof(panel)); DockPane pane; if (dockStyle == DockStyle.Top) pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(Content, DockState.DockTop, true); else if (dockStyle == DockStyle.Bottom) pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(Content, DockState.DockBottom, true); else if (dockStyle == DockStyle.Left) pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(Content, DockState.DockLeft, true); else if (dockStyle == DockStyle.Right) pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(Content, DockState.DockRight, true); else if (dockStyle == DockStyle.Fill) pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(Content, DockState.Document, true); else return; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using FiltersSample.Areas.HelpPage.ModelDescriptions; using FiltersSample.Areas.HelpPage.Models; namespace FiltersSample.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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.Composition.Runtime.Util; using System.Linq; namespace System.Composition.Hosting.Core { /// <summary> /// The link between exports and imports. /// </summary> public sealed class CompositionContract { private readonly Type _contractType; private readonly string _contractName; private readonly IDictionary<string, object> _metadataConstraints; /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> public CompositionContract(Type contractType) : this(contractType, null) { } /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> /// <param name="contractName">Optionally, a name that discriminates this contract from others with the same type.</param> public CompositionContract(Type contractType, string contractName) : this(contractType, contractName, null) { } /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> /// <param name="contractName">Optionally, a name that discriminates this contract from others with the same type.</param> /// <param name="metadataConstraints">Optionally, a non-empty collection of named constraints that apply to the contract.</param> public CompositionContract(Type contractType, string contractName, IDictionary<string, object> metadataConstraints) { if (contractType == null) throw new ArgumentNullException(nameof(contractType)); if (metadataConstraints != null && metadataConstraints.Count == 0) throw new ArgumentOutOfRangeException(nameof(metadataConstraints)); _contractType = contractType; _contractName = contractName; _metadataConstraints = metadataConstraints; } /// <summary> /// The type shared between the exporter and importer. /// </summary> public Type ContractType { get { return _contractType; } } /// <summary> /// A name that discriminates this contract from others with the same type. /// </summary> public string ContractName { get { return _contractName; } } /// <summary> /// Constraints applied to the contract. Instead of using this collection /// directly it is advisable to use the <see cref="TryUnwrapMetadataConstraint"/> method. /// </summary> public IEnumerable<KeyValuePair<string, object>> MetadataConstraints { get { return _metadataConstraints; } } /// <summary> /// Determines equality between two contracts. /// </summary> /// <param name="obj">The contract to test.</param> /// <returns>True if the the contracts are equivalent; otherwise, false.</returns> public override bool Equals(object obj) { var contract = obj as CompositionContract; return contract != null && contract._contractType.Equals(_contractType) && (_contractName == null ? contract._contractName == null : _contractName.Equals(contract._contractName)) && ConstraintEqual(_metadataConstraints, contract._metadataConstraints); } /// <summary> /// Gets a hash code for the contract. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { var hc = _contractType.GetHashCode(); if (_contractName != null) hc = hc ^ _contractName.GetHashCode(); if (_metadataConstraints != null) hc = hc ^ ConstraintHashCode(_metadataConstraints); return hc; } /// <summary> /// Creates a string representaiton of the contract. /// </summary> /// <returns>A string representaiton of the contract.</returns> public override string ToString() { var result = Formatters.Format(_contractType); if (_contractName != null) result += " " + Formatters.Format(_contractName); if (_metadataConstraints != null) result += string.Format(" {{ {0} }}", string.Join(Properties.Resources.Formatter_ListSeparatorWithSpace, _metadataConstraints.Select(kv => string.Format("{0} = {1}", kv.Key, Formatters.Format(kv.Value))))); return result; } /// <summary> /// Transform the contract into a matching contract with a /// new contract type (with the same contract name and constraints). /// </summary> /// <param name="newContractType">The contract type for the new contract.</param> /// <returns>A matching contract with a /// new contract type.</returns> public CompositionContract ChangeType(Type newContractType) { if (newContractType == null) throw new ArgumentNullException(nameof(newContractType)); return new CompositionContract(newContractType, _contractName, _metadataConstraints); } /// <summary> /// Check the contract for a constraint with a particular name and value, and, if it exists, /// retrieve both the value and the remainder of the contract with the constraint /// removed. /// </summary> /// <typeparam name="T">The type of the constraint value.</typeparam> /// <param name="constraintName">The name of the constraint.</param> /// <param name="constraintValue">The value if it is present and of the correct type, otherwise null.</param> /// <param name="remainingContract">The contract with the constraint removed if present, otherwise null.</param> /// <returns>True if the constraint is present and of the correct type, otherwise false.</returns> public bool TryUnwrapMetadataConstraint<T>(string constraintName, out T constraintValue, out CompositionContract remainingContract) { if (constraintName == null) throw new ArgumentNullException(nameof(constraintName)); constraintValue = default(T); remainingContract = null; if (_metadataConstraints == null) return false; object value; if (!_metadataConstraints.TryGetValue(constraintName, out value)) return false; if (!(value is T)) return false; constraintValue = (T)value; if (_metadataConstraints.Count == 1) { remainingContract = new CompositionContract(_contractType, _contractName); } else { var remainingConstraints = new Dictionary<string, object>(_metadataConstraints); remainingConstraints.Remove(constraintName); remainingContract = new CompositionContract(_contractType, _contractName, remainingConstraints); } return true; } internal static bool ConstraintEqual(IDictionary<string, object> first, IDictionary<string, object> second) { if (first == second) return true; if (first == null || second == null) return false; if (first.Count != second.Count) return false; foreach (var firstItem in first) { object secondValue; if (!second.TryGetValue(firstItem.Key, out secondValue)) return false; if (firstItem.Value == null && secondValue != null || secondValue == null && firstItem.Value != null) { return false; } else { var firstEnumerable = firstItem.Value as IEnumerable; if (firstEnumerable != null && !(firstEnumerable is string)) { var secondEnumerable = secondValue as IEnumerable; if (secondEnumerable == null || !Enumerable.SequenceEqual(firstEnumerable.Cast<object>(), secondEnumerable.Cast<object>())) return false; } else if (!firstItem.Value.Equals(secondValue)) { return false; } } } return true; } private static int ConstraintHashCode(IDictionary<string, object> metadata) { var result = -1; foreach (var kv in metadata) { result ^= kv.Key.GetHashCode(); if (kv.Value != null) { var sval = kv.Value as string; if (sval != null) { result ^= sval.GetHashCode(); } else { var enumerableValue = kv.Value as IEnumerable; if (enumerableValue != null) { foreach (var ev in enumerableValue) if (ev != null) result ^= ev.GetHashCode(); } else { result ^= kv.Value.GetHashCode(); } } } } return result; } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using Markdig.Helpers; using Markdig.Parsers; using Markdig.Syntax; using Markdig.Syntax.Inlines; namespace Markdig.Extensions.Footnotes { /// <summary> /// The block parser for a <see cref="Footnote"/>. /// </summary> /// <seealso cref="BlockParser" /> public class FootnoteParser : BlockParser { /// <summary> /// The key used to store at the document level the pending <see cref="FootnoteGroup"/> /// </summary> private static readonly object DocumentKey = typeof(Footnote); public FootnoteParser() { OpeningCharacters = new [] {'['}; } public override BlockState TryOpen(BlockProcessor processor) { return TryOpen(processor, false); } private BlockState TryOpen(BlockProcessor processor, bool isContinue) { // We expect footnote to appear only at document level and not indented more than a code indent block var currentContainer = processor.GetCurrentContainerOpened(); if (processor.IsCodeIndent || (!isContinue && currentContainer.GetType() != typeof(MarkdownDocument)) || (isContinue && !(currentContainer is FootnoteGroup))) { return BlockState.None; } var saved = processor.Column; int start = processor.Start; if (!LinkHelper.TryParseLabel(ref processor.Line, false, out string label, out SourceSpan labelSpan) || !label.StartsWith("^") || processor.CurrentChar != ':') { processor.GoToColumn(saved); return BlockState.None; } // Advance the column int deltaColumn = processor.Start - start; processor.Column = processor.Column + deltaColumn; processor.NextChar(); // Skip ':' var footnote = new Footnote(this) { Label = label, LabelSpan = labelSpan, }; // Maintain a list of all footnotes at document level var footnotes = processor.Document.GetData(DocumentKey) as FootnoteGroup; if (footnotes == null) { footnotes = new FootnoteGroup(this); processor.Document.Add(footnotes); processor.Document.SetData(DocumentKey, footnotes); processor.Document.ProcessInlinesEnd += Document_ProcessInlinesEnd; } footnotes.Add(footnote); var linkRef = new FootnoteLinkReferenceDefinition() { Footnote = footnote, CreateLinkInline = CreateLinkToFootnote, Line = processor.LineIndex, Span = new SourceSpan(start, processor.Start - 2), // account for ]: LabelSpan = labelSpan, Label = label }; processor.Document.SetLinkReferenceDefinition(footnote.Label, linkRef); processor.NewBlocks.Push(footnote); return BlockState.Continue; } public override BlockState TryContinue(BlockProcessor processor, Block block) { var footnote = (Footnote) block; if (processor.CurrentBlock == null || processor.CurrentBlock.IsBreakable) { if (processor.IsBlankLine) { footnote.IsLastLineEmpty = true; return BlockState.ContinueDiscard; } if (processor.Column == 0) { if (footnote.IsLastLineEmpty) { // Close the current footnote processor.Close(footnote); // Parse any opening footnote return TryOpen(processor); } // Make sure that consecutive footnotes without a blanklines are parsed correctly if (TryOpen(processor, true) == BlockState.Continue) { processor.Close(footnote); return BlockState.Continue; } } } footnote.IsLastLineEmpty = false; if (processor.IsCodeIndent) { processor.GoToCodeIndent(); } return BlockState.Continue; } /// <summary> /// Add footnotes to the end of the document /// </summary> /// <param name="state">The processor.</param> /// <param name="inline">The inline.</param> private void Document_ProcessInlinesEnd(InlineProcessor state, Inline inline) { // Unregister state.Document.ProcessInlinesEnd -= Document_ProcessInlinesEnd; var footnotes = ((FootnoteGroup)state.Document.GetData(DocumentKey)); // Remove the footnotes from the document and readd them at the end state.Document.Remove(footnotes); state.Document.Add(footnotes); state.Document.RemoveData(DocumentKey); footnotes.Sort( (leftObj, rightObj) => { var left = (Footnote)leftObj; var right = (Footnote)rightObj; return left.Order >= 0 && right.Order >= 0 ? left.Order.CompareTo(right.Order) : 0; }); int linkIndex = 0; for (int i = 0; i < footnotes.Count; i++) { var footnote = (Footnote)footnotes[i]; if (footnote.Order < 0) { // Remove this footnote if it doesn't have any links footnotes.RemoveAt(i); i--; continue; } // Insert all footnote backlinks var paragraphBlock = footnote.LastChild as ParagraphBlock; if (paragraphBlock == null) { paragraphBlock = new ParagraphBlock(); footnote.Add(paragraphBlock); } if (paragraphBlock.Inline == null) { paragraphBlock.Inline = new ContainerInline(); } foreach (var link in footnote.Links) { linkIndex++; link.Index = linkIndex; var backLink = new FootnoteLink() { Index = linkIndex, IsBackLink = true, Footnote = footnote }; paragraphBlock.Inline.AppendChild(backLink); } } } private static Inline CreateLinkToFootnote(InlineProcessor state, LinkReferenceDefinition linkRef, Inline child) { var footnote = ((FootnoteLinkReferenceDefinition)linkRef).Footnote; if (footnote.Order < 0) { var footnotes = (FootnoteGroup)state.Document.GetData(DocumentKey); footnotes.CurrentOrder++; footnote.Order = footnotes.CurrentOrder; } var link = new FootnoteLink() {Footnote = footnote}; footnote.Links.Add(link); return link; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyComplex { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class PolymorphismExtensions { /// <summary> /// Get complex types that are polymorphic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Fish GetValid(this IPolymorphism operations) { return Task.Factory.StartNew(s => ((IPolymorphism)s).GetValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get complex types that are polymorphic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Fish> GetValidAsync( this IPolymorphism operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put complex types that are polymorphic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put a salmon that looks like this: /// { /// 'fishtype':'Salmon', /// 'location':'alaska', /// 'iswild':true, /// 'species':'king', /// 'length':1.0, /// 'siblings':[ /// { /// 'fishtype':'Shark', /// 'age':6, /// 'birthday': '2012-01-05T01:00:00Z', /// 'length':20.0, /// 'species':'predator', /// }, /// { /// 'fishtype':'Sawshark', /// 'age':105, /// 'birthday': '1900-01-05T01:00:00Z', /// 'length':10.0, /// 'picture': new Buffer([255, 255, 255, 255, /// 254]).toString('base64'), /// 'species':'dangerous', /// }, /// { /// 'fishtype': 'goblin', /// 'age': 1, /// 'birthday': '2015-08-08T00:00:00Z', /// 'length': 30.0, /// 'species': 'scary', /// 'jawsize': 5 /// } /// ] /// }; /// </param> public static void PutValid(this IPolymorphism operations, Fish complexBody) { Task.Factory.StartNew(s => ((IPolymorphism)s).PutValidAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types that are polymorphic /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put a salmon that looks like this: /// { /// 'fishtype':'Salmon', /// 'location':'alaska', /// 'iswild':true, /// 'species':'king', /// 'length':1.0, /// 'siblings':[ /// { /// 'fishtype':'Shark', /// 'age':6, /// 'birthday': '2012-01-05T01:00:00Z', /// 'length':20.0, /// 'species':'predator', /// }, /// { /// 'fishtype':'Sawshark', /// 'age':105, /// 'birthday': '1900-01-05T01:00:00Z', /// 'length':10.0, /// 'picture': new Buffer([255, 255, 255, 255, /// 254]).toString('base64'), /// 'species':'dangerous', /// }, /// { /// 'fishtype': 'goblin', /// 'age': 1, /// 'birthday': '2015-08-08T00:00:00Z', /// 'length': 30.0, /// 'species': 'scary', /// 'jawsize': 5 /// } /// ] /// }; /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutValidAsync( this IPolymorphism operations, Fish complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutValidWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put complex types that are polymorphic, attempting to omit required /// 'birthday' field - the request should not be allowed from the client /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please attempt put a sawshark that looks like this, the client should not /// allow this data to be sent: /// { /// "fishtype": "sawshark", /// "species": "snaggle toothed", /// "length": 18.5, /// "age": 2, /// "birthday": "2013-06-01T01:00:00Z", /// "location": "alaska", /// "picture": base64(FF FF FF FF FE), /// "siblings": [ /// { /// "fishtype": "shark", /// "species": "predator", /// "birthday": "2012-01-05T01:00:00Z", /// "length": 20, /// "age": 6 /// }, /// { /// "fishtype": "sawshark", /// "species": "dangerous", /// "picture": base64(FF FF FF FF FE), /// "length": 10, /// "age": 105 /// } /// ] /// } /// </param> public static void PutValidMissingRequired(this IPolymorphism operations, Fish complexBody) { Task.Factory.StartNew(s => ((IPolymorphism)s).PutValidMissingRequiredAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types that are polymorphic, attempting to omit required /// 'birthday' field - the request should not be allowed from the client /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please attempt put a sawshark that looks like this, the client should not /// allow this data to be sent: /// { /// "fishtype": "sawshark", /// "species": "snaggle toothed", /// "length": 18.5, /// "age": 2, /// "birthday": "2013-06-01T01:00:00Z", /// "location": "alaska", /// "picture": base64(FF FF FF FF FE), /// "siblings": [ /// { /// "fishtype": "shark", /// "species": "predator", /// "birthday": "2012-01-05T01:00:00Z", /// "length": 20, /// "age": 6 /// }, /// { /// "fishtype": "sawshark", /// "species": "dangerous", /// "picture": base64(FF FF FF FF FE), /// "length": 10, /// "age": 105 /// } /// ] /// } /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutValidMissingRequiredAsync( this IPolymorphism operations, Fish complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutValidMissingRequiredWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } } }
// 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.Runtime.InteropServices; using System.Security; using Xunit; namespace System.Tests { public class SetEnvironmentVariable { private const int MAX_VAR_LENGTH_ALLOWED = 32767; private const string NullString = "\u0000"; internal static bool IsSupportedTarget(EnvironmentVariableTarget target) { return target == EnvironmentVariableTarget.Process || (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !PlatformDetection.IsUap); } [Fact] public void NullVariableThrowsArgumentNull() { Assert.Throws<ArgumentNullException>(() => Environment.SetEnvironmentVariable(null, "test")); } [Fact] public void IncorrectVariableThrowsArgument() { AssertExtensions.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable(string.Empty, "test")); AssertExtensions.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable(NullString, "test")); AssertExtensions.Throws<ArgumentException>("variable", null, () => Environment.SetEnvironmentVariable("Variable=Something", "test")); string varWithLenLongerThanAllowed = new string('c', MAX_VAR_LENGTH_ALLOWED + 1); AssertExtensions.Throws<ArgumentException>("variable", null, () => Environment.SetEnvironmentVariable(varWithLenLongerThanAllowed, "test")); } private static void ExecuteAgainstTarget( EnvironmentVariableTarget target, Action action, Action cleanUp = null) { bool shouldCleanUp = cleanUp != null; try { action(); } catch (SecurityException) { shouldCleanUp = false; Assert.True(target == EnvironmentVariableTarget.Machine || (target == EnvironmentVariableTarget.User && PlatformDetection.IsUap), "only machine target, or user when in uap, should have access issues"); Assert.True(PlatformDetection.IsWindows, "and it should be Windows"); Assert.False(PlatformDetection.IsWindowsAndElevated, "and we shouldn't be elevated"); } finally { if (shouldCleanUp) cleanUp(); } } [Theory] [MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))] public void Default(EnvironmentVariableTarget target) { string varName = $"Test_SetEnvironmentVariable_Default ({target})"; const string value = "true"; ExecuteAgainstTarget(target, () => { Environment.SetEnvironmentVariable(varName, value, target); Assert.Equal(IsSupportedTarget(target) ? value : null, Environment.GetEnvironmentVariable(varName, target)); }, () => { // Clear the test variable Environment.SetEnvironmentVariable(varName, null, target); }); } [Theory] [MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))] public void ModifyEnvironmentVariable(EnvironmentVariableTarget target) { string varName = $"Test_ModifyEnvironmentVariable ({target})"; const string value = "false"; ExecuteAgainstTarget(target, () => { // First set the value to something and then change it and ensure that it gets modified. Environment.SetEnvironmentVariable(varName, "true", target); Environment.SetEnvironmentVariable(varName, value, target); // Check whether the variable exists. Assert.Equal(IsSupportedTarget(target) ? value : null, Environment.GetEnvironmentVariable(varName, target)); }, () => { // Clear the test variable Environment.SetEnvironmentVariable(varName, null, target); }); } [Theory] [MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))] public void ModifyEnvironmentVariable_AndEnumerate(EnvironmentVariableTarget target) { string varName = $"Test_ModifyEnvironmentVariable_AndEnumerate ({target})"; const string value = "false"; ExecuteAgainstTarget(target, () => { // First set the value to something and then change it and ensure that it gets modified. Environment.SetEnvironmentVariable(varName, "true", target); // Enumerate to validate our first value to ensure we can still set after enumerating IDictionary variables = Environment.GetEnvironmentVariables(target); if (IsSupportedTarget(target)) { Assert.True(variables.Contains(varName), "has the key we entered"); Assert.Equal("true", variables[varName]); } Environment.SetEnvironmentVariable(varName, value, target); // Check whether the variable exists. Assert.Equal(IsSupportedTarget(target) ? value : null, Environment.GetEnvironmentVariable(varName, target)); }, () => { // Clear the test variable Environment.SetEnvironmentVariable(varName, null, target); }); } [Theory] [MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))] public void DeleteEnvironmentVariable(EnvironmentVariableTarget target) { string varName = $"Test_DeleteEnvironmentVariable ({target})"; const string value = "false"; ExecuteAgainstTarget(target, () => { // First set the value to something and then ensure that it can be deleted. Environment.SetEnvironmentVariable(varName, value); Environment.SetEnvironmentVariable(varName, string.Empty); Assert.Equal(null, Environment.GetEnvironmentVariable(varName)); Environment.SetEnvironmentVariable(varName, value); Environment.SetEnvironmentVariable(varName, null); Assert.Equal(null, Environment.GetEnvironmentVariable(varName)); Environment.SetEnvironmentVariable(varName, value); Environment.SetEnvironmentVariable(varName, NullString); Assert.Equal(null, Environment.GetEnvironmentVariable(varName)); }); } [Fact] public void DeleteEnvironmentVariableNonInitialNullInName() { const string varNamePrefix = "Begin_DeleteEnvironmentVariableNonInitialNullInName"; const string varNameSuffix = "End_DeleteEnvironmentVariableNonInitialNullInName"; const string varName = varNamePrefix + NullString + varNameSuffix; const string value = "false"; try { Environment.SetEnvironmentVariable(varName, value); Environment.SetEnvironmentVariable(varName, null); Assert.Equal(Environment.GetEnvironmentVariable(varName), null); Assert.Equal(Environment.GetEnvironmentVariable(varNamePrefix), null); } finally { // Clear the test variable Environment.SetEnvironmentVariable(varName, null); } } [Fact] public void DeleteEnvironmentVariableInitialNullInValue() { const string value = NullString + "test"; const string varName = "DeleteEnvironmentVariableInitialNullInValue"; try { Environment.SetEnvironmentVariable(varName, value); Assert.Equal(null, Environment.GetEnvironmentVariable(varName)); } finally { Environment.SetEnvironmentVariable(varName, String.Empty); } } [Fact] public void NonInitialNullCharacterInVariableName() { const string varNamePrefix = "NonInitialNullCharacterInVariableName_Begin"; const string varNameSuffix = "NonInitialNullCharacterInVariableName_End"; const string varName = varNamePrefix + NullString + varNameSuffix; const string value = "true"; try { Environment.SetEnvironmentVariable(varName, value); Assert.Equal(value, Environment.GetEnvironmentVariable(varName)); Assert.Equal(value, Environment.GetEnvironmentVariable(varNamePrefix)); } finally { Environment.SetEnvironmentVariable(varName, String.Empty); Environment.SetEnvironmentVariable(varNamePrefix, String.Empty); } } [Fact] public void NonInitialNullCharacterInValue() { const string varName = "Test_TestNonInitialZeroCharacterInValue"; const string valuePrefix = "Begin"; const string valueSuffix = "End"; const string value = valuePrefix + NullString + valueSuffix; try { Environment.SetEnvironmentVariable(varName, value); Assert.Equal(valuePrefix, Environment.GetEnvironmentVariable(varName)); } finally { Environment.SetEnvironmentVariable(varName, String.Empty); } } [Fact] public void DeleteNonExistentEnvironmentVariable() { const string varName = "Test_TestDeletingNonExistingEnvironmentVariable"; if (Environment.GetEnvironmentVariable(varName) != null) { Environment.SetEnvironmentVariable(varName, null); } Environment.SetEnvironmentVariable("TestDeletingNonExistingEnvironmentVariable", String.Empty); } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dataproc.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.Grpc; using apis = Google.Cloud.Dataproc.V1; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; /// <summary>Generated snippets</summary> public class GeneratedJobControllerClientSnippets { /// <summary>Snippet for SubmitJobAsync</summary> public async Task SubmitJobAsync() { // Snippet: SubmitJobAsync(string,string,Job,CallSettings) // Additional: SubmitJobAsync(string,string,Job,CancellationToken) // Create client JobControllerClient jobControllerClient = await JobControllerClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; string region = ""; Job job = new Job(); // Make the request Job response = await jobControllerClient.SubmitJobAsync(projectId, region, job); // End snippet } /// <summary>Snippet for SubmitJob</summary> public void SubmitJob() { // Snippet: SubmitJob(string,string,Job,CallSettings) // Create client JobControllerClient jobControllerClient = JobControllerClient.Create(); // Initialize request argument(s) string projectId = ""; string region = ""; Job job = new Job(); // Make the request Job response = jobControllerClient.SubmitJob(projectId, region, job); // End snippet } /// <summary>Snippet for SubmitJobAsync</summary> public async Task SubmitJobAsync_RequestObject() { // Snippet: SubmitJobAsync(SubmitJobRequest,CallSettings) // Additional: SubmitJobAsync(SubmitJobRequest,CancellationToken) // Create client JobControllerClient jobControllerClient = await JobControllerClient.CreateAsync(); // Initialize request argument(s) SubmitJobRequest request = new SubmitJobRequest { ProjectId = "", Region = "", Job = new Job(), }; // Make the request Job response = await jobControllerClient.SubmitJobAsync(request); // End snippet } /// <summary>Snippet for SubmitJob</summary> public void SubmitJob_RequestObject() { // Snippet: SubmitJob(SubmitJobRequest,CallSettings) // Create client JobControllerClient jobControllerClient = JobControllerClient.Create(); // Initialize request argument(s) SubmitJobRequest request = new SubmitJobRequest { ProjectId = "", Region = "", Job = new Job(), }; // Make the request Job response = jobControllerClient.SubmitJob(request); // End snippet } /// <summary>Snippet for GetJobAsync</summary> public async Task GetJobAsync() { // Snippet: GetJobAsync(string,string,string,CallSettings) // Additional: GetJobAsync(string,string,string,CancellationToken) // Create client JobControllerClient jobControllerClient = await JobControllerClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; string region = ""; string jobId = ""; // Make the request Job response = await jobControllerClient.GetJobAsync(projectId, region, jobId); // End snippet } /// <summary>Snippet for GetJob</summary> public void GetJob() { // Snippet: GetJob(string,string,string,CallSettings) // Create client JobControllerClient jobControllerClient = JobControllerClient.Create(); // Initialize request argument(s) string projectId = ""; string region = ""; string jobId = ""; // Make the request Job response = jobControllerClient.GetJob(projectId, region, jobId); // End snippet } /// <summary>Snippet for GetJobAsync</summary> public async Task GetJobAsync_RequestObject() { // Snippet: GetJobAsync(GetJobRequest,CallSettings) // Additional: GetJobAsync(GetJobRequest,CancellationToken) // Create client JobControllerClient jobControllerClient = await JobControllerClient.CreateAsync(); // Initialize request argument(s) GetJobRequest request = new GetJobRequest { ProjectId = "", Region = "", JobId = "", }; // Make the request Job response = await jobControllerClient.GetJobAsync(request); // End snippet } /// <summary>Snippet for GetJob</summary> public void GetJob_RequestObject() { // Snippet: GetJob(GetJobRequest,CallSettings) // Create client JobControllerClient jobControllerClient = JobControllerClient.Create(); // Initialize request argument(s) GetJobRequest request = new GetJobRequest { ProjectId = "", Region = "", JobId = "", }; // Make the request Job response = jobControllerClient.GetJob(request); // End snippet } /// <summary>Snippet for ListJobsAsync</summary> public async Task ListJobsAsync() { // Snippet: ListJobsAsync(string,string,string,int?,CallSettings) // Create client JobControllerClient jobControllerClient = await JobControllerClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; string region = ""; // Make the request PagedAsyncEnumerable<ListJobsResponse, Job> response = jobControllerClient.ListJobsAsync(projectId, region); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Job item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListJobsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Job item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Job> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Job item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListJobs</summary> public void ListJobs() { // Snippet: ListJobs(string,string,string,int?,CallSettings) // Create client JobControllerClient jobControllerClient = JobControllerClient.Create(); // Initialize request argument(s) string projectId = ""; string region = ""; // Make the request PagedEnumerable<ListJobsResponse, Job> response = jobControllerClient.ListJobs(projectId, region); // Iterate over all response items, lazily performing RPCs as required foreach (Job item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListJobsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Job item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Job> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Job item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListJobsAsync</summary> public async Task ListJobsAsync_RequestObject() { // Snippet: ListJobsAsync(ListJobsRequest,CallSettings) // Create client JobControllerClient jobControllerClient = await JobControllerClient.CreateAsync(); // Initialize request argument(s) ListJobsRequest request = new ListJobsRequest { ProjectId = "", Region = "", }; // Make the request PagedAsyncEnumerable<ListJobsResponse, Job> response = jobControllerClient.ListJobsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Job item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListJobsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Job item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Job> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Job item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListJobs</summary> public void ListJobs_RequestObject() { // Snippet: ListJobs(ListJobsRequest,CallSettings) // Create client JobControllerClient jobControllerClient = JobControllerClient.Create(); // Initialize request argument(s) ListJobsRequest request = new ListJobsRequest { ProjectId = "", Region = "", }; // Make the request PagedEnumerable<ListJobsResponse, Job> response = jobControllerClient.ListJobs(request); // Iterate over all response items, lazily performing RPCs as required foreach (Job item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListJobsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Job item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Job> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Job item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for UpdateJobAsync</summary> public async Task UpdateJobAsync_RequestObject() { // Snippet: UpdateJobAsync(UpdateJobRequest,CallSettings) // Additional: UpdateJobAsync(UpdateJobRequest,CancellationToken) // Create client JobControllerClient jobControllerClient = await JobControllerClient.CreateAsync(); // Initialize request argument(s) UpdateJobRequest request = new UpdateJobRequest { ProjectId = "", Region = "", JobId = "", Job = new Job(), UpdateMask = new FieldMask(), }; // Make the request Job response = await jobControllerClient.UpdateJobAsync(request); // End snippet } /// <summary>Snippet for UpdateJob</summary> public void UpdateJob_RequestObject() { // Snippet: UpdateJob(UpdateJobRequest,CallSettings) // Create client JobControllerClient jobControllerClient = JobControllerClient.Create(); // Initialize request argument(s) UpdateJobRequest request = new UpdateJobRequest { ProjectId = "", Region = "", JobId = "", Job = new Job(), UpdateMask = new FieldMask(), }; // Make the request Job response = jobControllerClient.UpdateJob(request); // End snippet } /// <summary>Snippet for CancelJobAsync</summary> public async Task CancelJobAsync() { // Snippet: CancelJobAsync(string,string,string,CallSettings) // Additional: CancelJobAsync(string,string,string,CancellationToken) // Create client JobControllerClient jobControllerClient = await JobControllerClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; string region = ""; string jobId = ""; // Make the request Job response = await jobControllerClient.CancelJobAsync(projectId, region, jobId); // End snippet } /// <summary>Snippet for CancelJob</summary> public void CancelJob() { // Snippet: CancelJob(string,string,string,CallSettings) // Create client JobControllerClient jobControllerClient = JobControllerClient.Create(); // Initialize request argument(s) string projectId = ""; string region = ""; string jobId = ""; // Make the request Job response = jobControllerClient.CancelJob(projectId, region, jobId); // End snippet } /// <summary>Snippet for CancelJobAsync</summary> public async Task CancelJobAsync_RequestObject() { // Snippet: CancelJobAsync(CancelJobRequest,CallSettings) // Additional: CancelJobAsync(CancelJobRequest,CancellationToken) // Create client JobControllerClient jobControllerClient = await JobControllerClient.CreateAsync(); // Initialize request argument(s) CancelJobRequest request = new CancelJobRequest { ProjectId = "", Region = "", JobId = "", }; // Make the request Job response = await jobControllerClient.CancelJobAsync(request); // End snippet } /// <summary>Snippet for CancelJob</summary> public void CancelJob_RequestObject() { // Snippet: CancelJob(CancelJobRequest,CallSettings) // Create client JobControllerClient jobControllerClient = JobControllerClient.Create(); // Initialize request argument(s) CancelJobRequest request = new CancelJobRequest { ProjectId = "", Region = "", JobId = "", }; // Make the request Job response = jobControllerClient.CancelJob(request); // End snippet } /// <summary>Snippet for DeleteJobAsync</summary> public async Task DeleteJobAsync() { // Snippet: DeleteJobAsync(string,string,string,CallSettings) // Additional: DeleteJobAsync(string,string,string,CancellationToken) // Create client JobControllerClient jobControllerClient = await JobControllerClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; string region = ""; string jobId = ""; // Make the request await jobControllerClient.DeleteJobAsync(projectId, region, jobId); // End snippet } /// <summary>Snippet for DeleteJob</summary> public void DeleteJob() { // Snippet: DeleteJob(string,string,string,CallSettings) // Create client JobControllerClient jobControllerClient = JobControllerClient.Create(); // Initialize request argument(s) string projectId = ""; string region = ""; string jobId = ""; // Make the request jobControllerClient.DeleteJob(projectId, region, jobId); // End snippet } /// <summary>Snippet for DeleteJobAsync</summary> public async Task DeleteJobAsync_RequestObject() { // Snippet: DeleteJobAsync(DeleteJobRequest,CallSettings) // Additional: DeleteJobAsync(DeleteJobRequest,CancellationToken) // Create client JobControllerClient jobControllerClient = await JobControllerClient.CreateAsync(); // Initialize request argument(s) DeleteJobRequest request = new DeleteJobRequest { ProjectId = "", Region = "", JobId = "", }; // Make the request await jobControllerClient.DeleteJobAsync(request); // End snippet } /// <summary>Snippet for DeleteJob</summary> public void DeleteJob_RequestObject() { // Snippet: DeleteJob(DeleteJobRequest,CallSettings) // Create client JobControllerClient jobControllerClient = JobControllerClient.Create(); // Initialize request argument(s) DeleteJobRequest request = new DeleteJobRequest { ProjectId = "", Region = "", JobId = "", }; // Make the request jobControllerClient.DeleteJob(request); // End snippet } } }
namespace FakeItEasy.Creation.DelegateProxies { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Castle.DynamicProxy; using FakeItEasy.Configuration; using FakeItEasy.Core; internal static class DelegateProxyGenerator { private static readonly ProxyGenerator ProxyGenerator = new ProxyGenerator(); private static readonly ConcurrentDictionary<Type, bool> AccessibleToDynamicProxyCache = new ConcurrentDictionary<Type, bool>(); [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Appropriate in Try-style methods")] public static ProxyGeneratorResult GenerateProxy( Type typeOfProxy, IFakeCallProcessorProvider fakeCallProcessorProvider) { Guard.AgainstNull(typeOfProxy); var invokeMethod = typeOfProxy.GetMethod("Invoke")!; if (!IsAccessibleToDynamicProxy(typeOfProxy)) { try { // This is the only way to get the proper error message. // The need for this will go away when we start really using DynamicProxy to generate delegate proxies. ProxyGenerator.CreateClassProxy(typeOfProxy); } catch (Exception ex) { return new ProxyGeneratorResult(ex.Message); } } var eventRaiser = new DelegateCallInterceptedEventRaiser(fakeCallProcessorProvider, invokeMethod, typeOfProxy); fakeCallProcessorProvider.EnsureInitialized(eventRaiser.Instance); return new ProxyGeneratorResult(eventRaiser.Instance); } private static bool IsAccessibleToDynamicProxy(Type type) { return AccessibleToDynamicProxyCache.GetOrAdd(type, IsAccessibleImpl); bool IsAccessibleImpl(Type t) { if (!ProxyUtil.IsAccessible(t)) { return false; } if (type.IsGenericType && !type.IsGenericTypeDefinition) { return t.GetGenericArguments().All(IsAccessibleToDynamicProxy); } return true; } } private static Delegate CreateDelegateProxy( Type typeOfProxy, MethodInfo invokeMethod, DelegateCallInterceptedEventRaiser eventRaiser) { var parameterExpressions = invokeMethod.GetParameters().Select(x => Expression.Parameter(x.ParameterType, x.Name)).ToArray(); var body = CreateBodyExpression(invokeMethod, eventRaiser, parameterExpressions); return Expression.Lambda(typeOfProxy, body, parameterExpressions).Compile(); } // Generate a method that: // - wraps its arguments in an object array // - passes this array to eventRaiser.Raise() // - assigns the output values back to the ref/out parameters // - casts and returns the result of eventRaiser.Raise() // // For instance, for a delegate like this: // // delegate int Foo(int x, ref int y, out int z); // // We generate a method like this: // // int ProxyFoo(int x, ref int y, out int z) // { // var arguments = new[]{ (object)x, (object)y, (object)z }; // var result = (int)eventRaiser.Raise(arguments); // y = (int)arguments[1]; // z = (int)arguments[2]; // return result; // } // // Or, for a delegate with void return type: // // delegate void Foo(int x, ref int y, out int z); // // void ProxyFoo(int x, ref int y, out int z) // { // var arguments = new[]{ (object)x, (object)y, (object)z }; // eventRaiser.Raise(arguments); // y = (int)arguments[1]; // z = (int)arguments[2]; // } private static Expression CreateBodyExpression( MethodInfo delegateMethod, DelegateCallInterceptedEventRaiser eventRaiser, ParameterExpression[] parameterExpressions) { bool isVoid = delegateMethod.ReturnType == typeof(void); // Local variables of the generated method var arguments = Expression.Variable(typeof(object[]), "arguments"); var result = isVoid ? null : Expression.Variable(delegateMethod.ReturnType, "result"); var bodyExpressions = new List<Expression>(); bodyExpressions.Add(Expression.Assign(arguments, WrapParametersInObjectArray(parameterExpressions))); Expression call = Expression.Call( Expression.Constant(eventRaiser), DelegateCallInterceptedEventRaiser.RaiseMethod, arguments); if (!isVoid) { // If the return type is non void, cast the result of eventRaiser.Raise() // to the real return type and assign to the result variable call = Expression.Assign(result!, Expression.Convert(call, delegateMethod.ReturnType)); } bodyExpressions.Add(call); // After the call, copy the values back to the ref/out parameters for (int index = 0; index < parameterExpressions.Length; index++) { var parameter = parameterExpressions[index]; if (parameter.IsByRef) { var assignment = AssignParameterFromArrayElement(arguments, index, parameter); bodyExpressions.Add(assignment); } } // Return the result if the return type is non-void if (!isVoid) { bodyExpressions.Add(result!); } var variables = isVoid ? new[] { arguments } : new[] { arguments, result! }; return Expression.Block(variables, bodyExpressions); } private static BinaryExpression AssignParameterFromArrayElement( ParameterExpression arguments, int index, ParameterExpression parameter) { return Expression.Assign( parameter, Expression.Convert(Expression.ArrayAccess(arguments, Expression.Constant(index)), parameter.Type)); } private static NewArrayExpression WrapParametersInObjectArray(ParameterExpression[] parameterExpressions) { return Expression.NewArrayInit( typeof(object), parameterExpressions.Select(x => Expression.Convert(x, typeof(object)))); } private class DelegateCallInterceptedEventRaiser { public static readonly MethodInfo RaiseMethod = typeof(DelegateCallInterceptedEventRaiser).GetMethod(nameof(Raise))!; private readonly IFakeCallProcessorProvider fakeCallProcessorProvider; private readonly MethodInfo method; public DelegateCallInterceptedEventRaiser(IFakeCallProcessorProvider fakeCallProcessorProvider, MethodInfo method, Type type) { this.fakeCallProcessorProvider = fakeCallProcessorProvider; this.method = method; this.Instance = CreateDelegateProxy(type, method, this); } public Delegate Instance { get; } public object? Raise(object[] arguments) { var call = new DelegateFakeObjectCall(this.Instance, this.method, arguments); this.fakeCallProcessorProvider.Fetch(this.Instance).Process(call); return call.ReturnValue; } } private class DelegateFakeObjectCall : InterceptedFakeObjectCall { private readonly object[] originalArguments; public DelegateFakeObjectCall(Delegate instance, MethodInfo method, object[] arguments) { this.FakedObject = instance; this.originalArguments = arguments.ToArray(); this.Arguments = new ArgumentCollection(arguments, method); this.Method = method; } public override object? ReturnValue { get; set; } public override MethodInfo Method { get; } public override ArgumentCollection Arguments { get; } public override object FakedObject { get; } public override void CallBaseMethod() { throw new FakeConfigurationException(ExceptionMessages.DelegateCannotCallBaseMethod); } public override void SetArgumentValue(int index, object? value) { this.Arguments.GetUnderlyingArgumentsArray()[index] = value; } public override CompletedFakeObjectCall ToCompletedCall() { return new CompletedFakeObjectCall( this, this.originalArguments); } } } }
/* 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: * * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using XenAPI; using XenAdmin.Actions.Wlb; using XenAdmin.Core; using XenAdmin.Wlb; using XenAdmin.Controls; namespace XenAdmin.Dialogs.Wlb { public partial class WlbReportSubscriptionDialog : XenAdmin.Dialogs.XenDialogBase { #region Variables private Pool _pool; private string _reportDisplayName; private Dictionary<string, string> _rpParams; private WlbReportSubscription _subscription; private string _subId = String.Empty; ToolTip InvalidParamToolTip = new ToolTip(); // Due to localization, changed email regex from @"^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)*[A-Z0-9-]+$" // to match anything with an @ sign in the middle private static readonly Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase); private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Constructors // Create new subscription public WlbReportSubscriptionDialog(string reportDisplayName, Dictionary<string, string> reportParams, Pool pool) : base(pool.Connection) { _rpParams = reportParams; _subscription = null; _reportDisplayName = reportDisplayName; _pool = pool; init(); } // Edit existing subscription public WlbReportSubscriptionDialog(string reportDisplayName, WlbReportSubscription subscription, Pool pool) : base(pool.Connection) { _subId = subscription.Id; _rpParams = subscription.ReportParameters; _subscription = subscription; _reportDisplayName = reportDisplayName; _pool = pool; init(); } #endregion #region Private Methods private void init() { InitializeComponent(); InitializeControls(); // Initialize InvalidParamToolTip InvalidParamToolTip.IsBalloon = true; InvalidParamToolTip.ToolTipIcon = ToolTipIcon.Warning; InvalidParamToolTip.ToolTipTitle = Messages.INVALID_PARAMETER; if (null != _subscription) { LoadSubscription(); } } private void InitializeControls() { this.Text = String.Concat(this.Text, this._reportDisplayName); this.rpParamComboBox.SelectedIndex = 0; this.rpRenderComboBox.SelectedIndex = 0; this.schedDeliverComboBox.DataSource = new BindingSource(BuildDaysOfWeek(), null); this.schedDeliverComboBox.ValueMember = "key"; this.schedDeliverComboBox.DisplayMember = "value"; ; this.schedDeliverComboBox.SelectedIndex = 1; this.dateTimePickerSchedEnd.Value = DateTime.Now.AddMonths(1); this.dateTimePickerSchedStart.Value = DateTime.Now; } private Dictionary<int, string> BuildDaysOfWeek() { Dictionary<int, string> days = new Dictionary<int, string>(); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.All, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.All)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Weekdays, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Weekdays)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Weekends, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Weekends)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Sunday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Sunday)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Monday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Monday)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Tuesday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Tuesday)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Wednesday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Wednesday)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Thursday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Thursday)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Friday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Friday)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Saturday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Saturday)); return days; } private string GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek daysOfWeek) { return WlbScheduledTask.DaysOfWeekL10N(daysOfWeek); } private void LoadSubscription() { // subscription name this.subNameTextBox.Text = this._subscription.Description; // report data range int days = 0; if (this._subscription.ReportParameters != null) { int.TryParse(this._subscription.ReportParameters["Start"], out days); } this.rpParamComboBox.SelectedIndex = (days-1)/-7 -1; // email info this.emailToTextBox.Text = this._subscription.EmailTo; this.emailCcTextBox.Text = this._subscription.EmailCc; this.emailBccTextBox.Text = this._subscription.EmailBcc; this.emailReplyTextBox.Text = this._subscription.EmailReplyTo; this.emailSubjectTextBox.Text = this._subscription.EmailSubject; this.emailCommentRichTextBox.Text = this._subscription.EmailComment; this.rpRenderComboBox.SelectedIndex = (int)this._subscription.ReportRenderFormat; // convert utc days of week and utc execute time to local days of week and local execute time DateTime localExecuteTime; WlbScheduledTask.WlbTaskDaysOfWeek localDaysOfWeek; WlbScheduledTask.GetLocalTaskTimes(this._subscription.DaysOfWeek, this._subscription.ExecuteTimeOfDay, out localDaysOfWeek, out localExecuteTime); // subscription run time this.dateTimePickerSubscriptionRunTime.Value = localExecuteTime; // subscription delivery day this.schedDeliverComboBox.SelectedValue = (int)localDaysOfWeek; // subscription enable start and end dates if (this._subscription.DisableDate != DateTime.MinValue) { this.dateTimePickerSchedEnd.Value = this._subscription.DisableDate.ToLocalTime(); } if (this._subscription.EnableDate != DateTime.MinValue) { this.dateTimePickerSchedStart.Value = this._subscription.EnableDate.ToLocalTime(); } } #endregion //Private Methods #region DateTimePicker and ComboBox Event Handler private void rpParamComboBox_SelectedIndexChanged(object sender, EventArgs e) { switch (this.rpParamComboBox.SelectedIndex) { case 0: this.dateTimePickerSchedStart.Value = DateTime.Now.AddDays(-7); break; case 1: this.dateTimePickerSchedStart.Value = DateTime.Now.AddDays(-14); break; case 2: this.dateTimePickerSchedStart.Value = DateTime.Now.AddDays(-21); break; case 3: this.dateTimePickerSchedStart.Value = DateTime.Now.AddMonths(-1); break; } this.dateTimePickerSchedEnd.Value = DateTime.Now; } private void dateTimePickerSchedEnd_ValueChanged(object sender, EventArgs e) { if (this.dateTimePickerSchedEnd.Value < this.dateTimePickerSchedStart.Value) { this.dateTimePickerSchedStart.Value = this.dateTimePickerSchedEnd.Value; } } private void dateTimePickerSchedStart_ValueChanged(object sender, EventArgs e) { if (this.dateTimePickerSchedStart.Value > this.dateTimePickerSchedEnd.Value) { this.dateTimePickerSchedEnd.Value = this.dateTimePickerSchedStart.Value; } } #endregion //DateTimePicker and ComboBox Event Handler #region Validators private bool ValidToSave() { foreach (Control ctl in this.tableLayoutPanelSubscriptionName.Controls) { if (!IsValidControl(ctl)) { HelpersGUI.ShowBalloonMessage(ctl, Messages.INVALID_PARAMETER, InvalidParamToolTip); return false; } } foreach (Control ctl in this.tableLayoutPanelDeliveryOptions.Controls) { if (!IsValidControl(ctl)) { HelpersGUI.ShowBalloonMessage(ctl, Messages.INVALID_PARAMETER, InvalidParamToolTip); return false; } } return true; } private bool IsValidControl(Control ctl) { if (String.Compare(this.subNameTextBox.Name, ctl.Name) == 0) { return !String.IsNullOrEmpty(ctl.Text); } else if (String.Compare(this.emailToTextBox.Name, ctl.Name) == 0 || String.Compare(this.emailReplyTextBox.Name, ctl.Name) == 0) { return IsValidEmail(ctl.Text); } else if (String.Compare(this.emailBccTextBox.Name, ctl.Name) == 0 || String.Compare(this.emailCcTextBox.Name, ctl.Name) == 0) { if (!String.IsNullOrEmpty(ctl.Text)) { return IsValidEmail(ctl.Text); } } return true; } private static bool IsValidEmail(string emailAddress) { foreach (string address in emailAddress.Split(new char[] { ';' })) { if (!emailRegex.IsMatch(address)) { return false; } } return true; } #endregion #region Button Click Event Handler private void saveButton_Click(object sender, EventArgs e) { if (!ValidToSave()) { this.DialogResult = DialogResult.None; } else { SaveSubscription(); InvalidParamToolTip.Dispose(); } } private void cancelButton_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; InvalidParamToolTip.Dispose(); } #endregion #region Private Methods private string GetLoggedInAsText() { if (_pool.Connection == null) { // Shouldn't happen return String.Empty; } Session session = _pool.Connection.Session; if (session == null) { return String.Empty; } return session.UserFriendlyName; } private void SaveSubscription() { if (this._subscription == null) { _subscription = new WlbReportSubscription(String.Empty); _subscription.SubscriberName = GetLoggedInAsText(); _subscription.Created = DateTime.UtcNow; } _subscription.Name = this.subNameTextBox.Text; _subscription.Description = this.subNameTextBox.Text; DateTime utcExecuteTime; WlbScheduledTask.WlbTaskDaysOfWeek utcDaysOfWeek; WlbScheduledTask.GetUTCTaskTimes((WlbScheduledTask.WlbTaskDaysOfWeek)this.schedDeliverComboBox.SelectedValue, this.dateTimePickerSubscriptionRunTime.Value, out utcDaysOfWeek, out utcExecuteTime); _subscription.ExecuteTimeOfDay = utcExecuteTime; _subscription.DaysOfWeek = utcDaysOfWeek; if (_subscription.DaysOfWeek != WlbScheduledTask.WlbTaskDaysOfWeek.All) { _subscription.TriggerType = (int)WlbScheduledTask.WlbTaskTriggerType.Weekly; } else { _subscription.TriggerType = (int)WlbScheduledTask.WlbTaskTriggerType.Daily; } _subscription.Enabled = true; _subscription.EnableDate = this.dateTimePickerSchedStart.Value == DateTime.MinValue ? DateTime.UtcNow : this.dateTimePickerSchedStart.Value.ToUniversalTime(); _subscription.DisableDate = this.dateTimePickerSchedEnd.Value == DateTime.MinValue ? DateTime.UtcNow.AddMonths(1) : this.dateTimePickerSchedEnd.Value.ToUniversalTime(); _subscription.LastTouched = DateTime.UtcNow; _subscription.LastTouchedBy = GetLoggedInAsText(); // store email info _subscription.EmailTo = this.emailToTextBox.Text.Trim(); _subscription.EmailCc = this.emailCcTextBox.Text.Trim(); _subscription.EmailBcc = this.emailBccTextBox.Text.Trim(); _subscription.EmailReplyTo = this.emailReplyTextBox.Text.Trim(); _subscription.EmailSubject = this.emailSubjectTextBox.Text.Trim(); _subscription.EmailComment = this.emailCommentRichTextBox.Text; // store reoprt Info //sub.ReportId = ; _subscription.ReportRenderFormat = this.rpRenderComboBox.SelectedIndex; Dictionary<string, string> rps = new Dictionary<string, string>(); foreach(string key in this._rpParams.Keys) { if (String.Compare(key, WlbReportSubscription.REPORT_NAME, true) == 0) _subscription.ReportName = this._rpParams[WlbReportSubscription.REPORT_NAME]; else { //Get start date range if (String.Compare(key, "start", true) == 0) { rps.Add(key, ((this.rpParamComboBox.SelectedIndex + 1) * (-7)+1).ToString()); } else { rps.Add(key, _rpParams[key]); } } } _subscription.ReportParameters = rps; SendWlbConfigurationAction action = new SendWlbConfigurationAction(this._pool, _subscription.ToDictionary(), SendWlbConfigurationKind.SetReportSubscription); using (var dialog = new ActionProgressDialog(action, ProgressBarStyle.Blocks)) { dialog.ShowCancel = true; dialog.ShowDialog(this); } if (action.Succeeded) { DialogResult = DialogResult.OK; this.Close(); } else if(!action.Cancelled) { using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Error, String.Format(Messages.WLB_SUBSCRIPTION_ERROR, _subscription.Description), Messages.XENCENTER))) { dlg.ShowDialog(this); } //log.ErrorFormat("There was an error calling SendWlbConfigurationAction to SetReportSubscription {0}, Action Result: {1}.", _subscription.Description, action.Result); DialogResult = DialogResult.None; } } #endregion //Button Click Event Handler } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; namespace PlayFab.PfEditor { public class PlayFabEditor : UnityEditor.EditorWindow { #if !UNITY_5_3_OR_NEWER public GUIContent titleContent; #endif #region EdEx Variables // vars for the plugin-wide event system public enum EdExStates { OnLogin, OnLogout, OnMenuItemClicked, OnSubmenuItemClicked, OnHttpReq, OnHttpRes, OnError, OnSuccess, OnWarning } public delegate void PlayFabEdExStateHandler(EdExStates state, string status, string misc); public static event PlayFabEdExStateHandler EdExStateUpdate; public static Dictionary<string, float> blockingRequests = new Dictionary<string, float>(); // key and blockingRequest start time private static float blockingRequestTimeOut = 10f; // abandon the block after this many seconds. public static string latestEdExVersion = string.Empty; internal static PlayFabEditor window; #endregion #region unity lopps & methods void OnEnable() { if (window == null) { window = this; window.minSize = new Vector2(320, 0); } if (!IsEventHandlerRegistered(StateUpdateHandler)) { EdExStateUpdate += StateUpdateHandler; } PlayFabEditorDataService.RefreshStudiosList(true); GetLatestEdExVersion(); } void OnDisable() { // clean up objects: PlayFabEditorPrefsSO.Instance.PanelIsShown = false; if (IsEventHandlerRegistered(StateUpdateHandler)) { EdExStateUpdate -= StateUpdateHandler; } } void OnFocus() { OnEnable(); } [MenuItem("Window/PlayFab/Editor Extensions")] static void PlayFabServices() { var editorAsm = typeof(UnityEditor.Editor).Assembly; var inspWndType = editorAsm.GetType("UnityEditor.SceneHierarchyWindow"); if (inspWndType == null) { inspWndType = editorAsm.GetType("UnityEditor.InspectorWindow"); } window = GetWindow<PlayFabEditor>(inspWndType); window.titleContent = new GUIContent("PlayFab EdEx"); PlayFabEditorPrefsSO.Instance.PanelIsShown = true; } [InitializeOnLoad] public static class Startup { static Startup() { if (PlayFabEditorPrefsSO.Instance.PanelIsShown || !PlayFabEditorSDKTools.IsInstalled) { EditorCoroutine.Start(OpenPlayServices()); } } } static IEnumerator OpenPlayServices() { yield return new WaitForSeconds(1f); if (!Application.isPlaying) { PlayFabServices(); } } private void OnGUI() { HideRepaintErrors(OnGuiInternal); } private void OnGuiInternal() { GUI.skin = PlayFabEditorHelper.uiStyle; using (new UnityVertical()) { //Run all updaters prior to drawing; PlayFabEditorHeader.DrawHeader(); GUI.enabled = blockingRequests.Count == 0 && !EditorApplication.isCompiling; if (PlayFabEditorAuthenticate.IsAuthenticated()) { PlayFabEditorMenu.DrawMenu(); switch (PlayFabEditorMenu._menuState) { case PlayFabEditorMenu.MenuStates.Sdks: PlayFabEditorSDKTools.DrawSdkPanel(); break; case PlayFabEditorMenu.MenuStates.Settings: PlayFabEditorSettings.DrawSettingsPanel(); break; case PlayFabEditorMenu.MenuStates.Help: PlayFabEditorHelpMenu.DrawHelpPanel(); break; case PlayFabEditorMenu.MenuStates.Data: PlayFabEditorDataMenu.DrawDataPanel(); break; case PlayFabEditorMenu.MenuStates.Tools: PlayFabEditorToolsMenu.DrawToolsPanel(); break; case PlayFabEditorMenu.MenuStates.Packages: PlayFabEditorPackages.DrawPackagesMenu(); break; default: break; } } else { PlayFabEditorAuthenticate.DrawAuthPanels(); } using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1"), GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true))) { GUILayout.FlexibleSpace(); } // help tag at the bottom of the help menu. if (PlayFabEditorMenu._menuState == PlayFabEditorMenu.MenuStates.Help) { DisplayHelpMenu(); } } PruneBlockingRequests(); Repaint(); } private static void HideRepaintErrors(Action action) { try { action(); } catch (Exception e) { if (!e.Message.ToLower().Contains("repaint")) throw; // Hide any repaint issues when recompiling } } private static void DisplayHelpMenu() { using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1"))) { using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear"))) { GUILayout.FlexibleSpace(); EditorGUILayout.LabelField("PlayFab Editor Extensions: " + PlayFabEditorHelper.EDEX_VERSION, PlayFabEditorHelper.uiStyle.GetStyle("versionText")); GUILayout.FlexibleSpace(); } //TODO Add plugin upgrade option here (if available); if (ShowEdExUpgrade()) { using (new UnityHorizontal()) { GUILayout.FlexibleSpace(); if (GUILayout.Button("UPGRADE EDEX", PlayFabEditorHelper.uiStyle.GetStyle("textButtonOr"))) { UpgradeEdEx(); } GUILayout.FlexibleSpace(); } } using (new UnityHorizontal()) { GUILayout.FlexibleSpace(); if (GUILayout.Button("VIEW DOCUMENTATION", PlayFabEditorHelper.uiStyle.GetStyle("textButton"))) { Application.OpenURL("https://github.com/PlayFab/UnityEditorExtensions"); } GUILayout.FlexibleSpace(); } using (new UnityHorizontal()) { GUILayout.FlexibleSpace(); if (GUILayout.Button("REPORT ISSUES", PlayFabEditorHelper.uiStyle.GetStyle("textButton"))) { Application.OpenURL("https://github.com/PlayFab/UnityEditorExtensions/issues"); } GUILayout.FlexibleSpace(); } if (!string.IsNullOrEmpty(PlayFabEditorHelper.EDEX_ROOT)) { using (new UnityHorizontal()) { GUILayout.FlexibleSpace(); if (GUILayout.Button("UNINSTALL ", PlayFabEditorHelper.uiStyle.GetStyle("textButton"))) { RemoveEdEx(); } GUILayout.FlexibleSpace(); } } } } #endregion #region menu and helper methods public static void RaiseStateUpdate(EdExStates state, string status = null, string json = null) { if (EdExStateUpdate != null) EdExStateUpdate(state, status, json); } private static void PruneBlockingRequests() { List<string> itemsToRemove = new List<string>(); foreach (var req in blockingRequests) if (req.Value + blockingRequestTimeOut < (float)EditorApplication.timeSinceStartup) itemsToRemove.Add(req.Key); foreach (var item in itemsToRemove) { ClearBlockingRequest(item); RaiseStateUpdate(EdExStates.OnWarning, string.Format(" Request {0} has timed out after {1} seconds.", item, blockingRequestTimeOut)); } } private static void AddBlockingRequest(string state) { blockingRequests[state] = (float)EditorApplication.timeSinceStartup; } private static void ClearBlockingRequest(string state = null) { if (state == null) { blockingRequests.Clear(); } else if (blockingRequests.ContainsKey(state)) { blockingRequests.Remove(state); } } /// <summary> /// Handles state updates within the editor extension. /// </summary> /// <param name="state">the state that triggered this event.</param> /// <param name="status">a generic message about the status.</param> /// <param name="json">a generic container for additional JSON encoded info.</param> private void StateUpdateHandler(EdExStates state, string status, string json) { switch (state) { case EdExStates.OnMenuItemClicked: PlayFabEditorPrefsSO.Instance.curSubMenuIdx = 0; break; case EdExStates.OnSubmenuItemClicked: int parsed; if (int.TryParse(json, out parsed)) PlayFabEditorPrefsSO.Instance.curSubMenuIdx = parsed; break; case EdExStates.OnHttpReq: object temp; if (string.IsNullOrEmpty(json) || Json.PlayFabSimpleJson.TryDeserializeObject(json, out temp)) break; var deserialized = temp as Json.JsonObject; object useSpinner = false; object blockUi = false; if (deserialized.TryGetValue("useSpinner", out useSpinner) && bool.Parse(useSpinner.ToString())) { ProgressBar.UpdateState(ProgressBar.ProgressBarStates.spin); } if (deserialized.TryGetValue("blockUi", out blockUi) && bool.Parse(blockUi.ToString())) { AddBlockingRequest(status); } break; case EdExStates.OnHttpRes: ProgressBar.UpdateState(ProgressBar.ProgressBarStates.off); ProgressBar.UpdateState(ProgressBar.ProgressBarStates.success); ClearBlockingRequest(status); break; case EdExStates.OnError: // deserialize and add json details // clear blocking requests ProgressBar.UpdateState(ProgressBar.ProgressBarStates.error); ClearBlockingRequest(); Debug.LogError(string.Format("PlayFab EditorExtensions: Caught an error:{0}", status)); break; case EdExStates.OnWarning: ProgressBar.UpdateState(ProgressBar.ProgressBarStates.warning); ClearBlockingRequest(); Debug.LogWarning(string.Format("PlayFab EditorExtensions: {0}", status)); break; case EdExStates.OnSuccess: ClearBlockingRequest(); ProgressBar.UpdateState(ProgressBar.ProgressBarStates.success); break; } } public static bool IsEventHandlerRegistered(PlayFabEdExStateHandler prospectiveHandler) { if (EdExStateUpdate == null) return false; foreach (PlayFabEdExStateHandler existingHandler in EdExStateUpdate.GetInvocationList()) if (existingHandler == prospectiveHandler) return true; return false; } private static void GetLatestEdExVersion() { var threshold = PlayFabEditorPrefsSO.Instance.EdSet_lastEdExVersionCheck != DateTime.MinValue ? PlayFabEditorPrefsSO.Instance.EdSet_lastEdExVersionCheck.AddHours(1) : DateTime.MinValue; if (DateTime.Today > threshold) { PlayFabEditorHttp.MakeGitHubApiCall("https://api.github.com/repos/PlayFab/UnityEditorExtensions/git/refs/tags", (version) => { latestEdExVersion = version ?? "Unknown"; PlayFabEditorPrefsSO.Instance.EdSet_latestEdExVersion = latestEdExVersion; }); } else { latestEdExVersion = PlayFabEditorPrefsSO.Instance.EdSet_latestEdExVersion; } } private static bool ShowEdExUpgrade() { if (string.IsNullOrEmpty(latestEdExVersion) || latestEdExVersion == "Unknown") return false; if (string.IsNullOrEmpty(PlayFabEditorHelper.EDEX_VERSION) || PlayFabEditorHelper.EDEX_VERSION == "Unknown") return true; string[] currrent = PlayFabEditorHelper.EDEX_VERSION.Split('.'); if (currrent.Length != 3) return true; string[] latest = latestEdExVersion.Split('.'); return latest.Length != 3 || int.Parse(latest[0]) > int.Parse(currrent[0]) || int.Parse(latest[1]) > int.Parse(currrent[1]) || int.Parse(latest[2]) > int.Parse(currrent[2]); } private static void RemoveEdEx(bool prompt = true) { if (prompt && !EditorUtility.DisplayDialog("Confirm Editor Extensions Removal", "This action will remove PlayFab Editor Extensions from the current project.", "Confirm", "Cancel")) return; try { window.Close(); var edExRoot = new DirectoryInfo(PlayFabEditorHelper.EDEX_ROOT); FileUtil.DeleteFileOrDirectory(edExRoot.Parent.FullName); AssetDatabase.Refresh(); } catch (Exception ex) { RaiseStateUpdate(EdExStates.OnError, ex.Message); } } private static void UpgradeEdEx() { if (EditorUtility.DisplayDialog("Confirm EdEx Upgrade", "This action will remove the current PlayFab Editor Extensions and install the lastet version.", "Confirm", "Cancel")) { window.Close(); ImportLatestEdEx(); } } private static void ImportLatestEdEx() { PlayFabEditorHttp.MakeDownloadCall("https://api.playfab.com/sdks/download/unity-edex-upgrade", (fileName) => { AssetDatabase.ImportPackage(fileName, false); Debug.Log("PlayFab EdEx Upgrade: Complete"); }); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Logic { using Azure; using Management; using Rest; using Rest.Azure; using Rest.Azure.OData; 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> /// SessionsOperations operations. /// </summary> internal partial class SessionsOperations : IServiceOperations<LogicManagementClient>, ISessionsOperations { /// <summary> /// Initializes a new instance of the SessionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal SessionsOperations(LogicManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the LogicManagementClient /// </summary> public LogicManagementClient Client { get; private set; } /// <summary> /// Gets a list of integration account sessions. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='integrationAccountName'> /// The integration account name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<IntegrationAccountSession>>> ListByIntegrationAccountsWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, ODataQuery<IntegrationAccountSessionFilter> odataQuery = default(ODataQuery<IntegrationAccountSessionFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (integrationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("integrationAccountName", integrationAccountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByIntegrationAccounts", 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.Logic/integrationAccounts/{integrationAccountName}/sessions").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<IntegrationAccountSession>>(); _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<IntegrationAccountSession>>(_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 an integration account session. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='integrationAccountName'> /// The integration account name. /// </param> /// <param name='sessionName'> /// The integration account session name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IntegrationAccountSession>> GetWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string sessionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (integrationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName"); } if (sessionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "sessionName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // 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("integrationAccountName", integrationAccountName); tracingParameters.Add("sessionName", sessionName); 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.Logic/integrationAccounts/{integrationAccountName}/sessions/{sessionName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName)); _url = _url.Replace("{sessionName}", System.Uri.EscapeDataString(sessionName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IntegrationAccountSession>(); _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<IntegrationAccountSession>(_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 an integration account session. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='integrationAccountName'> /// The integration account name. /// </param> /// <param name='sessionName'> /// The integration account session name. /// </param> /// <param name='session'> /// The integration account session. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IntegrationAccountSession>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string sessionName, IntegrationAccountSession session, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (integrationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName"); } if (sessionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "sessionName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (session == null) { throw new ValidationException(ValidationRules.CannotBeNull, "session"); } // 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("integrationAccountName", integrationAccountName); tracingParameters.Add("sessionName", sessionName); tracingParameters.Add("session", session); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/sessions/{sessionName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName)); _url = _url.Replace("{sessionName}", System.Uri.EscapeDataString(sessionName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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(session != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(session, 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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IntegrationAccountSession>(); _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<IntegrationAccountSession>(_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<IntegrationAccountSession>(_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 an integration account session. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='integrationAccountName'> /// The integration account name. /// </param> /// <param name='sessionName'> /// The integration account session name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string sessionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (integrationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName"); } if (sessionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "sessionName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // 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("integrationAccountName", integrationAccountName); tracingParameters.Add("sessionName", sessionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/sessions/{sessionName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName)); _url = _url.Replace("{sessionName}", System.Uri.EscapeDataString(sessionName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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 != 200 && (int)_statusCode != 204) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of integration account sessions. /// </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="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<IntegrationAccountSession>>> ListByIntegrationAccountsNextWithHttpMessagesAsync(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, "ListByIntegrationAccountsNext", 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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<IntegrationAccountSession>>(); _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<IntegrationAccountSession>>(_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 EncompassRest.Loans.Enums; using EncompassRest.Schema; namespace EncompassRest.Loans { /// <summary> /// Tax4506 /// </summary> [Entity(PropertiesToAlwaysSerialize = nameof(HistoryIndicator) + "," + nameof(Tax4506TIndicator), SerializeWholeListWhenDirty = true)] public sealed partial class Tax4506 : DirtyExtensibleObject, IIdentifiable { private DirtyValue<bool?>? _accountTranscript; private DirtyValue<string?>? _address; private DirtyValue<StringEnumValue<Owner>>? _authorizedSignor; private DirtyValue<StringEnumValue<Owner>>? _authorizedSignorSpouse; private DirtyValue<string?>? _city; private DirtyValue<decimal?>? _costForEachPeriod; private DirtyValue<string?>? _currentFirst; private DirtyValue<string?>? _currentLast; private DirtyValue<string?>? _first; private DirtyValue<bool?>? _formsSeriesTranscript; private DirtyValue<string?>? _historyId; private DirtyValue<bool?>? _historyIndicator; private DirtyValue<string?>? _id; private DirtyValue<bool?>? _ifTaxRecordNotFound; private DirtyValue<bool?>? _irs4506C; private DirtyValue<string?>? _last; private DirtyValue<DateTime?>? _lastUpdatedDate; private DirtyValue<int?>? _lastUpdatedHistory; private DirtyValue<string?>? _lastUpdatedTime; private DirtyValue<bool?>? _notifiedIrsIdentityTheftIndicator; private DirtyValue<int?>? _numberOfPeriods; private DirtyValue<StringEnumValue<Person>>? _person; private DirtyValue<bool?>? _recordOfAccount; private DirtyValue<string?>? _requestorPhoneNumber; private DirtyValue<StringEnumValue<RequestorTitle>>? _requestorTitle; private DirtyValue<DateTime?>? _requestYear1; private DirtyValue<DateTime?>? _requestYear2; private DirtyValue<DateTime?>? _requestYear3; private DirtyValue<DateTime?>? _requestYear4; private DirtyValue<DateTime?>? _requestYear5; private DirtyValue<DateTime?>? _requestYear6; private DirtyValue<DateTime?>? _requestYear7; private DirtyValue<DateTime?>? _requestYear8; private DirtyValue<string?>? _returnAddress; private DirtyValue<string?>? _returnCity; private DirtyValue<StringEnumValue<State>>? _returnState; private DirtyValue<bool?>? _returnTranscript; private DirtyValue<string?>? _returnZip; private DirtyValue<string?>? _selectedRecordNumber; private DirtyValue<string?>? _sendAddress; private DirtyValue<string?>? _sendCity; private DirtyValue<string?>? _sendFirst; private DirtyValue<string?>? _sendLast; private DirtyValue<string?>? _sendPhone; private DirtyValue<StringEnumValue<State>>? _sendState; private DirtyValue<string?>? _sendZip; private DirtyValue<bool?>? _signatoryAttestation; private DirtyValue<bool?>? _signatoryAttestationT; private DirtyValue<string?>? _spouseFirst; private DirtyValue<string?>? _spouseLast; private DirtyValue<string?>? _spouseSSN; private DirtyValue<bool?>? _spouseUseEIN; private DirtyValue<string?>? _sSN; private DirtyValue<StringEnumValue<State>>? _state; private DirtyValue<int?>? _tax4506Index; private DirtyValue<bool?>? _tax4506TIndicator; private DirtyValue<string?>? _taxFormNumber; private DirtyValue<bool?>? _theseCopiesMustBeCertified; private DirtyValue<decimal?>? _totalCost; private DirtyValue<bool?>? _useEIN; private DirtyValue<bool?>? _useWellsFargoRules; private DirtyValue<bool?>? _verificationOfNonfiling; private DirtyValue<string?>? _zip; /// <summary> /// Tax4506 AccountTranscript [IRS4506.X47] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"b\"}")] public bool? AccountTranscript { get => _accountTranscript; set => SetField(ref _accountTranscript, value); } /// <summary> /// Tax4506 Address [IRS4506.X35] /// </summary> public string? Address { get => _address; set => SetField(ref _address, value); } /// <summary> /// Tax4506 AuthorizedSignor [IRS4506.X63] /// </summary> [LoanFieldProperty(OptionsJson = "{\"CoBorrower\":\"Co-Borrower\"}")] public StringEnumValue<Owner> AuthorizedSignor { get => _authorizedSignor; set => SetField(ref _authorizedSignor, value); } /// <summary> /// Tax4506 AuthorizedSignorSpouse [IRS4506.X64] /// </summary> [LoanFieldProperty(OptionsJson = "{\"CoBorrower\":\"Co-Borrower\"}")] public StringEnumValue<Owner> AuthorizedSignorSpouse { get => _authorizedSignorSpouse; set => SetField(ref _authorizedSignorSpouse, value); } /// <summary> /// Tax4506 City [IRS4506.X36] /// </summary> public string? City { get => _city; set => SetField(ref _city, value); } /// <summary> /// Tax4506 CostForEachPeriod [IRS4506.X52] /// </summary> public decimal? CostForEachPeriod { get => _costForEachPeriod; set => SetField(ref _costForEachPeriod, value); } /// <summary> /// Tax4506 CurrentFirst [IRS4506.X39] /// </summary> public string? CurrentFirst { get => _currentFirst; set => SetField(ref _currentFirst, value); } /// <summary> /// Tax4506 CurrentLast [IRS4506.X40] /// </summary> public string? CurrentLast { get => _currentLast; set => SetField(ref _currentLast, value); } /// <summary> /// Tax4506 First [IRS4506.X2] /// </summary> public string? First { get => _first; set => SetField(ref _first, value); } /// <summary> /// Tax4506 FormsSeriesTranscript [IRS4506.X50] /// </summary> public bool? FormsSeriesTranscript { get => _formsSeriesTranscript; set => SetField(ref _formsSeriesTranscript, value); } /// <summary> /// Tax4506 HistoryId [IRNN63], [ARNN63] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? HistoryId { get => _historyId; set => SetField(ref _historyId, value); } /// <summary> /// Tax4506 HistoryIndicator /// </summary> public bool? HistoryIndicator { get => _historyIndicator; set => SetField(ref _historyIndicator, value); } /// <summary> /// Tax4506 Id /// </summary> public string? Id { get => _id; set => SetField(ref _id, value); } /// <summary> /// Tax4506 IfTaxRecordNotFound [IRS4506.X14] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"If we cannot find the tax return, we will refund the fee. If the refund should go to the third party listed on line 5, check here.\"}")] public bool? IfTaxRecordNotFound { get => _ifTaxRecordNotFound; set => SetField(ref _ifTaxRecordNotFound, value); } /// <summary> /// Use IRS 4506-C [IRS4506.X67] /// </summary> public bool? Irs4506C { get => _irs4506C; set => SetField(ref _irs4506C, value); } /// <summary> /// Tax4506 Last [IRS4506.X3] /// </summary> public string? Last { get => _last; set => SetField(ref _last, value); } /// <summary> /// Tax4506 LastUpdatedDate [IRNN61], [ARNN61] /// </summary> public DateTime? LastUpdatedDate { get => _lastUpdatedDate; set => SetField(ref _lastUpdatedDate, value); } /// <summary> /// Tax4506 LastUpdatedHistory [IR0099], [AR0099] /// </summary> public int? LastUpdatedHistory { get => _lastUpdatedHistory; set => SetField(ref _lastUpdatedHistory, value); } /// <summary> /// Tax4506 LastUpdatedTime [IRNN62], [ARNN62] /// </summary> public string? LastUpdatedTime { get => _lastUpdatedTime; set => SetField(ref _lastUpdatedTime, value); } /// <summary> /// Tax4506 NotifiedIrsIdentityTheftIndicator [IRS4506.X60] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Y\",\"N\":\"N\"}")] public bool? NotifiedIrsIdentityTheftIndicator { get => _notifiedIrsIdentityTheftIndicator; set => SetField(ref _notifiedIrsIdentityTheftIndicator, value); } /// <summary> /// Tax4506 NumberOfPeriods [IRS4506.X31] /// </summary> public int? NumberOfPeriods { get => _numberOfPeriods; set => SetField(ref _numberOfPeriods, value); } /// <summary> /// Tax4506 Person [IRS4506.X1] /// </summary> public StringEnumValue<Person> Person { get => _person; set => SetField(ref _person, value); } /// <summary> /// Tax4506 RecordOfAccount [IRS4506.X48] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"c\"}")] public bool? RecordOfAccount { get => _recordOfAccount; set => SetField(ref _recordOfAccount, value); } /// <summary> /// Tax4506 RequestorPhoneNumber [IRS4506.X27] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? RequestorPhoneNumber { get => _requestorPhoneNumber; set => SetField(ref _requestorPhoneNumber, value); } /// <summary> /// Tax4506 RequestorTitle [IRS4506.X28] /// </summary> public StringEnumValue<RequestorTitle> RequestorTitle { get => _requestorTitle; set => SetField(ref _requestorTitle, value); } /// <summary> /// Tax4506 RequestYear1 [IRS4506.X25] /// </summary> public DateTime? RequestYear1 { get => _requestYear1; set => SetField(ref _requestYear1, value); } /// <summary> /// Tax4506 RequestYear2 [IRS4506.X26] /// </summary> public DateTime? RequestYear2 { get => _requestYear2; set => SetField(ref _requestYear2, value); } /// <summary> /// Tax4506 RequestYear3 [IRS4506.X29] /// </summary> public DateTime? RequestYear3 { get => _requestYear3; set => SetField(ref _requestYear3, value); } /// <summary> /// Tax4506 RequestYear4 [IRS4506.X30] /// </summary> public DateTime? RequestYear4 { get => _requestYear4; set => SetField(ref _requestYear4, value); } /// <summary> /// Tax4506 RequestYear5 [IRS4506.X53] /// </summary> public DateTime? RequestYear5 { get => _requestYear5; set => SetField(ref _requestYear5, value); } /// <summary> /// Tax4506 RequestYear6 [IRS4506.X54] /// </summary> public DateTime? RequestYear6 { get => _requestYear6; set => SetField(ref _requestYear6, value); } /// <summary> /// Tax4506 RequestYear7 [IRS4506.X55] /// </summary> public DateTime? RequestYear7 { get => _requestYear7; set => SetField(ref _requestYear7, value); } /// <summary> /// Tax4506 RequestYear8 [IRS4506.X56] /// </summary> public DateTime? RequestYear8 { get => _requestYear8; set => SetField(ref _requestYear8, value); } /// <summary> /// Tax4506 ReturnAddress [IRS4506.X41] /// </summary> public string? ReturnAddress { get => _returnAddress; set => SetField(ref _returnAddress, value); } /// <summary> /// Tax4506 ReturnCity [IRS4506.X42] /// </summary> public string? ReturnCity { get => _returnCity; set => SetField(ref _returnCity, value); } /// <summary> /// Tax4506 ReturnState [IRS4506.X43] /// </summary> public StringEnumValue<State> ReturnState { get => _returnState; set => SetField(ref _returnState, value); } /// <summary> /// Tax4506 ReturnTranscript [IRS4506.X46] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"a\"}")] public bool? ReturnTranscript { get => _returnTranscript; set => SetField(ref _returnTranscript, value); } /// <summary> /// Tax4506 ReturnZip [IRS4506.X44] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)] public string? ReturnZip { get => _returnZip; set => SetField(ref _returnZip, value); } /// <summary> /// IRS - Selected Record Number [IRS4506.X98] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? SelectedRecordNumber { get => _selectedRecordNumber; set => SetField(ref _selectedRecordNumber, value); } /// <summary> /// Tax4506 SendAddress [IRS4506.X10] /// </summary> public string? SendAddress { get => _sendAddress; set => SetField(ref _sendAddress, value); } /// <summary> /// Tax4506 SendCity [IRS4506.X11] /// </summary> public string? SendCity { get => _sendCity; set => SetField(ref _sendCity, value); } /// <summary> /// Tax4506 SendFirst [IRS4506.X8] /// </summary> public string? SendFirst { get => _sendFirst; set => SetField(ref _sendFirst, value); } /// <summary> /// Tax4506 SendLast [IRS4506.X9] /// </summary> public string? SendLast { get => _sendLast; set => SetField(ref _sendLast, value); } /// <summary> /// Tax4506 SendPhone [IRS4506.X45] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? SendPhone { get => _sendPhone; set => SetField(ref _sendPhone, value); } /// <summary> /// Tax4506 SendState [IRS4506.X12] /// </summary> public StringEnumValue<State> SendState { get => _sendState; set => SetField(ref _sendState, value); } /// <summary> /// Tax4506 SendZip [IRS4506.X13] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)] public string? SendZip { get => _sendZip; set => SetField(ref _sendZip, value); } /// <summary> /// Tax4506 SignatoryAttestation [IRS4506.X61], [IR0064] /// </summary> public bool? SignatoryAttestation { get => _signatoryAttestation; set => SetField(ref _signatoryAttestation, value); } /// <summary> /// IRS 4506T - Signatory Attestation [IRS4506.X62] /// </summary> public bool? SignatoryAttestationT { get => _signatoryAttestationT; set => SetField(ref _signatoryAttestationT, value); } /// <summary> /// Tax4506 SpouseFirst [IRS4506.X6] /// </summary> public string? SpouseFirst { get => _spouseFirst; set => SetField(ref _spouseFirst, value); } /// <summary> /// Tax4506 SpouseLast [IRS4506.X7] /// </summary> public string? SpouseLast { get => _spouseLast; set => SetField(ref _spouseLast, value); } /// <summary> /// Tax4506 SpouseSSN [IRS4506.X5] /// </summary> public string? SpouseSSN { get => _spouseSSN; set => SetField(ref _spouseSSN, value); } /// <summary> /// Tax4506 SpouseUseEIN [IRS4506.X58] /// </summary> public bool? SpouseUseEIN { get => _spouseUseEIN; set => SetField(ref _spouseUseEIN, value); } /// <summary> /// Tax4506 SSN [IRS4506.X4] /// </summary> public string? SSN { get => _sSN; set => SetField(ref _sSN, value); } /// <summary> /// Tax4506 State [IRS4506.X37] /// </summary> public StringEnumValue<State> State { get => _state; set => SetField(ref _state, value); } /// <summary> /// Tax4506 Tax4506Index /// </summary> public int? Tax4506Index { get => _tax4506Index; set => SetField(ref _tax4506Index, value); } /// <summary> /// Tax4506 Tax4506TIndicator /// </summary> public bool? Tax4506TIndicator { get => _tax4506TIndicator; set => SetField(ref _tax4506TIndicator, value); } /// <summary> /// Tax4506 TaxFormNumber [IRS4506.X24] /// </summary> public string? TaxFormNumber { get => _taxFormNumber; set => SetField(ref _taxFormNumber, value); } /// <summary> /// Tax4506 TheseCopiesMustBeCertified [IRS4506.X18] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Copies must be certified for court or administrative proceedings\"}")] public bool? TheseCopiesMustBeCertified { get => _theseCopiesMustBeCertified; set => SetField(ref _theseCopiesMustBeCertified, value); } /// <summary> /// Tax4506 TotalCost [IRS4506.X32] /// </summary> public decimal? TotalCost { get => _totalCost; set => SetField(ref _totalCost, value); } /// <summary> /// Tax4506 UseEIN [IRS4506.X57] /// </summary> public bool? UseEIN { get => _useEIN; set => SetField(ref _useEIN, value); } /// <summary> /// Tax4506 UseWellsFargoRules [IRS4506.X59] /// </summary> public bool? UseWellsFargoRules { get => _useWellsFargoRules; set => SetField(ref _useWellsFargoRules, value); } /// <summary> /// Tax4506 VerificationOfNonfiling [IRS4506.X49] /// </summary> public bool? VerificationOfNonfiling { get => _verificationOfNonfiling; set => SetField(ref _verificationOfNonfiling, value); } /// <summary> /// Tax4506 Zip [IRS4506.X38] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)] public string? Zip { get => _zip; set => SetField(ref _zip, 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.Collections.Generic; using System.Globalization; using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption; using Microsoft.AspNetCore.DataProtection.KeyManagement.Internal; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; using Xunit; namespace Microsoft.AspNetCore.DataProtection.KeyManagement { public class DefaultKeyResolverTests { [Fact] public void ResolveDefaultKeyPolicy_EmptyKeyRing_ReturnsNullDefaultKey() { // Arrange var resolver = CreateDefaultKeyResolver(); // Act var resolution = resolver.ResolveDefaultKeyPolicy(DateTimeOffset.Now, new IKey[0]); // Assert Assert.Null(resolution.DefaultKey); Assert.True(resolution.ShouldGenerateNewKey); } [Fact] public void ResolveDefaultKeyPolicy_ValidExistingKey_ReturnsExistingKey() { // Arrange var resolver = CreateDefaultKeyResolver(); var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z"); var key2 = CreateKey("2016-03-01 00:00:00Z", "2017-03-01 00:00:00Z"); // Act var resolution = resolver.ResolveDefaultKeyPolicy("2016-02-20 23:59:00Z", key1, key2); // Assert Assert.Same(key1, resolution.DefaultKey); Assert.False(resolution.ShouldGenerateNewKey); } [Fact] public void ResolveDefaultKeyPolicy_ValidExistingKey_AllowsForClockSkew_KeysStraddleSkewLine_ReturnsExistingKey() { // Arrange var resolver = CreateDefaultKeyResolver(); var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z"); var key2 = CreateKey("2016-03-01 00:00:00Z", "2017-03-01 00:00:00Z"); // Act var resolution = resolver.ResolveDefaultKeyPolicy("2016-02-29 23:59:00Z", key1, key2); // Assert Assert.Same(key2, resolution.DefaultKey); Assert.False(resolution.ShouldGenerateNewKey); } [Fact] public void ResolveDefaultKeyPolicy_ValidExistingKey_AllowsForClockSkew_AllKeysInFuture_ReturnsExistingKey() { // Arrange var resolver = CreateDefaultKeyResolver(); var key1 = CreateKey("2016-03-01 00:00:00Z", "2017-03-01 00:00:00Z"); // Act var resolution = resolver.ResolveDefaultKeyPolicy("2016-02-29 23:59:00Z", key1); // Assert Assert.Same(key1, resolution.DefaultKey); Assert.False(resolution.ShouldGenerateNewKey); } [Fact] public void ResolveDefaultKeyPolicy_ValidExistingKey_NoSuccessor_ReturnsExistingKey_SignalsGenerateNewKey() { // Arrange var resolver = CreateDefaultKeyResolver(); var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z"); // Act var resolution = resolver.ResolveDefaultKeyPolicy("2016-02-29 23:59:00Z", key1); // Assert Assert.Same(key1, resolution.DefaultKey); Assert.True(resolution.ShouldGenerateNewKey); } [Fact] public void ResolveDefaultKeyPolicy_ValidExistingKey_NoLegitimateSuccessor_ReturnsExistingKey_SignalsGenerateNewKey() { // Arrange var resolver = CreateDefaultKeyResolver(); var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z"); var key2 = CreateKey("2016-03-01 00:00:00Z", "2017-03-01 00:00:00Z", isRevoked: true); var key3 = CreateKey("2016-03-01 00:00:00Z", "2016-03-02 00:00:00Z"); // key expires too soon // Act var resolution = resolver.ResolveDefaultKeyPolicy("2016-02-29 23:50:00Z", key1, key2, key3); // Assert Assert.Same(key1, resolution.DefaultKey); Assert.True(resolution.ShouldGenerateNewKey); } [Fact] public void ResolveDefaultKeyPolicy_MostRecentKeyIsInvalid_BecauseOfRevocation_ReturnsNull() { // Arrange var resolver = CreateDefaultKeyResolver(); var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z"); var key2 = CreateKey("2015-03-02 00:00:00Z", "2016-03-01 00:00:00Z", isRevoked: true); // Act var resolution = resolver.ResolveDefaultKeyPolicy("2015-04-01 00:00:00Z", key1, key2); // Assert Assert.Null(resolution.DefaultKey); Assert.True(resolution.ShouldGenerateNewKey); } [Fact] public void ResolveDefaultKeyPolicy_MostRecentKeyIsInvalid_BecauseOfFailureToDecipher_ReturnsNull() { // Arrange var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z"); var key2 = CreateKey("2015-03-02 00:00:00Z", "2016-03-01 00:00:00Z", createEncryptorThrows: true); var resolver = CreateDefaultKeyResolver(); // Act var resolution = resolver.ResolveDefaultKeyPolicy("2015-04-01 00:00:00Z", key1, key2); // Assert Assert.Null(resolution.DefaultKey); Assert.True(resolution.ShouldGenerateNewKey); } [Fact] public void ResolveDefaultKeyPolicy_FutureKeyIsValidAndWithinClockSkew_ReturnsFutureKey() { // Arrange var resolver = CreateDefaultKeyResolver(); var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z"); // Act var resolution = resolver.ResolveDefaultKeyPolicy("2015-02-28 23:55:00Z", key1); // Assert Assert.Same(key1, resolution.DefaultKey); Assert.False(resolution.ShouldGenerateNewKey); } [Fact] public void ResolveDefaultKeyPolicy_FutureKeyIsValidButNotWithinClockSkew_ReturnsNull() { // Arrange var resolver = CreateDefaultKeyResolver(); var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z"); // Act var resolution = resolver.ResolveDefaultKeyPolicy("2015-02-28 23:00:00Z", key1); // Assert Assert.Null(resolution.DefaultKey); Assert.True(resolution.ShouldGenerateNewKey); } [Fact] public void ResolveDefaultKeyPolicy_IgnoresExpiredOrRevokedFutureKeys() { // Arrange var resolver = CreateDefaultKeyResolver(); var key1 = CreateKey("2015-03-01 00:00:00Z", "2014-03-01 00:00:00Z"); // expiration before activation should never occur var key2 = CreateKey("2015-03-01 00:01:00Z", "2015-04-01 00:00:00Z", isRevoked: true); var key3 = CreateKey("2015-03-01 00:02:00Z", "2015-04-01 00:00:00Z"); // Act var resolution = resolver.ResolveDefaultKeyPolicy("2015-02-28 23:59:00Z", key1, key2, key3); // Assert Assert.Same(key3, resolution.DefaultKey); Assert.False(resolution.ShouldGenerateNewKey); } [Fact] public void ResolveDefaultKeyPolicy_FallbackKey_SelectsLatestBeforePriorPropagationWindow_IgnoresRevokedKeys() { // Arrange var resolver = CreateDefaultKeyResolver(); var key1 = CreateKey("2010-01-01 00:00:00Z", "2010-01-01 00:00:00Z", creationDate: "2000-01-01 00:00:00Z"); var key2 = CreateKey("2010-01-01 00:00:00Z", "2010-01-01 00:00:00Z", creationDate: "2000-01-02 00:00:00Z"); var key3 = CreateKey("2010-01-01 00:00:00Z", "2010-01-01 00:00:00Z", creationDate: "2000-01-03 00:00:00Z", isRevoked: true); var key4 = CreateKey("2010-01-01 00:00:00Z", "2010-01-01 00:00:00Z", creationDate: "2000-01-04 00:00:00Z"); // Act var resolution = resolver.ResolveDefaultKeyPolicy("2000-01-05 00:00:00Z", key1, key2, key3, key4); // Assert Assert.Same(key2, resolution.FallbackKey); Assert.True(resolution.ShouldGenerateNewKey); } [Fact] public void ResolveDefaultKeyPolicy_FallbackKey_SelectsLatestBeforePriorPropagationWindow_IgnoresFailures() { // Arrange var key1 = CreateKey("2010-01-01 00:00:00Z", "2010-01-01 00:00:00Z", creationDate: "2000-01-01 00:00:00Z"); var key2 = CreateKey("2010-01-01 00:00:00Z", "2010-01-01 00:00:00Z", creationDate: "2000-01-02 00:00:00Z"); var key3 = CreateKey("2010-01-01 00:00:00Z", "2010-01-01 00:00:00Z", creationDate: "2000-01-03 00:00:00Z", createEncryptorThrows: true); var key4 = CreateKey("2010-01-01 00:00:00Z", "2010-01-01 00:00:00Z", creationDate: "2000-01-04 00:00:00Z"); var resolver = CreateDefaultKeyResolver(); // Act var resolution = resolver.ResolveDefaultKeyPolicy("2000-01-05 00:00:00Z", key1, key2, key3, key4); // Assert Assert.Same(key2, resolution.FallbackKey); Assert.True(resolution.ShouldGenerateNewKey); } [Fact] public void ResolveDefaultKeyPolicy_FallbackKey_NoNonRevokedKeysBeforePriorPropagationWindow_SelectsEarliestNonRevokedKey() { // Arrange var resolver = CreateDefaultKeyResolver(); var key1 = CreateKey("2010-01-01 00:00:00Z", "2010-01-01 00:00:00Z", creationDate: "2000-01-03 00:00:00Z", isRevoked: true); var key2 = CreateKey("2010-01-01 00:00:00Z", "2010-01-01 00:00:00Z", creationDate: "2000-01-04 00:00:00Z"); var key3 = CreateKey("2010-01-01 00:00:00Z", "2010-01-01 00:00:00Z", creationDate: "2000-01-05 00:00:00Z"); // Act var resolution = resolver.ResolveDefaultKeyPolicy("2000-01-05 00:00:00Z", key1, key2, key3); // Assert Assert.Same(key2, resolution.FallbackKey); Assert.True(resolution.ShouldGenerateNewKey); } private static IDefaultKeyResolver CreateDefaultKeyResolver() { var options = Options.Create(new KeyManagementOptions()); return new DefaultKeyResolver(options, NullLoggerFactory.Instance); } private static IKey CreateKey(string activationDate, string expirationDate, string creationDate = null, bool isRevoked = false, bool createEncryptorThrows = false) { var mockKey = new Mock<IKey>(); mockKey.Setup(o => o.KeyId).Returns(Guid.NewGuid()); mockKey.Setup(o => o.CreationDate).Returns((creationDate != null) ? DateTimeOffset.ParseExact(creationDate, "u", CultureInfo.InvariantCulture) : DateTimeOffset.MinValue); mockKey.Setup(o => o.ActivationDate).Returns(DateTimeOffset.ParseExact(activationDate, "u", CultureInfo.InvariantCulture)); mockKey.Setup(o => o.ExpirationDate).Returns(DateTimeOffset.ParseExact(expirationDate, "u", CultureInfo.InvariantCulture)); mockKey.Setup(o => o.IsRevoked).Returns(isRevoked); if (createEncryptorThrows) { mockKey.Setup(o => o.CreateEncryptor()).Throws(new Exception("This method fails.")); } else { mockKey.Setup(o => o.CreateEncryptor()).Returns(Mock.Of<IAuthenticatedEncryptor>()); } return mockKey.Object; } } internal static class DefaultKeyResolverExtensions { public static DefaultKeyResolution ResolveDefaultKeyPolicy(this IDefaultKeyResolver resolver, string now, params IKey[] allKeys) { return resolver.ResolveDefaultKeyPolicy(DateTimeOffset.ParseExact(now, "u", CultureInfo.InvariantCulture), (IEnumerable<IKey>)allKeys); } } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using NUnit.Util; using NUnit.Core; using CP.Windows.Forms; using System.Diagnostics; namespace NUnit.UiKit { /// <summary> /// Summary description for ResultTabs. /// </summary> public class ResultTabs : System.Windows.Forms.UserControl, TestObserver { static Logger log = InternalTrace.GetLogger(typeof(ResultTabs)); private ISettings settings; private bool updating = false; private TextDisplayController displayController; private MenuItem tabsMenu; private MenuItem errorsTabMenuItem; private MenuItem notRunTabMenuItem; private MenuItem menuSeparator; private MenuItem textOutputMenuItem; private System.Windows.Forms.TabPage errorTab; private NUnit.UiKit.ErrorDisplay errorDisplay; private System.Windows.Forms.TabPage notRunTab; private NUnit.UiKit.NotRunTree notRunTree; private System.Windows.Forms.TabControl tabControl; private System.Windows.Forms.MenuItem copyDetailMenuItem; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public ResultTabs() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); this.tabsMenu = new MenuItem(); this.errorsTabMenuItem = new System.Windows.Forms.MenuItem(); this.notRunTabMenuItem = new System.Windows.Forms.MenuItem(); this.menuSeparator = new System.Windows.Forms.MenuItem(); this.textOutputMenuItem = new System.Windows.Forms.MenuItem(); this.tabsMenu.MergeType = MenuMerge.Add; this.tabsMenu.MergeOrder = 1; this.tabsMenu.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] { this.errorsTabMenuItem, this.notRunTabMenuItem, this.menuSeparator, this.textOutputMenuItem, } ); this.tabsMenu.Text = "&Result Tabs"; this.tabsMenu.Visible = true; this.errorsTabMenuItem.Index = 0; this.errorsTabMenuItem.Text = "&Errors && Failures"; this.errorsTabMenuItem.Click += new System.EventHandler(this.errorsTabMenuItem_Click); this.notRunTabMenuItem.Index = 1; this.notRunTabMenuItem.Text = "Tests &Not Run"; this.notRunTabMenuItem.Click += new System.EventHandler(this.notRunTabMenuItem_Click); this.menuSeparator.Index = 2; this.menuSeparator.Text = "-"; this.textOutputMenuItem.Index = 3; this.textOutputMenuItem.Text = "Text &Output..."; this.textOutputMenuItem.Click += new EventHandler(textOutputMenuItem_Click); displayController = new TextDisplayController(tabControl); // displayController.CreatePages(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.tabControl = new System.Windows.Forms.TabControl(); this.errorTab = new System.Windows.Forms.TabPage(); this.errorDisplay = new NUnit.UiKit.ErrorDisplay(); this.notRunTab = new System.Windows.Forms.TabPage(); this.notRunTree = new NUnit.UiKit.NotRunTree(); this.copyDetailMenuItem = new System.Windows.Forms.MenuItem(); this.tabControl.SuspendLayout(); this.errorTab.SuspendLayout(); this.notRunTab.SuspendLayout(); this.SuspendLayout(); // // tabControl // this.tabControl.Alignment = System.Windows.Forms.TabAlignment.Bottom; this.tabControl.Controls.Add(this.errorTab); this.tabControl.Controls.Add(this.notRunTab); this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl.Location = new System.Drawing.Point(0, 0); this.tabControl.Name = "tabControl"; this.tabControl.SelectedIndex = 0; this.tabControl.Size = new System.Drawing.Size(488, 280); this.tabControl.TabIndex = 3; this.tabControl.SelectedIndexChanged += new System.EventHandler(this.tabControl_SelectedIndexChanged); // // errorTab // this.errorTab.Controls.Add(this.errorDisplay); this.errorTab.ForeColor = System.Drawing.SystemColors.ControlText; this.errorTab.Location = new System.Drawing.Point(4, 4); this.errorTab.Name = "errorTab"; this.errorTab.Size = new System.Drawing.Size(480, 254); this.errorTab.TabIndex = 0; this.errorTab.Text = "Errors and Failures"; // // errorDisplay // this.errorDisplay.Dock = System.Windows.Forms.DockStyle.Fill; this.errorDisplay.Location = new System.Drawing.Point(0, 0); this.errorDisplay.Name = "errorDisplay"; this.errorDisplay.Size = new System.Drawing.Size(480, 254); this.errorDisplay.TabIndex = 0; // // notRunTab // this.notRunTab.Controls.Add(this.notRunTree); this.notRunTab.ForeColor = System.Drawing.SystemColors.ControlText; this.notRunTab.Location = new System.Drawing.Point(4, 4); this.notRunTab.Name = "notRunTab"; this.notRunTab.Size = new System.Drawing.Size(480, 254); this.notRunTab.TabIndex = 1; this.notRunTab.Text = "Tests Not Run"; this.notRunTab.Visible = false; // // notRunTree // this.notRunTree.Dock = System.Windows.Forms.DockStyle.Fill; this.notRunTree.ImageIndex = -1; this.notRunTree.Indent = 19; this.notRunTree.Location = new System.Drawing.Point(0, 0); this.notRunTree.Name = "notRunTree"; this.notRunTree.SelectedImageIndex = -1; this.notRunTree.Size = new System.Drawing.Size(480, 254); this.notRunTree.TabIndex = 0; // // copyDetailMenuItem // this.copyDetailMenuItem.Index = -1; this.copyDetailMenuItem.Text = "Copy"; // // ResultTabs // this.Controls.Add(this.tabControl); this.Name = "ResultTabs"; this.Size = new System.Drawing.Size(488, 280); this.tabControl.ResumeLayout(false); this.errorTab.ResumeLayout(false); this.notRunTab.ResumeLayout(false); this.ResumeLayout(false); } #endregion public bool IsTracingEnabled { get { return displayController.IsTracingEnabled; } } public LoggingThreshold MaximumLogLevel { get { return displayController.MaximumLogLevel; } } public void Clear() { errorDisplay.Clear(); notRunTree.Nodes.Clear(); displayController.Clear(); } public MenuItem TabsMenu { get { return tabsMenu; } } protected override void OnLoad(EventArgs e) { if ( !this.DesignMode ) { this.settings = Services.UserSettings; TextDisplayTabSettings tabSettings = new TextDisplayTabSettings(); tabSettings.LoadSettings( settings ); UpdateTabPages(); Subscribe( Services.TestLoader.Events ); Services.UserSettings.Changed += new SettingsEventHandler(UserSettings_Changed); ITestEvents events = Services.TestLoader.Events; errorDisplay.Subscribe( events ); notRunTree.Subscribe( events ); displayController.Subscribe( events ); } base.OnLoad (e); } private void UpdateTabPages() { errorsTabMenuItem.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayErrorsTab", true ); notRunTabMenuItem.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayNotRunTab", true ); log.Debug( "Updating tab pages" ); updating = true; tabControl.TabPages.Clear(); if ( errorsTabMenuItem.Checked ) tabControl.TabPages.Add( errorTab ); if ( notRunTabMenuItem.Checked ) tabControl.TabPages.Add( notRunTab ); displayController.UpdatePages(); tabControl.SelectedIndex = settings.GetSetting( "Gui.ResultTabs.SelectedTab", 0 ); updating = false; } private void UserSettings_Changed( object sender, SettingsEventArgs e ) { if( e.SettingName.StartsWith( "Gui.ResultTabs.Display" ) || e.SettingName == "Gui.TextOutput.TabList" || e.SettingName.StartsWith( "Gui.TextOut" ) && e.SettingName.EndsWith( "Enabled" ) ) UpdateTabPages(); } private void errorsTabMenuItem_Click(object sender, System.EventArgs e) { settings.SaveSetting( "Gui.ResultTabs.DisplayErrorsTab", errorsTabMenuItem.Checked = !errorsTabMenuItem.Checked ); } private void notRunTabMenuItem_Click(object sender, System.EventArgs e) { settings.SaveSetting( "Gui.ResultTabs.DisplayNotRunTab", notRunTabMenuItem.Checked = !notRunTabMenuItem.Checked ); } private void textOutputMenuItem_Click(object sender, System.EventArgs e) { SimpleSettingsDialog.Display( this.FindForm(), new TextOutputSettingsPage("Text Output") ); } private void tabControl_SelectedIndexChanged(object sender, System.EventArgs e) { if ( !updating ) { int index = tabControl.SelectedIndex; if ( index >=0 && index < tabControl.TabCount ) settings.SaveSetting( "Gui.ResultTabs.SelectedTab", index ); } } #region TestObserver Members public void Subscribe(ITestEvents events) { events.TestLoaded += new TestEventHandler(OnTestLoaded); events.TestUnloaded += new TestEventHandler(OnTestUnloaded); events.TestReloaded += new TestEventHandler(OnTestReloaded); events.RunStarting += new TestEventHandler(OnRunStarting); } private void OnRunStarting(object sender, TestEventArgs args) { this.Clear(); } private void OnTestLoaded(object sender, TestEventArgs args) { this.Clear(); } private void OnTestUnloaded(object sender, TestEventArgs args) { this.Clear(); } private void OnTestReloaded(object sender, TestEventArgs args) { if ( settings.GetSetting( "Options.TestLoader.ClearResultsOnReload", false ) ) this.Clear(); } #endregion private void tabControl_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e) { bool selected = e.Index == tabControl.SelectedIndex; Font font = selected ? new Font( e.Font, FontStyle.Bold ) : e.Font; Brush backBrush = new SolidBrush( selected ? SystemColors.Control : SystemColors.Window ); Brush foreBrush = new SolidBrush( SystemColors.ControlText ); e.Graphics.FillRectangle( backBrush, e.Bounds ); Rectangle r = e.Bounds; r.Y += 3; r.Height -= 3; StringFormat sf = new StringFormat(); sf.Alignment = StringAlignment.Center; e.Graphics.DrawString( tabControl.TabPages[e.Index].Text, font, foreBrush, r, sf ); foreBrush.Dispose(); backBrush.Dispose(); if ( selected ) font.Dispose(); } protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); tabControl.ItemSize = new Size(tabControl.ItemSize.Width, this.Font.Height + 7); } private class TextDisplayController : TestObserver { private TabControl tabControl; List<TextDisplayTabPage> tabPages = new List<TextDisplayTabPage>(); public TextDisplayController(TabControl tabControl) { this.tabControl = tabControl; Services.UserSettings.Changed += new SettingsEventHandler(UserSettings_Changed); } public bool IsTracingEnabled { get { foreach (TextDisplayTabPage page in tabPages) if (page.Display.Content.Trace) return true; return false; } } public LoggingThreshold MaximumLogLevel { get { LoggingThreshold logLevel = LoggingThreshold.Off; foreach (TextDisplayTabPage page in tabPages) { LoggingThreshold level = page.Display.Content.LogLevel; if (level > logLevel) logLevel = level; } return logLevel; } } public void Clear() { foreach( TextDisplayTabPage page in tabPages ) page.Display.Clear(); } public void UpdatePages() { TextDisplayTabSettings tabSettings = new TextDisplayTabSettings(); tabSettings.LoadSettings(); List <TextDisplayTabPage> oldPages = tabPages; tabPages = new List<TextDisplayTabPage>(); Font displayFont = GetFixedFont(); foreach( TextDisplayTabSettings.TabInfo tabInfo in tabSettings.Tabs ) { if ( tabInfo.Enabled ) { TextDisplayTabPage thePage = null; foreach( TextDisplayTabPage page in oldPages ) if ( page.Name == tabInfo.Name ) { thePage = page; break; } if ( thePage == null ) thePage = new TextDisplayTabPage( tabInfo ); thePage.DisplayFont = displayFont; tabPages.Add( thePage ); tabControl.TabPages.Add( thePage ); } } } private void UserSettings_Changed(object sender, SettingsEventArgs args) { string settingName = args.SettingName; string prefix = "Gui.TextOutput."; if ( settingName == "Gui.FixedFont" ) { Font displayFont = GetFixedFont(); foreach( TextDisplayTabPage page in tabPages ) page.DisplayFont = displayFont; } else if ( settingName.StartsWith( prefix ) ) { string fieldName = settingName.Substring( prefix.Length ); int dot = fieldName.IndexOf('.'); if ( dot > 0 ) { string tabName = fieldName.Substring( 0, dot ); string propName = fieldName.Substring( dot + 1 ); foreach( TextDisplayTabPage page in tabPages ) if ( page.Name == tabName ) { switch(propName) { case "Title": page.Text = (string)Services.UserSettings.GetSetting( settingName ); break; case "Content": page.Display.Content.LoadSettings(tabName); break; } } } } } private static Font GetFixedFont() { ISettings settings = Services.UserSettings; return settings == null ? new Font(FontFamily.GenericMonospace, 8.0f) : settings.GetSetting("Gui.FixedFont", new Font(FontFamily.GenericMonospace, 8.0f)); } #region TestObserver Members public void Subscribe(ITestEvents events) { foreach( TextDisplayTabPage page in tabPages ) page.Display.Subscribe(events); } #endregion } } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Runtime.InteropServices; using VSLangProj; using VSLangProj80; namespace Microsoft.VisualStudioTools.Project.Automation { /// <summary> /// Represents the automation equivalent of ReferenceNode /// </summary> /// <typeparam name="RefType"></typeparam> [ComVisible(true)] public abstract class OAReferenceBase : Reference3 { #region fields private ReferenceNode referenceNode; #endregion #region ctors internal OAReferenceBase(ReferenceNode referenceNode) { this.referenceNode = referenceNode; } #endregion #region properties internal ReferenceNode BaseReferenceNode { get { return referenceNode; } } #endregion #region Reference Members public virtual int BuildNumber { get { return 0; } } public virtual References Collection { get { return BaseReferenceNode.Parent.Object as References; } } public virtual EnvDTE.Project ContainingProject { get { return BaseReferenceNode.ProjectMgr.GetAutomationObject() as EnvDTE.Project; } } public virtual bool CopyLocal { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual string Culture { get { throw new NotImplementedException(); } } public virtual EnvDTE.DTE DTE { get { return BaseReferenceNode.ProjectMgr.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE; } } public virtual string Description { get { return this.Name; } } public virtual string ExtenderCATID { get { throw new NotImplementedException(); } } public virtual object ExtenderNames { get { throw new NotImplementedException(); } } public virtual string Identity { get { throw new NotImplementedException(); } } public virtual int MajorVersion { get { return 0; } } public virtual int MinorVersion { get { return 0; } } public virtual string Name { get { throw new NotImplementedException(); } } public virtual string Path { get { return BaseReferenceNode.Url; } } public virtual string PublicKeyToken { get { throw new NotImplementedException(); } } public virtual void Remove() { BaseReferenceNode.Remove(false); } public virtual int RevisionNumber { get { return 0; } } public virtual EnvDTE.Project SourceProject { get { return null; } } public virtual bool StrongName { get { return false; } } public virtual prjReferenceType Type { get { throw new NotImplementedException(); } } public virtual string Version { get { return new Version().ToString(); } } public virtual object get_Extender(string ExtenderName) { throw new NotImplementedException(); } #endregion public string Aliases { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public bool AutoReferenced { get { throw new NotImplementedException(); } } public virtual bool Isolated { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual uint RefType { get { // Default to native reference to help prevent callers from // making incorrect assumptions return (uint)__PROJECTREFERENCETYPE.PROJREFTYPE_NATIVE; } } public virtual bool Resolved { get { throw new NotImplementedException(); } } public string RuntimeVersion { get { throw new NotImplementedException(); } } public virtual bool SpecificVersion { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual string SubType { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// VELS Aggregated Dimensions /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SVAG : EduHubEntity { #region Navigation Property Cache private KCOHORT Cache_COHORT_KCOHORT; private KDI Cache_VDIMENSION_KDI; private KDO Cache_VDOMAIN_KDO; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// Unique identification of record /// </summary> public int SVAGKEY { get; internal set; } /// <summary> /// Link to cohort /// [Alphanumeric (2)] /// </summary> public string COHORT { get; internal set; } /// <summary> /// Year level of cohort /// [Uppercase Alphanumeric (4)] /// </summary> public string SCHOOL_YEAR { get; internal set; } /// <summary> /// Campus number of cohort /// </summary> public int? CAMPUS { get; internal set; } /// <summary> /// Year and semester YYYY.S eg 2005.1 /// [Alphanumeric (6)] /// </summary> public string YEAR_SEMESTER { get; internal set; } /// <summary> /// Link to dimension /// [Uppercase Alphanumeric (10)] /// </summary> public string VDIMENSION { get; internal set; } /// <summary> /// Link to domain /// [Uppercase Alphanumeric (10)] /// </summary> public string VDOMAIN { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT01 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT02 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT03 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT04 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT05 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT06 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT07 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT08 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT09 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT10 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT11 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT12 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT13 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT14 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT15 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT16 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT17 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT18 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT19 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT20 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT21 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT22 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT23 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT24 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT25 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT26 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT27 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT28 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT29 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT30 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT31 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT32 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT33 { get; internal set; } /// <summary> /// Number of students with each dimension score /// </summary> public short? NUMBER_AT34 { get; internal set; } /// <summary> /// Number of students that have a dimension score of N/A /// </summary> public short? NO_NA { get; internal set; } /// <summary> /// Number of students that have a dimension score of NT (Not Taught) /// </summary> public short? NO_NT { get; internal set; } /// <summary> /// Number of students that have a score of DNP (Did not participate) /// </summary> public short? NO_DNP { get; internal set; } /// <summary> /// Number of students in cohort /// </summary> public short? TOTAL_NUMBER { get; internal set; } /// <summary> /// Datetime of when record was extracted into SAB export /// </summary> public DateTime? SENT_TO_DEET { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last write operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Navigation Properties /// <summary> /// KCOHORT (Cohorts for data aggregation) related entity by [SVAG.COHORT]-&gt;[KCOHORT.COHORT] /// Link to cohort /// </summary> public KCOHORT COHORT_KCOHORT { get { if (COHORT == null) { return null; } if (Cache_COHORT_KCOHORT == null) { Cache_COHORT_KCOHORT = Context.KCOHORT.FindByCOHORT(COHORT); } return Cache_COHORT_KCOHORT; } } /// <summary> /// KDI (Victorian Curriculum Strands) related entity by [SVAG.VDIMENSION]-&gt;[KDI.KDIKEY] /// Link to dimension /// </summary> public KDI VDIMENSION_KDI { get { if (VDIMENSION == null) { return null; } if (Cache_VDIMENSION_KDI == null) { Cache_VDIMENSION_KDI = Context.KDI.FindByKDIKEY(VDIMENSION); } return Cache_VDIMENSION_KDI; } } /// <summary> /// KDO (Curriculum Area) related entity by [SVAG.VDOMAIN]-&gt;[KDO.KDOKEY] /// Link to domain /// </summary> public KDO VDOMAIN_KDO { get { if (VDOMAIN == null) { return null; } if (Cache_VDOMAIN_KDO == null) { Cache_VDOMAIN_KDO = Context.KDO.FindByKDOKEY(VDOMAIN); } return Cache_VDOMAIN_KDO; } } #endregion } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using NLog.Config; using NLog.LayoutRenderers; using NLog.Targets; /// <summary> /// A specialized layout that renders Log4j-compatible XML events. /// </summary> /// <remarks> /// <para> /// This layout is not meant to be used explicitly. Instead you can use ${log4jxmlevent} layout renderer. /// </para> /// <a href="https://github.com/NLog/NLog/wiki/Log4JXmlEventLayout">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/NLog/NLog/wiki/Log4JXmlEventLayout">Documentation on NLog Wiki</seealso> [Layout("Log4JXmlEventLayout")] [ThreadAgnostic] public class Log4JXmlEventLayout : Layout, IIncludeContext { /// <summary> /// Initializes a new instance of the <see cref="Log4JXmlEventLayout" /> class. /// </summary> public Log4JXmlEventLayout() { Renderer = new Log4JXmlEventLayoutRenderer(); Parameters = new List<NLogViewerParameterInfo>(); Renderer.Parameters = Parameters; } /// <summary> /// Gets the <see cref="Log4JXmlEventLayoutRenderer"/> instance that renders log events. /// </summary> public Log4JXmlEventLayoutRenderer Renderer { get; } /// <summary> /// Gets the collection of parameters. Each parameter contains a mapping /// between NLog layout and a named parameter. /// </summary> /// <docgen category='Layout Options' order='10' /> [ArrayParameter(typeof(NLogViewerParameterInfo), "parameter")] public IList<NLogViewerParameterInfo> Parameters { get => Renderer.Parameters; set => Renderer.Parameters = value; } /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeEventProperties { get => Renderer.IncludeEventProperties; set => Renderer.IncludeEventProperties = value; } /// <summary> /// Gets or sets whether to include the contents of the <see cref="ScopeContext"/> properties-dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeScopeProperties { get => Renderer.IncludeScopeProperties; set => Renderer.IncludeScopeProperties = value; } /// <summary> /// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeScopeNested { get => Renderer.IncludeScopeNested; set => Renderer.IncludeScopeNested = value; } /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeEventProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeAllProperties { get => IncludeEventProperties; set => IncludeEventProperties = value; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdc { get => Renderer.IncludeMdc; set => Renderer.IncludeMdc = value; } /// <summary> /// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Layout Options' order='10' /> public bool IncludeNdc { get => Renderer.IncludeNdc; set => Renderer.IncludeNdc = value; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdlc { get => Renderer.IncludeMdlc; set => Renderer.IncludeMdlc = value; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsLogicalContext"/> stack. /// </summary> /// <docgen category='Layout Options' order='10' /> [Obsolete("Replaced by IncludeScopeNested. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeNdlc { get => Renderer.IncludeNdlc; set => Renderer.IncludeNdlc = value; } /// <summary> /// Gets or sets the log4j:event logger-xml-attribute (Default ${logger}) /// </summary> /// <docgen category='Layout Options' order='100' /> public Layout LoggerName { get => Renderer.LoggerName; set => Renderer.LoggerName = value; } /// <summary> /// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain. /// </summary> /// <docgen category='Layout Options' order='100' /> public Layout AppInfo { get => Renderer.AppInfo; set => Renderer.AppInfo = value; } /// <summary> /// Gets or sets whether the log4j:throwable xml-element should be written as CDATA /// </summary> /// <docgen category='Layout Options' order='100' /> public bool WriteThrowableCData { get => Renderer.WriteThrowableCData; set => Renderer.WriteThrowableCData = value; } /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network. /// </summary> /// <docgen category='Layout Options' order='100' /> public bool IncludeCallSite { get => Renderer.IncludeCallSite; set => Renderer.IncludeCallSite = value; } /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network. /// </summary> /// <docgen category='Layout Options' order='100' /> public bool IncludeSourceInfo { get => Renderer.IncludeSourceInfo; set => Renderer.IncludeSourceInfo = value; } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target); } /// <inheritdoc/> protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } /// <inheritdoc/> protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { Renderer.RenderAppendBuilder(logEvent, target); } } }
/* * Copyright (2011) Intel Corporation and Sandia Corporation. Under the * terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the * U.S. Government retains certain rights in this software. * * 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 Intel Corporation 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 INTEL OR ITS * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using log4net; using Nini.Config; using OpenMetaverse; using System.Reflection; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using WaterWars.Events; using WaterWars.Feeds; using WaterWars.Models; using WaterWars.Persistence; using WaterWars.Persistence.Recorder; using WaterWars.Rules; using WaterWars.Rules.Allocators; using WaterWars.Rules.Distributors; using WaterWars.Rules.Generators; using WaterWars.States; using WaterWars.Views; using WaterWars.WebServices; namespace WaterWars { /// <summary> /// Commands that can be executed against Water Wars from outside the game. /// </summary> public class WaterWarsCommands { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected WaterWarsController m_controller; public WaterWarsCommands(WaterWarsController controller) { m_controller = controller; } /// <summary> /// Add plinths to the given scene. /// </summary> /// <param name="scene"></param> public void AddPlinths(Scene scene) { List<ILandObject> parcels = scene.LandChannel.AllParcels(); // We want to place the plinth a little back from the corner Vector3 rezAdjustment = new Vector3(-4, -4, 0); foreach (ILandObject lo in parcels) { Vector3 swPoint, nePoint; WaterWarsUtils.FindSquareParcelCorners(lo, out swPoint, out nePoint); Vector3 rezPoint = nePoint + rezAdjustment; //BuyPoint bp = Resolver.RegisterBuyPoint(State, so); m_controller.GameManagerView.CreateBuyPointView(scene, rezPoint); // Dispatcher.RegisterBuyPointView(bpv); // State.UpdateBuyPointStatus(bp); } } /// <summary> /// Remove plinths from the given scene. /// </summary> /// <param name="scene"></param> public void RemovePlinths(Scene scene) { IDictionary<UUID, BuyPoint> buyPoints = m_controller.Game.BuyPoints; lock (buyPoints) { foreach (BuyPoint bp in buyPoints.Values) { if (bp.Location.RegionName == scene.RegionInfo.RegionName) { m_log.InfoFormat("[WATER WARS]: Removing buy point {0} in region {1}", bp.Name, bp.Location.RegionName); m_controller.Dispatcher.RemoveBuyPointView(bp); } } } } /// <summary> /// End the turn of the given player. /// </summary> /// <param name="p"></param> public void EndTurn(Player p) { m_controller.State.EndTurn(p.Uuid); } /// <summary> /// Give money to a player. /// </summary> /// <param name="p"></param> /// <param name="amount"></param> public void GiveMoney(Player p, int amount) { m_controller.State.GiveMoney(p, amount); } /// <summary> /// Give water to a player. /// </summary> /// <param name="p"></param> /// <param name="amount"></param> public void GiveWater(Player p, int amount) { m_controller.State.GiveWater(p, amount); } /// <summary> /// Give water rights to a player. /// </summary> /// <param name="p"></param> /// <param name="amount"></param> public void GiveWaterRights(Player p, int amount) { m_controller.State.GiveWaterRights(p, amount); } /// <summary> /// Randomly buys parcels for players. /// </summary> /// This exists only for testing /// <param name="parcelsToBuy">The total number of parcels to buy for all players. Asset numbers are still uncontrolled</param> public void BuyRandom(int parcelsToBuy) { if (parcelsToBuy < 0) throw new Exception("Number of parcels to buy must be greater than 0"); int boughtCount = 0; int unownedCount = 0; List<BuyPoint> buyPoints; lock (m_controller.Game.BuyPoints) buyPoints = m_controller.Game.BuyPoints.Values.ToList(); List<Player> players; lock (m_controller.Game.Players) players = m_controller.Game.Players.Values.ToList(); foreach (BuyPoint bp in buyPoints) if (bp.DevelopmentRightsOwner == Player.None) unownedCount++; // Constrained the number of parcels to buy to the number actually available if (unownedCount < parcelsToBuy) parcelsToBuy = unownedCount; m_log.InfoFormat("[WATER WARS]: Buy random buying {0} parcels", parcelsToBuy); try { while (boughtCount < parcelsToBuy) { foreach (Player p in players) { AbstractGameAsset templateAsset = p.Role.AllowedAssets[0]; BuyPoint bp = buyPoints[WaterWarsUtils.Random.Next(0, buyPoints.Count)]; if (bp.DevelopmentRightsOwner == Player.None) { m_controller.State.BuyLandRights(bp, p); boughtCount++; int assetsToBuy; lock (bp.Fields) assetsToBuy = WaterWarsUtils.Random.Next(0, bp.Fields.Count) + 1; while (assetsToBuy-- > 0) { Field f; lock (bp.Fields) f = bp.Fields.Values.ToList()[WaterWarsUtils.Random.Next(0, bp.Fields.Count)]; bool foundExistingField = false; lock (bp.GameAssets) { // FIXME: This is the only way we can currently determine in game logic if a field // is currently visible or not! foreach (AbstractGameAsset ga in bp.GameAssets.Values) if (ga.Field == f) foundExistingField = true; } if (!foundExistingField) m_controller.State.BuildGameAsset( f, templateAsset, WaterWarsUtils.Random.Next(templateAsset.MinLevel, templateAsset.MaxLevel + 1)); } break; } } } } catch (WaterWarsGameLogicException e) { // BuyLandRights throws this exception if player does not have enough money or for other // conditions. This is not yet consistent across the board (e.g. BuyGameAsset doesn't do this). m_log.WarnFormat( "[WATER WARS]: Buy random command finished with {0}{1}", e.Message, e.StackTrace); } m_log.InfoFormat( "[WATER WARS]: ww buy random command bought {0} parcels out of {1} unowned", boughtCount, unownedCount); } /// <summary> /// Make the terrain for all game parcels completely level. /// </summary> /// <param name="scene"></param> /// <param name="raise">Raise the land? If this is false then we are lowering</param> public void LevelGameParcels(Scene scene, bool raise) { List<BuyPoint> buyPoints; lock (m_controller.Game.BuyPoints) buyPoints = m_controller.Game.BuyPoints.Values.ToList(); m_log.InfoFormat("[WATER WARS]: Leveling parcels in {0}", scene.RegionInfo.RegionName); foreach (BuyPoint bp in buyPoints) { ILandObject lo = bp.Location.Parcel; if (lo.RegionUUID != scene.RegionInfo.RegionID) continue; Vector3 swPoint, nePoint; WaterWarsUtils.FindSquareParcelCorners(lo, out swPoint, out nePoint); Vector3 refHeightPoint; if (raise) refHeightPoint = new Vector3(0, 0, 0); else refHeightPoint = new Vector3(0, 0, 255); for (int x = (int)Math.Floor(swPoint.X); x <= (int)Math.Floor(nePoint.X); x++) { for (int y = (int)Math.Floor(swPoint.Y); y <= (int)Math.Floor(nePoint.Y); y++) { float height = (float)scene.Heightmap[x, y]; if (raise) { if (height > refHeightPoint.Z) refHeightPoint = new Vector3(x, y, height); } else { if (height < refHeightPoint.Z) refHeightPoint = new Vector3(x, y, height); } } } m_log.InfoFormat( "[WATER WARS]: Found {0} height point for parcel ({1},{2}) at {3}", (raise ? "max" : "min"), nePoint, swPoint, refHeightPoint); //refHeightPoint.Z = (float)Math.Ceiling(refHeightPoint.Z); m_log.InfoFormat( "[WATER WARS]: Setting all terrain on parcel ({0},{1}) to {2}", nePoint, swPoint, refHeightPoint.Z); for (int x = (int)Math.Floor(swPoint.X); x <= (int)Math.Floor(nePoint.X); x++) for (int y = (int)Math.Floor(swPoint.Y); y <= (int)Math.Floor(nePoint.Y); y++) scene.Heightmap[x, y] = refHeightPoint.Z; } ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>(); terrainModule.TaintTerrain(); } public void RefreshHuds() { m_log.InfoFormat("[WATER WARS]: Refreshing all huds."); m_controller.HudManager.RefreshHuds(); } public void ShowHuds() { string playerIdToHudFormat = "{0,-38}{1,-38}{2,-12}"; m_log.InfoFormat(playerIdToHudFormat, "Player UUID", "Hud UUID", "Hud Local ID"); foreach (KeyValuePair<UUID, HudView> kvp in m_controller.HudManager.m_playerIdToHud) m_log.InfoFormat(playerIdToHudFormat, kvp.Key, kvp.Value.RootPart.UUID, kvp.Value.RootLocalId); string localIdToHudFormat = "{0,-38}{1,-8}"; m_log.InfoFormat(localIdToHudFormat, "Hud Local ID", "Hud UUID"); foreach (KeyValuePair<uint, HudView> kvp in m_controller.HudManager.m_localIdToHud) m_log.InfoFormat(localIdToHudFormat, kvp.Key, kvp.Value.RootPart.UUID); } public void ShowParcels() { List<BuyPoint> buyPoints; lock (m_controller.Game.BuyPoints) buyPoints = m_controller.Game.BuyPoints.Values.ToList(); m_log.InfoFormat("There are {0} parcels", buyPoints.Count); string tableFormat = "{0,-16}{1,-16}{2,-33}{3,-16}{4,-16}"; m_log.InfoFormat(tableFormat, "Name", "Region", "Position", "Zone", "Owner"); foreach (BuyPoint bp in buyPoints) m_log.InfoFormat(tableFormat, bp.Name, bp.Location.RegionName, bp.Location.LocalPosition, bp.Zone, bp.DevelopmentRightsOwner); } public void ShowStatus() { m_log.InfoFormat( "[WATER WARS]: Game status is {0}, turn {1} of {2}", m_controller.Game.State, m_controller.Game.CurrentRound, m_controller.Game.TotalRounds); string playersTableFormat = "{0,-32}{1,-14}{2,-17}{3,-14}{4,-14}{5,-7}{6,-8}{7,-12}"; List<Player> players; lock (m_controller.Game.Players) players = m_controller.Game.Players.Values.ToList(); m_log.InfoFormat("There are {0} players", players.Count); m_log.InfoFormat(playersTableFormat, "Player", "Role", "Parcels owned", "Assets owned", "Water rights", "Water", "Cash", "Turn Ended"); foreach (Player p in players) { List<BuyPoint> buyPointsOwned; lock (p.DevelopmentRightsOwned) buyPointsOwned = p.DevelopmentRightsOwned.Values.ToList(); int assetsCount = 0; foreach (BuyPoint bp in buyPointsOwned) { lock (bp.GameAssets) assetsCount += bp.GameAssets.Count; } string turnEnded; if (m_controller.State is AbstractPlayState) { AbstractPlayState aps = m_controller.State as AbstractPlayState; if (aps.HasPlayerEndedTurn(p)) turnEnded = "yes"; else turnEnded = "no"; } else { turnEnded = "n/a"; } m_log.InfoFormat( playersTableFormat, p.Name, p.Role.Type, buyPointsOwned.Count, assetsCount, p.WaterEntitlement, p.Water, p.Money, turnEnded); } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using Appccelerate.EventBroker; using Appccelerate.EventBroker.Handlers; using Appccelerate.Events; using Eto; using Eto.Forms; using Eto.Gl; using Ninject; using Ninject.Extensions.Logging; using SharpFlame.Core; using SharpFlame.Domain; using SharpFlame.Domain.ObjData; using SharpFlame.Mapping; using SharpFlame.Mapping.Objects; using SharpFlame.Mapping.Tools; using SharpFlame.MouseTools; using SharpFlame.Settings; using Z.ExtensionMethods.ObjectExtensions; namespace SharpFlame.Gui.Sections { public class PlaceObjectGridViewItem { public PlaceObjectGridViewItem(UnitTypeBase obj) { string code = null; obj.GetCode(ref code); this.InternalName = code; this.InGameName = obj.GetName().Replace("*", ""); this.UnitBaseType = obj; } public UnitTypeBase UnitBaseType { get; set; } public string InternalName { get; set; } public string InGameName { get; set; } } public class PlaceObjectGridView : GridView<PlaceObjectGridViewItem> { } public class PlaceObjectsTab : TabPage { public enum FilterType { Structs, Feature, Droids } [Inject] internal ToolOptions ToolOptions { get; set; } [Inject] internal SettingsManager SettingsManager { get; set; } [Inject] internal ILogger Logger { get; set; } [Inject] internal IEventBroker EventBroker { get; set; } [Inject] internal KeyboardManager KeyboardManager { get; set; } [Inject] internal ObjectManager ObjectManager { get; set; } private Button cmdPlaceOne; private Button cmdPlaceRow; private NumericUpDown nRotation; private CheckBox chkRandom; private CheckBox chkRotateFootprints; private CheckBox chkAutoWalls; private GroupBox grpPlayers; void ObjectDataDirectories_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { try { var result = new Result("Reloading object data.", false); // Just reload Object Data. this.ObjectManager.ObjectData = new ObjectData(); foreach( var path in this.SettingsManager.ObjectDataDirectories ) { if( !string.IsNullOrEmpty(path) ) { result.Add(this.ObjectManager.ObjectData.LoadDirectory(path)); } } if( result.HasProblems || result.HasWarnings ) { App.StatusDialog = new Gui.Dialogs.Status(result); App.StatusDialog.Show(); } } catch( Exception ex ) { Logger.Error(ex, "Got an Exception while loading object data."); } } [EventSubscription(EventTopics.OnMapLoad, typeof(OnPublisher))] public void HandleMapLoad(Map args) { this.map = args; //load preset groups this.grpPlayers.Children.OfType<Button>() .ForEach(b => { if( b.Text.StartsWith("P") ) { var player = b.Text.Substring(1).ToInt32(); b.Tag = this.map.UnitGroups[player]; } else if( b.Text.StartsWith("Scav") ) { b.Tag = this.map.ScavengerUnitGroup; } }); } [EventSubscription(EventTopics.OnObjectManagerLoaded, typeof(OnPublisher))] public void HandleObjectManagerLoaded(object sender, EventArgs e) { this.RefreshGridViews(); } public PlaceObjectsTab () { XomlReader.Load(this); this.cmdPlaceOne.Image = Resources.Place; this.cmdPlaceRow.Image = Resources.Line; this.SettingsManager.ObjectDataDirectories.CollectionChanged += ObjectDataDirectories_CollectionChanged; this.features = new FilterCollection<PlaceObjectGridViewItem>(); this.structs = new FilterCollection<PlaceObjectGridViewItem>(); this.droids = new FilterCollection<PlaceObjectGridViewItem>(); gFeatures.Columns.Add(new GridColumn { HeaderText = "Internal Name", DataCell = new TextBoxCell("InternalName"), Editable = false, Sortable = true, AutoSize = true}); gFeatures.Columns.Add(new GridColumn { HeaderText = "In-Game Name", DataCell = new TextBoxCell("InGameName"), Editable = false, Sortable = true, AutoSize = true}); gStructures.Columns.Add(new GridColumn { HeaderText = "Internal Name", DataCell = new TextBoxCell("InternalName"), Editable = false, Sortable = true }); gStructures.Columns.Add(new GridColumn { HeaderText = "In-Game Name", DataCell = new TextBoxCell("InGameName"), Editable = false, Sortable = true }); gDroids.Columns.Add(new GridColumn { HeaderText = "Internal Name", DataCell = new TextBoxCell("InternalName"), Editable = false, Sortable = true }); gDroids.Columns.Add(new GridColumn { HeaderText = "In-Game Name", DataCell = new TextBoxCell("InGameName"), Editable = false, Sortable = true }); } private Panel panDroids; private Panel panStructs; private Panel panFeatures; public PlaceObjectGridView gFeatures; public PlaceObjectGridView gStructures; public PlaceObjectGridView gDroids; private LinkButton cmdSelectAll; protected override void OnPreLoad(EventArgs e) { base.OnPreLoad(e); this.nRotation.Bind(n => n.Enabled, this.chkRandom.CheckedBinding.Convert(g => !g.Value)); this.nRotation.ValueBinding.Bind(this.ToolOptions.PlaceObject, p => p.Rotation); this.chkAutoWalls.CheckedBinding.Bind(this.ToolOptions.PlaceObject, p => p.AutoWalls); this.chkRandom.CheckedBinding.Bind(this.ToolOptions.PlaceObject, p => p.RotationRandom); this.chkRotateFootprints.CheckedBinding.Bind(this.ToolOptions.PlaceObject, p => p.RotateFootprints); this.cmdSelectAll.TextBinding.BindDataContext<Button>(getValue: b => { return "Select All {0} Units".FormatWith(b.Text); }, setValue: null, mode: DualBindingMode.OneWay, defaultGetValue:""); } public void RefreshGridViews() { var objFeatures = this.ObjectManager.ObjectData.FeatureTypes.CopyList() .Select(f => new PlaceObjectGridViewItem(f)); this.features.Clear(); this.features.AddRange(objFeatures); this.gFeatures.DataStore = features; var objStrcuts = this.ObjectManager.ObjectData.StructureTypes.CopyList() .Select(f => new PlaceObjectGridViewItem(f)); this.structs.Clear(); this.structs.AddRange(objStrcuts); this.gStructures.DataStore = this.structs; var objDroids = this.ObjectManager.ObjectData.DroidTemplates.CopyList() .Select(f => new PlaceObjectGridViewItem(f)); this.droids.Clear(); this.droids.AddRange(objDroids); this.gDroids.DataStore = this.droids; } protected override void OnLoadComplete(EventArgs lcEventArgs) { base.OnLoadComplete(lcEventArgs); this.Click += (sender, args) => { ToolOptions.MouseTool = MouseTool.Default; }; } void AnyPlayer_Click(object sender, EventArgs e) { if( this.map == null ) return; this.grpPlayers.DataContext = sender; var button = sender as Button; var group = button.Tag.To<clsUnitGroup>(); this.map.SelectedUnitGroup.Item = group; if( map.SelectedUnits.Count <= 0 ) return; if( this.map.SelectedUnits.Count > 1 ) { if( MessageBox.Show(this, "Change player of multiple objects?", MessageBoxButtons.YesNo) != DialogResult.Yes ) { return; } } var objUnitGroup = new clsObjectUnitGroup() { Map = this.map, UnitGroup = group }; this.map.SelectedUnitsAction(objUnitGroup); this.map.UndoStepCreate("Object Player Changed"); if( this.SettingsManager.MinimapTeamColours ) { this.EventBroker.RefreshMinimap(this); } this.EventBroker.DrawLater(this); } void AnyPlayer_PreLoad(object sender, EventArgs e) { var button = sender as Button; button.Bind(b => b.Enabled, Binding.Delegate(() => this.grpPlayers.DataContext != button, addChangeEvent: handlerToExecuteWhenSourceChanges => this.grpPlayers.DataContextChanged += handlerToExecuteWhenSourceChanges, removeChangeEvent: handlerToExecuteWhenSourceChanges => this.grpPlayers.DataContextChanged += handlerToExecuteWhenSourceChanges)); button.Bind(b => b.BackgroundColor, Binding.Delegate(() => { if( this.grpPlayers.DataContext == button ) { return Eto.Drawing.Colors.SkyBlue; } return Eto.Drawing.Colors.Transparent; }, addChangeEvent: h => this.grpPlayers.DataContextChanged += h, removeChangeEvent: h => this.grpPlayers.DataContextChanged += h)); } void cmdSelectAll_Click(object sender, EventArgs e) { if( this.map == null ) return; if( !KeyboardManager.Commands[CommandName.Multiselect].Active ) { this.map.SelectedUnits.Clear(); } var unitGroup = this.map.SelectedUnitGroup.Item; foreach( var unit in this.map.Units ) { if( unit.UnitGroup == unitGroup ) { if( unit.TypeBase.Type != UnitType.Feature ) { if( !unit.MapSelectedUnitLink.IsConnected ) { unit.MapSelectedUnitLink.Connect(this.map.SelectedUnits); } } } } this.EventBroker.DrawLater(this); } void AnyGrid_SelectionChanged(object sender, EventArgs e) { var grid = sender as PlaceObjectGridView; var types = grid.SelectedItems .Select(gvi => gvi.UnitBaseType).ToList(); this.ToolOptions.PlaceObject.SelectedObjectTypes = types; this.EventBroker.DrawLater(this); } void ToolSelection_Click(object sender, EventArgs e) { var button = sender as Button; var tool = button.Tag.To<MouseTool>(); ToolOptions.MouseTool = tool; if( sender == this.cmdPlaceOne ) { this.cmdPlaceOne.Enabled = false; this.cmdPlaceRow.Enabled = true; this.cmdPlaceOne.BackgroundColor = Eto.Drawing.Colors.Coral; this.cmdPlaceRow.BackgroundColor = Eto.Drawing.Colors.Transparent; } else if( sender == this.cmdPlaceRow ) { this.cmdPlaceRow.Enabled = false; this.cmdPlaceOne.Enabled = true; this.cmdPlaceRow.BackgroundColor = Eto.Drawing.Colors.Coral; this.cmdPlaceOne.BackgroundColor = Eto.Drawing.Colors.Transparent; } } private FilterCollection<PlaceObjectGridViewItem> features; private FilterCollection<PlaceObjectGridViewItem> structs; private FilterCollection<PlaceObjectGridViewItem> droids; private Map map; void Filter_KeyUp(object sender, KeyEventArgs e) { var search = sender as SearchBox; var searchType = search.Tag.To<FilterType>(); FilterCollection<PlaceObjectGridViewItem> collection = null; if( searchType == FilterType.Feature) { collection = features; } else if( searchType == FilterType.Structs ) { collection = structs; } else if( searchType == FilterType.Droids ) { collection = droids; } if( search.Text.IsNullOrWhiteSpace() ) { collection.Filter = null; return; } var searchTokens = search.Text.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); collection.Filter = item => { return searchTokens.Any(t => item.InGameName.IndexOf(t, StringComparison.OrdinalIgnoreCase) >= 0); }; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using OpenTK; using OpenTK.Graphics; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Rulesets.Scoring; using osu.Game.Screens.Play; using osu.Game.Screens.Select.Leaderboards; using osu.Game.Users; using osu.Framework.Graphics.Shapes; namespace osu.Game.Screens.Ranking { internal class ResultsPageScore : ResultsPage { private ScoreCounter scoreCounter; public ResultsPageScore(Score score, WorkingBeatmap beatmap) : base(score, beatmap) { } private FillFlowContainer<DrawableScoreStatistic> statisticsContainer; [BackgroundDependencyLoader] private void load(OsuColour colours) { const float user_header_height = 120; Children = new Drawable[] { new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Top = user_header_height }, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.White, }, } }, new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Children = new Drawable[] { new UserHeader(Score.User) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.X, Height = user_header_height, }, new DrawableRank(Score.Rank) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Size = new Vector2(150, 60), Margin = new MarginPadding(20), }, new Container { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.X, Height = 60, Children = new Drawable[] { new SongProgressGraph { RelativeSizeAxes = Axes.Both, Alpha = 0.5f, Objects = Beatmap.Beatmap.HitObjects, }, scoreCounter = new SlowScoreCounter(6) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Colour = colours.PinkDarker, Y = 10, TextSize = 56, }, } }, new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Colour = colours.PinkDarker, Shadow = false, Font = @"Exo2.0-Bold", TextSize = 16, Text = "total score", Margin = new MarginPadding { Bottom = 15 }, }, new BeatmapDetails(Beatmap.BeatmapInfo) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Margin = new MarginPadding { Bottom = 10 }, }, new DateTimeDisplay(Score.Date.LocalDateTime) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, new Container { RelativeSizeAxes = Axes.X, Size = new Vector2(0.75f, 1), Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Margin = new MarginPadding { Top = 10, Bottom = 10 }, Children = new Drawable[] { new Box { Colour = ColourInfo.GradientHorizontal( colours.GrayC.Opacity(0), colours.GrayC.Opacity(0.9f)), RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f, 1), }, new Box { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, Colour = ColourInfo.GradientHorizontal( colours.GrayC.Opacity(0.9f), colours.GrayC.Opacity(0)), RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f, 1), }, } }, statisticsContainer = new FillFlowContainer<DrawableScoreStatistic> { AutoSizeAxes = Axes.Both, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Direction = FillDirection.Horizontal, LayoutDuration = 200, LayoutEasing = Easing.OutQuint } } } }; statisticsContainer.ChildrenEnumerable = Score.Statistics.Select(s => new DrawableScoreStatistic(s)); } protected override void LoadComplete() { base.LoadComplete(); Schedule(() => { scoreCounter.Increment(Score.TotalScore); int delay = 0; foreach (var s in statisticsContainer.Children) { s.FadeOut() .Then(delay += 200) .FadeIn(300 + delay, Easing.Out); } }); } private class DrawableScoreStatistic : Container { private readonly KeyValuePair<string, object> statistic; public DrawableScoreStatistic(KeyValuePair<string, object> statistic) { this.statistic = statistic; AutoSizeAxes = Axes.Both; Margin = new MarginPadding { Left = 5, Right = 5 }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Children = new Drawable[] { new SpriteText { Text = statistic.Value.ToString().PadLeft(4, '0'), Colour = colours.Gray7, TextSize = 30, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, new SpriteText { Text = statistic.Key, Colour = colours.Gray7, Font = @"Exo2.0-Bold", Y = 26, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, }; } } private class DateTimeDisplay : Container { private DateTime datetime; public DateTimeDisplay(DateTime datetime) { this.datetime = datetime; AutoSizeAxes = Axes.Y; Width = 140; Masking = true; CornerRadius = 5; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = colours.Gray6, }, new OsuSpriteText { Origin = Anchor.CentreLeft, Anchor = Anchor.CentreLeft, Text = datetime.ToString("HH:mm"), Padding = new MarginPadding { Left = 10, Right = 10, Top = 5, Bottom = 5 }, Colour = Color4.White, }, new OsuSpriteText { Origin = Anchor.CentreRight, Anchor = Anchor.CentreRight, Text = datetime.ToString("yyyy/MM/dd"), Padding = new MarginPadding { Left = 10, Right = 10, Top = 5, Bottom = 5 }, Colour = Color4.White, } }; } } private class BeatmapDetails : Container { private readonly BeatmapInfo beatmap; private readonly OsuSpriteText title; private readonly OsuSpriteText artist; private readonly OsuSpriteText versionMapper; public BeatmapDetails(BeatmapInfo beatmap) { this.beatmap = beatmap; AutoSizeAxes = Axes.Both; Children = new Drawable[] { new FillFlowContainer { Direction = FillDirection.Vertical, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { title = new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Shadow = false, TextSize = 24, Font = @"Exo2.0-BoldItalic", }, artist = new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Shadow = false, TextSize = 20, Font = @"Exo2.0-BoldItalic", }, versionMapper = new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Shadow = false, TextSize = 16, Font = @"Exo2.0-Bold", }, } } }; } [BackgroundDependencyLoader] private void load(OsuColour colours, LocalisationEngine localisation) { title.Colour = artist.Colour = colours.BlueDarker; versionMapper.Colour = colours.Gray8; versionMapper.Text = $"{beatmap.Version} - mapped by {beatmap.Metadata.Author}"; title.Current = localisation.GetUnicodePreference(beatmap.Metadata.TitleUnicode, beatmap.Metadata.Title); artist.Current = localisation.GetUnicodePreference(beatmap.Metadata.ArtistUnicode, beatmap.Metadata.Artist); } } private class UserHeader : Container { private readonly User user; private readonly Sprite cover; public UserHeader(User user) { this.user = user; Children = new Drawable[] { cover = new Sprite { RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fill, Anchor = Anchor.Centre, Origin = Anchor.Centre, }, new OsuSpriteText { Font = @"Exo2.0-RegularItalic", Text = user.Username, Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre, TextSize = 30, Padding = new MarginPadding { Bottom = 10 }, } }; } [BackgroundDependencyLoader] private void load(TextureStore textures) { if (!string.IsNullOrEmpty(user.CoverUrl)) cover.Texture = textures.Get(user.CoverUrl); } } private class SlowScoreCounter : ScoreCounter { protected override double RollingDuration => 3000; protected override Easing RollingEasing => Easing.OutPow10; public SlowScoreCounter(uint leading = 0) : base(leading) { DisplayedCountSpriteText.Shadow = false; DisplayedCountSpriteText.Font = @"Venera-Light"; UseCommaSeparator = true; } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Year Levels Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KCYDataSet : EduHubDataSet<KCY> { /// <inheritdoc /> public override string Name { get { return "KCY"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KCYDataSet(EduHubContext Context) : base(Context) { Index_KCYKEY = new Lazy<Dictionary<string, KCY>>(() => this.ToDictionary(i => i.KCYKEY)); Index_NEXT_YR = new Lazy<NullDictionary<string, IReadOnlyList<KCY>>>(() => this.ToGroupedNullDictionary(i => i.NEXT_YR)); Index_TEACHER = new Lazy<NullDictionary<string, IReadOnlyList<KCY>>>(() => this.ToGroupedNullDictionary(i => i.TEACHER)); Index_TEACHER_B = new Lazy<NullDictionary<string, IReadOnlyList<KCY>>>(() => this.ToGroupedNullDictionary(i => i.TEACHER_B)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KCY" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KCY" /> fields for each CSV column header</returns> internal override Action<KCY, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KCY, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KCYKEY": mapper[i] = (e, v) => e.KCYKEY = v; break; case "DESCRIPTION": mapper[i] = (e, v) => e.DESCRIPTION = v; break; case "NUM_EQVT": mapper[i] = (e, v) => e.NUM_EQVT = v == null ? (short?)null : short.Parse(v); break; case "SHORT_DESC": mapper[i] = (e, v) => e.SHORT_DESC = v; break; case "TEACHER": mapper[i] = (e, v) => e.TEACHER = v; break; case "TEACHER_B": mapper[i] = (e, v) => e.TEACHER_B = v; break; case "NEXT_YR": mapper[i] = (e, v) => e.NEXT_YR = v; break; case "FINAL_YR": mapper[i] = (e, v) => e.FINAL_YR = v; break; case "CSF_REQUIRED": mapper[i] = (e, v) => e.CSF_REQUIRED = v; break; case "HALF_DAY_ABS": mapper[i] = (e, v) => e.HALF_DAY_ABS = v; break; case "PERIOD_ABS": mapper[i] = (e, v) => e.PERIOD_ABS = v; break; case "BIRTHDATE_FROM": mapper[i] = (e, v) => e.BIRTHDATE_FROM = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "BIRTHDATE_TO": mapper[i] = (e, v) => e.BIRTHDATE_TO = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KCY" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KCY" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KCY" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KCY}"/> of entities</returns> internal override IEnumerable<KCY> ApplyDeltaEntities(IEnumerable<KCY> Entities, List<KCY> DeltaEntities) { HashSet<string> Index_KCYKEY = new HashSet<string>(DeltaEntities.Select(i => i.KCYKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KCYKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KCYKEY.Remove(entity.KCYKEY); if (entity.KCYKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, KCY>> Index_KCYKEY; private Lazy<NullDictionary<string, IReadOnlyList<KCY>>> Index_NEXT_YR; private Lazy<NullDictionary<string, IReadOnlyList<KCY>>> Index_TEACHER; private Lazy<NullDictionary<string, IReadOnlyList<KCY>>> Index_TEACHER_B; #endregion #region Index Methods /// <summary> /// Find KCY by KCYKEY field /// </summary> /// <param name="KCYKEY">KCYKEY value used to find KCY</param> /// <returns>Related KCY entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCY FindByKCYKEY(string KCYKEY) { return Index_KCYKEY.Value[KCYKEY]; } /// <summary> /// Attempt to find KCY by KCYKEY field /// </summary> /// <param name="KCYKEY">KCYKEY value used to find KCY</param> /// <param name="Value">Related KCY entity</param> /// <returns>True if the related KCY entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKCYKEY(string KCYKEY, out KCY Value) { return Index_KCYKEY.Value.TryGetValue(KCYKEY, out Value); } /// <summary> /// Attempt to find KCY by KCYKEY field /// </summary> /// <param name="KCYKEY">KCYKEY value used to find KCY</param> /// <returns>Related KCY entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCY TryFindByKCYKEY(string KCYKEY) { KCY value; if (Index_KCYKEY.Value.TryGetValue(KCYKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find KCY by NEXT_YR field /// </summary> /// <param name="NEXT_YR">NEXT_YR value used to find KCY</param> /// <returns>List of related KCY entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCY> FindByNEXT_YR(string NEXT_YR) { return Index_NEXT_YR.Value[NEXT_YR]; } /// <summary> /// Attempt to find KCY by NEXT_YR field /// </summary> /// <param name="NEXT_YR">NEXT_YR value used to find KCY</param> /// <param name="Value">List of related KCY entities</param> /// <returns>True if the list of related KCY entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByNEXT_YR(string NEXT_YR, out IReadOnlyList<KCY> Value) { return Index_NEXT_YR.Value.TryGetValue(NEXT_YR, out Value); } /// <summary> /// Attempt to find KCY by NEXT_YR field /// </summary> /// <param name="NEXT_YR">NEXT_YR value used to find KCY</param> /// <returns>List of related KCY entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCY> TryFindByNEXT_YR(string NEXT_YR) { IReadOnlyList<KCY> value; if (Index_NEXT_YR.Value.TryGetValue(NEXT_YR, out value)) { return value; } else { return null; } } /// <summary> /// Find KCY by TEACHER field /// </summary> /// <param name="TEACHER">TEACHER value used to find KCY</param> /// <returns>List of related KCY entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCY> FindByTEACHER(string TEACHER) { return Index_TEACHER.Value[TEACHER]; } /// <summary> /// Attempt to find KCY by TEACHER field /// </summary> /// <param name="TEACHER">TEACHER value used to find KCY</param> /// <param name="Value">List of related KCY entities</param> /// <returns>True if the list of related KCY entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTEACHER(string TEACHER, out IReadOnlyList<KCY> Value) { return Index_TEACHER.Value.TryGetValue(TEACHER, out Value); } /// <summary> /// Attempt to find KCY by TEACHER field /// </summary> /// <param name="TEACHER">TEACHER value used to find KCY</param> /// <returns>List of related KCY entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCY> TryFindByTEACHER(string TEACHER) { IReadOnlyList<KCY> value; if (Index_TEACHER.Value.TryGetValue(TEACHER, out value)) { return value; } else { return null; } } /// <summary> /// Find KCY by TEACHER_B field /// </summary> /// <param name="TEACHER_B">TEACHER_B value used to find KCY</param> /// <returns>List of related KCY entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCY> FindByTEACHER_B(string TEACHER_B) { return Index_TEACHER_B.Value[TEACHER_B]; } /// <summary> /// Attempt to find KCY by TEACHER_B field /// </summary> /// <param name="TEACHER_B">TEACHER_B value used to find KCY</param> /// <param name="Value">List of related KCY entities</param> /// <returns>True if the list of related KCY entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTEACHER_B(string TEACHER_B, out IReadOnlyList<KCY> Value) { return Index_TEACHER_B.Value.TryGetValue(TEACHER_B, out Value); } /// <summary> /// Attempt to find KCY by TEACHER_B field /// </summary> /// <param name="TEACHER_B">TEACHER_B value used to find KCY</param> /// <returns>List of related KCY entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCY> TryFindByTEACHER_B(string TEACHER_B) { IReadOnlyList<KCY> value; if (Index_TEACHER_B.Value.TryGetValue(TEACHER_B, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KCY table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KCY]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KCY]( [KCYKEY] varchar(4) NOT NULL, [DESCRIPTION] varchar(30) NULL, [NUM_EQVT] smallint NULL, [SHORT_DESC] varchar(10) NULL, [TEACHER] varchar(4) NULL, [TEACHER_B] varchar(4) NULL, [NEXT_YR] varchar(4) NULL, [FINAL_YR] varchar(1) NULL, [CSF_REQUIRED] varchar(1) NULL, [HALF_DAY_ABS] varchar(1) NULL, [PERIOD_ABS] varchar(1) NULL, [BIRTHDATE_FROM] datetime NULL, [BIRTHDATE_TO] datetime NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KCY_Index_KCYKEY] PRIMARY KEY CLUSTERED ( [KCYKEY] ASC ) ); CREATE NONCLUSTERED INDEX [KCY_Index_NEXT_YR] ON [dbo].[KCY] ( [NEXT_YR] ASC ); CREATE NONCLUSTERED INDEX [KCY_Index_TEACHER] ON [dbo].[KCY] ( [TEACHER] ASC ); CREATE NONCLUSTERED INDEX [KCY_Index_TEACHER_B] ON [dbo].[KCY] ( [TEACHER_B] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCY]') AND name = N'KCY_Index_NEXT_YR') ALTER INDEX [KCY_Index_NEXT_YR] ON [dbo].[KCY] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCY]') AND name = N'KCY_Index_TEACHER') ALTER INDEX [KCY_Index_TEACHER] ON [dbo].[KCY] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCY]') AND name = N'KCY_Index_TEACHER_B') ALTER INDEX [KCY_Index_TEACHER_B] ON [dbo].[KCY] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCY]') AND name = N'KCY_Index_NEXT_YR') ALTER INDEX [KCY_Index_NEXT_YR] ON [dbo].[KCY] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCY]') AND name = N'KCY_Index_TEACHER') ALTER INDEX [KCY_Index_TEACHER] ON [dbo].[KCY] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCY]') AND name = N'KCY_Index_TEACHER_B') ALTER INDEX [KCY_Index_TEACHER_B] ON [dbo].[KCY] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KCY"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KCY"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KCY> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_KCYKEY = new List<string>(); foreach (var entity in Entities) { Index_KCYKEY.Add(entity.KCYKEY); } builder.AppendLine("DELETE [dbo].[KCY] WHERE"); // Index_KCYKEY builder.Append("[KCYKEY] IN ("); for (int index = 0; index < Index_KCYKEY.Count; index++) { if (index != 0) builder.Append(", "); // KCYKEY var parameterKCYKEY = $"@p{parameterIndex++}"; builder.Append(parameterKCYKEY); command.Parameters.Add(parameterKCYKEY, SqlDbType.VarChar, 4).Value = Index_KCYKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KCY data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KCY data set</returns> public override EduHubDataSetDataReader<KCY> GetDataSetDataReader() { return new KCYDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KCY data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KCY data set</returns> public override EduHubDataSetDataReader<KCY> GetDataSetDataReader(List<KCY> Entities) { return new KCYDataReader(new EduHubDataSetLoadedReader<KCY>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KCYDataReader : EduHubDataSetDataReader<KCY> { public KCYDataReader(IEduHubDataSetReader<KCY> Reader) : base (Reader) { } public override int FieldCount { get { return 16; } } public override object GetValue(int i) { switch (i) { case 0: // KCYKEY return Current.KCYKEY; case 1: // DESCRIPTION return Current.DESCRIPTION; case 2: // NUM_EQVT return Current.NUM_EQVT; case 3: // SHORT_DESC return Current.SHORT_DESC; case 4: // TEACHER return Current.TEACHER; case 5: // TEACHER_B return Current.TEACHER_B; case 6: // NEXT_YR return Current.NEXT_YR; case 7: // FINAL_YR return Current.FINAL_YR; case 8: // CSF_REQUIRED return Current.CSF_REQUIRED; case 9: // HALF_DAY_ABS return Current.HALF_DAY_ABS; case 10: // PERIOD_ABS return Current.PERIOD_ABS; case 11: // BIRTHDATE_FROM return Current.BIRTHDATE_FROM; case 12: // BIRTHDATE_TO return Current.BIRTHDATE_TO; case 13: // LW_DATE return Current.LW_DATE; case 14: // LW_TIME return Current.LW_TIME; case 15: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // DESCRIPTION return Current.DESCRIPTION == null; case 2: // NUM_EQVT return Current.NUM_EQVT == null; case 3: // SHORT_DESC return Current.SHORT_DESC == null; case 4: // TEACHER return Current.TEACHER == null; case 5: // TEACHER_B return Current.TEACHER_B == null; case 6: // NEXT_YR return Current.NEXT_YR == null; case 7: // FINAL_YR return Current.FINAL_YR == null; case 8: // CSF_REQUIRED return Current.CSF_REQUIRED == null; case 9: // HALF_DAY_ABS return Current.HALF_DAY_ABS == null; case 10: // PERIOD_ABS return Current.PERIOD_ABS == null; case 11: // BIRTHDATE_FROM return Current.BIRTHDATE_FROM == null; case 12: // BIRTHDATE_TO return Current.BIRTHDATE_TO == null; case 13: // LW_DATE return Current.LW_DATE == null; case 14: // LW_TIME return Current.LW_TIME == null; case 15: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KCYKEY return "KCYKEY"; case 1: // DESCRIPTION return "DESCRIPTION"; case 2: // NUM_EQVT return "NUM_EQVT"; case 3: // SHORT_DESC return "SHORT_DESC"; case 4: // TEACHER return "TEACHER"; case 5: // TEACHER_B return "TEACHER_B"; case 6: // NEXT_YR return "NEXT_YR"; case 7: // FINAL_YR return "FINAL_YR"; case 8: // CSF_REQUIRED return "CSF_REQUIRED"; case 9: // HALF_DAY_ABS return "HALF_DAY_ABS"; case 10: // PERIOD_ABS return "PERIOD_ABS"; case 11: // BIRTHDATE_FROM return "BIRTHDATE_FROM"; case 12: // BIRTHDATE_TO return "BIRTHDATE_TO"; case 13: // LW_DATE return "LW_DATE"; case 14: // LW_TIME return "LW_TIME"; case 15: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KCYKEY": return 0; case "DESCRIPTION": return 1; case "NUM_EQVT": return 2; case "SHORT_DESC": return 3; case "TEACHER": return 4; case "TEACHER_B": return 5; case "NEXT_YR": return 6; case "FINAL_YR": return 7; case "CSF_REQUIRED": return 8; case "HALF_DAY_ABS": return 9; case "PERIOD_ABS": return 10; case "BIRTHDATE_FROM": return 11; case "BIRTHDATE_TO": return 12; case "LW_DATE": return 13; case "LW_TIME": return 14; case "LW_USER": return 15; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using UnityEngine; using UnityEngine.Rendering; using System.Collections.Generic; using DFHack; using RemoteFortressReader; using UnityEngine.UI; using System.IO; using UnitFlags; // The class responsible for talking to DF and meshing the data it gets. // Relevant vocabulary: A "map tile" is an individual square on the map. // A "map block" is a 16x16x1 area of map tiles stored by DF; think minecraft "chunks". public class GameMap : MonoBehaviour { // Things to be set from the Unity Editor. public Material basicTerrainMaterial; // Can be any terrain you want. public Material stencilTerrainMaterial; // Foliage & other stenciled materials. public Material waterMaterial; public Material magmaMaterial; public Material invisibleMaterial; public Material invisibleStencilMaterial; Material BasicTopMaterial { get { if (firstPerson) return basicTerrainMaterial; else if (overheadShadows) return invisibleMaterial; else return null; } } Material StencilTopMaterial { get { if (firstPerson) return stencilTerrainMaterial; else if (overheadShadows) return invisibleStencilMaterial; else return null; } } public Light magmaGlowPrefab; public Text genStatus; public Text cursorProperties; public bool overheadShadows = true; public bool firstPerson = false; public int cursX = -30000; public int cursY = -30000; public int cursZ = -30000; public WorldMapMaker worldMap; // Parameters managing the currently visible area of the map. // Tracking: int PosXBlock { get { return posXTile / 16; } } int PosYBlock { get { return posYTile / 16; } } public int posXTile = 0; public int posYTile = 0; public int posZ = 0; public int PosZ { // Public accessor; used from MapSelection get { return posZ; } } public int PosXTile { get { return posXTile; } } public int PosYTile { get { return posYTile; } } // Preferences: public int rangeX = 4; public int rangeY = 4; public int rangeZup = 0; public int rangeZdown = 5; public int blocksToProcess = 1; public int cameraViewDist = 25; public int meshingThreads = 0; // Stored view information RemoteFortressReader.ViewInfo view; BlockMesher mesher; // The actual unity meshes used to draw things on screen. Mesh[, ,] blocks; // Terrain data. Mesh[, ,] stencilBlocks; // Foliage &ct. Mesh[, , ,] liquidBlocks; // Water & magma. Extra dimension is a liquid type. // Dirty flags for those meshes bool[, ,] blockDirtyBits; bool[, ,] liquidBlockDirtyBits; // Lights from magma. Light[, ,] magmaGlow; // Stuff to let the material list & various meshes & whatnot be loaded from xml specs at runtime. Dictionary<MatPairStruct, RemoteFortressReader.MaterialDefinition> materials; Dictionary<MatPairStruct, RemoteFortressReader.MaterialDefinition> items; // Coordinate system stuff. public const float tileHeight = 3.0f; public const float floorHeight = 0.5f; public const float tileWidth = 2.0f; public const int blockSize = 16; public static Vector3 DFtoUnityCoord(int x, int y, int z) { Vector3 outCoord = new Vector3(x * tileWidth, z * tileHeight, y * (-tileWidth)); return outCoord; } public static Vector3 DFtoUnityCoord(DFCoord input) { Vector3 outCoord = new Vector3(input.x * tileWidth, input.z * tileHeight, input.y * (-tileWidth)); return outCoord; } public static Vector3 DFtoUnityTileCenter(DFCoord input) { Vector3 result = DFtoUnityCoord(input); result.y += tileHeight / 2; return result; } public static Vector3 DFtoUnityBottomCorner(DFCoord input) { Vector3 result = DFtoUnityCoord(input); result.x -= tileWidth / 2; result.z -= tileWidth / 2; return result; } public static DFCoord UnityToDFCoord(Vector3 input) { int x = Mathf.RoundToInt(input.x / tileWidth); int y = Mathf.RoundToInt(input.z / -tileWidth); int z = Mathf.FloorToInt(input.y / tileHeight); return new DFCoord(x, y, z); } public static bool IsBlockCorner(DFCoord input) { return input.x % blockSize == 0 && input.y % blockSize == 0; } // Used while meshing blocks MeshCombineUtility.MeshInstance[] meshBuffer; MeshCombineUtility.MeshInstance[] stencilMeshBuffer; // Used for random diagnostics System.Diagnostics.Stopwatch blockListTimer = new System.Diagnostics.Stopwatch(); System.Diagnostics.Stopwatch cullTimer = new System.Diagnostics.Stopwatch(); System.Diagnostics.Stopwatch lazyLoadTimer = new System.Diagnostics.Stopwatch(); // Does about what you'd think it does. void Start() { enabled = false; DFConnection.RegisterConnectionCallback(this.OnConnectToDF); } void OnConnectToDF() { Debug.Log("Connected"); enabled = true; mesher = BlockMesher.GetMesher(meshingThreads); // Initialize materials if (materials == null) materials = new Dictionary<MatPairStruct, RemoteFortressReader.MaterialDefinition>(); materials.Clear(); foreach (RemoteFortressReader.MaterialDefinition material in DFConnection.Instance.NetMaterialList.material_list) { materials[material.mat_pair] = material; } // Initialize items if (items == null) items = new Dictionary<MatPairStruct, RemoteFortressReader.MaterialDefinition>(); items.Clear(); foreach (RemoteFortressReader.MaterialDefinition material in DFConnection.Instance.NetItemList.material_list) { items[material.mat_pair] = material; } SaveTileTypeList(); SaveMaterialList(DFConnection.Instance.NetMaterialList.material_list, "MaterialList.csv"); SaveMaterialList(DFConnection.Instance.NetItemList.material_list, "ItemList.csv"); SaveBuildingList(); UpdateView(); blockListTimer.Start(); cullTimer.Start(); lazyLoadTimer.Start(); InitializeBlocks(); } // Run once per frame. void Update() { //UpdateView(); ShowCursorInfo(); UpdateRequestRegion(); blockListTimer.Reset(); blockListTimer.Start(); UpdateCreatures(); UpdateBlocks(); DrawBlocks(); } void OnDestroy() { if (mesher != null) { mesher.Terminate(); mesher = null; } } void UpdateView() { RemoteFortressReader.ViewInfo newView = DFConnection.Instance.PopViewInfoUpdate(); if (newView == null) return; //Debug.Log("Got view"); view = newView; posXTile = (view.view_pos_x + (view.view_size_x / 2)); posYTile = (view.view_pos_y + (view.view_size_y / 2)); posZ = view.view_pos_z + 1; } // Update the region we're requesting void UpdateRequestRegion() { DFConnection.Instance.SetRequestRegion( new BlockCoord( PosXBlock - rangeX, PosYBlock - rangeY, posZ - rangeZdown ), new BlockCoord( PosXBlock + rangeX, PosYBlock + rangeY, posZ + rangeZup )); } void UpdateBlocks() { loadWatch.Reset(); loadWatch.Start(); while (true) { RemoteFortressReader.MapBlock block = DFConnection.Instance.PopMapBlockUpdate(); if (block == null) break; MapDataStore.Main.StoreTiles(block); if (block.tiles.Count > 0) SetDirtyBlock(block.map_x, block.map_y, block.map_z); if (block.water.Count > 0 || block.magma.Count > 0) SetDirtyLiquidBlock(block.map_x, block.map_y, block.map_z); } loadWatch.Stop(); genWatch.Reset(); genWatch.Start(); EnqueueMeshUpdates(); genWatch.Stop(); mesher.Poll(); FetchNewMeshes(); } void InitializeBlocks() { int blockSizeX = DFConnection.Instance.NetMapInfo.block_size_x; int blockSizeY = DFConnection.Instance.NetMapInfo.block_size_y; int blockSizeZ = DFConnection.Instance.NetMapInfo.block_size_z; Debug.Log("Map Size: " + blockSizeX + ", " + blockSizeY + ", " + blockSizeZ); blocks = new Mesh[blockSizeX * 16 / blockSize, blockSizeY * 16 / blockSize, blockSizeZ]; stencilBlocks = new Mesh[blockSizeX * 16 / blockSize, blockSizeY * 16 / blockSize, blockSizeZ]; liquidBlocks = new Mesh[blockSizeX * 16 / blockSize, blockSizeY * 16 / blockSize, blockSizeZ, 2]; blockDirtyBits = new bool[blockSizeX * 16 / blockSize, blockSizeY * 16 / blockSize, blockSizeZ]; liquidBlockDirtyBits = new bool[blockSizeX * 16 / blockSize, blockSizeY * 16 / blockSize, blockSizeZ]; magmaGlow = new Light[blockSizeX * 16, blockSizeY * 16, blockSizeZ]; } void SetDirtyBlock(int mapBlockX, int mapBlockY, int mapBlockZ) { mapBlockX = mapBlockX / blockSize; mapBlockY = mapBlockY / blockSize; blockDirtyBits[mapBlockX, mapBlockY, mapBlockZ] = true; } void SetDirtyLiquidBlock(int mapBlockX, int mapBlockY, int mapBlockZ) { mapBlockX = mapBlockX / blockSize; mapBlockY = mapBlockY / blockSize; liquidBlockDirtyBits[mapBlockX, mapBlockY, mapBlockZ] = true; } void PrintFullMaterialList() { int totalCount = DFConnection.Instance.NetMaterialList.material_list.Count; int limit = totalCount; if (limit >= 100) limit = 100; //Don't ever do this. for (int i = totalCount - limit; i < totalCount; i++) { //no really, don't. RemoteFortressReader.MaterialDefinition material = DFConnection.Instance.NetMaterialList.material_list[i]; Debug.Log("{" + material.mat_pair.mat_index + "," + material.mat_pair.mat_type + "}, " + material.id + ", " + material.name); } } void SaveTileTypeList() { try { File.Delete("TiletypeList.csv"); } catch (IOException) { return; } using (StreamWriter writer = new StreamWriter("TiletypeList.csv")) { foreach (Tiletype item in DFConnection.Instance.NetTiletypeList.tiletype_list) { writer.WriteLine( item.name + ";" + item.shape + ":" + item.special + ":" + item.material + ":" + item.variant + ":" + item.direction ); } } } void SaveBuildingList() { try { File.Delete("BuildingList.csv"); } catch (IOException) { return; } using (StreamWriter writer = new StreamWriter("BuildingList.csv")) { foreach (var item in DFConnection.Instance.NetBuildingList.building_list) { writer.WriteLine( item.name + ";" + item.id + ";" + item.building_type.building_type + ":" + item.building_type.building_subtype + ":" + item.building_type.building_custom ); } } } void SaveMaterialList(List<MaterialDefinition> list, string filename) { try { File.Delete(filename); } catch (IOException) { return; } using (StreamWriter writer = new StreamWriter(filename)) { foreach (var item in list) { writer.WriteLine( item.name + ";" + item.id + ";" + item.mat_pair.mat_type + ";" + item.mat_pair.mat_index ); } } } // Have the mesher mesh all dirty tiles in the region void EnqueueMeshUpdates() { for (int zz = DFConnection.Instance.RequestRegionMin.z; zz < DFConnection.Instance.RequestRegionMax.z; zz++) for (int yy = DFConnection.Instance.RequestRegionMin.y; yy <= DFConnection.Instance.RequestRegionMax.y; yy++) for (int xx = DFConnection.Instance.RequestRegionMin.x; xx <= DFConnection.Instance.RequestRegionMax.x; xx++) { if (xx < 0 || yy < 0 || zz < 0 || xx >= blocks.GetLength(0) || yy >= blocks.GetLength(1) || zz >= blocks.GetLength(2)) { continue; } if (!blockDirtyBits[xx, yy, zz] && !liquidBlockDirtyBits[xx, yy, zz]) { continue; } mesher.Enqueue(new DFCoord(xx * 16, yy * 16, zz), blockDirtyBits[xx, yy, zz], liquidBlockDirtyBits[xx, yy, zz]); blockDirtyBits[xx, yy, zz] = false; liquidBlockDirtyBits[xx, yy, zz] = false; } } // Get new meshes from the mesher void FetchNewMeshes() { while (mesher.HasNewMeshes) { var newMeshes = mesher.Dequeue().Value; int block_x = newMeshes.location.x / blockSize; int block_y = newMeshes.location.y / blockSize; int block_z = newMeshes.location.z; if (newMeshes.tiles != null) { if (blocks[block_x, block_y, block_z] == null) { blocks[block_x, block_y, block_z] = new Mesh(); } Mesh tileMesh = blocks[block_x, block_y, block_z]; tileMesh.Clear(); newMeshes.tiles.CopyToMesh(tileMesh); } if (newMeshes.stencilTiles != null) { if (stencilBlocks[block_x, block_y, block_z] == null) { stencilBlocks[block_x, block_y, block_z] = new Mesh(); } Mesh stencilMesh = stencilBlocks[block_x, block_y, block_z]; stencilMesh.Clear(); newMeshes.stencilTiles.CopyToMesh(stencilMesh); } if (newMeshes.water != null) { if (liquidBlocks[block_x, block_y, block_z, MapDataStore.WATER_INDEX] == null) { liquidBlocks[block_x, block_y, block_z, MapDataStore.WATER_INDEX] = new Mesh(); } Mesh waterMesh = liquidBlocks[block_x, block_y, block_z, MapDataStore.WATER_INDEX]; waterMesh.Clear(); newMeshes.water.CopyToMesh(waterMesh); } if (newMeshes.magma != null) { if (liquidBlocks[block_x, block_y, block_z, MapDataStore.MAGMA_INDEX] == null) { liquidBlocks[block_x, block_y, block_z, MapDataStore.MAGMA_INDEX] = new Mesh(); } Mesh magmaMesh = liquidBlocks[block_x, block_y, block_z, MapDataStore.MAGMA_INDEX]; magmaMesh.Clear(); newMeshes.magma.CopyToMesh(magmaMesh); } } } System.Diagnostics.Stopwatch loadWatch = new System.Diagnostics.Stopwatch(); System.Diagnostics.Stopwatch genWatch = new System.Diagnostics.Stopwatch(); void ClearMap() { foreach (var item in blocks) { if (item != null) item.Clear(); } foreach (var item in stencilBlocks) { if (item != null) item.Clear(); } foreach (var item in liquidBlocks) { if (item != null) item.Clear(); } foreach (var item in magmaGlow) { Destroy(item); } MapDataStore.Main.Reset(); } void ShowCursorInfo() { cursorProperties.text = ""; cursorProperties.text += "Cursor: "; cursorProperties.text += cursX + ","; cursorProperties.text += cursY + ","; cursorProperties.text += cursZ + "\n"; var maybeTile = MapDataStore.Main[cursX, cursY, cursZ]; if (maybeTile != null) { var tile = maybeTile.Value; cursorProperties.text += "Tiletype:\n"; var tiletype = DFConnection.Instance.NetTiletypeList.tiletype_list [tile.tileType]; cursorProperties.text += tiletype.name + "\n"; cursorProperties.text += tiletype.shape + ":" + tiletype.special + ":" + tiletype.material + ":" + tiletype.variant + ":" + tiletype.direction + "\n"; var mat = tile.material; cursorProperties.text += "Material: "; cursorProperties.text += mat.mat_type + ","; cursorProperties.text += mat.mat_index + "\n"; if (materials.ContainsKey(mat)) { cursorProperties.text += "Material Name: "; cursorProperties.text += materials[mat].id + "\n"; } else cursorProperties.text += "Unknown Material\n"; cursorProperties.text += "\n"; var basemat = tile.base_material; cursorProperties.text += "Base Material: "; cursorProperties.text += basemat.mat_type + ","; cursorProperties.text += basemat.mat_index + "\n"; if (materials.ContainsKey(basemat)) { cursorProperties.text += "Base Material Name: "; cursorProperties.text += materials[basemat].id + "\n"; } else cursorProperties.text += "Unknown Base Material\n"; cursorProperties.text += "\n"; var layermat = tile.layer_material; cursorProperties.text += "Layer Material: "; cursorProperties.text += layermat.mat_type + ","; cursorProperties.text += layermat.mat_index + "\n"; if (materials.ContainsKey(layermat)) { cursorProperties.text += "Layer Material Name: "; cursorProperties.text += materials[layermat].id + "\n"; } else cursorProperties.text += "Unknown Layer Material\n"; cursorProperties.text += "\n"; var veinmat = tile.vein_material; cursorProperties.text += "Vein Material: "; cursorProperties.text += veinmat.mat_type + ","; cursorProperties.text += veinmat.mat_index + "\n"; if (materials.ContainsKey(veinmat)) { cursorProperties.text += "Vein Material Name: "; cursorProperties.text += materials[veinmat].id + "\n"; } else cursorProperties.text += "Unknown Vein Material\n"; cursorProperties.text += "\n"; var cons = tile.construction_item; cursorProperties.text += "Construction Item: "; cursorProperties.text += cons.mat_type + ","; cursorProperties.text += cons.mat_index + "\n"; if (materials.ContainsKey(cons)) { cursorProperties.text += "Construction Item Name: "; cursorProperties.text += items[cons].id + "\n"; } else cursorProperties.text += "Unknown Construction Item\n"; } if (unitList != null) foreach (UnitDefinition unit in unitList.creature_list) { UnitFlags1 flags1 = (UnitFlags1)unit.flags1; UnitFlags2 flags2 = (UnitFlags2)unit.flags2; UnitFlags3 flags3 = (UnitFlags3)unit.flags3; if (((flags1 & UnitFlags1.dead) == UnitFlags1.dead) || ((flags1 & UnitFlags1.left) == UnitFlags1.left)) continue; if (unit.pos_x != cursX || unit.pos_y != cursY || unit.pos_z != cursZ) continue; CreatureRaw creatureRaw = null; if (DFConnection.Instance.NetCreatureRawList != null) creatureRaw = DFConnection.Instance.NetCreatureRawList.creature_raws[unit.race.mat_type]; if (creatureRaw != null) { cursorProperties.text += "Unit: \n"; cursorProperties.text += "Race: "; cursorProperties.text += creatureRaw.creature_id + ":"; cursorProperties.text += creatureRaw.caste[unit.race.mat_index].caste_id; cursorProperties.text += "\n"; cursorProperties.text += flags1 + "\n"; cursorProperties.text += flags2 + "\n"; cursorProperties.text += flags3 + "\n"; } break; } } Dictionary<int, AtlasSprite> creatureList; public AtlasSprite creatureTemplate; RemoteFortressReader.UnitList unitList = null; void UpdateCreatures() { unitList = DFConnection.Instance.PopUnitListUpdate(); if (unitList == null) return; foreach (var unit in unitList.creature_list) { if (creatureList == null) creatureList = new Dictionary<int, AtlasSprite>(); UnitFlags1 flags1 = (UnitFlags1)unit.flags1; //UnitFlags2 flags2 = (UnitFlags2)unit.flags2; //UnitFlags3 flags3 = (UnitFlags3)unit.flags3; if (((flags1 & UnitFlags1.dead) == UnitFlags1.dead) || ((flags1 & UnitFlags1.left) == UnitFlags1.left)) { if (creatureList.ContainsKey(unit.id)) { Destroy(creatureList[unit.id]); creatureList.Remove(unit.id); } } else { CreatureRaw creatureRaw = null; if (DFConnection.Instance.NetCreatureRawList != null) creatureRaw = DFConnection.Instance.NetCreatureRawList.creature_raws[unit.race.mat_type]; if (!creatureList.ContainsKey(unit.id)) { creatureList[unit.id] = Instantiate(creatureTemplate); creatureList[unit.id].transform.parent = gameObject.transform; creatureList[unit.id].ClearMesh(); Color color = new Color(unit.profession_color.red / 255.0f, unit.profession_color.green / 255.0f, unit.profession_color.blue / 255.0f, 1); if (creatureRaw != null) creatureList[unit.id].AddTile(creatureRaw.creature_tile, color); } creatureList[unit.id].gameObject.SetActive(unit.pos_z < PosZ && unit.pos_z > (PosZ - cameraViewDist)); if (creatureList[unit.id].gameObject.activeSelf) //Only update stuff if it's actually visible. { Vector3 position = DFtoUnityCoord(unit.pos_x, unit.pos_y, unit.pos_z); if((flags1 & UnitFlags1.on_ground) == UnitFlags1.on_ground) { creatureList[unit.id].transform.position = position + new Vector3(0, 0.51f, 0); creatureList[unit.id].cameraFacing.enabled = false; creatureList[unit.id].transform.rotation = Quaternion.Euler(90, 0, 0); } else { creatureList[unit.id].transform.position = position + new Vector3(0, 1.5f, 0); creatureList[unit.id].cameraFacing.enabled = true; } creatureList[unit.id].SetColor(0, new Color(unit.profession_color.red / 255.0f, unit.profession_color.green / 255.0f, unit.profession_color.blue / 255.0f, 1)); if (creatureRaw != null) { if (unit.is_soldier) creatureList[unit.id].SetTile(0, creatureRaw.creature_soldier_tile); else creatureList[unit.id].SetTile(0, creatureRaw.creature_tile); } } } } } public void UpdateCenter(Vector3 pos) { DFCoord dfPos = UnityToDFCoord(pos); posXTile = dfPos.x; posYTile = dfPos.y; if(posZ != dfPos.z+1) { posZ = dfPos.z+1; } } private void DrawBlocks() { for (int z = posZ - cameraViewDist; z < posZ; z++) { if (z < 0) z = 0; if (z >= blocks.GetLength(2)) continue; for (int x = 0; x < blocks.GetLength(0); x++) for (int y = 0; y < blocks.GetLength(1); y++) { if (blocks[x, y, z] != null && blocks[x, y, z].vertexCount > 0) Graphics.DrawMesh(blocks[x, y, z], Vector3.zero, Quaternion.identity, basicTerrainMaterial, 0, null, 0, null, ShadowCastingMode.On, true, transform); if (stencilBlocks[x, y, z] != null && stencilBlocks[x, y, z].vertexCount > 0) Graphics.DrawMesh(stencilBlocks[x, y, z], Vector3.zero, Quaternion.identity, stencilTerrainMaterial, 1, null, 0, null, ShadowCastingMode.On, true, transform); if (liquidBlocks[x, y, z, MapDataStore.WATER_INDEX] != null && liquidBlocks[x, y, z, MapDataStore.WATER_INDEX].vertexCount > 0) Graphics.DrawMesh(liquidBlocks[x, y, z, MapDataStore.WATER_INDEX], Vector3.zero, Quaternion.identity, waterMaterial, 4, null, 0, null, ShadowCastingMode.On, true, transform); if (liquidBlocks[x, y, z, MapDataStore.MAGMA_INDEX] != null && liquidBlocks[x, y, z, MapDataStore.MAGMA_INDEX].vertexCount > 0) Graphics.DrawMesh(liquidBlocks[x, y, z, MapDataStore.MAGMA_INDEX], Vector3.zero, Quaternion.identity, magmaMaterial, 4, null, 0, null, ShadowCastingMode.On, true, transform); } } for (int z = posZ; z <= posZ + cameraViewDist; z++) { if (z < 0) z = 0; if (z >= blocks.GetLength(2)) continue; for (int x = 0; x < blocks.GetLength(0); x++) for (int y = 0; y < blocks.GetLength(1); y++) { if (blocks[x, y, z] != null && blocks[x, y, z].vertexCount > 0 && BasicTopMaterial != null) Graphics.DrawMesh(blocks[x, y, z], Vector3.zero, Quaternion.identity, BasicTopMaterial, 0, null, 0, null, ShadowCastingMode.On, true, transform); if (stencilBlocks[x, y, z] != null && stencilBlocks[x, y, z].vertexCount > 0 && StencilTopMaterial != null) Graphics.DrawMesh(stencilBlocks[x, y, z], Vector3.zero, Quaternion.identity, StencilTopMaterial, 1, null, 0, null, ShadowCastingMode.On, true, transform); //if (liquidBlocks[x, y, z, MapDataStore.WATER_INDEX] != null && liquidBlocks[x, y, z, MapDataStore.WATER_INDEX].vertexCount > 0) // Graphics.DrawMesh(liquidBlocks[x, y, z, MapDataStore.WATER_INDEX], Matrix4x4.identity, waterMaterial, 4); //if (liquidBlocks[x, y, z, MapDataStore.MAGMA_INDEX] != null && liquidBlocks[x, y, z, MapDataStore.MAGMA_INDEX].vertexCount > 0) // Graphics.DrawMesh(liquidBlocks[x, y, z, MapDataStore.MAGMA_INDEX], Matrix4x4.identity, magmaMaterial, 4); } } } }
using Prism.Events; using System; using System.Collections.Generic; using System.Linq; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace Prism.Windows.Navigation { /// <summary> /// Abstracts the <see cref="Frame"/> object for use by apps that derive from the <see cref="PrismApplication"/> class. /// </summary> public class FrameFacadeAdapter : IFrameFacade { private readonly Frame _frame; private readonly NavigationStateChangedEvent _navigationStateChangedEvent; private readonly List<EventHandler<NavigatedToEventArgs>> _navigatedToEventHandlers = new List<EventHandler<NavigatedToEventArgs>>(); private readonly List<EventHandler<NavigatingFromEventArgs>> _navigatingFromEventHandlers = new List<EventHandler<NavigatingFromEventArgs>>(); /// <summary> /// Initializes a new instance of the <see cref="FrameFacadeAdapter"/> class. /// </summary> /// <param name="frame">The <see cref="Frame"/> that will be wrapped.</param> /// <param name="eventAggregator">The event aggregator to be used for publishing a <see cref="NavigationStateChangedEvent"/>. Can be null if events aren't needed.</param> public FrameFacadeAdapter(Frame frame, IEventAggregator eventAggregator = null) { if (eventAggregator != null) { _navigationStateChangedEvent = eventAggregator.GetEvent<NavigationStateChangedEvent>(); } _frame = frame; } /// <summary> /// Gets or sets the content of a ContentControl. /// </summary> /// /// <returns> /// An object that contains the control's content. The default is null. /// </returns> public object Content { get => _frame.Content; set => _frame.Content = value; } /// <summary> /// Navigates to the most recent item in back navigation history, if a Frame manages its own navigation history. /// </summary> public void GoBack() { _frame.GoBack(); _navigationStateChangedEvent?.Publish(new NavigationStateChangedEventArgs(this, StateChangeType.Back)); } /// <returns> /// The string-form serialized navigation history. See Remarks. /// </returns> public string GetNavigationState() { var navigationState = _frame.GetNavigationState(); return navigationState; } /// <summary> /// Reads and restores the navigation history of a Frame from a provided serialization string. /// </summary> /// <param name="navigationState">The serialization string that supplies the restore point for navigation history.</param> public void SetNavigationState(string navigationState) { _frame.SetNavigationState(navigationState); _navigationStateChangedEvent?.Publish(new NavigationStateChangedEventArgs(this, StateChangeType.Set)); } /// <summary> /// Navigates to a page of the requested type. /// </summary> /// <param name="sourcePageType">The type of the page that will be navigated to.</param> /// <param name="parameter">The page's navigation parameter.</param> /// /// <returns>True if navigation was successful; false otherwise.</returns> public bool Navigate(Type sourcePageType, object parameter) { try { var success = _frame.Navigate(sourcePageType, parameter); if (success) { _navigationStateChangedEvent?.Publish(new NavigationStateChangedEventArgs(this, StateChangeType.Forward)); } return success; } catch { return false; } } /// <summary> /// Gets the number of entries in the navigation back stack. /// </summary> /// /// <returns> /// The number of entries in the navigation back stack. /// </returns> public int BackStackDepth { get { return _frame.BackStackDepth; } } public IReadOnlyList<PageStackEntry> BackStack => _frame.BackStack.ToList(); /// <summary> /// Gets a value that indicates whether there is at least one entry in back navigation history. /// </summary> /// /// <returns> /// True if there is at least one entry in back navigation history; false if there are no entries in back navigation history or the Frame does not own its own navigation history. /// </returns> public bool CanGoBack { get { return _frame.CanGoBack; } } /// <summary> /// Goes to the next page in the navigation stack. /// </summary> public void GoForward() { _frame.GoForward(); _navigationStateChangedEvent?.Publish(new NavigationStateChangedEventArgs(this, StateChangeType.Forward)); } /// <summary> /// Determines whether the navigation service can navigate to the next page or not. /// </summary> /// <returns> /// <c>true</c> if the navigation service can go forward; otherwise, <c>false</c>. /// </returns> public bool CanGoForward() { return _frame.CanGoForward; } /// <summary> /// Remove a <see cref="PageStackEntry"/> from the Frame's back stack. /// </summary> /// <param name="entry">The <see cref="PageStackEntry"/> to remove.</param> /// <returns>True if item was successfully removed from the back stack; otherwise, false. This method also returns false if item is not found in the back stack.</returns> public bool RemoveBackStackEntry(PageStackEntry entry) { var success = _frame.BackStack.Remove(entry); if (success) { _navigationStateChangedEvent?.Publish(new NavigationStateChangedEventArgs(this, StateChangeType.Remove)); } return success; } /// <summary> /// Clears the Frame's back stack. /// </summary> /// <returns></returns> public void ClearBackStack() { _frame.BackStack.Clear(); _navigationStateChangedEvent?.Publish(new NavigationStateChangedEventArgs(this, StateChangeType.Clear)); } /// <summary> /// Occurs when the content that is being navigated to has been found and is available from the Content property, although it may not have completed loading. /// </summary> public event EventHandler<NavigatedToEventArgs> NavigatedTo { add { if (_navigatedToEventHandlers.Contains(value)) return; _navigatedToEventHandlers.Add(value); if (_navigatedToEventHandlers.Count == 1) { _frame.Navigated += OnFrameNavigatedTo; } } remove { if (!_navigatedToEventHandlers.Contains(value)) return; _navigatedToEventHandlers.Remove(value); if (_navigatedToEventHandlers.Count == 0) { _frame.Navigated -= OnFrameNavigatedTo; } } } /// <summary> /// Occurs when a new navigation is requested. /// </summary> public event EventHandler<NavigatingFromEventArgs> NavigatingFrom { add { if (_navigatingFromEventHandlers.Contains(value)) return; _navigatingFromEventHandlers.Add(value); if (_navigatingFromEventHandlers.Count == 1) { _frame.Navigating += OnFrameNavigatingFrom; } } remove { if (!_navigatingFromEventHandlers.Contains(value)) return; _navigatingFromEventHandlers.Remove(value); if (_navigatingFromEventHandlers.Count == 0) { _frame.Navigating -= OnFrameNavigatingFrom; } } } /// <summary> /// Returns the current effective value of a dependency property from a <see cref="DependencyObject"/>. /// </summary> /// /// <returns> /// Returns the current effective value. /// </returns> /// <param name="dependencyProperty">The <see cref="DependencyProperty"/> identifier of the property for which to retrieve the value.</param> public object GetValue(DependencyProperty dependencyProperty) { return _frame.GetValue(dependencyProperty); } /// <summary> /// Sets the local value of a dependency property on a <see cref="DependencyObject"/>. /// </summary> /// <param name="dependencyProperty">The identifier of the dependency property to set.</param><param name="value">The new local value.</param> public void SetValue(DependencyProperty dependencyProperty, object value) { _frame.SetValue(dependencyProperty, value); } /// <summary> /// Clears the local value of a dependency property. /// </summary> /// <param name="dependencyProperty">The <see cref="DependencyProperty"/> identifier of the property for which to clear the value.</param> public void ClearValue(DependencyProperty dependencyProperty) { _frame.ClearValue(dependencyProperty); } private void OnFrameNavigatedTo(object sender, NavigationEventArgs e) { if (_navigatedToEventHandlers.Count > 0) { var args = new NavigatedToEventArgs(e); foreach (var handler in _navigatedToEventHandlers) handler(this, args); } } private void OnFrameNavigatingFrom(object sender, NavigatingCancelEventArgs e) { if (_navigatingFromEventHandlers.Count > 0) { var args = new NavigatingFromEventArgs(e); foreach (var handler in _navigatingFromEventHandlers) handler(this, args); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.Mail; using Umbraco.Cms.Core.Mapping; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.ContentEditing; using Umbraco.Cms.Core.Models.Email; using Umbraco.Cms.Core.Models.Membership; using Umbraco.Cms.Core.Net; using Umbraco.Cms.Core.Security; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Web.BackOffice.Filters; using Umbraco.Cms.Web.BackOffice.Security; using Umbraco.Cms.Web.Common.ActionsResults; using Umbraco.Cms.Web.Common.Attributes; using Umbraco.Cms.Web.Common.Authorization; using Umbraco.Cms.Web.Common.Controllers; using Umbraco.Cms.Web.Common.Filters; using Umbraco.Cms.Web.Common.Models; using Umbraco.Extensions; using Constants = Umbraco.Cms.Core.Constants; using SignInResult = Microsoft.AspNetCore.Identity.SignInResult; namespace Umbraco.Cms.Web.BackOffice.Controllers { // See // for a bigger example of this type of controller implementation in netcore: // https://github.com/dotnet/AspNetCore.Docs/blob/2efb4554f8f659be97ee7cd5dd6143b871b330a5/aspnetcore/migration/1x-to-2x/samples/AspNetCoreDotNetCore2App/AspNetCoreDotNetCore2App/Controllers/AccountController.cs // https://github.com/dotnet/AspNetCore.Docs/blob/ad16f5e1da6c04fa4996ee67b513f2a90fa0d712/aspnetcore/common/samples/WebApplication1/Controllers/AccountController.cs // with authenticator app // https://github.com/dotnet/AspNetCore.Docs/blob/master/aspnetcore/security/authentication/identity/sample/src/ASPNETCore-IdentityDemoComplete/IdentityDemo/Controllers/AccountController.cs [PluginController(Constants.Web.Mvc.BackOfficeApiArea)] // TODO: Maybe this could be applied with our Application Model conventions //[ValidationFilter] // TODO: I don't actually think this is required with our custom Application Model conventions applied [AngularJsonOnlyConfiguration] // TODO: This could be applied with our Application Model conventions [IsBackOffice] [DisableBrowserCache] public class AuthenticationController : UmbracoApiControllerBase { // NOTE: Each action must either be explicitly authorized or explicitly [AllowAnonymous], the latter is optional because // this controller itself doesn't require authz but it's more clear what the intention is. private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IBackOfficeUserManager _userManager; private readonly IBackOfficeSignInManager _signInManager; private readonly IUserService _userService; private readonly ILocalizedTextService _textService; private readonly IUmbracoMapper _umbracoMapper; private readonly GlobalSettings _globalSettings; private readonly SecuritySettings _securitySettings; private readonly ILogger<AuthenticationController> _logger; private readonly IIpResolver _ipResolver; private readonly UserPasswordConfigurationSettings _passwordConfiguration; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly IHostingEnvironment _hostingEnvironment; private readonly LinkGenerator _linkGenerator; private readonly IBackOfficeExternalLoginProviders _externalAuthenticationOptions; private readonly IBackOfficeTwoFactorOptions _backOfficeTwoFactorOptions; // TODO: We need to review all _userManager.Raise calls since many/most should be on the usermanager or signinmanager, very few should be here public AuthenticationController( IBackOfficeSecurityAccessor backofficeSecurityAccessor, IBackOfficeUserManager backOfficeUserManager, IBackOfficeSignInManager signInManager, IUserService userService, ILocalizedTextService textService, IUmbracoMapper umbracoMapper, IOptions<GlobalSettings> globalSettings, IOptions<SecuritySettings> securitySettings, ILogger<AuthenticationController> logger, IIpResolver ipResolver, IOptions<UserPasswordConfigurationSettings> passwordConfiguration, IEmailSender emailSender, ISmsSender smsSender, IHostingEnvironment hostingEnvironment, LinkGenerator linkGenerator, IBackOfficeExternalLoginProviders externalAuthenticationOptions, IBackOfficeTwoFactorOptions backOfficeTwoFactorOptions) { _backofficeSecurityAccessor = backofficeSecurityAccessor; _userManager = backOfficeUserManager; _signInManager = signInManager; _userService = userService; _textService = textService; _umbracoMapper = umbracoMapper; _globalSettings = globalSettings.Value; _securitySettings = securitySettings.Value; _logger = logger; _ipResolver = ipResolver; _passwordConfiguration = passwordConfiguration.Value; _emailSender = emailSender; _smsSender = smsSender; _hostingEnvironment = hostingEnvironment; _linkGenerator = linkGenerator; _externalAuthenticationOptions = externalAuthenticationOptions; _backOfficeTwoFactorOptions = backOfficeTwoFactorOptions; } /// <summary> /// Returns the configuration for the backoffice user membership provider - used to configure the change password dialog /// </summary> [AllowAnonymous] // Needed for users that are invited when they use the link from the mail they are not authorized [Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)] // Needed to enforce the principle set on the request, if one exists. public IDictionary<string, object> GetPasswordConfig(int userId) { Attempt<int> currentUserId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId(); return _passwordConfiguration.GetConfiguration( currentUserId.Success ? currentUserId.Result != userId : true); } /// <summary> /// Checks if a valid token is specified for an invited user and if so logs the user in and returns the user object /// </summary> /// <param name="id"></param> /// <param name="token"></param> /// <returns></returns> /// <remarks> /// This will also update the security stamp for the user so it can only be used once /// </remarks> [ValidateAngularAntiForgeryToken] [Authorize(Policy = AuthorizationPolicies.DenyLocalLoginIfConfigured)] public async Task<ActionResult<UserDisplay>> PostVerifyInvite([FromQuery] int id, [FromQuery] string token) { if (string.IsNullOrWhiteSpace(token)) return NotFound(); var decoded = token.FromUrlBase64(); if (decoded.IsNullOrWhiteSpace()) return NotFound(); var identityUser = await _userManager.FindByIdAsync(id.ToString()); if (identityUser == null) return NotFound(); var result = await _userManager.ConfirmEmailAsync(identityUser, decoded); if (result.Succeeded == false) { return ValidationErrorResult.CreateNotificationValidationErrorResult(result.Errors.ToErrorMessage()); } await _signInManager.SignOutAsync(); await _signInManager.SignInAsync(identityUser, false); var user = _userService.GetUserById(id); return _umbracoMapper.Map<UserDisplay>(user); } [Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)] [ValidateAngularAntiForgeryToken] public async Task<IActionResult> PostUnLinkLogin(UnLinkLoginModel unlinkLoginModel) { var user = await _userManager.FindByIdAsync(User.Identity.GetUserId()); if (user == null) throw new InvalidOperationException("Could not find user"); var authType = (await _signInManager.GetExternalAuthenticationSchemesAsync()) .FirstOrDefault(x => x.Name == unlinkLoginModel.LoginProvider); if (authType == null) { _logger.LogWarning("Could not find external authentication provider registered: {LoginProvider}", unlinkLoginModel.LoginProvider); } else { BackOfficeExternaLoginProviderScheme opt = await _externalAuthenticationOptions.GetAsync(authType.Name); if (opt == null) { return BadRequest($"Could not find external authentication options registered for provider {unlinkLoginModel.LoginProvider}"); } else { if (!opt.ExternalLoginProvider.Options.AutoLinkOptions.AllowManualLinking) { // If AllowManualLinking is disabled for this provider we cannot unlink return BadRequest(); } } } var result = await _userManager.RemoveLoginAsync( user, unlinkLoginModel.LoginProvider, unlinkLoginModel.ProviderKey); if (result.Succeeded) { await _signInManager.SignInAsync(user, true); return Ok(); } else { AddModelErrors(result); return new ValidationErrorResult(ModelState); } } [HttpGet] [AllowAnonymous] public async Task<double> GetRemainingTimeoutSeconds() { // force authentication to occur since this is not an authorized endpoint var result = await this.AuthenticateBackOfficeAsync(); if (!result.Succeeded) { return 0; } var remainingSeconds = result.Principal.GetRemainingAuthSeconds(); if (remainingSeconds <= 30) { var username = result.Principal.FindFirst(ClaimTypes.Name)?.Value; //NOTE: We are using 30 seconds because that is what is coded into angular to force logout to give some headway in // the timeout process. _logger.LogInformation( "User logged will be logged out due to timeout: {Username}, IP Address: {IPAddress}", username ?? "unknown", _ipResolver.GetCurrentRequestIpAddress()); } return remainingSeconds; } /// <summary> /// Checks if the current user's cookie is valid and if so returns OK or a 400 (BadRequest) /// </summary> /// <returns></returns> [HttpGet] [AllowAnonymous] public async Task<bool> IsAuthenticated() { // force authentication to occur since this is not an authorized endpoint var result = await this.AuthenticateBackOfficeAsync(); return result.Succeeded; } /// <summary> /// Returns the currently logged in Umbraco user /// </summary> /// <returns></returns> /// <remarks> /// We have the attribute [SetAngularAntiForgeryTokens] applied because this method is called initially to determine if the user /// is valid before the login screen is displayed. The Auth cookie can be persisted for up to a day but the csrf cookies are only session /// cookies which means that the auth cookie could be valid but the csrf cookies are no longer there, in that case we need to re-set the csrf cookies. /// </remarks> [Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)] [SetAngularAntiForgeryTokens] [CheckIfUserTicketDataIsStale] public UserDetail GetCurrentUser() { var user = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; var result = _umbracoMapper.Map<UserDetail>(user); //set their remaining seconds result.SecondsUntilTimeout = HttpContext.User.GetRemainingAuthSeconds(); return result; } /// <summary> /// When a user is invited they are not approved but we need to resolve the partially logged on (non approved) /// user. /// </summary> /// <returns></returns> /// <remarks> /// We cannot user GetCurrentUser since that requires they are approved, this is the same as GetCurrentUser but doesn't require them to be approved /// </remarks> [Authorize(Policy = AuthorizationPolicies.BackOfficeAccessWithoutApproval)] [SetAngularAntiForgeryTokens] [Authorize(Policy = AuthorizationPolicies.DenyLocalLoginIfConfigured)] public ActionResult<UserDetail> GetCurrentInvitedUser() { var user = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; if (user.IsApproved) { // if they are approved, than they are no longer invited and we can return an error return Forbid(); } var result = _umbracoMapper.Map<UserDetail>(user); // set their remaining seconds result.SecondsUntilTimeout = HttpContext.User.GetRemainingAuthSeconds(); return result; } /// <summary> /// Logs a user in /// </summary> /// <returns></returns> [SetAngularAntiForgeryTokens] [Authorize(Policy = AuthorizationPolicies.DenyLocalLoginIfConfigured)] public async Task<ActionResult<UserDetail>> PostLogin(LoginModel loginModel) { // Sign the user in with username/password, this also gives a chance for developers to // custom verify the credentials and auto-link user accounts with a custom IBackOfficePasswordChecker SignInResult result = await _signInManager.PasswordSignInAsync( loginModel.Username, loginModel.Password, isPersistent: true, lockoutOnFailure: true); if (result.Succeeded) { // return the user detail return GetUserDetail(_userService.GetByUsername(loginModel.Username)); } if (result.RequiresTwoFactor) { var twofactorView = _backOfficeTwoFactorOptions.GetTwoFactorView(loginModel.Username); if (twofactorView.IsNullOrWhiteSpace()) { return new ValidationErrorResult($"The registered {typeof(IBackOfficeTwoFactorOptions)} of type {_backOfficeTwoFactorOptions.GetType()} did not return a view for two factor auth "); } IUser attemptedUser = _userService.GetByUsername(loginModel.Username); // create a with information to display a custom two factor send code view var verifyResponse = new ObjectResult(new { twoFactorView = twofactorView, userId = attemptedUser.Id }) { StatusCode = StatusCodes.Status402PaymentRequired }; return verifyResponse; } // TODO: We can check for these and respond differently if we think it's important // result.IsLockedOut // result.IsNotAllowed // return BadRequest (400), we don't want to return a 401 because that get's intercepted // by our angular helper because it thinks that we need to re-perform the request once we are // authorized and we don't want to return a 403 because angular will show a warning message indicating // that the user doesn't have access to perform this function, we just want to return a normal invalid message. return BadRequest(); } /// <summary> /// Processes a password reset request. Looks for a match on the provided email address /// and if found sends an email with a link to reset it /// </summary> /// <returns></returns> [SetAngularAntiForgeryTokens] [Authorize(Policy = AuthorizationPolicies.DenyLocalLoginIfConfigured)] public async Task<IActionResult> PostRequestPasswordReset(RequestPasswordResetModel model) { // If this feature is switched off in configuration the UI will be amended to not make the request to reset password available. // So this is just a server-side secondary check. if (_securitySettings.AllowPasswordReset == false) return BadRequest(); var identityUser = await _userManager.FindByEmailAsync(model.Email); if (identityUser != null) { var user = _userService.GetByEmail(model.Email); if (user != null) { var from = _globalSettings.Smtp.From; var code = await _userManager.GeneratePasswordResetTokenAsync(identityUser); var callbackUrl = ConstructCallbackUrl(identityUser.Id, code); var message = _textService.Localize("login","resetPasswordEmailCopyFormat", // Ensure the culture of the found user is used for the email! UmbracoUserExtensions.GetUserCulture(identityUser.Culture, _textService, _globalSettings), new[] { identityUser.UserName, callbackUrl }); var subject = _textService.Localize("login","resetPasswordEmailCopySubject", // Ensure the culture of the found user is used for the email! UmbracoUserExtensions.GetUserCulture(identityUser.Culture, _textService, _globalSettings)); var mailMessage = new EmailMessage(from, user.Email, subject, message, true); await _emailSender.SendAsync(mailMessage, Constants.Web.EmailTypes.PasswordReset); _userManager.NotifyForgotPasswordRequested(User, user.Id.ToString()); } } return Ok(); } /// <summary> /// Used to retrieve the 2FA providers for code submission /// </summary> /// <returns></returns> [SetAngularAntiForgeryTokens] [AllowAnonymous] public async Task<ActionResult<IEnumerable<string>>> Get2FAProviders() { var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { _logger.LogWarning("Get2FAProviders :: No verified user found, returning 404"); return NotFound(); } var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user); return new ObjectResult(userFactors); } [SetAngularAntiForgeryTokens] [AllowAnonymous] public async Task<IActionResult> PostSend2FACode([FromBody] string provider) { if (provider.IsNullOrWhiteSpace()) return NotFound(); var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { _logger.LogWarning("PostSend2FACode :: No verified user found, returning 404"); return NotFound(); } var from = _globalSettings.Smtp.From; // Generate the token and send it var code = await _userManager.GenerateTwoFactorTokenAsync(user, provider); if (string.IsNullOrWhiteSpace(code)) { _logger.LogWarning("PostSend2FACode :: Could not generate 2FA code"); return BadRequest("Invalid code"); } var subject = _textService.Localize("login","mfaSecurityCodeSubject", // Ensure the culture of the found user is used for the email! UmbracoUserExtensions.GetUserCulture(user.Culture, _textService, _globalSettings)); var message = _textService.Localize("login","mfaSecurityCodeMessage", // Ensure the culture of the found user is used for the email! UmbracoUserExtensions.GetUserCulture(user.Culture, _textService, _globalSettings), new[] { code }); if (provider == "Email") { var mailMessage = new EmailMessage(from, user.Email, subject, message, true); await _emailSender.SendAsync(mailMessage, Constants.Web.EmailTypes.TwoFactorAuth); } else if (provider == "Phone") { await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message); } return Ok(); } [SetAngularAntiForgeryTokens] [AllowAnonymous] public async Task<ActionResult<UserDetail>> PostVerify2FACode(Verify2FACodeModel model) { if (ModelState.IsValid == false) { return new ValidationErrorResult(ModelState); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { _logger.LogWarning("PostVerify2FACode :: No verified user found, returning 404"); return NotFound(); } var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.IsPersistent, model.RememberClient); if (result.Succeeded) { return GetUserDetail(_userService.GetByUsername(user.UserName)); } if (result.IsLockedOut) { return new ValidationErrorResult("User is locked out"); } if (result.IsNotAllowed) { return new ValidationErrorResult("User is not allowed"); } return new ValidationErrorResult("Invalid code"); } /// <summary> /// Processes a set password request. Validates the request and sets a new password. /// </summary> /// <returns></returns> [SetAngularAntiForgeryTokens] [AllowAnonymous] public async Task<IActionResult> PostSetPassword(SetPasswordModel model) { var identityUser = await _userManager.FindByIdAsync(model.UserId.ToString(CultureInfo.InvariantCulture)); var result = await _userManager.ResetPasswordAsync(identityUser, model.ResetCode, model.Password); if (result.Succeeded) { var lockedOut = await _userManager.IsLockedOutAsync(identityUser); if (lockedOut) { _logger.LogInformation("User {UserId} is currently locked out, unlocking and resetting AccessFailedCount", model.UserId); //// var user = await UserManager.FindByIdAsync(model.UserId); var unlockResult = await _userManager.SetLockoutEndDateAsync(identityUser, DateTimeOffset.Now); if (unlockResult.Succeeded == false) { _logger.LogWarning("Could not unlock for user {UserId} - error {UnlockError}", model.UserId, unlockResult.Errors.First().Description); } var resetAccessFailedCountResult = await _userManager.ResetAccessFailedCountAsync(identityUser); if (resetAccessFailedCountResult.Succeeded == false) { _logger.LogWarning("Could not reset access failed count {UserId} - error {UnlockError}", model.UserId, unlockResult.Errors.First().Description); } } // They've successfully set their password, we can now update their user account to be confirmed // if user was only invited, then they have not been approved // but a successful forgot password flow (e.g. if their token had expired and they did a forgot password instead of request new invite) // means we have verified their email if (!await _userManager.IsEmailConfirmedAsync(identityUser)) { await _userManager.ConfirmEmailAsync(identityUser, model.ResetCode); } // invited is not approved, never logged in, invited date present /* if (LastLoginDate == default && IsApproved == false && InvitedDate != null) return UserState.Invited; */ if (identityUser != null && !identityUser.IsApproved) { var user = _userService.GetByUsername(identityUser.UserName); // also check InvitedDate and never logged in, otherwise this would allow a disabled user to reactivate their account with a forgot password if (user.LastLoginDate == default && user.InvitedDate != null) { user.IsApproved = true; user.InvitedDate = null; _userService.Save(user); } } _userManager.NotifyForgotPasswordChanged(User, model.UserId.ToString(CultureInfo.InvariantCulture)); return Ok(); } return new ValidationErrorResult(result.Errors.Any() ? result.Errors.First().Description : "Set password failed"); } /// <summary> /// Logs the current user out /// </summary> /// <returns></returns> [ValidateAngularAntiForgeryToken] [AllowAnonymous] public async Task<IActionResult> PostLogout() { // force authentication to occur since this is not an authorized endpoint var result = await this.AuthenticateBackOfficeAsync(); if (!result.Succeeded) return Ok(); await _signInManager.SignOutAsync(); _logger.LogInformation("User {UserName} from IP address {RemoteIpAddress} has logged out", User.Identity == null ? "UNKNOWN" : User.Identity.Name, HttpContext.Connection.RemoteIpAddress); var userId = result.Principal.Identity.GetUserId(); var args = _userManager.NotifyLogoutSuccess(User, userId); if (!args.SignOutRedirectUrl.IsNullOrWhiteSpace()) { return new ObjectResult(new { signOutRedirectUrl = args.SignOutRedirectUrl }); } return Ok(); } /// <summary> /// Return the <see cref="UserDetail"/> for the given <see cref="IUser"/> /// </summary> /// <param name="user"></param> /// <param name="principal"></param> /// <returns></returns> private UserDetail GetUserDetail(IUser user) { if (user == null) throw new ArgumentNullException(nameof(user)); var userDetail = _umbracoMapper.Map<UserDetail>(user); // update the userDetail and set their remaining seconds userDetail.SecondsUntilTimeout = _globalSettings.TimeOut.TotalSeconds; return userDetail; } private string ConstructCallbackUrl(string userId, string code) { // Get an mvc helper to get the url var action = _linkGenerator.GetPathByAction( nameof(BackOfficeController.ValidatePasswordResetCode), ControllerExtensions.GetControllerName<BackOfficeController>(), new { area = Constants.Web.Mvc.BackOfficeArea, u = userId, r = code }); // Construct full URL using configured application URL (which will fall back to request) var applicationUri = _hostingEnvironment.ApplicationMainUrl; var callbackUri = new Uri(applicationUri, action); return callbackUri.ToString(); } private void AddModelErrors(IdentityResult result, string prefix = "") { foreach (var error in result.Errors) { ModelState.AddModelError(prefix, error.Description); } } } }
#region License // // ElementListLabel.cs July 2006 // // Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net> // // 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 #region Using directives using SimpleFramework.Xml.Strategy; using SimpleFramework.Xml.Stream; using SimpleFramework.Xml; using System; #endregion namespace SimpleFramework.Xml.Core { /// <summary> /// The <c>ElementListLabel</c> represents a label that is used /// to represent an XML element list in a class schema. This element /// list label can be used to convert an XML node into a collection of /// composite objects. Each element converted with the converter this /// creates must be an XML serializable element. /// </summary> /// <seealso> /// SimpleFramework.Xml.ElementList /// </seealso> class ElementListLabel : Label { /// <summary> /// This is the decorator that is associated with the element. /// </summary> private Decorator decorator; /// <summary> /// This references the annotation that the field uses. /// </summary> private ElementList label; /// <summary> /// This contains the details of the annotated contact object. /// </summary> private Signature detail; /// <summary> /// This is the type of collection this list will instantiate. /// </summary> private Class type; /// <summary> /// Represents the type of objects this list will hold. /// </summary> private Class item; /// <summary> /// This is the name of the XML entry from the annotation. /// </summary> private String entry; /// <summary> /// This is the name of the element for this label instance. /// </summary> private String name; /// <summary> /// Constructor for the <c>ElementListLabel</c> object. This /// creates a label object, which can be used to convert an XML /// node to a <c>Collection</c> of XML serializable objects. /// </summary> /// <param name="contact"> /// this is the contact that this label represents /// </param> /// <param name="label"> /// the annotation that contains the schema details /// </param> public ElementListLabel(Contact contact, ElementList label) { this.detail = new Signature(contact, this); this.decorator = new Qualifier(contact); this.type = contact.Type; this.entry = label.entry(); this.item = label.type(); this.name = label.name(); this.label = label; } /// <summary> /// This is used to acquire the <c>Decorator</c> for this. /// A decorator is an object that adds various details to the /// node without changing the overall structure of the node. For /// example comments and namespaces can be added to the node with /// a decorator as they do not affect the deserialization. /// </summary> /// <returns> /// this returns the decorator associated with this /// </returns> public Decorator Decorator { get { return decorator; } } //public Decorator GetDecorator() { // return decorator; //} /// This will create a <c>Converter</c> for transforming an XML /// element into a collection of XML serializable objects. The XML /// schema class for these objects must be present the element list /// annotation. /// </summary> /// <param name="context"> /// this is the context object used for serialization /// </param> /// <returns> /// this returns the converter for creating a collection /// </returns> public Converter GetConverter(Context context) { String entry = GetEntry(context); if(!label.inline()) { return GetConverter(context, entry); } return GetInlineConverter(context, entry); } /// <summary> /// This will create a <c>Converter</c> for transforming an XML /// element into a collection of XML serializable objects. The XML /// schema class for these objects must be present the element list /// annotation. /// </summary> /// <param name="context"> /// this is the context object used for serialization /// </param> /// <param name="name"> /// this is the name of the XML entry element to use /// </param> /// <returns> /// this returns the converter for creating a collection /// </returns> public Converter GetConverter(Context context, String name) { Type item = Dependent; Type type = Contact; if(!context.isPrimitive(item)) { return new CompositeList(context, type, item, name); } return new PrimitiveList(context, type, item, name); } /// <summary> /// This will create a <c>Converter</c> for transforming an XML /// element into a collection of XML serializable objects. The XML /// schema class for these objects must be present the element list /// annotation. /// </summary> /// <param name="context"> /// this is the context object used for serialization /// </param> /// <returns> /// this returns the converter for creating a collection /// </returns> public Converter GetInlineConverter(Context context, String name) { Type item = Dependent; Type type = Contact; if(!context.isPrimitive(item)) { return new CompositeInlineList(context, type, item, name); } return new PrimitiveInlineList(context, type, item, name); } /// <summary> /// This is used to acquire the name of the element or attribute /// that is used by the class schema. The name is determined by /// checking for an override within the annotation. If it contains /// a name then that is used, if however the annotation does not /// specify a name the the field or method name is used instead. /// </summary> /// <returns> /// returns the name that is used for the XML property /// </returns> public String GetName(Context context) { Style style = context.getStyle(); String name = detail.GetName(); return style.getElement(name); } /// <summary> /// This is used to either provide the entry value provided within /// the annotation or compute a entry value. If the entry string /// is not provided the the entry value is calculated as the type /// of primitive the object is as a simplified class name. /// </summary> /// <param name="context"> /// this is the context used to style the entry /// </param> /// <returns> /// this returns the name of the XML entry element used /// </returns> public String GetEntry(Context context) { Style style = context.getStyle(); String entry = GetEntry(); return style.getElement(entry); } /// <summary> /// This is used to provide a configured empty value used when the /// annotated value is null. This ensures that XML can be created /// with required details regardless of whether values are null or /// not. It also provides a means for sensible default values. /// </summary> /// <param name="context"> /// this is the context object for the serialization /// </param> /// <returns> /// this returns the string to use for default values /// </returns> public Object GetEmpty(Context context) { Type list = new ClassType(type); Factory factory = new CollectionFactory(context, list); if(!label.empty()) { return factory.getInstance(); } return null; } /// <summary> /// This is used to acquire the dependent type for the annotated /// list. This will simply return the type that the collection is /// composed to hold. This must be a serializable type, that is, /// a type that is annotated with the <c>Root</c> class. /// </summary> /// <returns> /// this returns the component type for the collection /// </returns> public Type Dependent { get { Contact contact = Contact; if(item == void.class) { item = contact.Dependent; } if(item == null) { throw new ElementException("Unable to determine type for %s", contact); } return new ClassType(item); } } //public Type GetDependent() { // Contact contact = Contact; // if(item == void.class) { // item = contact.Dependent; // } // if(item == null) { // throw new ElementException("Unable to determine type for %s", contact); // } // return new ClassType(item); //} /// This is used to either provide the entry value provided within /// the annotation or compute a entry value. If the entry string /// is not provided the the entry value is calculated as the type /// of primitive the object is as a simplified class name. /// </summary> /// <returns> /// this returns the name of the XML entry element used /// </returns> public String Entry { get { if(detail.IsEmpty(entry)) { entry = detail.GetEntry(); } return entry; } } //public String GetEntry() { // if(detail.IsEmpty(entry)) { // entry = detail.GetEntry(); // } // return entry; //} /// This is used to acquire the name of the element or attribute /// that is used by the class schema. The name is determined by /// checking for an override within the annotation. If it contains /// a name then that is used, if however the annotation does not /// specify a name the the field or method name is used instead. /// </summary> /// <returns> /// returns the name that is used for the XML property /// </returns> public String Name { get { return detail.GetName(); } } //public String GetName() { // return detail.GetName(); //} /// This acts as a convenience method used to determine the type of /// contact this represents. This is used when an object is written /// to XML. It determines whether a <c>class</c> attribute /// is required within the serialized XML element, that is, if the /// class returned by this is different from the actual value of the /// object to be serialized then that type needs to be remembered. /// </summary> /// <returns> /// this returns the type of the contact class /// </returns> public Class Type { get { return type; } } //public Class GetType() { // return type; //} /// This is used to acquire the contact object for this label. The /// contact retrieved can be used to set any object or primitive that /// has been deserialized, and can also be used to acquire values to /// be serialized in the case of object persistence. All contacts /// that are retrieved from this method will be accessible. /// </summary> /// <returns> /// returns the contact that this label is representing /// </returns> public Contact Contact { get { return detail.Contact; } } //public Contact GetContact() { // return detail.Contact; //} /// This is used to acquire the name of the element or attribute /// as taken from the annotation. If the element or attribute /// explicitly specifies a name then that name is used for the /// XML element or attribute used. If however no overriding name /// is provided then the method or field is used for the name. /// </summary> /// <returns> /// returns the name of the annotation for the contact /// </returns> public String Override { get { return name; } } //public String GetOverride() { // return name; //} /// This is used to determine whether the annotation requires it /// and its children to be written as a CDATA block. This is done /// when a primitive or other such element requires a text value /// and that value needs to be encapsulated within a CDATA block. /// </summary> /// <returns> /// currently the element list does not require CDATA /// </returns> public bool IsData() { return label.data(); } /// <summary> /// This method is used to determine if the label represents an /// attribute. This is used to style the name so that elements /// are styled as elements and attributes are styled as required. /// </summary> /// <returns> /// this is used to determine if this is an attribute /// </returns> public bool IsAttribute() { return false; } /// <summary> /// This is used to determine if the label is a collection. If the /// label represents a collection then any original assignment to /// the field or method can be written to without the need to /// create a new collection. This allows obscure collections to be /// used and also allows initial entries to be maintained. /// </summary> /// <returns> /// true if the label represents a collection value /// </returns> public bool IsCollection() { return true; } /// <summary> /// This is used to determine whether the XML element is required. /// This ensures that if an XML element is missing from a document /// that deserialization can continue. Also, in the process of /// serialization, if a value is null it does not need to be /// written to the resulting XML document. /// </summary> /// <returns> /// true if the label represents a some required data /// </returns> public bool IsRequired() { return label.required(); } /// <summary> /// This is used to determine whether the list has been specified /// as inline. If the list is inline then no overrides are needed /// and the outer XML element for the list is not used. /// </summary> /// <returns> /// this returns whether the annotation is inline /// </returns> public bool IsInline() { return label.inline(); } /// <summary> /// This is used to describe the annotation and method or field /// that this label represents. This is used to provide error /// messages that can be used to debug issues that occur when /// processing a method. This will provide enough information /// such that the problem can be isolated correctly. /// </summary> /// <returns> /// this returns a string representation of the label /// </returns> public String ToString() { return detail.ToString(); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Codes : MonoBehaviour { public static SpawnSphere shapeSpawn; public static List<string> goodCodes = null;// new List<string> (); public static List<string> triCodes = null; public static List<string> pentCodes = null; public static List<string> sqCodes = null; public static List<string> badCodes = null;// new List<string> (); public static List<string> allCodes = null; public static List<string> drawCodes = null; public static float theta = 0.0f; public static float angularOffset = 0.0f; public static int counter = 0; public static float timeCounter = 0.0f; public static Color codeColor = Color.red; // Use this for initialization void Start () { shapeSpawn = GameObject.Find ("OculusEverything/SphereMaker").GetComponent<SpawnSphere>(); if (goodCodes == null) { //haven't set up the codes yet goodCodes = new List<string> (); triCodes = new List<string> (); pentCodes = new List<string> (); sqCodes = new List<string> (); badCodes = new List<string> (); allCodes = new List<string> (); for (int i = 0; i < 10; i++) { triCodes.Add (makeRandomCode ()); pentCodes.Add (makeRandomCode ()); sqCodes.Add (makeRandomCode ()); badCodes.Add (makeRandomCode ()); goodCodes.Add (triCodes [i]); goodCodes.Add (pentCodes [i]); goodCodes.Add (sqCodes [i]); allCodes.Add (pentCodes [i]); allCodes.Add (sqCodes [i]); allCodes.Add (badCodes [i]); allCodes.Add (triCodes [i]); } } } public string makeRandomCode () { string newCode = ""; for (int j = 0; j < 4; j++) { newCode = newCode + Random.Range (1, 9); } return newCode; } public static string receiveCode (string code) { bool wasTriCode = triCodes.Contains (code); bool wasPentCode = pentCodes.Contains (code); bool wasSqCode = sqCodes.Contains (code); bool wasGoodCode = goodCodes.Contains (code); bool wasBadCode = badCodes.Contains (code); string result = ""; if (wasGoodCode) { goodCodes.Remove (code); //could add a new code } else if (wasBadCode == false) { result= ("reset"); } if (wasTriCode) { triCodes.Remove (code); allCodes.Remove (code); result= ("triangle"); shapeSpawn.spawnSphere(0); } if (wasPentCode) { pentCodes.Remove (code); allCodes.Remove (code); result= ("pentagon"); shapeSpawn.spawnSphere(1); } if (wasSqCode) { sqCodes.Remove (code); allCodes.Remove (code); result= ("square"); shapeSpawn.spawnSphere(2); } if (wasBadCode) { badCodes.Remove (code); allCodes.Remove (code); result= ("dud"); } print (result); return result; } // Update is called once per frame void Update () ///////input keys for easy play test////////// { if (Input.GetKeyDown(KeyCode.A)) { receiveCode(triCodes[0]); } if (Input.GetKeyDown(KeyCode.S)) { receiveCode(pentCodes[0]); } if (Input.GetKeyDown(KeyCode.D)) { receiveCode(sqCodes[0]); } if (Input.GetKeyDown(KeyCode.F)) { receiveCode(badCodes[0]); } //////////////////////////////////////////// if (timeCounter < 90) { timeCounter ++; } else { timeCounter = 0; if (counter < allCodes.Count) { counter += 1; } else { counter = 0; } } } void OnGUI () { for (int i = 0; i < allCodes.Count; i++) { theta = 2*Mathf.PI*i/(allCodes.Count); float angleIncrement = 2*Mathf.PI/(allCodes.Count); theta += angleIncrement*counter; //codeColor = HSVToRGB (i/40, 1, 1); AlexUtil.DrawText (new Vector2 (((Mathf.Sin(theta)*((Screen.height*allCodes.Count/2-400)/40))+Screen.width/2), (Mathf.Cos(theta)*((Screen.height*allCodes.Count/2-400)/40)+Screen.height/2)-5), "" + allCodes [i], 12, Color.black); } /*for (int i = 0; i < badCodes.Count; i++) { AlexUtil.DrawText (new Vector2 (200, 10 + 20 * i), "code: " + badCodes [i], 24, Color.white); }*/ } // public Color HSVToRGB(float H, float S, float V) // { // if (S == 0f) // return new Color(V,V,V); // else if (V == 0f) // return Color.black; // else // { // Color col = Color.black; // float Hval = H * 6f; // int sel = Mathf.FloorToInt(Hval); // float mod = Hval - sel; // float v1 = V * (1f - S); // float v2 = V * (1f - S * mod); // float v3 = V * (1f - S * (1f - mod)); // switch (sel + 1) // { // case 0: // col.r = V; // col.g = v1; // col.b = v2; // break; // case 1: // col.r = V; // col.g = v3; // col.b = v1; // break; // case 2: // col.r = v2; // col.g = V; // col.b = v1; // break; // case 3: // col.r = v1; // col.g = V; // col.b = v3; // break; // case 4: // col.r = v1; // col.g = v2; // col.b = V; // break; // case 5: // col.r = v3; // col.g = v1; // col.b = V; // break; // case 6: // col.r = V; // col.g = v1; // col.b = v2; // break; // case 7: // col.r = V; // col.g = v3; // col.b = v1; // break; // } // col.r = Mathf.Clamp(col.r, 0f, 1f); // col.g = Mathf.Clamp(col.g, 0f, 1f); // col.b = Mathf.Clamp(col.b, 0f, 1f); // return col; // } // } }
#if UNITY_STANDALONE || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX #define COHERENT_UNITY_STANDALONE #endif #if UNITY_NACL || UNITY_WEBPLAYER #define COHERENT_UNITY_UNSUPPORTED_PLATFORM #endif //#if UNITY_EDITOR && (UNITY_IPHONE || UNITY_ANDROID) //#define COHERENT_SIMULATE_MOBILE_IN_EDITOR //#endif using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; #if COHERENT_UNITY_STANDALONE || COHERENT_UNITY_UNSUPPORTED_PLATFORM using Coherent.UI; using CoherentUI = Coherent.UI; #elif UNITY_IPHONE || UNITY_ANDROID using Coherent.UI.Mobile; using CoherentUI = Coherent.UI.Mobile; #endif /// <summary> /// Component controlling the CoherentUI System /// </summary> [AddComponentMenu("Coherent UI/UI System")] public class CoherentUISystem : MonoBehaviour { private static CoherentUISystem m_Instance = null; public static CoherentUISystem Instance { get { if (m_Instance == null) { m_Instance = Component.FindObjectOfType(typeof(CoherentUISystem)) as CoherentUISystem; if (m_Instance == null) { m_Instance = CoherentUISystem.Create(); if (m_Instance == null) { throw new System.ApplicationException("Unable to create Coherent UI System"); } } } return m_Instance; } } public const byte COHERENT_PREFIX = 177; public enum CoherentRenderingEventType { DrawView = 1, WakeRenderer = 2 }; public enum CoherentRenderingFlags { None = 0, FlipY = 1, CorrectGamma = 2 }; public enum CoherentFilteringModes { PointFiltering = 1, LinearFiltering = 2 }; private UISystem m_UISystem; private SystemListener m_SystemListener; private ILogHandler m_LogHandler; private FileHandler m_FileHandler; /// <summary> /// Creates the FileHandler instance for the system. Change to allow usage of custom FileHandler /// </summary> public static System.Func<FileHandler> FileHandlerFactoryFunc = () => { #if UNITY_ANDROID && !UNITY_EDITOR // Android's default file handler is implemented in the Coherent library for better performance. // If you need custom reading, check the Android custom file handler sample. return null; #else return new UnityFileHandler(); #endif }; /// <summary> /// Creates the SystemListener instance for the system. Change to allow usage of custom EventListener /// <remarks>custom OnSystemReady override must call SystemListener.OnSystemReady</remarks> /// <para>Action to be given to SystemListener constructor</para> /// </summary> public static System.Func<System.Action, SystemListener> SystemListenerFactoryFunc; #if COHERENT_UNITY_STANDALONE private Vector2 m_LastMousePosition = new Vector2(-1, -1); private MouseEventData m_MouseMoveEvent = new MouseEventData() { MouseModifiers = new EventMouseModifiersState(), Modifiers = new EventModifiersState() }; #endif #if !UNITY_EDITOR && (UNITY_ANDROID) private string m_TouchScreenKeyboardText = SystemListener.GetTouchScreenKbdInitialText(); private TouchScreenKeyboard m_TouchScreenKeyboard; private bool m_ExpectKbdShow = false; private bool m_ExpectedKbdClosed = false; public TouchScreenKeyboard TouchscreenKeyboard { get { return m_TouchScreenKeyboard; } set { if (m_ExpectedKbdClosed) { m_ExpectedKbdClosed = false; // assert value == null if (value != null) { Debug.LogWarning("Setting touch-screen object to non-null when keyboard was closed!"); } m_TouchScreenKeyboard = null; m_TouchScreenKeyboardText = SystemListener.GetTouchScreenKbdInitialText(); return; } if (m_ExpectKbdShow) { m_ExpectKbdShow = false; // Send signal for closing foreach (CoherentUIView view in m_Views) { if (view != null && view.Listener != null && view.Listener.View != null) { view.Listener.View.DispatchKeyEventInternal(101, 0); } } m_ExpectedKbdClosed = true; } if (value == null && m_TouchScreenKeyboard != null && TouchScreenKeyboard.visible) { foreach (CoherentUIView view in m_Views) { if (view != null && view.Listener != null && view.Listener.View != null) { view.Listener.View.DispatchKeyEventInternal(100, 0); } } m_ExpectKbdShow = true; } if (value == null) { m_TouchScreenKeyboardText = SystemListener.GetTouchScreenKbdInitialText(); } m_TouchScreenKeyboard = value; } } #endif /// <summary> /// Indicates whether one of the views in the system is keeping input focus. /// </summary> private bool m_SystemHasFocusedView = false; /// <summary> /// Determines whether the Coherent UI System component is currently in its Update() method /// </summary> /// <returns> /// <c>true</c> if this instance is updating; otherwise, <c>false</c>. /// </returns> public bool IsUpdating { get; private set; } public delegate void OnUISystemDestroyingDelegate(); public event OnUISystemDestroyingDelegate UISystemDestroying; public delegate void SystemReadyEventHandler(); private SystemReadyEventHandler SystemReadyHandlers; public event SystemReadyEventHandler SystemReady { add { if (!IsReady()) { SystemReadyHandlers += value; } else { m_ReadyHandlers.Add(value); } } remove { SystemReadyHandlers -= value; } } private List<SystemReadyEventHandler> m_ReadyHandlers = new List<SystemReadyEventHandler>(); private List<CoherentUIView> m_Views = new List<CoherentUIView>(); internal void AddView(CoherentUIView view) { m_Views.Add(view); } internal bool RemoveView(CoherentUIView view) { return m_Views.Remove(view); } public List<CoherentUIView> UIViews { get { return m_Views; } } public static CoherentUISystem Create() { if (GameObject.Find("CoherentUISystem") != null) { Debug.LogWarning("Unable to create CoherentUISystem because a GameObject with the same name already exists!"); return null; } var go = new GameObject("CoherentUISystem"); CoherentUISystem system = go.AddComponent("CoherentUISystem") as CoherentUISystem; if (system != null && Debug.isDebugBuild) { system.DebuggerPort = 9999; } return system; } private static string GetDefaultHostDirectory() { #if UNITY_EDITOR return (Application.platform == RuntimePlatform.WindowsEditor)? "StreamingAssets/CoherentUI_Host/windows" : "StreamingAssets/CoherentUI_Host/macosx"; #elif UNITY_STANDALONE_WIN return "StreamingAssets/CoherentUI_Host/windows"; #elif UNITY_STANDALONE_LINUX return "StreamingAssets/CoherentUI_Host/linux"; #elif UNITY_STANDALONE_OSX return "Data/StreamingAssets/CoherentUI_Host/macosx"; #elif UNITY_IPHONE || UNITY_ANDROID return ""; #else #warning Unsupported Unity platform throw new System.ApplicationException("Coherent UI doesn't support the target platfrom"); #endif } /// <summary> /// the path to CoherentUI_Host executable /// </summary> [HideInInspector] [SerializeField] private string m_HostDirectory = GetDefaultHostDirectory(); [CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.General, PrettyName = "Host directory", Tooltip="The directory where the Host executable is located", IsStatic=true)] public string HostDirectory { get { return m_HostDirectory; } set { m_HostDirectory = value; } } /// <summary> /// enable proxy support for loading web pages /// </summary> [HideInInspector] [SerializeField] private bool m_EnableProxy = false; [CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.General, PrettyName = "Proxy", Tooltip="Enables proxy support", IsStatic=true)] public bool EnableProxy { get { return m_EnableProxy; } set { m_EnableProxy = value; } } /// <summary> /// allow cookies /// </summary> [HideInInspector] [SerializeField] private bool m_AllowCookies = true; [CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.General, PrettyName = "Cookies", Tooltip="Enables support for cookies", IsStatic=true)] public bool AllowCookies { get { return m_AllowCookies; } set { m_AllowCookies = value; } } /// <summary> /// URL for storing persistent cookies /// </summary> [HideInInspector] [SerializeField] private string m_CookiesResource = "cookies.dat"; [CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.General, PrettyName = "Cookies file", Tooltip="The file where cookies will be saved", IsStatic=true)] public string CookiesResource { get { return m_CookiesResource; } set { m_CookiesResource = value; } } /// <summary> /// path for browser cache /// </summary> [HideInInspector] [SerializeField] private string m_CachePath = "cui_cache"; [CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.General, PrettyName = "Cache path", Tooltip="The folder where the navigation cache will be saved", IsStatic=true)] public string CachePath { get { return m_CachePath; } set { m_CachePath = value; } } /// <summary> /// path for HTML5 localStorage /// </summary> [HideInInspector] [SerializeField] private string m_HTML5LocalStoragePath = "cui_app_cache"; [CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.General, PrettyName = "Local storage path", Tooltip="The directory where the HTML5 local storage will be saved", IsStatic=true)] public string HTML5LocalStoragePath { get { return m_HTML5LocalStoragePath; } set { m_HTML5LocalStoragePath = value; } } /// <summary> /// disable fullscreen for plugins like Flash and Silverlight /// </summary> [HideInInspector] [SerializeField] private bool m_ForceDisablePluginFullscreen = true; [CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.General, PrettyName = "Disable fullscreen plugins", Tooltip="All plugins will have their fullscreen support disabled", IsStatic=true)] public bool ForceDisablePluginFullscreen { get { return m_ForceDisablePluginFullscreen; } set { m_ForceDisablePluginFullscreen = value; } } /// <summary> /// disable web security like cross-domain checks /// </summary> [HideInInspector] [SerializeField] private bool m_DisableWebSecutiry = false; [CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.General, PrettyName = "Disable web security", Tooltip="Allows loading making HTTP requests from coui://", IsStatic=true)] public bool DisableWebSecutiry { get { return m_DisableWebSecutiry; } set { m_DisableWebSecutiry = value; } } /// <summary> /// port for debugging Views, -1 to disable /// </summary> [HideInInspector] [SerializeField] private int m_DebuggerPort = 9999; [CoherentExposePropertyStandalone(Category = CoherentExposePropertyInfo.FoldoutType.General, PrettyName = "Debugger port", Tooltip="The port where the system will listen for the debugger", IsStatic=true)] public int DebuggerPort { get { return m_DebuggerPort; } set { m_DebuggerPort = value; } } /// <summary> /// The main camera. Used for obtaining mouse position over the HUD and raycasting in the world. /// </summary> public Camera m_MainCamera = null; [HideInInspector] public bool DeviceSupportsSharedTextures = false; [HideInInspector] [SerializeField] private bool m_UseURLCache = true; /// <summary> /// Sets if the system should use the URL Cache. NOTE: This should almost always be enabled. /// Disable it if you already set the URL cache yourself for the app /// </summary> /// <value> /// If to set the cache /// </value> [CoherentExposePropertyiOS(Category = CoherentExposePropertyInfo.FoldoutType.General, PrettyName = "URL cache", Tooltip="Use the URL cache of the device", IsStatic=true)] public bool UseURLCache { get { return m_UseURLCache; } set { m_UseURLCache = value; } } [HideInInspector] [SerializeField] private int m_MemoryCacheSize = 4*1024*1024; /// <summary> /// Sets the in-memory size of the URL cache /// </summary> /// <value> /// The maximum size of the in-memory cache /// </value> [CoherentExposePropertyiOS(Category = CoherentExposePropertyInfo.FoldoutType.General, PrettyName = "Memory cache size", Tooltip="The maximum size of the in-memory cache", IsStatic=true)] public int MemoryCacheSize { get { return m_MemoryCacheSize; } set { m_MemoryCacheSize = value; } } [HideInInspector] [SerializeField] private int m_DiskCacheSize = 32*1024*1024; /// <summary> /// Sets the on-disk size of the URL cache /// </summary> /// <value> /// The maximum size of the on-disk cache /// </value> [CoherentExposePropertyiOS(Category = CoherentExposePropertyInfo.FoldoutType.General, PrettyName = "Disk cache size", Tooltip="The maximum size of the disk cache", IsStatic=true)] public int DiskCacheSize { get { return m_DiskCacheSize; } set { m_DiskCacheSize = value; } } // Use this for initialization void Start () { if (SystemInfo.graphicsDeviceVersion.StartsWith("Direct3D 11") || SystemInfo.operatingSystem.Contains("Mac")) { DeviceSupportsSharedTextures = true; } if (m_UISystem == null) { m_SystemListener = (SystemListenerFactoryFunc != null)? SystemListenerFactoryFunc(this.OnSystemReady) : new SystemListener(this.OnSystemReady); m_LogHandler = new UnityLogHandler(); if (FileHandlerFactoryFunc != null) { m_FileHandler = FileHandlerFactoryFunc(); } #if !UNITY_ANDROID || UNITY_EDITOR if (m_FileHandler == null) { Debug.LogWarning("Unable to create file handler using factory function! Falling back to default handler."); m_FileHandler = new UnityFileHandler(); } #endif #if COHERENT_UNITY_STANDALONE || COHERENT_UNITY_UNSUPPORTED_PLATFORM SystemSettings settings = new SystemSettings() { HostDirectory = Path.Combine(Application.dataPath, this.HostDirectory), EnableProxy = this.EnableProxy, AllowCookies = this.AllowCookies, CookiesResource = "file:///" + Application.persistentDataPath + '/' + this.CookiesResource, CachePath = Path.Combine(Application.temporaryCachePath, this.CachePath), HTML5LocalStoragePath = Path.Combine(Application.temporaryCachePath, this.HTML5LocalStoragePath), ForceDisablePluginFullscreen = this.ForceDisablePluginFullscreen, DisableWebSecurity = this.DisableWebSecutiry, DebuggerPort = this.DebuggerPort, }; int sdkVersion = Coherent.UI.Versioning.SDKVersion; #elif UNITY_IPHONE || UNITY_ANDROID SystemSettings settings = new SystemSettings() { iOS_UseURLCache = m_UseURLCache, iOS_URLMemoryCacheSize = (uint)m_MemoryCacheSize, iOS_URLDiskCacheSize = (uint)m_DiskCacheSize, }; int sdkVersion = Coherent.UI.Mobile.Versioning.SDKVersion; #endif m_UISystem = CoherentUI_Native.InitializeUISystem(sdkVersion, Coherent.UI.License.COHERENT_KEY, settings, m_SystemListener, Severity.Info, m_LogHandler, m_FileHandler); if (m_UISystem == null) { throw new System.ApplicationException("UI System initialization failed!"); } Debug.Log ("Coherent UI system initialized.."); #if COHERENT_UNITY_STANDALONE CoherentUIViewRenderer.WakeRenderer(); #endif } m_StartTime = Time.realtimeSinceStartup; DontDestroyOnLoad(this.gameObject); } private void OnSystemReady() { if (SystemReadyHandlers != null) { SystemReadyHandlers(); } } /// <summary> /// Determines whether this instance is ready. /// </summary> /// <returns> /// <c>true</c> if this instance is ready; otherwise, <c>false</c>. /// </returns> public bool IsReady() { return m_UISystem != null && m_SystemListener.IsReady; } /// <summary> /// Determines whether there is an focused Click-to-focus view /// </summary> /// <value> /// <c>true</c> if there is an focused Click-to-focus view; otherwise, <c>false</c>. /// </value> public bool HasFocusedView { get { return m_SystemHasFocusedView; } } public delegate void OnViewFocusedDelegate(bool focused); /// <summary> /// Occurs when a Click-to-focus view gains or loses focus /// </summary> public event OnViewFocusedDelegate OnViewFocused; private void SetViewFocused(bool focused) { m_SystemHasFocusedView = focused; if (OnViewFocused != null) { OnViewFocused(focused); } } private void TrackInputFocus() { #if COHERENT_UNITY_STANDALONE if (m_MainCamera == null) { m_MainCamera = Camera.main; if (m_MainCamera == null) { return; } } bool isClick = Input.GetMouseButtonDown(0); if (!m_SystemHasFocusedView && !isClick) { // Do nothing if the left mouse button isn't clicked // (and there is no focused view; if there is, we need to track the mouse) return; } CoherentUIView cameraView = m_MainCamera.gameObject.GetComponent<CoherentUIView>(); if (cameraView && cameraView.ClickToFocus) { var view = cameraView.View; if (view != null) { var normX = (Input.mousePosition.x / cameraView.Width); var normY = (1 - Input.mousePosition.y / cameraView.Height); normX = normX * cameraView.WidthToCamWidthRatio(m_MainCamera.pixelWidth); normY = 1 - ((1 - normY) * cameraView.HeightToCamHeightRatio(m_MainCamera.pixelHeight)); if (normX >= 0 && normX <= 1 && normY >= 0 && normY <= 1) { view.IssueMouseOnUIQuery(normX, normY); view.FetchMouseOnUIQuery(); if (view.IsMouseOnView()) { if (isClick) { // Reset input processing for all views foreach (var item in m_Views) { item.ReceivesInput = false; } // Set input to the clicked view cameraView.ReceivesInput = true; SetViewFocused(true); } return; } } } } // Activate input processing for the view below the mouse cursor RaycastHit hitInfo; if (Physics.Raycast(m_MainCamera.ScreenPointToRay(Input.mousePosition), out hitInfo)) { CoherentUIView viewComponent = hitInfo.collider.gameObject.GetComponent(typeof(CoherentUIView)) as CoherentUIView; if (viewComponent == null) { viewComponent = hitInfo.collider.gameObject.GetComponentInChildren(typeof(CoherentUIView)) as CoherentUIView; } if (viewComponent != null && viewComponent.ClickToFocus) { if (isClick) { // Reset input processing for all views foreach (var item in m_Views) { item.ReceivesInput = false; } // Set input to the clicked view viewComponent.ReceivesInput = true; SetViewFocused(true); } viewComponent.SetMousePosition( (int)(hitInfo.textureCoord.x * viewComponent.Width), (int)(hitInfo.textureCoord.y * viewComponent.Height)); return; } } // If neither the HUD nor an object was clicked, clear the focus if (m_SystemHasFocusedView && isClick) { // Reset input processing for all views foreach (var item in m_Views) { item.ReceivesInput = false; } SetViewFocused(false); } #endif } // Update is called once per frame void Update () { #if UNITY_EDITOR if(UnityEditor.EditorApplication.isCompiling) { OnAssemblyReload(); } #endif if (m_UISystem != null) { IsUpdating = true; m_UISystem.Update(); if (m_ReadyHandlers.Count > 0) { foreach (var handler in m_ReadyHandlers) { handler(); } m_ReadyHandlers.Clear(); } TrackInputFocus(); #if UNITY_ANDROID && !UNITY_EDITOR foreach (CoherentUIView view in UIViews) { if (view == null || view.Listener == null || view.Listener.View == null) { continue; } if (m_TouchScreenKeyboard != null) { int lengthDiff = m_TouchScreenKeyboard.text.Length - m_TouchScreenKeyboardText.Length; if (lengthDiff != 0) { if (lengthDiff < 0) { for (int i = 0; i < -lengthDiff; ++i) { view.Listener.View.DispatchKeyEventInternal(1, 0x08); // Backspace } } else { for (int i = m_TouchScreenKeyboardText.Length; i < m_TouchScreenKeyboard.text.Length; ++i) { view.Listener.View.DispatchKeyEventInternal(1, (int)m_TouchScreenKeyboard.text[i]); } } m_TouchScreenKeyboardText = m_TouchScreenKeyboard.text; } } } #endif IsUpdating = false; } } #if COHERENT_UNITY_STANDALONE void MouseMovedViewUpdate(CoherentUIView view) { if (view.ReceivesInput && view != null && view.View != null) { if (view.MouseX != -1 && view.MouseY != -1) { m_MouseMoveEvent.X = view.MouseX; m_MouseMoveEvent.Y = view.MouseY; } else { CalculateScaledMouseCoordinates(ref m_MouseMoveEvent, view, true); } view.View.MouseEvent(m_MouseMoveEvent); } } #endif void LateUpdate() { #if UNITY_ANDROID || COHERENT_SIMULATE_MOBILE_IN_EDITOR || COHERENT_SIMULATE_MOBILE_IN_PLAYER CoherentUI.InputManager.PrepareForNextFrame(); #elif COHERENT_UNITY_STANDALONE // Check if the mouse moved Vector2 mousePosition = Input.mousePosition; if (mousePosition != m_LastMousePosition) { if (m_MouseMoveEvent != null && m_Views != null) { Coherent.UI.InputManager.GenerateMouseMoveEvent( ref m_MouseMoveEvent); //Cache the initial mouse X and Y int mouseX = m_MouseMoveEvent.X; int mouseY = m_MouseMoveEvent.Y; foreach (var item in m_Views) { CoherentUIView view = item; MouseMovedViewUpdate(view); //Since we are using a single mouse event for all //of the views and the MouseMovedViewUpdate //mutates the event's X and Y per view, we have to //reset the X and Y for the next view m_MouseMoveEvent.X = mouseX; m_MouseMoveEvent.Y = mouseY; } } m_LastMousePosition = mousePosition; } #endif } void OnApplicationQuit() { if (m_UISystem != null) { if(UISystemDestroying != null) { UISystemDestroying(); } m_UISystem.Uninitialize(); m_SystemListener.Dispose(); m_UISystem.Dispose(); m_UISystem = null; } } public void OnAssemblyReload() { if(m_UISystem != null) { for(int i = m_Views.Count - 1; i >= 0; --i) { m_Views[i].DestroyView(); } Debug.LogWarning("Assembly reload detected. UI System will shut down."); OnApplicationQuit(); } } private bool IsPointInsideAnyView(int x, int y) { if (m_Views == null) { return false; } for (int i = 0; i < m_Views.Count; ++i) { var view = m_Views[i]; if (view.InputState == CoherentUIView.CoherentViewInputState.TakeNone) { continue; } if (x >= view.XPos && x <= view.XPos + view.Width && y >= view.YPos && y <= view.YPos + view.Height) { return true; } } return false; } public virtual void OnGUI() { if (m_Views == null) { return; } #if UNITY_ANDROID || COHERENT_SIMULATE_MOBILE_IN_EDITOR || COHERENT_SIMULATE_MOBILE_IN_PLAYER if (Event.current.isMouse && !IsPointInsideAnyView( (int)Event.current.mousePosition.x, (int)Event.current.mousePosition.y)) { var evt = Event.current; int x = (int)evt.mousePosition.x; int y = (int)evt.mousePosition.y; switch (evt.type) { case EventType.MouseDown: CoherentUI.InputManager.ProcessTouchEvent( (int)TouchPhase.Began, evt.button, x, y); break; case EventType.MouseUp: CoherentUI.InputManager.ProcessTouchEvent( (int)TouchPhase.Ended, evt.button, x, y); break; case EventType.MouseDrag: CoherentUI.InputManager.ProcessTouchEvent( (int)TouchPhase.Moved, evt.button, x, y); break; } } #endif #if COHERENT_UNITY_STANDALONE MouseEventData mouseEventData = null; KeyEventData keyEventData = null; KeyEventData keyEventDataChar = null; switch (Event.current.type) { case EventType.MouseDown: { mouseEventData = Coherent.UI.InputManager.ProcessMouseEvent(Event.current); mouseEventData.Type = MouseEventData.EventType.MouseDown; } break; case EventType.MouseUp: { mouseEventData = Coherent.UI.InputManager.ProcessMouseEvent(Event.current); mouseEventData.Type = MouseEventData.EventType.MouseUp; } break; case EventType.ScrollWheel: { if (Event.current.delta.SqrMagnitude() > 0) { mouseEventData = Coherent.UI.InputManager.ProcessMouseEvent(Event.current); mouseEventData.Type = MouseEventData.EventType.MouseWheel; } } break; case EventType.KeyDown: if (Event.current.keyCode != KeyCode.None) { keyEventData = Coherent.UI.InputManager.ProcessKeyEvent(Event.current); keyEventData.Type = KeyEventData.EventType.KeyDown; if (keyEventData.KeyCode == 0) { keyEventData = null; } } if (Event.current.character != 0) { keyEventDataChar = Coherent.UI.InputManager.ProcessCharEvent(Event.current); if(keyEventDataChar.KeyCode == 10) { keyEventDataChar.KeyCode = 13; } } break; case EventType.KeyUp: { keyEventData = Coherent.UI.InputManager.ProcessKeyEvent(Event.current); keyEventData.Type = KeyEventData.EventType.KeyUp; if (keyEventData.KeyCode == 0) { keyEventData = null; } } break; } foreach (var item in m_Views) { var view = item.View; #if COHERENT_SIMULATE_MOBILE_IN_EDITOR || COHERENT_SIMULATE_MOBILE_IN_PLAYER bool forwardInput = (item.InputState != CoherentUIView.CoherentViewInputState.TakeNone); #else bool forwardInput = item.ReceivesInput; #endif if (forwardInput && view != null) { if (mouseEventData != null) { if (item.MouseX != -1 && item.MouseY != -1) { mouseEventData.X = item.MouseX; mouseEventData.Y = item.MouseY; } //Check if there is a camera attached to the view's parent //Views attached on surfaces do not have such camera. var isOnSurface = item.gameObject.camera == null; if (!isOnSurface) { CalculateScaledMouseCoordinates(ref mouseEventData, item, false); } view.MouseEvent(mouseEventData); //Note: The Event.current.Use() marks the event as used, //and makes the other GUI elements to ignore it, but does //not destroy the event immediately Event.current.Use(); } if (keyEventData != null) { view.KeyEvent(keyEventData); Event.current.Use(); } if (keyEventDataChar != null) { view.KeyEvent(keyEventDataChar); Event.current.Use(); } } } #endif } #if COHERENT_UNITY_STANDALONE private void CalculateScaledMouseCoordinates(ref MouseEventData data, CoherentUIView view, bool invertY) { float camWidth; float camHeight; var isOnSurface = view.gameObject.camera == null; if (!isOnSurface) { camWidth = view.gameObject.camera.pixelWidth; camHeight = view.gameObject.camera.pixelHeight; } else { var surfaceCameraObj = view.gameObject.transform.Find ("CoherentRenderingCamera" + view.View.GetId()); if (surfaceCameraObj != null && surfaceCameraObj.camera != null) { camWidth = surfaceCameraObj.camera.pixelWidth; camHeight = surfaceCameraObj.camera.pixelHeight; } else { return; } } float factorX = view.WidthToCamWidthRatio(camWidth); float factorY = view.HeightToCamHeightRatio(camHeight); float y = (invertY)? (camHeight - data.Y) : data.Y; data.X = (int)(data.X * factorX); data.Y = (int)(y * factorY); } #endif /// <summary> /// Gets the user interface system. /// </summary> /// <value> /// The user interface system. /// </value> public UISystem UISystem { get { return m_UISystem; } } public float StartTime { get { return m_StartTime; } } private float m_StartTime; }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Diagnostics; using System.Linq; using System.Threading; using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Orders; using QuantConnect.Securities; namespace QuantConnect.Tests.Brokerages { public abstract class BrokerageTests { // ideally this class would be abstract, but I wanted to keep the order test cases here which use the // various parameters required from derived types private IBrokerage _brokerage; private OrderProvider _orderProvider; private SecurityProvider _securityProvider; /// <summary> /// Provides the data required to test each order type in various cases /// </summary> public virtual TestCaseData[] OrderParameters { get { return new [] { new TestCaseData(new MarketOrderTestParameters(Symbol)).SetName("MarketOrder"), new TestCaseData(new LimitOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("LimitOrder"), new TestCaseData(new StopMarketOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("StopMarketOrder"), new TestCaseData(new StopLimitOrderTestParameters(Symbol, HighPrice, LowPrice)).SetName("StopLimitOrder") }; } } #region Test initialization and cleanup [SetUp] public void Setup() { Log.Trace(""); Log.Trace(""); Log.Trace("--- SETUP ---"); Log.Trace(""); Log.Trace(""); // we want to regenerate these for each test _brokerage = null; _orderProvider = null; _securityProvider = null; Thread.Sleep(1000); CancelOpenOrders(); LiquidateHoldings(); Thread.Sleep(1000); } [TearDown] public void Teardown() { try { Log.Trace(""); Log.Trace(""); Log.Trace("--- TEARDOWN ---"); Log.Trace(""); Log.Trace(""); Thread.Sleep(1000); CancelOpenOrders(); LiquidateHoldings(); Thread.Sleep(1000); } finally { if (_brokerage != null) { DisposeBrokerage(_brokerage); } } } public IBrokerage Brokerage { get { if (_brokerage == null) { _brokerage = InitializeBrokerage(); } return _brokerage; } } private IBrokerage InitializeBrokerage() { Log.Trace(""); Log.Trace("- INITIALIZING BROKERAGE -"); Log.Trace(""); var brokerage = CreateBrokerage(OrderProvider, SecurityProvider); brokerage.Connect(); if (!brokerage.IsConnected) { Assert.Fail("Failed to connect to brokerage"); } Log.Trace(""); Log.Trace("GET OPEN ORDERS"); Log.Trace(""); foreach (var openOrder in brokerage.GetOpenOrders()) { OrderProvider.Add(openOrder); } Log.Trace(""); Log.Trace("GET ACCOUNT HOLDINGS"); Log.Trace(""); foreach (var accountHolding in brokerage.GetAccountHoldings()) { // these securities don't need to be real, just used for the ISecurityProvider impl, required // by brokerages to track holdings SecurityProvider[accountHolding.Symbol] = CreateSecurity(accountHolding.Symbol); } brokerage.OrderStatusChanged += (sender, args) => { Log.Trace(""); Log.Trace("ORDER STATUS CHANGED: " + args); Log.Trace(""); // we need to keep this maintained properly if (args.Status == OrderStatus.Filled || args.Status == OrderStatus.PartiallyFilled) { Log.Trace("FILL EVENT: " + args.FillQuantity + " units of " + args.Symbol.ToString()); Security security; if (_securityProvider.TryGetValue(args.Symbol, out security)) { var holding = _securityProvider[args.Symbol].Holdings; holding.SetHoldings(args.FillPrice, holding.Quantity + args.FillQuantity); } else { _securityProvider[args.Symbol] = CreateSecurity(args.Symbol); _securityProvider[args.Symbol].Holdings.SetHoldings(args.FillPrice, args.FillQuantity); } Log.Trace("--HOLDINGS: " + _securityProvider[args.Symbol]); // update order mapping var order = _orderProvider.GetOrderById(args.OrderId); order.Status = args.Status; } }; return brokerage; } internal static Security CreateSecurity(Symbol symbol) { return new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), new SubscriptionDataConfig(typeof (TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, false, false, false), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)); } public OrderProvider OrderProvider { get { return _orderProvider ?? (_orderProvider = new OrderProvider()); } } public SecurityProvider SecurityProvider { get { return _securityProvider ?? (_securityProvider = new SecurityProvider()); } } /// <summary> /// Creates the brokerage under test and connects it /// </summary> /// <returns>A connected brokerage instance</returns> protected abstract IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider); /// <summary> /// Disposes of the brokerage and any external resources started in order to create it /// </summary> /// <param name="brokerage">The brokerage instance to be disposed of</param> protected virtual void DisposeBrokerage(IBrokerage brokerage) { } /// <summary> /// This is used to ensure each test starts with a clean, known state. /// </summary> protected void LiquidateHoldings() { Log.Trace(""); Log.Trace("LIQUIDATE HOLDINGS"); Log.Trace(""); var holdings = Brokerage.GetAccountHoldings(); foreach (var holding in holdings) { if (holding.Quantity == 0) continue; Log.Trace("Liquidating: " + holding); var order = new MarketOrder(holding.Symbol, (int)-holding.Quantity, DateTime.Now); _orderProvider.Add(order); PlaceOrderWaitForStatus(order, OrderStatus.Filled); } } protected void CancelOpenOrders() { Log.Trace(""); Log.Trace("CANCEL OPEN ORDERS"); Log.Trace(""); var openOrders = Brokerage.GetOpenOrders(); foreach (var openOrder in openOrders) { Log.Trace("Canceling: " + openOrder); Brokerage.CancelOrder(openOrder); } } #endregion /// <summary> /// Gets the symbol to be traded, must be shortable /// </summary> protected abstract Symbol Symbol { get; } /// <summary> /// Gets the security type associated with the <see cref="Symbol"/> /// </summary> protected abstract SecurityType SecurityType { get; } /// <summary> /// Gets a high price for the specified symbol so a limit sell won't fill /// </summary> protected abstract decimal HighPrice { get; } /// <summary> /// Gets a low price for the specified symbol so a limit buy won't fill /// </summary> protected abstract decimal LowPrice { get; } /// <summary> /// Gets the current market price of the specified security /// </summary> protected abstract decimal GetAskPrice(Symbol symbol); /// <summary> /// Gets the default order quantity /// </summary> protected virtual int GetDefaultQuantity() { return 1; } [Test] public void IsConnected() { Assert.IsTrue(Brokerage.IsConnected); } [Test, TestCaseSource("OrderParameters")] public void LongFromZero(OrderTestParameters parameters) { Log.Trace(""); Log.Trace("LONG FROM ZERO"); Log.Trace(""); PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus); } [Test, TestCaseSource("OrderParameters")] public void CloseFromLong(OrderTestParameters parameters) { Log.Trace(""); Log.Trace("CLOSE FROM LONG"); Log.Trace(""); // first go long PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()), OrderStatus.Filled); // now close it PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus); } [Test, TestCaseSource("OrderParameters")] public void ShortFromZero(OrderTestParameters parameters) { Log.Trace(""); Log.Trace("SHORT FROM ZERO"); Log.Trace(""); PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus); } [Test, TestCaseSource("OrderParameters")] public void CloseFromShort(OrderTestParameters parameters) { Log.Trace(""); Log.Trace("CLOSE FROM SHORT"); Log.Trace(""); // first go short PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(GetDefaultQuantity()), OrderStatus.Filled); // now close it PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus); } [Test, TestCaseSource("OrderParameters")] public void ShortFromLong(OrderTestParameters parameters) { Log.Trace(""); Log.Trace("SHORT FROM LONG"); Log.Trace(""); // first go long PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity())); // now go net short var order = PlaceOrderWaitForStatus(parameters.CreateShortOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus); if (parameters.ModifyUntilFilled) { ModifyOrderUntilFilled(order, parameters); } } [Test, TestCaseSource("OrderParameters")] public void LongFromShort(OrderTestParameters parameters) { Log.Trace(""); Log.Trace("LONG FROM SHORT"); Log.Trace(""); // first fo short PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(-GetDefaultQuantity()), OrderStatus.Filled); // now go long var order = PlaceOrderWaitForStatus(parameters.CreateLongOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus); if (parameters.ModifyUntilFilled) { ModifyOrderUntilFilled(order, parameters); } } [Test] public void GetCashBalanceContainsUSD() { Log.Trace(""); Log.Trace("GET CASH BALANCE"); Log.Trace(""); var balance = Brokerage.GetCashBalance(); Assert.AreEqual(1, balance.Count(x => x.Symbol == "USD")); } [Test] public void GetAccountHoldings() { Log.Trace(""); Log.Trace("GET ACCOUNT HOLDINGS"); Log.Trace(""); var before = Brokerage.GetAccountHoldings(); PlaceOrderWaitForStatus(new MarketOrder(Symbol, GetDefaultQuantity(), DateTime.Now)); var after = Brokerage.GetAccountHoldings(); var beforeHoldings = before.FirstOrDefault(x => x.Symbol == Symbol); var afterHoldings = after.FirstOrDefault(x => x.Symbol == Symbol); var beforeQuantity = beforeHoldings == null ? 0 : beforeHoldings.Quantity; var afterQuantity = afterHoldings == null ? 0 : afterHoldings.Quantity; Assert.AreEqual(GetDefaultQuantity(), afterQuantity - beforeQuantity); } [Test, Ignore("This test requires reading the output and selection of a low volume security for the Brokerageage")] public void PartialFills() { var manualResetEvent = new ManualResetEvent(false); var qty = 1000000m; var remaining = qty; var sync = new object(); Brokerage.OrderStatusChanged += (sender, orderEvent) => { lock (sync) { remaining -= orderEvent.FillQuantity; Console.WriteLine("Remaining: " + remaining + " FillQuantity: " + orderEvent.FillQuantity); if (orderEvent.Status == OrderStatus.Filled) { manualResetEvent.Set(); } } }; // pick a security with low, but some, volume var symbol = Symbols.EURUSD; var order = new MarketOrder(symbol, qty, DateTime.UtcNow) { Id = 1 }; Brokerage.PlaceOrder(order); // pause for a while to wait for fills to come in manualResetEvent.WaitOne(2500); manualResetEvent.WaitOne(2500); manualResetEvent.WaitOne(2500); Console.WriteLine("Remaining: " + remaining); Assert.AreEqual(0, remaining); } /// <summary> /// Updates the specified order in the brokerage until it fills or reaches a timeout /// </summary> /// <param name="order">The order to be modified</param> /// <param name="parameters">The order test parameters that define how to modify the order</param> /// <param name="secondsTimeout">Maximum amount of time to wait until the order fills</param> protected void ModifyOrderUntilFilled(Order order, OrderTestParameters parameters, double secondsTimeout = 90) { if (order.Status == OrderStatus.Filled) { return; } var filledResetEvent = new ManualResetEvent(false); EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) => { if (args.Status == OrderStatus.Filled) { filledResetEvent.Set(); } if (args.Status == OrderStatus.Canceled || args.Status == OrderStatus.Invalid) { Log.Trace("ModifyOrderUntilFilled(): " + order); Assert.Fail("Unexpected order status: " + args.Status); } }; Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged; Log.Trace(""); Log.Trace("MODIFY UNTIL FILLED: " + order); Log.Trace(""); var stopwatch = Stopwatch.StartNew(); while (!filledResetEvent.WaitOne(3000) && stopwatch.Elapsed.TotalSeconds < secondsTimeout) { filledResetEvent.Reset(); if (order.Status == OrderStatus.PartiallyFilled) continue; var marketPrice = GetAskPrice(order.Symbol); Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): Ask: " + marketPrice); var updateOrder = parameters.ModifyOrderToFill(Brokerage, order, marketPrice); if (updateOrder) { if (order.Status == OrderStatus.Filled) break; Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): " + order); if (!Brokerage.UpdateOrder(order)) { Assert.Fail("Brokerage failed to update the order"); } } } Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged; } /// <summary> /// Places the specified order with the brokerage and wait until we get the <paramref name="expectedStatus"/> back via an OrderStatusChanged event. /// This function handles adding the order to the <see cref="IOrderProvider"/> instance as well as incrementing the order ID. /// </summary> /// <param name="order">The order to be submitted</param> /// <param name="expectedStatus">The status to wait for</param> /// <param name="secondsTimeout">Maximum amount of time to wait for <paramref name="expectedStatus"/></param> /// <returns>The same order that was submitted.</returns> protected Order PlaceOrderWaitForStatus(Order order, OrderStatus expectedStatus = OrderStatus.Filled, double secondsTimeout = 10.0, bool allowFailedSubmission = false) { var requiredStatusEvent = new ManualResetEvent(false); var desiredStatusEvent = new ManualResetEvent(false); EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) => { // no matter what, every order should fire at least one of these if (args.Status == OrderStatus.Submitted || args.Status == OrderStatus.Invalid) { Log.Trace(""); Log.Trace("SUBMITTED: " + args); Log.Trace(""); requiredStatusEvent.Set(); } // make sure we fire the status we're expecting if (args.Status == expectedStatus) { Log.Trace(""); Log.Trace("EXPECTED: " + args); Log.Trace(""); desiredStatusEvent.Set(); } }; Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged; OrderProvider.Add(order); if (!Brokerage.PlaceOrder(order) && !allowFailedSubmission) { Assert.Fail("Brokerage failed to place the order: " + order); } requiredStatusEvent.WaitOneAssertFail((int) (1000*secondsTimeout), "Expected every order to fire a submitted or invalid status event"); desiredStatusEvent.WaitOneAssertFail((int) (1000*secondsTimeout), "OrderStatus " + expectedStatus + " was not encountered within the timeout. Order Id:" + order.Id); Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged; return order; } } }
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 ImagesDownloader.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) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Build.Engine { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web; using HtmlAgilityPack; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.Plugins; public class TemplateModelTransformer { private const string GlobalVariableKey = "__global"; private const int MaxInvalidXrefMessagePerFile = 10; private readonly DocumentBuildContext _context; private readonly ApplyTemplateSettings _settings; private readonly TemplateCollection _templateCollection; private readonly RendererLoader _rendererLoader; private readonly IDictionary<string, object> _globalVariables; public TemplateModelTransformer(DocumentBuildContext context, TemplateCollection templateCollection, ApplyTemplateSettings settings, IDictionary<string, object> globals) { _context = context ?? throw new ArgumentNullException(nameof(context)); _templateCollection = templateCollection; _settings = settings; _globalVariables = globals; _rendererLoader = new RendererLoader(templateCollection.Reader, templateCollection.MaxParallelism); } /// <summary> /// Must guarantee thread safety /// </summary> /// <param name="item"></param> /// <returns></returns> internal ManifestItem Transform(InternalManifestItem item) { if (item.Model == null || item.Model.Content == null) { throw new ArgumentNullException("Content for item.Model should not be null!"); } var model = ConvertObjectToDictionary(item.Model.Content); AppendGlobalMetadata(model); if (_settings.Options.HasFlag(ApplyTemplateOptions.ExportRawModel)) { ExportModel(model, item.FileWithoutExtension, _settings.RawModelExportSettings); } var manifestItem = new ManifestItem { DocumentType = item.DocumentType, SourceRelativePath = item.LocalPathFromRoot, Metadata = item.Metadata, Version = _context.VersionName, Group = _context.GroupInfo?.Name, }; var outputDirectory = _settings.OutputFolder ?? Directory.GetCurrentDirectory(); // 1. process resource if (item.ResourceFile != null) { // Resource file has already been processed in its plugin var ofi = new OutputFileInfo { RelativePath = item.ResourceFile, LinkToPath = GetLinkToPath(item.ResourceFile), }; manifestItem.OutputFiles.Add("resource", ofi); } // 2. process model var templateBundle = _templateCollection[item.DocumentType]; if (templateBundle == null) { return manifestItem; } var unresolvedXRefs = new List<XRefDetails>(); // Must convert to JObject first as we leverage JsonProperty as the property name for the model foreach (var template in templateBundle.Templates) { if (template.Renderer == null) { continue; } try { var extension = template.Extension; string outputFile = item.FileWithoutExtension + extension; object viewModel = null; try { viewModel = template.TransformModel(model); } catch (Exception e) { string message; if (_settings.DebugMode) { // save raw model for further investigation: var rawModelPath = ExportModel(model, item.FileWithoutExtension, _settings.RawModelExportSettingsForDebug); message = $"Error transforming model \"{rawModelPath}\" generated from \"{item.LocalPathFromRoot}\" using \"{template.ScriptName}\". {e.Message}"; } else { message = $"Error transforming model generated from \"{item.LocalPathFromRoot}\" using \"{template.ScriptName}\". To get the detailed raw model, please run docfx with debug mode --debug. {e.Message} "; } Logger.LogError(message, code: ErrorCodes.Template.ApplyTemplatePreprocessorError); throw new DocumentException(message, e); } string result; try { result = template.Transform(viewModel); } catch (Exception e) { string message; if (_settings.DebugMode) { // save view model for further investigation: var viewModelPath = ExportModel(viewModel, outputFile, _settings.ViewModelExportSettingsForDebug); message = $"Error applying template \"{template.Name}\" to view model \"{viewModelPath}\" generated from \"{item.LocalPathFromRoot}\". {e.Message}"; } else { message = $"Error applying template \"{template.Name}\" generated from \"{item.LocalPathFromRoot}\". To get the detailed view model, please run docfx with debug mode --debug. {e.Message}"; } Logger.LogError(message, code: ErrorCodes.Template.ApplyTemplateRendererError); throw new DocumentException(message, e); } if (_settings.Options.HasFlag(ApplyTemplateOptions.ExportViewModel)) { ExportModel(viewModel, outputFile, _settings.ViewModelExportSettings); } if (_settings.Options.HasFlag(ApplyTemplateOptions.TransformDocument)) { if (string.IsNullOrWhiteSpace(result) && _settings.DebugMode) { ExportModel(viewModel, outputFile, _settings.ViewModelExportSettingsForDebug); } TransformDocument(result ?? string.Empty, extension, _context, outputFile, manifestItem, out List<XRefDetails> invalidXRefs); unresolvedXRefs.AddRange(invalidXRefs); Logger.LogDiagnostic($"Transformed model \"{item.LocalPathFromRoot}\" to \"{outputFile}\"."); } } catch (PathTooLongException e) { var message = $"Error processing {item.LocalPathFromRoot}: {e.Message}"; throw new PathTooLongException(message, e); } } item.Model = null; LogInvalidXRefs(unresolvedXRefs); return manifestItem; } private void LogInvalidXRefs(List<XRefDetails> unresolvedXRefs) { if (unresolvedXRefs == null || unresolvedXRefs.Count == 0) { return; } var distinctUids = unresolvedXRefs.Select(i => i.RawSource ?? i.Uid).Distinct().Select(s => $"\"{HttpUtility.HtmlDecode(s)}\"").ToList(); Logger.LogWarning( $"{distinctUids.Count} invalid cross reference(s) {distinctUids.ToDelimitedString(", ")}.", code: WarningCodes.Build.UidNotFound); foreach (var group in unresolvedXRefs.GroupBy(i => i.SourceFile)) { // For each source file, print the first 10 invalid cross reference var details = group.Take(MaxInvalidXrefMessagePerFile).Select(i => $"\"{HttpUtility.HtmlDecode(i.RawSource)}\" in line {i.SourceStartLineNumber.ToString()}").Distinct().ToList(); var prefix = details.Count > MaxInvalidXrefMessagePerFile ? $"top {MaxInvalidXrefMessagePerFile} " : string.Empty; var message = $"Details for {prefix}invalid cross reference(s): {details.ToDelimitedString(", ")}"; if (group.Key != null) { Logger.LogInfo(message, file: group.Key); } else { Logger.LogInfo(message); } } } private string GetLinkToPath(string fileName) { if (EnvironmentContext.FileAbstractLayerImpl == null) { return null; } string pp; try { pp = ((FileAbstractLayer)EnvironmentContext.FileAbstractLayerImpl).GetOutputPhysicalPath(fileName); } catch (FileNotFoundException) { pp = ((FileAbstractLayer)EnvironmentContext.FileAbstractLayerImpl).GetPhysicalPath(fileName); } var expandPP = Path.GetFullPath(Environment.ExpandEnvironmentVariables(pp)); var outputPath = Path.GetFullPath(_context.BuildOutputFolder); if (expandPP.Length > outputPath.Length && (expandPP[outputPath.Length] == '\\' || expandPP[outputPath.Length] == '/') && FilePathComparer.OSPlatformSensitiveStringComparer.Equals(outputPath, expandPP.Remove(outputPath.Length))) { return null; } else { return pp; } } private void AppendGlobalMetadata(IDictionary<string, object> model) { if (_globalVariables == null) { return; } if (model.ContainsKey(GlobalVariableKey)) { Logger.LogWarning($"Data model contains key {GlobalVariableKey}, {GlobalVariableKey} is to keep system level global metadata and is not allowed to overwrite. The {GlobalVariableKey} property inside data model will be ignored."); } model[GlobalVariableKey] = new Dictionary<string, object>(_globalVariables); } private static IDictionary<string, object> ConvertObjectToDictionary(object model) { if (model is IDictionary<string, object> dictionary) { return dictionary; } if (!(ConvertToObjectHelper.ConvertStrongTypeToObject(model) is IDictionary<string, object> objectModel)) { throw new ArgumentException("Only object model is supported for template transformation."); } return objectModel; } private static string ExportModel(object model, string modelFileRelativePath, ExportSettings settings) { if (model == null) { return null; } var outputFolder = settings.OutputFolder ?? string.Empty; string modelPath; try { modelPath = Path.GetFullPath(Path.Combine(outputFolder, settings.PathRewriter(modelFileRelativePath))); } catch (PathTooLongException) { modelPath = Path.GetFullPath(Path.Combine(outputFolder, Path.GetRandomFileName())); } JsonUtility.Serialize(modelPath, model); return StringExtension.ToDisplayPath(modelPath); } private void TransformDocument(string result, string extension, IDocumentBuildContext context, string destFilePath, ManifestItem manifestItem, out List<XRefDetails> unresolvedXRefs) { Task<byte[]> hashTask; unresolvedXRefs = new List<XRefDetails>(); using (var stream = EnvironmentContext.FileAbstractLayer.Create(destFilePath).WithSha256Hash(out hashTask)) { using var sw = new StreamWriter(stream); if (extension.Equals(".html", StringComparison.OrdinalIgnoreCase)) { TransformHtml(context, result, manifestItem.SourceRelativePath, destFilePath, sw, out unresolvedXRefs); } else { sw.Write(result); } } var ofi = new OutputFileInfo { RelativePath = destFilePath, LinkToPath = GetLinkToPath(destFilePath), Hash = Convert.ToBase64String(hashTask.Result) }; manifestItem.OutputFiles.Add(extension, ofi); } private void TransformHtml(IDocumentBuildContext context, string html, string sourceFilePath, string destFilePath, StreamWriter outputWriter, out List<XRefDetails> unresolvedXRefs) { // Update href and xref HtmlDocument document = new HtmlDocument(); document.LoadHtml(html); unresolvedXRefs = new List<XRefDetails>(); TransformXrefInHtml(context, sourceFilePath, destFilePath, document.DocumentNode, unresolvedXRefs); TransformLinkInHtml(context, sourceFilePath, destFilePath, document.DocumentNode); document.Save(outputWriter); } private void TransformXrefInHtml(IDocumentBuildContext context, string sourceFilePath, string destFilePath, HtmlNode node, List<XRefDetails> unresolvedXRefs) { var xrefLinkNodes = node.SelectNodes("//a[starts-with(@href, 'xref:')]"); if (xrefLinkNodes != null) { foreach (var xref in xrefLinkNodes) { TransformXrefLink(xref, context); } } var xrefNodes = node.SelectNodes("//xref"); var hasResolved = false; if (xrefNodes != null) { foreach (var xref in xrefNodes) { var (resolved, warn) = UpdateXref(xref, context, Constants.DefaultLanguage, out var xrefDetails); if (warn) { unresolvedXRefs.Add(xrefDetails); } hasResolved = hasResolved || resolved; } } if (hasResolved) { // transform again as the resolved content may also contain xref to resolve TransformXrefInHtml(context, sourceFilePath, destFilePath, node, unresolvedXRefs); } } private void TransformLinkInHtml(IDocumentBuildContext context, string sourceFilePath, string destFilePath, HtmlNode node) { var srcNodes = node.SelectNodes("//*/@src"); if (srcNodes != null) { foreach (var link in srcNodes) { UpdateHref(link, "src", context, sourceFilePath, destFilePath); } } var hrefNodes = node.SelectNodes("//*/@href"); if (hrefNodes != null) { foreach (var link in hrefNodes) { UpdateHref(link, "href", context, sourceFilePath, destFilePath); } } } private static void TransformXrefLink(HtmlNode node, IDocumentBuildContext context) { var convertedNode = XRefDetails.ConvertXrefLinkNodeToXrefNode(node); node.ParentNode.ReplaceChild(convertedNode, node); } private (bool resolved, bool warn) UpdateXref(HtmlNode node, IDocumentBuildContext context, string language, out XRefDetails xref) { xref = XRefDetails.From(node); XRefSpec xrefSpec = null; if (!string.IsNullOrEmpty(xref.Uid)) { // Resolve external xref map first, and then internal xref map. // Internal one overrides external one xrefSpec = context.GetXrefSpec(HttpUtility.HtmlDecode(xref.Uid)); xref.ApplyXrefSpec(xrefSpec); } var renderer = xref.TemplatePath == null ? null : _rendererLoader.Load(xref.TemplatePath); var (convertedNode, resolved) = xref.ConvertToHtmlNode(language, renderer); node.ParentNode.ReplaceChild(convertedNode, node); var warn = xrefSpec == null && xref.ThrowIfNotResolved; return (resolved, warn); } private void UpdateHref(HtmlNode link, string attribute, IDocumentBuildContext context, string sourceFilePath, string destFilePath) { var originalHref = link.GetAttributeValue(attribute, null); var path = UriUtility.GetPath(originalHref); var anchorFromNode = link.GetAttributeValue("anchor", null); var segments = anchorFromNode ?? UriUtility.GetQueryStringAndFragment(originalHref); link.Attributes.Remove("anchor"); if (RelativePath.TryParse(path) == null) { if (!string.IsNullOrEmpty(anchorFromNode)) { link.SetAttributeValue(attribute, originalHref + anchorFromNode); } return; } var fli = FileLinkInfo.Create(sourceFilePath, destFilePath, path, context); // fragment and query in original href takes precedence over the one from hrefGenerator var href = _settings.HrefGenerator?.GenerateHref(fli); link.SetAttributeValue( attribute, href == null ? fli.Href + segments : UriUtility.MergeHref(href, segments)); } } }
using System; using System.Collections.Generic; using System.Linq; using SourceCode.Clay; using Xunit; using crypt = System.Security.Cryptography; namespace SourceCode.Chasm.Tests { public static class TreeNodeMapTests { private static readonly crypt.SHA1 s_hasher = crypt.SHA1.Create(); private static readonly TreeNode s_node0 = new TreeNode("Node0", NodeKind.Tree, s_hasher.HashData("Node0")); private static readonly TreeNode s_blob0 = new TreeNode("Node0", NodeKind.Blob, s_hasher.HashData("Blob0")); private static readonly TreeNode s_node1 = new TreeNode("Node1", NodeKind.Blob, s_hasher.HashData("Node1")); private static readonly TreeNode s_node2 = new TreeNode("Node2", NodeKind.Tree, s_hasher.HashData("Node2")); private static readonly TreeNode s_node3 = new TreeNode("Node3", NodeKind.Blob, s_hasher.HashData("Node3")); private static void AssertEmpty(TreeNodeMap tree) { Assert.Empty(tree); Assert.Equal(TreeNodeMap.Empty, tree); // By design Assert.Equal(TreeNodeMap.Empty.GetHashCode(), tree.GetHashCode()); Assert.Empty(tree.Keys); Assert.Throws<IndexOutOfRangeException>(() => tree[0]); Assert.Throws<KeyNotFoundException>(() => tree["x"]); Assert.False(tree.TryGetValue("x", out _)); Assert.False(tree.TryGetValue("x", NodeKind.Blob, out _)); Assert.False(tree.Equals(new object())); Assert.Contains("Count: 0", tree.ToString()); Assert.Equal(-1, tree.IndexOf(Guid.NewGuid().ToString())); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Empty() { var noData = new TreeNodeMap(); AssertEmpty(noData); var nullData = new TreeNodeMap(null); AssertEmpty(nullData); var collData = new TreeNodeMap((IList<TreeNode>)null); AssertEmpty(collData); var emptyData = new TreeNodeMap(Array.Empty<TreeNode>()); AssertEmpty(emptyData); Assert.Empty(TreeNodeMap.Empty); Assert.Equal(default, TreeNodeMap.Empty); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Sorting() { TreeNode[] nodes = new[] { s_node0, s_node1 }; var tree0 = new TreeNodeMap(nodes.OrderBy(n => n.Sha1).ToArray()); var tree1 = new TreeNodeMap(nodes.OrderByDescending(n => n.Sha1).ToList()); // ICollection<T> Assert.Equal(tree0[0], tree1[0]); Assert.Equal(tree0[1], tree1[1]); Assert.True(tree1[s_node0.Name] == s_node0); Assert.True(tree1[s_node1.Name] == s_node1); Assert.False(tree1.ContainsKey("x")); Assert.True(tree1.ContainsKey(s_node0.Name)); Assert.True(tree1.ContainsKey(s_node1.Name)); Assert.False(tree1.TryGetValue("x", out _)); Assert.True(tree1.TryGetValue(s_node0.Name, out TreeNode v20) && v20 == s_node0); Assert.True(tree1.TryGetValue(s_node1.Name, out TreeNode v21) && v21 == s_node1); Assert.False(tree1.TryGetValue(s_node0.Name, NodeKind.Blob, out _)); Assert.True(tree1.TryGetValue(s_node0.Name, s_node0.Kind, out _)); nodes = new[] { s_node0, s_node1, s_node2 }; tree0 = new TreeNodeMap(nodes.OrderBy(n => n.Sha1).ToArray()); tree1 = new TreeNodeMap(nodes.OrderByDescending(n => n.Sha1).ToList()); // ICollection<T> Assert.True(tree1[s_node0.Name] == s_node0); Assert.True(tree1[s_node1.Name] == s_node1); Assert.True(tree1[s_node2.Name] == s_node2); Assert.False(tree1.ContainsKey("x")); Assert.True(tree1.ContainsKey(s_node0.Name)); Assert.True(tree1.ContainsKey(s_node1.Name)); Assert.True(tree1.ContainsKey(s_node2.Name)); Assert.False(tree1.TryGetValue("x", out _)); Assert.True(tree1.TryGetValue(s_node0.Name, out TreeNode v30) && v30 == s_node0); Assert.True(tree1.TryGetValue(s_node1.Name, out TreeNode v31) && v31 == s_node1); Assert.True(tree1.TryGetValue(s_node2.Name, out TreeNode v32) && v32 == s_node2); Assert.Equal(tree0[0], tree1[0]); Assert.Equal(tree0[1], tree1[1]); Assert.Equal(tree0[2], tree1[2]); nodes = new[] { s_node0, s_node1, s_node2, s_node3 }; tree0 = new TreeNodeMap(nodes.OrderBy(n => n.Sha1).ToArray()); tree1 = new TreeNodeMap(nodes.OrderByDescending(n => n.Sha1).ToList()); // ICollection<T> Assert.True(tree1[s_node0.Name] == s_node0); Assert.True(tree1[s_node1.Name] == s_node1); Assert.True(tree1[s_node2.Name] == s_node2); Assert.True(tree1[s_node3.Name] == s_node3); Assert.False(tree1.ContainsKey("x")); Assert.True(tree1.ContainsKey(s_node0.Name)); Assert.True(tree1.ContainsKey(s_node1.Name)); Assert.True(tree1.ContainsKey(s_node2.Name)); Assert.True(tree1.ContainsKey(s_node3.Name)); Assert.False(tree1.TryGetValue("x", out _)); Assert.True(tree1.TryGetValue(s_node0.Name, out TreeNode v40) && v40 == s_node0); Assert.True(tree1.TryGetValue(s_node1.Name, out TreeNode v41) && v41 == s_node1); Assert.True(tree1.TryGetValue(s_node2.Name, out TreeNode v42) && v42 == s_node2); Assert.True(tree1.TryGetValue(s_node3.Name, out TreeNode v43) && v43 == s_node3); Assert.Equal(tree0[0], tree1[0]); Assert.Equal(tree0[1], tree1[1]); Assert.Equal(tree0[2], tree1[2]); Assert.Equal(tree0[3], tree1[3]); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Duplicate_Full_2() { TreeNode[] nodes = new[] { s_node0, s_node0 }; var tree = new TreeNodeMap(nodes); Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, s_node0)); tree = new TreeNodeMap(nodes.ToList()); // ICollection<T> Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, s_node0)); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Duplicate_Full_3() { TreeNode[] nodes = new[] { s_node0, s_node1, s_node0 }; // Shuffled var tree = new TreeNodeMap(nodes); Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, s_node0), n => Assert.Equal(n, s_node1)); tree = new TreeNodeMap(nodes.ToList()); // ICollection<T> Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, s_node0), n => Assert.Equal(n, s_node1)); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Duplicate_Full_2_Exception() { // Arrange TreeNode[] nodes = new[] { s_node0, s_blob0 }; // Shuffled // Action ArgumentException ex = Assert.Throws<ArgumentException>(() => new TreeNodeMap(nodes)); // Assert Assert.Contains(s_node0.Name, ex.Message); Assert.Contains(s_node0.Sha1.ToString(), ex.Message); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Duplicate_Full_3_Exception() { // Arrange TreeNode[] nodes = new[] { s_node0, s_blob0, s_node1 }; // Shuffled // Action ArgumentException ex = Assert.Throws<ArgumentException>(() => new TreeNodeMap(nodes)); // Assert Assert.Contains(s_node0.Name, ex.Message); Assert.Contains(s_node0.Sha1.ToString(), ex.Message); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Duplicate_Full_4() { TreeNode[] nodes = new[] { s_node0, s_node2, s_node1, s_node0 }; // Shuffled var tree = new TreeNodeMap(nodes); Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, s_node0), n => Assert.Equal(n, s_node1), n => Assert.Equal(n, s_node2)); tree = new TreeNodeMap(nodes.ToList()); // ICollection<T> Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, s_node0), n => Assert.Equal(n, s_node1), n => Assert.Equal(n, s_node2)); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Duplicate_Full_N() { TreeNode[] nodes = new[] { s_node3, s_node1, s_node2, s_node0, s_node3, s_node0, s_node1, s_node0, s_node1, s_node2, s_node0, s_node3 }; // Shuffled var tree = new TreeNodeMap(nodes); Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, s_node0), n => Assert.Equal(n, s_node1), n => Assert.Equal(n, s_node2), n => Assert.Equal(n, s_node3)); tree = new TreeNodeMap(nodes.ToList()); // ICollection<T> Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, s_node0), n => Assert.Equal(n, s_node1), n => Assert.Equal(n, s_node2), n => Assert.Equal(n, s_node3)); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Duplicate_Name() { TreeNode[] nodes = new[] { new TreeNode(s_node0.Name, NodeKind.Tree, s_node1.Sha1), s_node0 }; // Reversed Assert.Throws<ArgumentException>(() => new TreeNodeMap(nodes)); Assert.Throws<ArgumentException>(() => new TreeNodeMap(nodes.ToList())); // ICollection<T> } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Duplicate_Sha1() { TreeNode[] nodes = new[] { new TreeNode(s_node1.Name, NodeKind.Tree, s_node0.Sha1), s_node0 }; // Reversed var tree0 = new TreeNodeMap(nodes); Assert.Collection<TreeNode>(tree0, n => Assert.Equal(n, s_node0), n => Assert.Equal(n, nodes[0])); tree0 = new TreeNodeMap(nodes.ToList()); // ICollection<T> Assert.Collection<TreeNode>(tree0, n => Assert.Equal(n, s_node0), n => Assert.Equal(n, nodes[0])); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Equality() { var expected = new TreeNodeMap(new[] { new TreeNode("c1", NodeKind.Blob, s_hasher.HashData("c1")), new TreeNode("c2", NodeKind.Tree, s_hasher.HashData("c2")) }); var node3 = new TreeNode("c3", NodeKind.Tree, s_hasher.HashData("c3")); // Equal TreeNodeMap actual = new TreeNodeMap().Merge(expected); Assert.Equal(expected, actual); Assert.Equal(expected.GetHashCode(), actual.GetHashCode()); Assert.True(actual.Equals((object)expected)); Assert.True(expected == actual); Assert.False(expected != actual); // Less Nodes actual = new TreeNodeMap().Add(expected[0]); Assert.NotEqual(expected, actual); Assert.NotEqual(expected.GetHashCode(), actual.GetHashCode()); Assert.False(actual.Equals((object)expected)); Assert.False(expected == actual); Assert.True(expected != actual); // More Nodes actual = new TreeNodeMap().Merge(expected).Add(node3); Assert.NotEqual(expected, actual); Assert.NotEqual(expected.GetHashCode(), actual.GetHashCode()); Assert.False(actual.Equals((object)expected)); Assert.False(expected == actual); Assert.True(expected != actual); // Different Nodes actual = new TreeNodeMap().Add(expected[0]).Add(node3); Assert.NotEqual(expected, actual); // hashcode is the same (node count) Assert.False(actual.Equals((object)expected)); Assert.False(expected == actual); Assert.True(expected != actual); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_IndexOf() { // Arrange var actual = new TreeNodeMap(new[] { s_node0, s_node1 }); // Action/Assert Assert.Equal(-1, actual.IndexOf(null)); Assert.True(actual.IndexOf(Guid.NewGuid().ToString()) < 0); Assert.Equal(0, actual.IndexOf(s_node0.Name)); Assert.Equal(1, actual.IndexOf(s_node1.Name)); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Merge_Empty() { var emptyTreeNodeMap = new TreeNodeMap(); var node = new TreeNode("b", NodeKind.Blob, s_hasher.HashData("Test1")); var tree = new TreeNodeMap(node); // TreeNodeMap TreeNodeMap merged = tree.Merge(emptyTreeNodeMap); Assert.Equal(tree, merged); merged = emptyTreeNodeMap.Merge(tree); Assert.Equal(tree, merged); // ICollection merged = tree.Merge(Array.Empty<TreeNode>()); Assert.Equal(tree, merged); merged = emptyTreeNodeMap.Merge(tree.Values.ToArray()); Assert.Equal(tree, merged); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Merge_Null() { // Arrange var tree = new TreeNodeMap(s_node0); // Action TreeNodeMap merged = tree.Merge(null); // Assert Assert.Equal(tree, merged); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Merge_Single() { var tree = new TreeNodeMap(); tree = tree.Add(new TreeNode("b", NodeKind.Blob, s_hasher.HashData("Test1"))); tree = tree.Add(new TreeNode("a", NodeKind.Tree, s_hasher.HashData("Test2"))); tree = tree.Add(new TreeNode("c", NodeKind.Blob, s_hasher.HashData("Test3"))); tree = tree.Add(new TreeNode("d", NodeKind.Tree, s_hasher.HashData("Test4"))); tree = tree.Add(new TreeNode("g", NodeKind.Blob, s_hasher.HashData("Test5"))); tree = tree.Add(new TreeNode("e", NodeKind.Tree, s_hasher.HashData("Test6"))); tree = tree.Add(new TreeNode("f", NodeKind.Blob, s_hasher.HashData("Test7"))); string prev = tree.Keys.First(); foreach (string cur in tree.Keys.Skip(1)) { Assert.True(string.CompareOrdinal(cur, prev) > 0); prev = cur; } } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Merge_Single_Exist() { // Arrange var tree = new TreeNodeMap(); string expectedName = Guid.NewGuid().ToString(); NodeKind expectedKind = NodeKind.Tree; Sha1 expectedSha1 = s_hasher.HashData(Guid.NewGuid().ToString()); tree = tree.Add(new TreeNode(expectedName, NodeKind.Blob, s_hasher.HashData("Test1"))); // Action TreeNodeMap actual = tree.Add(new TreeNode(expectedName, expectedKind, expectedSha1)); TreeNode actualNode = actual[expectedName]; // Assert Assert.Equal(expectedName, actualNode.Name); Assert.Equal(expectedKind, actualNode.Kind); Assert.Equal(expectedSha1, actualNode.Sha1); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Merge_TreeNodeMap() { var tree1 = new TreeNodeMap(); tree1 = tree1.Add(new TreeNode("d", NodeKind.Tree, s_hasher.HashData("Test4"))); tree1 = tree1.Add(new TreeNode("e", NodeKind.Tree, s_hasher.HashData("Test5"))); tree1 = tree1.Add(new TreeNode("f", NodeKind.Blob, s_hasher.HashData("Test6"))); tree1 = tree1.Add(new TreeNode("g", NodeKind.Blob, s_hasher.HashData("Test7"))); var tree2 = new TreeNodeMap(); tree2 = tree2.Add(new TreeNode("a", NodeKind.Tree, s_hasher.HashData("Test1"))); tree2 = tree2.Add(new TreeNode("b", NodeKind.Blob, s_hasher.HashData("Test2"))); tree2 = tree2.Add(new TreeNode("c", NodeKind.Blob, s_hasher.HashData("Test3"))); tree2 = tree2.Add(new TreeNode("d", NodeKind.Tree, s_hasher.HashData("Test4 Replace"))); tree2 = tree2.Add(new TreeNode("g", NodeKind.Blob, s_hasher.HashData("Test5 Replace"))); tree2 = tree2.Add(new TreeNode("q", NodeKind.Tree, s_hasher.HashData("Test8"))); tree2 = tree2.Add(new TreeNode("r", NodeKind.Blob, s_hasher.HashData("Test9"))); TreeNodeMap tree3 = tree1.Merge(tree2); Assert.Equal(9, tree3.Count); Assert.Equal("a", tree3[0].Name); Assert.Equal("b", tree3[1].Name); Assert.Equal("c", tree3[2].Name); Assert.Equal("d", tree3[3].Name); Assert.Equal("e", tree3[4].Name); Assert.Equal("f", tree3[5].Name); Assert.Equal("g", tree3[6].Name); Assert.Equal("q", tree3[7].Name); Assert.Equal("r", tree3[8].Name); Assert.Equal(tree2[0].Sha1, tree3[0].Sha1); Assert.Equal(tree2[1].Sha1, tree3[1].Sha1); Assert.Equal(tree2[2].Sha1, tree3[2].Sha1); Assert.Equal(tree2[3].Sha1, tree3[3].Sha1); Assert.Equal(tree1[1].Sha1, tree3[4].Sha1); Assert.Equal(tree1[2].Sha1, tree3[5].Sha1); Assert.Equal(tree2[4].Sha1, tree3[6].Sha1); Assert.Equal(tree2[5].Sha1, tree3[7].Sha1); Assert.Equal(tree2[6].Sha1, tree3[8].Sha1); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Merge_Collection() { var tree1 = new TreeNodeMap(); tree1 = tree1.Add(new TreeNode("d", NodeKind.Tree, s_hasher.HashData("Test4"))); tree1 = tree1.Add(new TreeNode("e", NodeKind.Tree, s_hasher.HashData("Test5"))); tree1 = tree1.Add(new TreeNode("f", NodeKind.Blob, s_hasher.HashData("Test6"))); tree1 = tree1.Add(new TreeNode("g", NodeKind.Blob, s_hasher.HashData("Test7"))); TreeNode[] tree2 = new[] { new TreeNode("c", NodeKind.Blob, s_hasher.HashData("Test3")), new TreeNode("a", NodeKind.Tree, s_hasher.HashData("Test1")), new TreeNode("b", NodeKind.Blob, s_hasher.HashData("Test2")), new TreeNode("d", NodeKind.Tree, s_hasher.HashData("Test4 Replace")), new TreeNode("g", NodeKind.Blob, s_hasher.HashData("Test5 Replace")), new TreeNode("q", NodeKind.Tree, s_hasher.HashData("Test8")), new TreeNode("r", NodeKind.Blob, s_hasher.HashData("Test9")), }; TreeNodeMap tree3 = tree1.Merge(tree2); Assert.Equal(9, tree3.Count); Assert.Equal("a", tree3[0].Name); Assert.Equal("b", tree3[1].Name); Assert.Equal("c", tree3[2].Name); Assert.Equal("d", tree3[3].Name); Assert.Equal("e", tree3[4].Name); Assert.Equal("f", tree3[5].Name); Assert.Equal("g", tree3[6].Name); Assert.Equal("q", tree3[7].Name); Assert.Equal("r", tree3[8].Name); Assert.Equal(tree2[1].Sha1, tree3[0].Sha1); Assert.Equal(tree2[2].Sha1, tree3[1].Sha1); Assert.Equal(tree2[0].Sha1, tree3[2].Sha1); Assert.Equal(tree2[3].Sha1, tree3[3].Sha1); Assert.Equal(tree1[1].Sha1, tree3[4].Sha1); Assert.Equal(tree1[2].Sha1, tree3[5].Sha1); Assert.Equal(tree2[4].Sha1, tree3[6].Sha1); Assert.Equal(tree2[5].Sha1, tree3[7].Sha1); Assert.Equal(tree2[6].Sha1, tree3[8].Sha1); TreeNode[] dupes = new[] { new TreeNode(tree2[0].Name, tree2[0].Kind, tree2[1].Sha1), new TreeNode(tree2[1].Name, tree2[1].Kind, tree2[2].Sha1), new TreeNode(tree2[2].Name, tree2[2].Kind, tree2[3].Sha1), new TreeNode(tree2[3].Name, tree2[3].Kind, tree2[0].Sha1) }; tree3 = tree3.Merge(dupes); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Delete() { var tree = new TreeNodeMap ( new TreeNode("a", NodeKind.Blob, s_hasher.HashData("a")), new TreeNode("b", NodeKind.Blob, s_hasher.HashData("b")), new TreeNode("c", NodeKind.Blob, s_hasher.HashData("c")) ); TreeNodeMap removed = tree.Delete("a"); Assert.Equal(2, removed.Count); Assert.Equal("b", removed[0].Name); Assert.Equal("c", removed[1].Name); removed = tree.Delete("b"); Assert.Equal(2, removed.Count); Assert.Equal("a", removed[0].Name); Assert.Equal("c", removed[1].Name); removed = tree.Delete("c"); Assert.Equal(2, removed.Count); Assert.Equal("a", removed[0].Name); Assert.Equal("b", removed[1].Name); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_Delete_Predicate() { var tree = new TreeNodeMap ( new TreeNode("a", NodeKind.Blob, s_hasher.HashData("a")), new TreeNode("b", NodeKind.Blob, s_hasher.HashData("b")), new TreeNode("c", NodeKind.Blob, s_hasher.HashData("c")) ); var set = new HashSet<string>(StringComparer.Ordinal) { "a", "b", "d" }; TreeNodeMap removed = tree.Delete(set.Contains); Assert.Single(removed); Assert.Equal("c", removed[0].Name); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_IReadOnlyDictionary_Empty_GetEnumerator() { // Arrange var tree = new TreeNodeMap(); var readOnlyDictionary = tree as IReadOnlyDictionary<string, TreeNode>; // Action IEnumerator<KeyValuePair<string, TreeNode>> enumerator = readOnlyDictionary.GetEnumerator(); // Assert Assert.False(enumerator.MoveNext()); KeyValuePair<string, TreeNode> current = enumerator.Current; Assert.Null(current.Key); Assert.Equal(TreeNode.Empty, current.Value); } [Trait("Type", "Unit")] [Fact] public static void TreeNodeMap_IReadOnlyDictionary_GetEnumerator() { // Arrange TreeNode[] nodes = new[] { s_node0, s_node1 }; var tree = new TreeNodeMap(nodes); var readOnlyDictionary = tree as IReadOnlyDictionary<string, TreeNode>; // Action IEnumerator<KeyValuePair<string, TreeNode>> enumerator = readOnlyDictionary.GetEnumerator(); // Assert Assert.True(enumerator.MoveNext()); Assert.Equal(s_node0, enumerator.Current.Value); Assert.True(enumerator.MoveNext()); Assert.Equal(s_node1, enumerator.Current.Value); Assert.False(enumerator.MoveNext()); Assert.Equal(s_node1, enumerator.Current.Value); } } }
/* * Copyright 2007-2019 JetBrains s.r.o. * * 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. */ /* MIT License Copyright (c) 2016 JetBrains http://www.jetbrains.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. */ #pragma warning disable 1591 // ReSharper disable UnusedMember.Global // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable IntroduceOptionalParameters.Global // ReSharper disable MemberCanBeProtected.Global // ReSharper disable InconsistentNaming namespace JetBrains.TeamCity.ServiceMessages { using System; /// <summary> /// Indicates that the value of the marked element could be <c>null</c> sometimes, /// so the check for <c>null</c> is necessary before its usage. /// </summary> /// <example><code> /// [CanBeNull] object Test() => null; /// /// void UseTest() { /// var p = Test(); /// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException' /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] internal sealed class CanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the value of the marked element could never be <c>null</c>. /// </summary> /// <example><code> /// [NotNull] object Foo() { /// return null; // Warning: Possible 'null' assignment /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] internal sealed class NotNullAttribute : Attribute { } /// <summary> /// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property /// or of the Lazy.Value property can never be null. /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field)] internal sealed class ItemNotNullAttribute : Attribute { } /// <summary> /// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property /// or of the Lazy.Value property can be null. /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field)] internal sealed class ItemCanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the marked method builds string by format pattern and (optional) arguments. /// Parameter, which contains format string, should be given in constructor. The format string /// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form. /// </summary> /// <example><code> /// [StringFormatMethod("message")] /// void ShowError(string message, params object[] args) { /* do something */ } /// /// void Foo() { /// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string /// } /// </code></example> [AttributeUsage( AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Delegate)] internal sealed class StringFormatMethodAttribute : Attribute { /// <param name="formatParameterName"> /// Specifies which parameter of an annotated method should be treated as format-string /// </param> public StringFormatMethodAttribute([NotNull] string formatParameterName) { FormatParameterName = formatParameterName; } [NotNull] public string FormatParameterName { get; private set; } } /// <summary> /// For a parameter that is expected to be one of the limited set of values. /// Specify fields of which type should be used as values for this parameter. /// </summary> [AttributeUsage( AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] internal sealed class ValueProviderAttribute : Attribute { public ValueProviderAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } /// <summary> /// Indicates that the function argument should be string literal and match one /// of the parameters of the caller function. For example, ReSharper annotates /// the parameter of <see cref="System.ArgumentNullException"/>. /// </summary> /// <example><code> /// void Foo(string param) { /// if (param == null) /// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class InvokerParameterNameAttribute : Attribute { } /// <summary> /// Indicates that the method is contained in a type that implements /// <c>System.ComponentModel.INotifyPropertyChanged</c> interface and this method /// is used to notify that some property value changed. /// </summary> /// <remarks> /// The method should be non-static and conform to one of the supported signatures: /// <list> /// <item><c>NotifyChanged(string)</c></item> /// <item><c>NotifyChanged(params string[])</c></item> /// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item> /// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item> /// <item><c>SetProperty{T}(ref T, T, string)</c></item> /// </list> /// </remarks> /// <example><code> /// public class Foo : INotifyPropertyChanged { /// public event PropertyChangedEventHandler PropertyChanged; /// /// [NotifyPropertyChangedInvocator] /// protected virtual void NotifyChanged(string propertyName) { ... } /// /// string _name; /// /// public string Name { /// get { return _name; } /// set { _name = value; NotifyChanged("LastName"); /* Warning */ } /// } /// } /// </code> /// Examples of generated notifications: /// <list> /// <item><c>NotifyChanged("Property")</c></item> /// <item><c>NotifyChanged(() =&gt; Property)</c></item> /// <item><c>NotifyChanged((VM x) =&gt; x.Property)</c></item> /// <item><c>SetProperty(ref myField, value, "Property")</c></item> /// </list> /// </example> [AttributeUsage(AttributeTargets.Method)] internal sealed class NotifyPropertyChangedInvocatorAttribute : Attribute { public NotifyPropertyChangedInvocatorAttribute() { } public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName) { ParameterName = parameterName; } [CanBeNull] public string ParameterName { get; private set; } } /// <summary> /// Describes dependency between method input and output. /// </summary> /// <syntax> /// <p>Function Definition Table syntax:</p> /// <list> /// <item>FDT ::= FDTRow [;FDTRow]*</item> /// <item>FDTRow ::= Input =&gt; Output | Output &lt;= Input</item> /// <item>Input ::= ParameterName: Value [, Input]*</item> /// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item> /// <item>Value ::= true | false | null | notnull | canbenull</item> /// </list> /// If method has single input parameter, it's name could be omitted.<br/> /// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same) for method output /// means that the methos doesn't return normally (throws or terminates the process).<br/> /// Value <c>canbenull</c> is only applicable for output parameters.<br/> /// You can use multiple <c>[ContractAnnotation]</c> for each FDT row, or use single attribute /// with rows separated by semicolon. There is no notion of order rows, all rows are checked /// for applicability and applied per each program state tracked by R# analysis.<br/> /// </syntax> /// <examples><list> /// <item><code> /// [ContractAnnotation("=&gt; halt")] /// public void TerminationMethod() /// </code></item> /// <item><code> /// [ContractAnnotation("halt &lt;= condition: false")] /// public void Assert(bool condition, string text) // regular assertion method /// </code></item> /// <item><code> /// [ContractAnnotation("s:null =&gt; true")] /// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty() /// </code></item> /// <item><code> /// // A method that returns null if the parameter is null, /// // and not null if the parameter is not null /// [ContractAnnotation("null =&gt; null; notnull =&gt; notnull")] /// public object Transform(object data) /// </code></item> /// <item><code> /// [ContractAnnotation("=&gt; true, result: notnull; =&gt; false, result: null")] /// public bool TryParse(string s, out Person result) /// </code></item> /// </list></examples> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] internal sealed class ContractAnnotationAttribute : Attribute { public ContractAnnotationAttribute([NotNull] string contract) : this(contract, false) { } public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) { Contract = contract; ForceFullStates = forceFullStates; } [NotNull] public string Contract { get; private set; } public bool ForceFullStates { get; private set; } } /// <summary> /// Indicates that marked element should be localized or not. /// </summary> /// <example><code> /// [LocalizationRequiredAttribute(true)] /// class Foo { /// string str = "my string"; // Warning: Localizable string /// } /// </code></example> [AttributeUsage(AttributeTargets.All)] internal sealed class LocalizationRequiredAttribute : Attribute { public LocalizationRequiredAttribute() : this(true) { } public LocalizationRequiredAttribute(bool required) { Required = required; } public bool Required { get; private set; } } /// <summary> /// Indicates that the value of the marked type (or its derivatives) /// cannot be compared using '==' or '!=' operators and <c>Equals()</c> /// should be used instead. However, using '==' or '!=' for comparison /// with <c>null</c> is always permitted. /// </summary> /// <example><code> /// [CannotApplyEqualityOperator] /// class NoEquality { } /// /// class UsesNoEquality { /// void Test() { /// var ca1 = new NoEquality(); /// var ca2 = new NoEquality(); /// if (ca1 != null) { // OK /// bool condition = ca1 == ca2; // Warning /// } /// } /// } /// </code></example> [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)] internal sealed class CannotApplyEqualityOperatorAttribute : Attribute { } /// <summary> /// When applied to a target attribute, specifies a requirement for any type marked /// with the target attribute to implement or inherit specific type or types. /// </summary> /// <example><code> /// [BaseTypeRequired(typeof(IComponent)] // Specify requirement /// class ComponentAttribute : Attribute { } /// /// [Component] // ComponentAttribute requires implementing IComponent interface /// class MyComponent : IComponent { } /// </code></example> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [BaseTypeRequired(typeof(Attribute))] internal sealed class BaseTypeRequiredAttribute : Attribute { public BaseTypeRequiredAttribute([NotNull] Type baseType) { BaseType = baseType; } [NotNull] public Type BaseType { get; private set; } } /// <summary> /// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library), /// so this symbol will not be marked as unused (as well as by other usage inspections). /// </summary> [AttributeUsage(AttributeTargets.All)] internal sealed class UsedImplicitlyAttribute : Attribute { public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } public ImplicitUseKindFlags UseKindFlags { get; private set; } public ImplicitUseTargetFlags TargetFlags { get; private set; } } /// <summary> /// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes /// as unused (as well as by other usage inspections) /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter)] internal sealed class MeansImplicitUseAttribute : Attribute { public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; } [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; } } [Flags] internal enum ImplicitUseKindFlags { Default = Access | Assign | InstantiatedWithFixedConstructorSignature, /// <summary>Only entity marked with attribute considered used.</summary> Access = 1, /// <summary>Indicates implicit assignment to a member.</summary> Assign = 2, /// <summary> /// Indicates implicit instantiation of a type with fixed constructor signature. /// That means any unused constructor parameters won't be reported as such. /// </summary> InstantiatedWithFixedConstructorSignature = 4, /// <summary>Indicates implicit instantiation of a type.</summary> InstantiatedNoFixedConstructorSignature = 8, } /// <summary> /// Specify what is considered used implicitly when marked /// with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>. /// </summary> [Flags] internal enum ImplicitUseTargetFlags { Default = Itself, Itself = 1, /// <summary>Members of entity marked with attribute are considered used.</summary> Members = 2, /// <summary>Entity marked with attribute and all its members considered used.</summary> WithMembers = Itself | Members } /// <summary> /// This attribute is intended to mark publicly available API /// which should not be removed and so is treated as used. /// </summary> [MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)] internal sealed class PublicAPIAttribute : Attribute { public PublicAPIAttribute() { } public PublicAPIAttribute([NotNull] string comment) { Comment = comment; } [CanBeNull] public string Comment { get; private set; } } /// <summary> /// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack. /// If the parameter is a delegate, indicates that delegate is executed while the method is executed. /// If the parameter is an enumerable, indicates that it is enumerated while the method is executed. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class InstantHandleAttribute : Attribute { } /// <summary> /// Indicates that a method does not make any observable state changes. /// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>. /// </summary> /// <example><code> /// [Pure] int Multiply(int x, int y) => x * y; /// /// void M() { /// Multiply(123, 42); // Waring: Return value of pure method is not used /// } /// </code></example> [AttributeUsage(AttributeTargets.Method)] internal sealed class PureAttribute : Attribute { } /// <summary> /// Indicates that the return value of method invocation must be used. /// </summary> [AttributeUsage(AttributeTargets.Method)] internal sealed class MustUseReturnValueAttribute : Attribute { public MustUseReturnValueAttribute() { } public MustUseReturnValueAttribute([NotNull] string justification) { Justification = justification; } [CanBeNull] public string Justification { get; private set; } } /// <summary> /// Indicates the type member or parameter of some type, that should be used instead of all other ways /// to get the value that type. This annotation is useful when you have some "context" value evaluated /// and stored somewhere, meaning that all other ways to get this value must be consolidated with existing one. /// </summary> /// <example><code> /// class Foo { /// [ProvidesContext] IBarService _barService = ...; /// /// void ProcessNode(INode node) { /// DoSomething(node, node.GetGlobalServices().Bar); /// // ^ Warning: use value of '_barService' field /// } /// } /// </code></example> [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.GenericParameter)] internal sealed class ProvidesContextAttribute : Attribute { } /// <summary> /// Indicates that a parameter is a path to a file or a folder within a web project. /// Path can be relative or absolute, starting from web root (~). /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class PathReferenceAttribute : Attribute { public PathReferenceAttribute() { } public PathReferenceAttribute([NotNull, PathReference] string basePath) { BasePath = basePath; } [CanBeNull] public string BasePath { get; private set; } } /// <summary> /// An extension method marked with this attribute is processed by ReSharper code completion /// as a 'Source Template'. When extension method is completed over some expression, it's source code /// is automatically expanded like a template at call site. /// </summary> /// <remarks> /// Template method body can contain valid source code and/or special comments starting with '$'. /// Text inside these comments is added as source code when the template is applied. Template parameters /// can be used either as additional method parameters or as identifiers wrapped in two '$' signs. /// Use the <see cref="MacroAttribute"/> attribute to specify macros for parameters. /// </remarks> /// <example> /// In this example, the 'forEach' method is a source template available over all values /// of enumerable types, producing ordinary C# 'foreach' statement and placing caret inside block: /// <code> /// [SourceTemplate] /// public static void forEach&lt;T&gt;(this IEnumerable&lt;T&gt; xs) { /// foreach (var x in xs) { /// //$ $END$ /// } /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Method)] internal sealed class SourceTemplateAttribute : Attribute { } /// <summary> /// Allows specifying a macro for a parameter of a <see cref="SourceTemplateAttribute">source template</see>. /// </summary> /// <remarks> /// You can apply the attribute on the whole method or on any of its additional parameters. The macro expression /// is defined in the <see cref="MacroAttribute.Expression"/> property. When applied on a method, the target /// template parameter is defined in the <see cref="MacroAttribute.Target"/> property. To apply the macro silently /// for the parameter, set the <see cref="MacroAttribute.Editable"/> property value = -1. /// </remarks> /// <example> /// Applying the attribute on a source template method: /// <code> /// [SourceTemplate, Macro(Target = "item", Expression = "suggestVariableName()")] /// public static void forEach&lt;T&gt;(this IEnumerable&lt;T&gt; collection) { /// foreach (var item in collection) { /// //$ $END$ /// } /// } /// </code> /// Applying the attribute on a template method parameter: /// <code> /// [SourceTemplate] /// public static void something(this Entity x, [Macro(Expression = "guid()", Editable = -1)] string newguid) { /// /*$ var $x$Id = "$newguid$" + x.ToString(); /// x.DoSomething($x$Id); */ /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = true)] internal sealed class MacroAttribute : Attribute { /// <summary> /// Allows specifying a macro that will be executed for a <see cref="SourceTemplateAttribute">source template</see> /// parameter when the template is expanded. /// </summary> [CanBeNull] public string Expression { get; set; } /// <summary> /// Allows specifying which occurrence of the target parameter becomes editable when the template is deployed. /// </summary> /// <remarks> /// If the target parameter is used several times in the template, only one occurrence becomes editable; /// other occurrences are changed synchronously. To specify the zero-based index of the editable occurrence, /// use values >= 0. To make the parameter non-editable when the template is expanded, use -1. /// </remarks>> public int Editable { get; set; } /// <summary> /// Identifies the target parameter of a <see cref="SourceTemplateAttribute">source template</see> if the /// <see cref="MacroAttribute"/> is applied on a template method. /// </summary> [CanBeNull] public string Target { get; set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute { public AspMvcAreaMasterLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute { public AspMvcAreaPartialViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class AspMvcAreaViewLocationFormatAttribute : Attribute { public AspMvcAreaViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class AspMvcMasterLocationFormatAttribute : Attribute { public AspMvcMasterLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class AspMvcPartialViewLocationFormatAttribute : Attribute { public AspMvcPartialViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class AspMvcViewLocationFormatAttribute : Attribute { public AspMvcViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC action. If applied to a method, the MVC action name is calculated /// implicitly from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] internal sealed class AspMvcActionAttribute : Attribute { public AspMvcActionAttribute() { } public AspMvcActionAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC area. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcAreaAttribute : Attribute { public AspMvcAreaAttribute() { } public AspMvcAreaAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is /// an MVC controller. If applied to a method, the MVC controller name is calculated /// implicitly from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] internal sealed class AspMvcControllerAttribute : Attribute { public AspMvcControllerAttribute() { } public AspMvcControllerAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. Use this attribute /// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcMasterAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type. Use this attribute /// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, Object)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcModelTypeAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC /// partial view. If applied to a method, the MVC partial view name is calculated implicitly /// from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] internal sealed class AspMvcPartialViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] internal sealed class AspMvcSuppressViewErrorAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcDisplayTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcEditorTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC template. /// Use this attribute for custom wrappers similar to /// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component. If applied to a method, the MVC view name is calculated implicitly /// from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Controller.View(Object)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] internal sealed class AspMvcViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component name. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcViewComponentAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component view. If applied to a method, the MVC view component view name is default. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] internal sealed class AspMvcViewComponentViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. When applied to a parameter of an attribute, /// indicates that this parameter is an MVC action name. /// </summary> /// <example><code> /// [ActionName("Foo")] /// public ActionResult Login(string returnUrl) { /// ViewBag.ReturnUrl = Url.Action("Foo"); // OK /// return RedirectToAction("Bar"); // Error: Cannot resolve action /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] internal sealed class AspMvcActionSelectorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)] internal sealed class HtmlElementAttributesAttribute : Attribute { public HtmlElementAttributesAttribute() { } public HtmlElementAttributesAttribute([NotNull] string name) { Name = name; } [CanBeNull] public string Name { get; private set; } } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] internal sealed class HtmlAttributeValueAttribute : Attribute { public HtmlAttributeValueAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } /// <summary> /// Razor attribute. Indicates that a parameter or a method is a Razor section. /// Use this attribute for custom wrappers similar to /// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] internal sealed class RazorSectionAttribute : Attribute { } /// <summary> /// Indicates how method, constructor invocation or property access /// over collection type affects content of the collection. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] internal sealed class CollectionAccessAttribute : Attribute { public CollectionAccessAttribute(CollectionAccessType collectionAccessType) { CollectionAccessType = collectionAccessType; } public CollectionAccessType CollectionAccessType { get; private set; } } [Flags] internal enum CollectionAccessType { /// <summary>Method does not use or modify content of the collection.</summary> None = 0, /// <summary>Method only reads content of the collection but does not modify it.</summary> Read = 1, /// <summary>Method can change content of the collection but does not add new elements.</summary> ModifyExistingContent = 2, /// <summary>Method can add new elements to the collection.</summary> UpdatedContent = ModifyExistingContent | 4 } /// <summary> /// Indicates that the marked method is assertion method, i.e. it halts control flow if /// one of the conditions is satisfied. To set the condition, mark one of the parameters with /// <see cref="AssertionConditionAttribute"/> attribute. /// </summary> [AttributeUsage(AttributeTargets.Method)] internal sealed class AssertionMethodAttribute : Attribute { } /// <summary> /// Indicates the condition parameter of the assertion method. The method itself should be /// marked by <see cref="AssertionMethodAttribute"/> attribute. The mandatory argument of /// the attribute is the assertion type. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AssertionConditionAttribute : Attribute { public AssertionConditionAttribute(AssertionConditionType conditionType) { ConditionType = conditionType; } public AssertionConditionType ConditionType { get; private set; } } /// <summary> /// Specifies assertion type. If the assertion method argument satisfies the condition, /// then the execution continues. Otherwise, execution is assumed to be halted. /// </summary> internal enum AssertionConditionType { /// <summary>Marked parameter should be evaluated to true.</summary> IS_TRUE = 0, /// <summary>Marked parameter should be evaluated to false.</summary> IS_FALSE = 1, /// <summary>Marked parameter should be evaluated to null value.</summary> IS_NULL = 2, /// <summary>Marked parameter should be evaluated to not null value.</summary> IS_NOT_NULL = 3, } /// <summary> /// Indicates that the marked method unconditionally terminates control flow execution. /// For example, it could unconditionally throw exception. /// </summary> [Obsolete("Use [ContractAnnotation('=> halt')] instead")] [AttributeUsage(AttributeTargets.Method)] internal sealed class TerminatesProgramAttribute : Attribute { } /// <summary> /// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select, /// .Where). This annotation allows inference of [InstantHandle] annotation for parameters /// of delegate type by analyzing LINQ method chains. /// </summary> [AttributeUsage(AttributeTargets.Method)] internal sealed class LinqTunnelAttribute : Attribute { } /// <summary> /// Indicates that IEnumerable, passed as parameter, is not enumerated. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class NoEnumerationAttribute : Attribute { } /// <summary> /// Indicates that parameter is regular expression pattern. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class RegexPatternAttribute : Attribute { } /// <summary> /// Prevents the Member Reordering feature from tossing members of the marked class. /// </summary> /// <remarks> /// The attribute must be mentioned in your member reordering patterns /// </remarks> [AttributeUsage( AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum)] internal sealed class NoReorderAttribute : Attribute { } /// <summary> /// XAML attribute. Indicates the type that has <c>ItemsSource</c> property and should be treated /// as <c>ItemsControl</c>-derived type, to enable inner items <c>DataContext</c> type resolve. /// </summary> [AttributeUsage(AttributeTargets.Class)] internal sealed class XamlItemsControlAttribute : Attribute { } /// <summary> /// XAML attribute. Indicates the property of some <c>BindingBase</c>-derived type, that /// is used to bind some item of <c>ItemsControl</c>-derived type. This annotation will /// enable the <c>DataContext</c> type resolve for XAML bindings for such properties. /// </summary> /// <remarks> /// Property should have the tree ancestor of the <c>ItemsControl</c> type or /// marked with the <see cref="XamlItemsControlAttribute"/> attribute. /// </remarks> [AttributeUsage(AttributeTargets.Property)] internal sealed class XamlItemBindingOfItemsControlAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal sealed class AspChildControlTypeAttribute : Attribute { public AspChildControlTypeAttribute([NotNull] string tagName, [NotNull] Type controlType) { TagName = tagName; ControlType = controlType; } [NotNull] public string TagName { get; private set; } [NotNull] public Type ControlType { get; private set; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] internal sealed class AspDataFieldAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] internal sealed class AspDataFieldsAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] internal sealed class AspMethodPropertyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal sealed class AspRequiredAttributeAttribute : Attribute { public AspRequiredAttributeAttribute([NotNull] string attribute) { Attribute = attribute; } [NotNull] public string Attribute { get; private set; } } [AttributeUsage(AttributeTargets.Property)] internal sealed class AspTypePropertyAttribute : Attribute { public bool CreateConstructorReferences { get; private set; } public AspTypePropertyAttribute(bool createConstructorReferences) { CreateConstructorReferences = createConstructorReferences; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class RazorImportNamespaceAttribute : Attribute { public RazorImportNamespaceAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class RazorInjectionAttribute : Attribute { public RazorInjectionAttribute([NotNull] string type, [NotNull] string fieldName) { Type = type; FieldName = fieldName; } [NotNull] public string Type { get; private set; } [NotNull] public string FieldName { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class RazorDirectiveAttribute : Attribute { public RazorDirectiveAttribute([NotNull] string directive) { Directive = directive; } [NotNull] public string Directive { get; private set; } } [AttributeUsage(AttributeTargets.Method)] internal sealed class RazorHelperCommonAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] internal sealed class RazorLayoutAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class RazorWriteLiteralMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class RazorWriteMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class RazorWriteMethodParameterAttribute : Attribute { } }
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 WingtipSearchAppWeb { 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 } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * 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.IO; using System.Security.Cryptography; using System.Text; using System.Threading; using MindTouch.Extensions.Time; using MindTouch.Tasking; using MindTouch.Text; namespace MindTouch.IO { using Yield = IEnumerator<IYield>; /// <summary> /// A set of static and extension methods to simplify common stream opreations and add <see cref="Result"/> based asynchronous operations /// </summary> public static class StreamUtil { //--- Constants --- /// <summary> /// Common size for internal byte buffer used for Stream operations /// </summary> public const int BUFFER_SIZE = 16 * 1024; private static readonly TimeSpan READ_TIMEOUT = TimeSpan.FromSeconds(30); //--- Class Fields --- private static readonly Random Randomizer = new Random(); private static log4net.ILog _log = log4net.LogManager.GetLogger(typeof(StreamUtil)); //--- Extension Methods --- /// <summary> /// Write a string to <see cref="Stream"/> /// </summary> /// <param name="stream">Target <see cref="Stream"/></param> /// <param name="encoding">Encoding to use to convert the string to bytes</param> /// <param name="text">Regular string or composite format string to write to the <see cref="Stream"/></param> /// <param name="args">An System.Object array containing zero or more objects to format.</param> public static void Write(this Stream stream, Encoding encoding, string text, params object[] args) { const int bufferSize = BUFFER_SIZE / sizeof(char); if(text.Length > bufferSize) { // to avoid a allocating a byte array of greater than 64k, we chunk our string writing here if(args.Length != 0) { text = string.Format(text, args); } var length = text.Length; var idx = 0; var buffer = new char[bufferSize]; while(true) { var size = Math.Min(bufferSize, length - idx); if(size == 0) { break; } text.CopyTo(idx, buffer, 0, size); stream.Write(encoding.GetBytes(buffer, 0, size)); idx += size; } } else { if(args.Length == 0) { stream.Write(encoding.GetBytes(text)); } else { stream.Write(encoding.GetBytes(string.Format(text, args))); } } } /// <summary> /// Write an entire buffer to a <see cref="Stream"/> /// </summary> /// <param name="stream">Target <see cref="Stream"/></param> /// <param name="buffer">An array of bytes to write to the <see cref="Stream"/></param> public static void Write(this Stream stream, byte[] buffer) { stream.Write(buffer, 0, buffer.Length); } /// <summary> /// Determine whether a <see cref="Stream"/> contents are in memory /// </summary> /// <param name="stream">Target <see cref="Stream"/></param> /// <returns><see langword="true"/> If the <see cref="Stream"/> contents are in memory</returns> public static bool IsStreamMemorized(this Stream stream) { #pragma warning disable 612,618 return stream is MemoryStream; #pragma warning restore 612,618 } /// <summary> /// Asynchronously read from a <see cref="Stream"/> /// </summary> /// <param name="stream">Source <see cref="Stream"/></param> /// <param name="buffer">Byte array to fill from the source</param> /// <param name="offset">Position in buffer to start writing to</param> /// <param name="count">Number of bytes to read from the <see cref="Stream"/></param> /// <param name="result">The <see cref="Result"/> instance to be returned by the call.</param> /// <returns>Synchronization handle for the number of bytes read.</returns> public static Result<int> Read(this Stream stream, byte[] buffer, int offset, int count, Result<int> result) { if(SysUtil.UseAsyncIO) { return AsyncUtil.From(stream.BeginRead, stream.EndRead, buffer, offset, count, null, result); } return AsyncUtil.Fork(() => SyncRead_Helper(stream, buffer, offset, count), result); } private static int SyncRead_Helper(Stream stream, byte[] buffer, int offset, int count) { var readTotal = 0; while(count != 0) { var read = stream.Read(buffer, offset, count); if(read <= 0) { return readTotal; } readTotal += read; offset += read; count -= read; } return readTotal; } /// <summary> /// Asynchronously write to a <see cref="Stream"/>. /// </summary> /// <param name="stream">Target <see cref="Stream"/>.</param> /// <param name="buffer">Byte array to write to the target.</param> /// <param name="offset">Position in buffer to start reading from.</param> /// <param name="count">Number of bytes to read from buffer.</param> /// <param name="result">The <see cref="Result"/> instance to be returned by the call.</param> /// <returns>Synchronization handle for the number of bytes read.</returns> public static Result Write(this Stream stream, byte[] buffer, int offset, int count, Result result) { if(SysUtil.UseAsyncIO) { return AsyncUtil.From(stream.BeginWrite, stream.EndWrite, buffer, offset, count, null, result); } return AsyncUtil.Fork(() => stream.Write(buffer, offset, count), result); } /// <summary> /// Synchronous copying of one stream to another. /// </summary> /// <param name="source">Source <see cref="Stream"/>.</param> /// <param name="target">Target <see cref="Stream"/>.</param> /// <param name="length">Number of bytes to copy from source to target.</param> /// <returns>Actual bytes copied.</returns> public static long CopyToStream(this Stream source, Stream target, long length) { var bufferLength = length >= 0 ? length : long.MaxValue; var buffer = new byte[Math.Min(bufferLength, BUFFER_SIZE)]; long total = 0; while(length != 0) { var count = (length >= 0) ? Math.Min(length, buffer.LongLength) : buffer.LongLength; count = source.Read(buffer, 0, (int)count); if(count == 0) { break; } target.Write(buffer, 0, (int)count); total += count; length -= count; } return total; } /// <summary> /// Asynchronous copying of one stream to another. /// </summary> /// <param name="source">Source <see cref="Stream"/>.</param> /// <param name="target">Target <see cref="Stream"/>.</param> /// <param name="length">Number of bytes to copy from source to target.</param> /// <param name="result">The <see cref="Result"/> instance to be returned by the call.</param> /// <returns>Synchronization handle for the number of bytes copied.</returns> public static Result<long> CopyToStream(this Stream source, Stream target, long length, Result<long> result) { if(!SysUtil.UseAsyncIO) { return AsyncUtil.Fork(() => CopyToStream(source, target, length), result); } // NOTE (steveb): intermediary copy steps already have a timeout operation, no need to limit the duration of the entire copy operation if((source == Stream.Null) || (length == 0)) { result.Return(0); } else if(source.IsStreamMemorized() && target.IsStreamMemorized()) { // source & target are memory streams; let's do the copy inline as fast as we can result.Return(CopyToStream(source, target, length)); } else { // use new task environment so we don't copy the task state over and over again TaskEnv.ExecuteNew(() => Coroutine.Invoke(CopyTo_Helper, source, target, length, result)); } return result; } private static Yield CopyTo_Helper(Stream source, Stream target, long length, Result<long> result) { byte[] readBuffer = new byte[BUFFER_SIZE]; byte[] writeBuffer = new byte[BUFFER_SIZE]; long total = 0; int zero_read_counter = 0; Result write = null; // NOTE (steveb): we stop when we've read the expected number of bytes and the length was non-negative, // otherwise we stop when we can't read anymore bytes. while(length != 0) { // read first long count = (length >= 0) ? Math.Min(length, readBuffer.LongLength) : readBuffer.LongLength; if(source.IsStreamMemorized()) { count = source.Read(readBuffer, 0, (int)count); // check if we failed to read if(count == 0) { break; } } else { yield return Read(source, readBuffer, 0, (int)count, new Result<int>(READ_TIMEOUT)).Set(v => count = v); // check if we failed to read if(count == 0) { // let's abort after 10 tries to read more data if(++zero_read_counter > 10) { break; } continue; } zero_read_counter = 0; } total += count; length -= count; // swap buffers byte[] tmp = writeBuffer; writeBuffer = readBuffer; readBuffer = tmp; // write second if((target == Stream.Null) || target.IsStreamMemorized()) { target.Write(writeBuffer, 0, (int)count); } else { if(write != null) { yield return write; } write = Write(target, writeBuffer, 0, (int)count, new Result()); } } if(write != null) { yield return write; } // return result result.Return(total); } /// <summary> /// Asynchrounously copy a <see cref="Stream"/> to several targets /// </summary> /// <param name="source">Source <see cref="Stream"/></param> /// <param name="targets">Array of target <see cref="Stream"/> objects</param> /// <param name="length">Number of bytes to copy from source to targets</param> /// <param name="result">The <see cref="Result"/> instance to be returned by the call.</param> /// <returns>Synchronization handle for the number of bytes copied to each target.</returns> public static Result<long?[]> CopyTo(this Stream source, Stream[] targets, long length, Result<long?[]> result) { // NOTE (steveb): intermediary copy steps already have a timeout operation, no need to limit the duration of the entire copy operation if((source == Stream.Null) || (length == 0)) { long?[] totals = new long?[targets.Length]; for(int i = 0; i < totals.Length; ++i) { totals[i] = 0; } result.Return(totals); } else { // use new task environment so we don't copy the task state over and over again TaskEnv.ExecuteNew(() => Coroutine.Invoke(CopyTo_Helper, source, targets, length, result)); } return result; } private static Yield CopyTo_Helper(Stream source, Stream[] targets, long length, Result<long?[]> result) { byte[] readBuffer = new byte[BUFFER_SIZE]; byte[] writeBuffer = new byte[BUFFER_SIZE]; int zero_read_counter = 0; Result[] writes = new Result[targets.Length]; // initialize totals long?[] totals = new long?[targets.Length]; for(int i = 0; i < totals.Length; ++i) { totals[i] = 0; } // NOTE (steveb): we stop when we've read the expected number of bytes when the length was non-negative, // otherwise we stop when we can't read anymore bytes. while(length != 0) { // read first long count = (length >= 0) ? Math.Min(length, readBuffer.LongLength) : readBuffer.LongLength; if(source.IsStreamMemorized()) { count = source.Read(readBuffer, 0, (int)count); // check if we failed to read if(count == 0) { break; } } else { yield return Read(source, readBuffer, 0, (int)count, new Result<int>(READ_TIMEOUT)).Set(v => count = v); // check if we failed to read if(count == 0) { // let's abort after 10 tries to read more data if(++zero_read_counter > 10) { break; } continue; } zero_read_counter = 0; } length -= count; // swap buffers byte[] tmp = writeBuffer; writeBuffer = readBuffer; readBuffer = tmp; // wait for pending writes to complete for(int i = 0; i < writes.Length; ++i) { if(writes[i] != null) { yield return writes[i].Catch(); if(writes[i].HasException) { totals[i] = null; } writes[i] = null; } } // write second for(int i = 0; i < targets.Length; ++i) { // check that write hasn't had an error yet if(totals[i] != null) { totals[i] += count; Stream target = targets[i]; if((target == Stream.Null) || target.IsStreamMemorized()) { target.Write(writeBuffer, 0, (int)count); } else { writes[i] = Write(target, writeBuffer, 0, (int)count, new Result()); } } } } // wait for pending writes to complete for(int i = 0; i < writes.Length; ++i) { if(writes[i] != null) { yield return writes[i].Catch(); if(writes[i].HasException) { totals[i] = null; } } } // return result result.Return(totals); } #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif /// <summary> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </summary> public static void CopyToFile(this Stream stream, string filename, long length) { FileStream file = null; try { using(file = File.Create(filename)) { CopyToStream(stream, file, length); } } catch { // check if we created a file, if so delete it if(file != null) { try { File.Delete(filename); } catch { } } throw; } finally { // make sure the source stream is closed try { stream.Close(); } catch { } } } /// <summary> /// Asychronously Pad a stream with a sequence of bytes /// </summary> /// <param name="stream">Target <see cref="Stream"/></param> /// <param name="count">Number of bytes to pad</param> /// <param name="value">Byte value to use for padding</param> /// <param name="result">The <see cref="Result"/> instance to be returned by the call.</param> /// <returns>Synchronization handle for completion of padding action.</returns> public static Result Pad(this Stream stream, long count, byte value, Result result) { if(count < 0) { throw new ArgumentException("count must be non-negative"); } // NOTE (steveb): intermediary copy steps already have a timeout operation, no need to limit the duration of the entire copy operation if(count == 0) { result.Return(); } else { // initialize buffer so we can write in large chunks if need be byte[] bytes = new byte[(int)Math.Min(4096L, count)]; for(int i = 0; i < bytes.Length; ++i) { bytes[i] = value; } // use new task environment so we don't copy the task state over and over again TaskEnv.ExecuteNew(() => Coroutine.Invoke(Pad_Helper, stream, count, bytes, result)); } return result; } private static Yield Pad_Helper(Stream stream, long count, byte[] bytes, Result result) { // write until we reach zero while(count > 0) { var byteCount = (int)Math.Min(count, bytes.LongLength); yield return Write(stream, bytes, 0, byteCount, new Result()); count -= byteCount; } result.Return(); } /// <summary> /// Compute the MD5 hash. /// </summary> /// <param name="stream">Stream to hash.</param> /// <returns>MD5 hash.</returns> public static byte[] ComputeHash(this Stream stream) { return MD5.Create().ComputeHash(stream); } /// <summary> /// Compute the MD5 hash string. /// </summary> /// <param name="stream">Stream to hash.</param> /// <returns>MD5 hash string.</returns> public static string ComputeHashString(this Stream stream) { return StringUtil.HexStringFromBytes(ComputeHash(stream)); } #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif /// <summary> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </summary> public static byte[] ReadBytes(this Stream source, long length) { var result = new MemoryStream(); CopyToStream(source, result, length); return result.ToArray(); } #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif /// <summary> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </summary> public static Result<MemoryStream> ToMemoryStream(this Stream stream, long length, Result<MemoryStream> result) { MemoryStream copy; if(stream is MemoryStream) { var mem = (MemoryStream)stream; copy = new MemoryStream(mem.GetBuffer(), 0, (int)mem.Length, false, true); result.Return(copy); } else { copy = new MemoryStream(); stream.CopyToStream(copy, length, new Result<long>(TimeSpan.MaxValue)).WhenDone( v => { copy.Position = 0; result.Return(copy); }, result.Throw ); } return result; } /// <summary> /// Detect stream encoding. /// </summary> /// <param name="stream">Stream to examine</param> /// <returns>Encoding type detected or null</returns> public static Encoding DetectEncoding(this Stream stream) { return new BOMEncodingDetector().Detect(stream) ?? new HtmlMetaEncodingDetector().Detect(stream) ?? new CharacterEncodingDetector().Detect(stream); } //--- Class Methods --- #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif /// <summary> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </summary> public static Stream[] DupStream(Stream stream, long length, int copies) { if(copies < 2) { throw new ArgumentException("copies"); } Stream[] result = new Stream[copies]; // make master stream MemoryStream master = stream.ToMemoryStream(length, new Result<MemoryStream>()).Wait(); result[0] = master; for(int i = 1; i < copies; i++) { result[i] = new MemoryStream(master.GetBuffer(), 0, (int)master.Length, false, true); } return result; } /// <summary> /// Try to open a file for exclusive read/write access /// </summary> /// <param name="filename">Path to file</param> /// <returns>A <see cref="Stream"/> for the opened file, or <see langword="null"/> on failure to open the file.</returns> public static Stream FileOpenExclusive(string filename) { for(int attempts = 0; attempts < 10; ++attempts) { try { return File.Open(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } catch(IOException e) { _log.TraceExceptionMethodCall(e, "FileOpenExclusive", filename, attempts); } catch(UnauthorizedAccessException e) { _log.TraceExceptionMethodCall(e, "FileOpenExclusive", filename, attempts); } AsyncUtil.Sleep(((attempts + 1) * Randomizer.Next(100)).Milliseconds()); } return null; } /// <summary> /// Create a pipe /// </summary> /// <param name="writer">The writer endpoint of the pipe</param> /// <param name="reader">The reader endpoint of the pipe</param> public static void CreatePipe(out Stream writer, out Stream reader) { PipeStreamBuffer buffer = new PipeStreamBuffer(); writer = new PipeStreamWriter(buffer); reader = new PipeStreamReader(buffer); } /// <summary> /// Create a pipe /// </summary> /// <param name="size">The size of the pipe buffer</param> /// <param name="writer">The writer endpoint of the pipe</param> /// <param name="reader">The reader endpoint of the pipe</param> public static void CreatePipe(int size, out Stream writer, out Stream reader) { PipeStreamBuffer buffer = new PipeStreamBuffer(size); writer = new PipeStreamWriter(buffer); reader = new PipeStreamReader(buffer); } } }
// Copyright 2011, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.AdWords.Lib; using Google.Api.Ads.Common.Logging; using Google.Api.Ads.Common.Util; using Google.Api.Ads.Common.Util.Reports; using System; using System.Collections.Generic; using System.Net; using System.Web; using System.Xml; namespace Google.Api.Ads.AdWords.Util.Reports { /// <summary> /// Defines report utility functions for the client library. /// </summary> public class ReportUtilities : AdsReportUtilities { /// <summary> /// The feature ID for this class. /// </summary> private const AdsFeatureUsageRegistry.Features FEATURE_ID = AdsFeatureUsageRegistry.Features.ReportDownloader; /// <summary> /// The registry for saving feature usage information.. /// </summary> private readonly AdsFeatureUsageRegistry featureUsageRegistry = AdsFeatureUsageRegistry.Instance; /// <summary> /// Default report version. /// </summary> internal const string DEFAULT_REPORT_VERSION = "v201809"; /// <summary> /// Sets the reporting API version to use. /// </summary> private string reportVersion = DEFAULT_REPORT_VERSION; /// <summary> /// The report download url format for ad-hoc reports. /// </summary> private const string QUERY_REPORT_URL_FORMAT = "{0}/api/adwords/reportdownload/{1}?" + "__fmt={2}"; /// <summary> /// The report download url format for ad-hoc reports. /// </summary> private const string ADHOC_REPORT_URL_FORMAT = "{0}/api/adwords/reportdownload/{1}"; /// <summary> /// The list of headers to mask in the logs. /// </summary> private readonly HashSet<string> HEADERS_TO_MASK = new HashSet<string> { "developerToken", "Authorization" }; /// <summary> /// The AWQL query for downloading this report. /// </summary> private string query; /// <summary> /// The format in which the report is downloaded. /// </summary> private string format; /// <summary> /// The report definition for downloading this report. /// </summary> private IReportDefinition reportDefinition; /// <summary> /// True, if the user wants to use AWQL for downloading reports, false if /// the user wants to use reportDefinition instead. /// </summary> private bool usesQuery = false; /// <summary> /// Initializes a new instance of the <see cref="ReportUtilities" /> class. /// </summary> /// <param name="user">AdWords user to be used along with this /// utilities object.</param> /// <param name="query">The AWQL for downloading reports.</param> /// <param name="format">The report download format.</param> public ReportUtilities(AdWordsUser user, string query, string format) : this(user, DEFAULT_REPORT_VERSION, query, format) { } /// <summary> /// Initializes a new instance of the <see cref="ReportUtilities"/> class. /// </summary> /// <param name="user">AdWords user to be used along with this /// utilities object.</param> /// <param name="reportDefinition">The report definition.</param> public ReportUtilities(AdWordsUser user, IReportDefinition reportDefinition) : this(user, DEFAULT_REPORT_VERSION, reportDefinition) { } /// <summary> /// Initializes a new instance of the <see cref="ReportUtilities" /> class. /// </summary> /// <param name="user">AdWords user to be used along with this /// utilities object.</param> /// <param name="query">The AWQL for downloading reports.</param> /// <param name="format">The report download format.</param> /// <param name="reportVersion">The report version.</param> public ReportUtilities(AdWordsUser user, string reportVersion, string query, string format) : base(user) { this.reportVersion = reportVersion; this.query = query; this.format = format; this.usesQuery = true; } /// <summary> /// Initializes a new instance of the <see cref="ReportUtilities"/> class. /// </summary> /// <param name="user">AdWords user to be used along with this /// utilities object.</param> /// <param name="reportDefinition">The report definition.</param> /// <param name="reportVersion">The report version.</param> public ReportUtilities(AdWordsUser user, string reportVersion, IReportDefinition reportDefinition) : base(user) { this.reportVersion = reportVersion; this.reportDefinition = reportDefinition; this.usesQuery = false; } /// <summary> /// Gets the report response. /// </summary> /// <returns> /// The report response. /// </returns> protected override ReportResponse GetReport() { AdWordsAppConfig config = (AdWordsAppConfig) User.Config; string postBody; string downloadUrl; if (usesQuery) { downloadUrl = string.Format(QUERY_REPORT_URL_FORMAT, config.AdWordsApiServer, reportVersion, format); postBody = string.Format("__rdquery={0}", HttpUtility.UrlEncode(query)); } else { downloadUrl = string.Format(ADHOC_REPORT_URL_FORMAT, config.AdWordsApiServer, reportVersion); postBody = "__rdxml=" + HttpUtility.UrlEncode(ConvertDefinitionToXml(reportDefinition)); } return DownloadReport(downloadUrl, postBody); } /// <summary> /// Downloads a report to stream. /// </summary> /// <param name="downloadUrl">The download url.</param> /// <param name="postBody">The POST body.</param> private ReportResponse DownloadReport(string downloadUrl, string postBody) { WebResponse response = null; HttpWebRequest request = null; LogEntry logEntry = new LogEntry(User.Config, new DefaultDateTimeProvider()); try { request = BuildRequest(downloadUrl, postBody, logEntry); response = request.GetResponse(); logEntry.LogResponse(new ResponseInfo(response, "REDACTED REPORT DATA")); logEntry.Flush(); return new ReportResponse(response); } catch (WebException e) { Exception reportsException = null; string contents = HttpUtilities.GetErrorResponseBody(e); logEntry.LogResponse(new ResponseInfo(e.Response, "") { ErrorMessage = contents }); logEntry.Flush(); reportsException = ParseException(e, contents); throw reportsException; } finally { featureUsageRegistry.Clear(); } } /// <summary> /// Builds an HTTP request for downloading reports. /// </summary> /// <param name="downloadUrl">The download url.</param> /// <param name="postBody">The POST body.</param> /// <param name="logEntry">The logEntry to write the HTTP logs.</param> /// <returns>A webrequest to download reports.</returns> private HttpWebRequest BuildRequest(string downloadUrl, string postBody, LogEntry logEntry) { AdWordsAppConfig config = this.User.Config as AdWordsAppConfig; HttpWebRequest request = (HttpWebRequest) HttpUtilities.BuildRequest(downloadUrl, "POST", config); request.Headers.Add("clientCustomerId: " + config.ClientCustomerId); request.ContentType = "application/x-www-form-urlencoded"; // Set an authorization header only if the authorization mode is OAuth2. For testing // purposes, the authorization method will be set to Insecure, and no authorization // header will be sent. if (config.AuthorizationMethod == AdWordsAuthorizationMethod.OAuth2 && this.User.OAuthProvider != null) { request.Headers["Authorization"] = this.User.OAuthProvider.GetAuthHeader(); } else { throw new AdWordsApiException(null, AdWordsErrorMessages.OAuthProviderCannotBeNull); } request.Headers.Add("developerToken: " + config.DeveloperToken); // The client library will use only apiMode = true. request.Headers.Add("apiMode", "true"); request.Headers.Add("skipReportHeader", config.SkipReportHeader.ToString().ToLower()); request.Headers.Add("skipReportSummary", config.SkipReportSummary.ToString().ToLower()); request.Headers.Add("skipColumnHeader", config.SkipColumnHeader.ToString().ToLower()); // Send the includeZeroImpressions header only if the user explicitly // requested it through the config object. if (config.IncludeZeroImpressions.HasValue) { request.Headers.Add("includeZeroImpressions", config.IncludeZeroImpressions.ToString().ToLower()); } // Send the useRawEnumValues header only if the user explicitly // requested it through the config object. if (config.UseRawEnumValues.HasValue) { request.Headers.Add("useRawEnumValues", config.UseRawEnumValues.ToString().ToLower()); } HttpUtilities.WritePostBodyAndLog(request, postBody, "reportdownload", logEntry, HEADERS_TO_MASK); return request; } /// <summary> /// Parses the error response into an exception. /// </summary> /// <param name="exception">The original exception.</param> /// <param name="contents">The errors XML.</param> /// <returns>An AdWords Reports exception that represents the error.</returns> private AdWordsReportsException ParseException(Exception exception, string contents) { List<ReportDownloadError> errorList = new List<ReportDownloadError>(); try { XmlDocument xDoc = XmlUtilities.CreateDocument(contents); XmlNodeList errorNodes = xDoc.DocumentElement.SelectNodes("ApiError"); foreach (XmlElement errorNode in errorNodes) { ReportDownloadError downloadError = new ReportDownloadError(); downloadError.ErrorType = errorNode.SelectSingleNode("type").InnerText; downloadError.FieldPath = errorNode.SelectSingleNode("fieldPath").InnerText; downloadError.Trigger = errorNode.SelectSingleNode("trigger").InnerText; errorList.Add(downloadError); } } catch { } AdWordsReportsException retval = new AdWordsReportsException(this.reportVersion, AdWordsErrorMessages.ReportingExceptionOccurred, exception); retval.Errors = errorList.ToArray(); return retval; } /// <summary> /// Converts the report definition to XML format. /// </summary> /// <param name="definition">The report definition.</param> /// <returns>The report definition serialized as an XML string.</returns> private string ConvertDefinitionToXml(IReportDefinition definition) { string xml = SerializationUtilities.SerializeAsXmlText(definition) .Replace("ReportDefinition", "reportDefinition"); XmlDocument doc = XmlUtilities.CreateDocument(xml); XmlNodeList xmlNodes = doc.SelectNodes("descendant::*"); foreach (XmlElement node in xmlNodes) { node.RemoveAllAttributes(); } return doc.OuterXml; } /// <summary> /// Gets the report download response. /// </summary> /// <returns>The report response.</returns> public override ReportResponse GetResponse() { // Mark the usage. featureUsageRegistry.MarkUsage(FEATURE_ID); return base.GetResponse(); } /// <summary> /// Gets the report download response asynchronously. /// </summary> public override void GetResponseAsync() { // Mark the usage. featureUsageRegistry.MarkUsage(FEATURE_ID); base.GetResponseAsync(); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace CslaSample.Business { /// <summary> /// FolderList (read only list).<br/> /// This is a generated base class of <see cref="FolderList"/> business object. /// This class is a root collection. /// </summary> /// <remarks> /// The items of the collection are <see cref="FolderInfo"/> objects. /// </remarks> [Serializable] public partial class FolderList : ReadOnlyBindingListBase<FolderList, FolderInfo> { #region Collection Business Methods /// <summary> /// Determines whether a <see cref="FolderInfo"/> item is in the collection. /// </summary> /// <param name="folderId">The FolderId of the item to search for.</param> /// <returns><c>true</c> if the FolderInfo is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int folderId) { foreach (var folderInfo in this) { if (folderInfo.FolderId == folderId) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="FolderInfo"/> item of the <see cref="FolderList"/> collection, based on a given FolderId. /// </summary> /// <param name="folderId">The FolderId.</param> /// <returns>A <see cref="FolderInfo"/> object.</returns> public FolderInfo FindFolderInfoByFolderId(int folderId) { for (var i = 0; i < this.Count; i++) { if (this[i].FolderId.Equals(folderId)) { return this[i]; } } return null; } #endregion #region Private Fields private static FolderList _list; #endregion #region Cache Management Methods /// <summary> /// Clears the in-memory FolderList cache so it is reloaded on the next request. /// </summary> public static void InvalidateCache() { _list = null; } /// <summary> /// Used by async loaders to load the cache. /// </summary> /// <param name="list">The list to cache.</param> internal static void SetCache(FolderList list) { _list = list; } internal static bool IsCached { get { return _list != null; } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="FolderList"/> collection. /// </summary> /// <returns>A reference to the fetched <see cref="FolderList"/> collection.</returns> public static FolderList GetFolderList() { if (_list == null) _list = DataPortal.Fetch<FolderList>(); return _list; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="FolderList"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public FolderList() { // Use factory methods and do not use direct creation. var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = false; AllowEdit = false; AllowRemove = false; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="FolderList"/> collection from the database or from the cache. /// </summary> protected void DataPortal_Fetch() { if (IsCached) { LoadCachedList(); return; } using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.CslaSampleConnection, false)) { using (var cmd = new SqlCommand("GetFolderList", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; var args = new DataPortalHookArgs(cmd); OnFetchPre(args); LoadCollection(cmd); OnFetchPost(args); } } _list = this; } private void LoadCachedList() { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AddRange(_list); RaiseListChangedEvents = rlce; IsReadOnly = true; } private void LoadCollection(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { Fetch(dr); } } /// <summary> /// Loads all <see cref="FolderList"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(FolderInfo.GetFolderInfo(dr)); } RaiseListChangedEvents = rlce; IsReadOnly = true; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace MS.Internal.Xml.XPath { using System; using Microsoft.Xml; using Microsoft.Xml.XPath; using System.Diagnostics; using System.Globalization; using System.Collections; using Microsoft.Xml.Xsl; internal class CompiledXpathExpr : XPathExpression { private Query _query; private string _expr; private bool _needContext; internal CompiledXpathExpr(Query query, string expression, bool needContext) { _query = query; _expr = expression; _needContext = needContext; } internal Query QueryTree { get { if (_needContext) { throw XPathException.Create(ResXml.Xp_NoContext); } return _query; } } public override string Expression { get { return _expr; } } public virtual void CheckErrors() { Debug.Assert(_query != null, "In case of error in XPath we create ErrorXPathExpression"); } public override void AddSort(object expr, IComparer comparer) { // sort makes sense only when we are dealing with a query that // returns a nodeset. Query evalExpr; if (expr is string) { evalExpr = new QueryBuilder().Build((string)expr, out _needContext); // this will throw if expr is invalid } else if (expr is CompiledXpathExpr) { evalExpr = ((CompiledXpathExpr)expr).QueryTree; } else { throw XPathException.Create(ResXml.Xp_BadQueryObject); } SortQuery sortQuery = _query as SortQuery; if (sortQuery == null) { _query = sortQuery = new SortQuery(_query); } sortQuery.AddSort(evalExpr, comparer); } public override void AddSort(object expr, XmlSortOrder order, XmlCaseOrder caseOrder, string lang, XmlDataType dataType) { AddSort(expr, new XPathComparerHelper(order, caseOrder, lang, dataType)); } public override XPathExpression Clone() { return new CompiledXpathExpr(Query.Clone(_query), _expr, _needContext); } public override void SetContext(XmlNamespaceManager nsManager) { SetContext((IXmlNamespaceResolver)nsManager); } public override void SetContext(IXmlNamespaceResolver nsResolver) { XsltContext xsltContext = nsResolver as XsltContext; if (xsltContext == null) { if (nsResolver == null) { nsResolver = new XmlNamespaceManager(new NameTable()); } xsltContext = new UndefinedXsltContext(nsResolver); } _query.SetXsltContext(xsltContext); _needContext = false; } public override XPathResultType ReturnType { get { return _query.StaticType; } } private class UndefinedXsltContext : XsltContext { private IXmlNamespaceResolver _nsResolver; public UndefinedXsltContext(IXmlNamespaceResolver nsResolver) : base(/*dummy*/false) { _nsResolver = nsResolver; } //----- Namespace support ----- public override string DefaultNamespace { get { return string.Empty; } } public override string LookupNamespace(string prefix) { Debug.Assert(prefix != null); if (prefix.Length == 0) { return string.Empty; } string ns = _nsResolver.LookupNamespace(prefix); if (ns == null) { throw XPathException.Create(ResXml.XmlUndefinedAlias, prefix); } return ns; } //----- XsltContext support ----- public override IXsltContextVariable ResolveVariable(string prefix, string name) { throw XPathException.Create(ResXml.Xp_UndefinedXsltContext); } public override IXsltContextFunction ResolveFunction(string prefix, string name, XPathResultType[] ArgTypes) { throw XPathException.Create(ResXml.Xp_UndefinedXsltContext); } public override bool Whitespace { get { return false; } } public override bool PreserveWhitespace(XPathNavigator node) { return false; } public override int CompareDocument(string baseUri, string nextbaseUri) { return string.CompareOrdinal(baseUri, nextbaseUri); } } } internal sealed class XPathComparerHelper : IComparer { private XmlSortOrder _order; private XmlCaseOrder _caseOrder; private CultureInfo _cinfo; private XmlDataType _dataType; public XPathComparerHelper(XmlSortOrder order, XmlCaseOrder caseOrder, string lang, XmlDataType dataType) { if (lang == null) { _cinfo = CultureInfo.CurrentCulture; // System.Threading.Thread.CurrentThread.CurrentCulture; } else { try { _cinfo = new CultureInfo(lang); } catch (System.ArgumentException) { throw; // Throwing an XsltException would be a breaking change } } if (order == XmlSortOrder.Descending) { if (caseOrder == XmlCaseOrder.LowerFirst) { caseOrder = XmlCaseOrder.UpperFirst; } else if (caseOrder == XmlCaseOrder.UpperFirst) { caseOrder = XmlCaseOrder.LowerFirst; } } _order = order; _caseOrder = caseOrder; _dataType = dataType; } public int Compare(object x, object y) { switch (_dataType) { case XmlDataType.Text: string s1 = Convert.ToString(x, _cinfo); string s2 = Convert.ToString(y, _cinfo); int result = string.Compare(s1, s2, /*ignoreCase:*/ _caseOrder != XmlCaseOrder.None); //, this.cinfo); if (result != 0 || _caseOrder == XmlCaseOrder.None) return (_order == XmlSortOrder.Ascending) ? result : -result; // If we came this far, it means that strings s1 and s2 are // equal to each other when case is ignored. Now it's time to check // and see if they differ in case only and take into account the user // requested case order for sorting purposes. result = string.Compare(s1, s2, /*ignoreCase:*/ false); //, this.cinfo); return (_caseOrder == XmlCaseOrder.LowerFirst) ? result : -result; case XmlDataType.Number: double r1 = XmlConvert.ToXPathDouble(x); double r2 = XmlConvert.ToXPathDouble(y); result = r1.CompareTo(r2); return (_order == XmlSortOrder.Ascending) ? result : -result; default: // dataType doesn't support any other value throw new InvalidOperationException(ResXml.Xml_InvalidOperation); } } // Compare () } // class XPathComparerHelper }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if !CLR2 using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Security; using System.Threading; //using Microsoft.Scripting.Generation; using AstUtils = System.Management.Automation.Interpreter.Utils; namespace System.Management.Automation.Interpreter { internal sealed class LightLambdaCompileEventArgs : EventArgs { public Delegate Compiled { get; private set; } internal LightLambdaCompileEventArgs(Delegate compiled) { Compiled = compiled; } } internal partial class LightLambda { private readonly StrongBox<object>[] _closure; private readonly Interpreter _interpreter; private static readonly CacheDict<Type, Func<LightLambda, Delegate>> s_runCache = new CacheDict<Type, Func<LightLambda, Delegate>>(100); // Adaptive compilation support private readonly LightDelegateCreator _delegateCreator; private Delegate _compiled; private int _compilationThreshold; /// <summary> /// Provides notification that the LightLambda has been compiled. /// </summary> public event EventHandler<LightLambdaCompileEventArgs> Compile; internal LightLambda(LightDelegateCreator delegateCreator, StrongBox<object>[] closure, int compilationThreshold) { _delegateCreator = delegateCreator; _closure = closure; _interpreter = delegateCreator.Interpreter; _compilationThreshold = compilationThreshold; } private static Func<LightLambda, Delegate> GetRunDelegateCtor(Type delegateType) { lock (s_runCache) { Func<LightLambda, Delegate> fastCtor; if (s_runCache.TryGetValue(delegateType, out fastCtor)) { return fastCtor; } return MakeRunDelegateCtor(delegateType); } } private static Func<LightLambda, Delegate> MakeRunDelegateCtor(Type delegateType) { var method = delegateType.GetMethod("Invoke"); var paramInfos = method.GetParameters(); Type[] paramTypes; string name = "Run"; if (paramInfos.Length >= MaxParameters) { return null; } if (method.ReturnType == typeof(void)) { name += "Void"; paramTypes = new Type[paramInfos.Length]; } else { paramTypes = new Type[paramInfos.Length + 1]; paramTypes[paramTypes.Length - 1] = method.ReturnType; } MethodInfo runMethod; if (method.ReturnType == typeof(void) && paramTypes.Length == 2 && paramInfos[0].ParameterType.IsByRef && paramInfos[1].ParameterType.IsByRef) { runMethod = typeof(LightLambda).GetMethod("RunVoidRef2", BindingFlags.NonPublic | BindingFlags.Instance); paramTypes[0] = paramInfos[0].ParameterType.GetElementType(); paramTypes[1] = paramInfos[1].ParameterType.GetElementType(); } else if (method.ReturnType == typeof(void) && paramTypes.Length == 0) { runMethod = typeof(LightLambda).GetMethod("RunVoid0", BindingFlags.NonPublic | BindingFlags.Instance); } else { for (int i = 0; i < paramInfos.Length; i++) { paramTypes[i] = paramInfos[i].ParameterType; if (paramTypes[i].IsByRef) { return null; } } if (DelegateHelpers.MakeDelegate(paramTypes) == delegateType) { name = "Make" + name + paramInfos.Length; MethodInfo ctorMethod = typeof(LightLambda).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(paramTypes); return s_runCache[delegateType] = (Func<LightLambda, Delegate>)ctorMethod.CreateDelegate(typeof(Func<LightLambda, Delegate>)); } runMethod = typeof(LightLambda).GetMethod(name + paramInfos.Length, BindingFlags.NonPublic | BindingFlags.Instance); } #if !SILVERLIGHT try { DynamicMethod dm = new DynamicMethod("FastCtor", typeof(Delegate), new[] { typeof(LightLambda) }, typeof(LightLambda), true); var ilgen = dm.GetILGenerator(); ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Ldftn, runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod); ilgen.Emit(OpCodes.Newobj, delegateType.GetConstructor(new[] { typeof(object), typeof(IntPtr) })); ilgen.Emit(OpCodes.Ret); return s_runCache[delegateType] = (Func<LightLambda, Delegate>)dm.CreateDelegate(typeof(Func<LightLambda, Delegate>)); } catch (SecurityException) { } #endif // we don't have permission for restricted skip visibility dynamic methods, use the slower Delegate.CreateDelegate. var targetMethod = runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod; return s_runCache[delegateType] = lambda => targetMethod.CreateDelegate(delegateType, lambda); } // TODO enable sharing of these custom delegates private Delegate CreateCustomDelegate(Type delegateType) { // PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Synchronously compiling a custom delegate"); var method = delegateType.GetMethod("Invoke"); var paramInfos = method.GetParameters(); var parameters = new ParameterExpression[paramInfos.Length]; var parametersAsObject = new Expression[paramInfos.Length]; for (int i = 0; i < paramInfos.Length; i++) { ParameterExpression parameter = Expression.Parameter(paramInfos[i].ParameterType, paramInfos[i].Name); parameters[i] = parameter; parametersAsObject[i] = Expression.Convert(parameter, typeof(object)); } var data = Expression.NewArrayInit(typeof(object), parametersAsObject); var self = AstUtils.Constant(this); var runMethod = typeof(LightLambda).GetMethod("Run"); var body = Expression.Convert(Expression.Call(self, runMethod, data), method.ReturnType); var lambda = Expression.Lambda(delegateType, body, parameters); return lambda.Compile(); } internal Delegate MakeDelegate(Type delegateType) { Func<LightLambda, Delegate> fastCtor = GetRunDelegateCtor(delegateType); if (fastCtor != null) { return fastCtor(this); } else { return CreateCustomDelegate(delegateType); } } private bool TryGetCompiled() { // Use the compiled delegate if available. if (_delegateCreator.HasCompiled) { _compiled = _delegateCreator.CreateCompiledDelegate(_closure); // Send it to anyone who's interested. var compileEvent = Compile; if (compileEvent != null && _delegateCreator.SameDelegateType) { compileEvent(this, new LightLambdaCompileEventArgs(_compiled)); } return true; } // Don't lock here, it's a frequently hit path. // // There could be multiple threads racing, but that is okay. // Two bad things can happen: // * We miss decrements (some thread sets the counter forward) // * We might enter the "if" branch more than once. // // The first is okay, it just means we take longer to compile. // The second we explicitly guard against inside of Compile(). // // We can't miss 0. The first thread that writes -1 must have read 0 and hence start compilation. if (unchecked(_compilationThreshold--) == 0) { #if SILVERLIGHT if (PlatformAdaptationLayer.IsCompactFramework) { _compilationThreshold = Int32.MaxValue; return false; } #endif if (_interpreter.CompileSynchronously) { _delegateCreator.Compile(null); return TryGetCompiled(); } else { // Kick off the compile on another thread so this one can keep going ThreadPool.QueueUserWorkItem(_delegateCreator.Compile, null); } } return false; } private InterpretedFrame MakeFrame() { return new InterpretedFrame(_interpreter, _closure); } internal void RunVoidRef2<T0, T1>(ref T0 arg0, ref T1 arg1) { // if (_compiled != null || TryGetCompiled()) { // ((ActionRef<T0, T1>)_compiled)(ref arg0, ref arg1); // return; // } // copy in and copy out for today... var frame = MakeFrame(); frame.Data[0] = arg0; frame.Data[1] = arg1; var currentFrame = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(currentFrame); arg0 = (T0)frame.Data[0]; arg1 = (T1)frame.Data[1]; } } public object Run(params object[] arguments) { if (_compiled != null || TryGetCompiled()) { return _compiled.DynamicInvoke(arguments); } var frame = MakeFrame(); for (int i = 0; i < arguments.Length; i++) { frame.Data[i] = arguments[i]; } var currentFrame = frame.Enter(); try { _interpreter.Run(frame); } finally { frame.Leave(currentFrame); } return frame.Pop(); } } }