context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Eto.Drawing; using aa = Android.App; using ac = Android.Content; using ao = Android.OS; using ar = Android.Runtime; using av = Android.Views; using aw = Android.Widget; using ag = Android.Graphics; namespace Eto.Android.Drawing { /// <summary> /// Handler for <see cref="IGraphics"/> /// </summary> /// <copyright>(c) 2013 by Vivek Jhaveri</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class GraphicsHandler : WidgetHandler<ag.Canvas, Graphics>, Graphics.IHandler { public GraphicsHandler() { } public float PointsPerPixel { get { return 1f; } } // TODO public PixelOffsetMode PixelOffsetMode { get; set; } // TODO public void CreateFromImage(Bitmap image) { Control = new ag.Canvas((ag.Bitmap)image.ControlObject); } public void DrawLine(Pen pen, float startx, float starty, float endx, float endy) { Control.DrawLine(startx, starty, endx, endy, pen.ToAndroid()); } public void DrawRectangle(Pen pen, float x, float y, float width, float height) { Control.DrawRect(new RectangleF(x, y, width, height).ToAndroid(), pen.ToAndroid()); } public void FillRectangle(Brush brush, float x, float y, float width, float height) { Control.DrawRect(new RectangleF(x, y, width, height).ToAndroid(), brush.ToAndroid()); } public void FillEllipse(Brush brush, float x, float y, float width, float height) { Control.DrawOval(new RectangleF(x, y, width, height).ToAndroid(), brush.ToAndroid()); } public void DrawEllipse(Pen pen, float x, float y, float width, float height) { Control.DrawOval(new RectangleF(x, y, width, height).ToAndroid(), pen.ToAndroid()); } public void DrawArc(Pen pen, float x, float y, float width, float height, float startAngle, float sweepAngle) { Control.DrawArc(new RectangleF(x, y, width, height).ToAndroid(), startAngle, sweepAngle, false, pen.ToAndroid()); } public void FillPie(Brush brush, float x, float y, float width, float height, float startAngle, float sweepAngle) { Control.DrawArc(new RectangleF(x, y, width, height).ToAndroid(), startAngle, sweepAngle, true, brush.ToAndroid()); } public void FillPath(Brush brush, IGraphicsPath path) { Control.DrawPath(path.ToAndroid(), brush.ToAndroid()); } public void DrawPath(Pen pen, IGraphicsPath path) { Control.DrawPath(path.ToAndroid(), pen.ToAndroid()); } public void DrawImage(Image image, float x, float y) { var handler = image.Handler as IAndroidImage; handler.DrawImage(this, x, y); } public void DrawImage(Image image, float x, float y, float width, float height) { var handler = image.Handler as IAndroidImage; handler.DrawImage(this, x, y, width, height); } public void DrawImage(Image image, RectangleF source, RectangleF destination) { var handler = image.Handler as IAndroidImage; handler.DrawImage(this, source, destination); } public void DrawText(Font font, SolidBrush brush, float x, float y, string text) { var paint = GetTextPaint(font); paint.Color = brush.ToAndroid().Color; // this overwrites the color on the cached paint, but that's ok since it is only used here. Control.DrawText(text, x, y, paint); } public SizeF MeasureString(Font font, string text) { if (string.IsNullOrEmpty(text)) // needed to avoid exception return SizeF.Empty; var paint = GetTextPaint(font); // See http://stackoverflow.com/questions/7549182/android-paint-measuretext-vs-gettextbounds var bounds = new ag.Rect(); paint.GetTextBounds(text, 0, text.Length, bounds); // TODO: see the above article; the width may be truncated to the nearest integer. return new SizeF(bounds.Width(), bounds.Height()); } /// <summary> /// Returns a Paint that is cached on the font. /// This is used by all font operations (across all Canvases) that use the same font. /// </summary> private ag.Paint GetTextPaint(Font font) { var paint = (font.Handler as FontHandler).Paint; paint.AntiAlias = AntiAlias; return paint; } public void Flush() { } // The ANTI_ALIAS flag on Paint (not Canvas) causes it to render antialiased. // SUBPIXEL_TEXT_FLAG is currently unsupported on Android. // See http://stackoverflow.com/questions/4740565/meaning-of-some-paint-constants-in-android public bool AntiAlias { get; set; } // TODO: setting the FILTER_BITMAP_FLAG on Paint (not Canvas) // causes it to do a bilinear interpolation. public ImageInterpolation ImageInterpolation { get; set; } public bool IsRetained { get { return false; } } public void TranslateTransform(float offsetX, float offsetY) { Control.Translate(offsetX, offsetY); } public void RotateTransform(float angle) { Control.Rotate(angle); } public void ScaleTransform(float scaleX, float scaleY) { Control.Scale(scaleX, scaleY); } public void MultiplyTransform(IMatrix matrix) { Control.Concat(matrix.ToAndroid()); } public void SaveTransform() { Control.Save(ag.SaveFlags.Matrix); } public void RestoreTransform() { Control.Restore(); } public IMatrix CurrentTransform { get { return Control.Matrix.ToEto(); } } public RectangleF ClipBounds { get { return Control.ClipBounds.ToEto(); } } public void SetClip(RectangleF rectangle) { Control.ClipRect(rectangle.ToAndroid(), ag.Region.Op.Replace); } public void SetClip(IGraphicsPath path) { // NOTE: This may not work with hardware acceleration. // See http://developer.android.com/guide/topics/graphics/hardware-accel.html#drawing-support // See http://stackoverflow.com/questions/16889815/canvas-clippath-only-works-on-android-emulator Control.ClipPath(path.ToAndroid(), ag.Region.Op.Replace); } public void ResetClip() { Control.ClipRect(new ag.Rect(int.MinValue, int.MinValue, int.MaxValue, int.MaxValue)); } public void Clear(SolidBrush brush) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using DataInput = Lucene.Net.Store.DataInput; using DataOutput = Lucene.Net.Store.DataOutput; using IndexInput = Lucene.Net.Store.IndexInput; /// <summary> /// Represents a logical <see cref="T:byte[]"/> as a series of pages. You /// can write-once into the logical <see cref="T:byte[]"/> (append only), /// using copy, and then retrieve slices (<see cref="BytesRef"/>) into it /// using fill. /// <para/> /// @lucene.internal /// </summary> // TODO: refactor this, byteblockpool, fst.bytestore, and any // other "shift/mask big arrays". there are too many of these classes! public sealed class PagedBytes { private readonly IList<byte[]> blocks = new List<byte[]>(); // TODO: these are unused? private readonly IList<int> blockEnd = new List<int>(); private readonly int blockSize; private readonly int blockBits; private readonly int blockMask; private bool didSkipBytes; private bool frozen; private int upto; private byte[] currentBlock; private readonly long bytesUsedPerBlock; private static readonly byte[] EMPTY_BYTES = #if FEATURE_ARRAYEMPTY Array.Empty<byte>(); #else new byte[0]; #endif /// <summary> /// Provides methods to read <see cref="BytesRef"/>s from a frozen /// <see cref="PagedBytes"/>. /// </summary> /// <seealso cref="Freeze(bool)"/> public sealed class Reader { private readonly byte[][] blocks; private readonly int[] blockEnds; private readonly int blockBits; private readonly int blockMask; private readonly int blockSize; internal Reader(PagedBytes pagedBytes) { blocks = new byte[pagedBytes.blocks.Count][]; for (var i = 0; i < blocks.Length; i++) { blocks[i] = pagedBytes.blocks[i]; } blockEnds = new int[blocks.Length]; for (int i = 0; i < blockEnds.Length; i++) { blockEnds[i] = pagedBytes.blockEnd[i]; } blockBits = pagedBytes.blockBits; blockMask = pagedBytes.blockMask; blockSize = pagedBytes.blockSize; } /// <summary> /// Gets a slice out of <see cref="PagedBytes"/> starting at <paramref name="start"/> with a /// given length. If the slice spans across a block border this method will /// allocate sufficient resources and copy the paged data. /// <para> /// Slices spanning more than two blocks are not supported. /// </para> /// @lucene.internal /// </summary> public void FillSlice(BytesRef b, long start, int length) { Debug.Assert(length >= 0, "length=" + length); Debug.Assert(length <= blockSize + 1, "length=" + length); b.Length = length; if (length == 0) { return; } var index = (int)(start >> blockBits); var offset = (int)(start & blockMask); if (blockSize - offset >= length) { // Within block b.Bytes = blocks[index]; b.Offset = offset; } else { // Split b.Bytes = new byte[length]; b.Offset = 0; Array.Copy(blocks[index], offset, b.Bytes, 0, blockSize - offset); Array.Copy(blocks[1 + index], 0, b.Bytes, blockSize - offset, length - (blockSize - offset)); } } /// <summary> /// Reads length as 1 or 2 byte vInt prefix, starting at <paramref name="start"/>. /// <para> /// <b>Note:</b> this method does not support slices spanning across block /// borders. /// </para> /// @lucene.internal /// </summary> // TODO: this really needs to be refactored into fieldcacheimpl public void Fill(BytesRef b, long start) { var index = (int)(start >> blockBits); var offset = (int)(start & blockMask); var block = b.Bytes = blocks[index]; if ((block[offset] & 128) == 0) { b.Length = block[offset]; b.Offset = offset + 1; } else { b.Length = ((block[offset] & 0x7f) << 8) | (block[1 + offset] & 0xff); b.Offset = offset + 2; Debug.Assert(b.Length > 0); } } /// <summary> /// Returns approximate RAM bytes used. </summary> public long RamBytesUsed() { return ((blocks != null) ? (blockSize * blocks.Length) : 0); } } /// <summary> /// 1&lt;&lt;blockBits must be bigger than biggest single /// <see cref="BytesRef"/> slice that will be pulled. /// </summary> public PagedBytes(int blockBits) { Debug.Assert(blockBits > 0 && blockBits <= 31, blockBits.ToString()); this.blockSize = 1 << blockBits; this.blockBits = blockBits; blockMask = blockSize - 1; upto = blockSize; bytesUsedPerBlock = blockSize + RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + RamUsageEstimator.NUM_BYTES_OBJECT_REF; } /// <summary> /// Read this many bytes from <paramref name="in"/>. </summary> public void Copy(IndexInput @in, long byteCount) { while (byteCount > 0) { int left = blockSize - upto; if (left == 0) { if (currentBlock != null) { blocks.Add(currentBlock); blockEnd.Add(upto); } currentBlock = new byte[blockSize]; upto = 0; left = blockSize; } if (left < byteCount) { @in.ReadBytes(currentBlock, upto, left, false); upto = blockSize; byteCount -= left; } else { @in.ReadBytes(currentBlock, upto, (int)byteCount, false); upto += (int)byteCount; break; } } } /// <summary> /// Copy <see cref="BytesRef"/> in, setting <see cref="BytesRef"/> out to the result. /// Do not use this if you will use <c>Freeze(true)</c>. /// This only supports <c>bytes.Length &lt;= blockSize</c>/ /// </summary> public void Copy(BytesRef bytes, BytesRef @out) { int left = blockSize - upto; if (bytes.Length > left || currentBlock == null) { if (currentBlock != null) { blocks.Add(currentBlock); blockEnd.Add(upto); didSkipBytes = true; } currentBlock = new byte[blockSize]; upto = 0; left = blockSize; Debug.Assert(bytes.Length <= blockSize); // TODO: we could also support variable block sizes } @out.Bytes = currentBlock; @out.Offset = upto; @out.Length = bytes.Length; Array.Copy(bytes.Bytes, bytes.Offset, currentBlock, upto, bytes.Length); upto += bytes.Length; } /// <summary> /// Commits final <see cref="T:byte[]"/>, trimming it if necessary and if <paramref name="trim"/>=true. </summary> public Reader Freeze(bool trim) { if (frozen) { throw new InvalidOperationException("already frozen"); } if (didSkipBytes) { throw new InvalidOperationException("cannot freeze when copy(BytesRef, BytesRef) was used"); } if (trim && upto < blockSize) { var newBlock = new byte[upto]; Array.Copy(currentBlock, 0, newBlock, 0, upto); currentBlock = newBlock; } if (currentBlock == null) { currentBlock = EMPTY_BYTES; } blocks.Add(currentBlock); blockEnd.Add(upto); frozen = true; currentBlock = null; return new PagedBytes.Reader(this); } public long GetPointer() { if (currentBlock == null) { return 0; } else { return (blocks.Count * ((long)blockSize)) + upto; } } /// <summary> /// Return approx RAM usage in bytes. </summary> public long RamBytesUsed() { return (blocks.Count + (currentBlock != null ? 1 : 0)) * bytesUsedPerBlock; } /// <summary> /// Copy bytes in, writing the length as a 1 or 2 byte /// vInt prefix. /// </summary> // TODO: this really needs to be refactored into fieldcacheimpl public long CopyUsingLengthPrefix(BytesRef bytes) { if (bytes.Length >= 32768) { throw new ArgumentException("max length is 32767 (got " + bytes.Length + ")"); } if (upto + bytes.Length + 2 > blockSize) { if (bytes.Length + 2 > blockSize) { throw new ArgumentException("block size " + blockSize + " is too small to store length " + bytes.Length + " bytes"); } if (currentBlock != null) { blocks.Add(currentBlock); blockEnd.Add(upto); } currentBlock = new byte[blockSize]; upto = 0; } long pointer = GetPointer(); if (bytes.Length < 128) { currentBlock[upto++] = (byte)bytes.Length; } else { currentBlock[upto++] = unchecked((byte)(0x80 | (bytes.Length >> 8))); currentBlock[upto++] = unchecked((byte)(bytes.Length & 0xff)); } Array.Copy(bytes.Bytes, bytes.Offset, currentBlock, upto, bytes.Length); upto += bytes.Length; return pointer; } public sealed class PagedBytesDataInput : DataInput { private readonly PagedBytes outerInstance; private int currentBlockIndex; private int currentBlockUpto; private byte[] currentBlock; internal PagedBytesDataInput(PagedBytes outerInstance) { this.outerInstance = outerInstance; currentBlock = outerInstance.blocks[0]; } public override object Clone() { PagedBytesDataInput clone = outerInstance.GetDataInput(); clone.SetPosition(GetPosition()); return clone; } /// <summary> /// Returns the current byte position. </summary> public long GetPosition() { return (long)currentBlockIndex * outerInstance.blockSize + currentBlockUpto; } /// <summary> /// Seek to a position previously obtained from <see cref="GetPosition()"/>. /// </summary> /// <param name="position"></param> public void SetPosition(long position) { currentBlockIndex = (int)(position >> outerInstance.blockBits); currentBlock = outerInstance.blocks[currentBlockIndex]; currentBlockUpto = (int)(position & outerInstance.blockMask); } public override byte ReadByte() { if (currentBlockUpto == outerInstance.blockSize) { NextBlock(); } return (byte)currentBlock[currentBlockUpto++]; } public override void ReadBytes(byte[] b, int offset, int len) { Debug.Assert(b.Length >= offset + len); int offsetEnd = offset + len; while (true) { int blockLeft = outerInstance.blockSize - currentBlockUpto; int left = offsetEnd - offset; if (blockLeft < left) { System.Buffer.BlockCopy(currentBlock, currentBlockUpto, b, offset, blockLeft); NextBlock(); offset += blockLeft; } else { // Last block System.Buffer.BlockCopy(currentBlock, currentBlockUpto, b, offset, left); currentBlockUpto += left; break; } } } private void NextBlock() { currentBlockIndex++; currentBlockUpto = 0; currentBlock = outerInstance.blocks[currentBlockIndex]; } } public sealed class PagedBytesDataOutput : DataOutput { private readonly PagedBytes outerInstance; public PagedBytesDataOutput(PagedBytes outerInstance) { this.outerInstance = outerInstance; } public override void WriteByte(byte b) { if (outerInstance.upto == outerInstance.blockSize) { if (outerInstance.currentBlock != null) { outerInstance.blocks.Add(outerInstance.currentBlock); outerInstance.blockEnd.Add(outerInstance.upto); } outerInstance.currentBlock = new byte[outerInstance.blockSize]; outerInstance.upto = 0; } outerInstance.currentBlock[outerInstance.upto++] = (byte)b; } public override void WriteBytes(byte[] b, int offset, int length) { Debug.Assert(b.Length >= offset + length); if (length == 0) { return; } if (outerInstance.upto == outerInstance.blockSize) { if (outerInstance.currentBlock != null) { outerInstance.blocks.Add(outerInstance.currentBlock); outerInstance.blockEnd.Add(outerInstance.upto); } outerInstance.currentBlock = new byte[outerInstance.blockSize]; outerInstance.upto = 0; } int offsetEnd = offset + length; while (true) { int left = offsetEnd - offset; int blockLeft = outerInstance.blockSize - outerInstance.upto; if (blockLeft < left) { System.Buffer.BlockCopy(b, offset, outerInstance.currentBlock, outerInstance.upto, blockLeft); outerInstance.blocks.Add(outerInstance.currentBlock); outerInstance.blockEnd.Add(outerInstance.blockSize); outerInstance.currentBlock = new byte[outerInstance.blockSize]; outerInstance.upto = 0; offset += blockLeft; } else { // Last block System.Buffer.BlockCopy(b, offset, outerInstance.currentBlock, outerInstance.upto, left); outerInstance.upto += left; break; } } } /// <summary> /// Return the current byte position. </summary> public long GetPosition() { return outerInstance.GetPointer(); } } /// <summary> /// Returns a <see cref="DataInput"/> to read values from this /// <see cref="PagedBytes"/> instance. /// </summary> public PagedBytesDataInput GetDataInput() { if (!frozen) { throw new InvalidOperationException("must call Freeze() before GetDataInput()"); } return new PagedBytesDataInput(this); } /// <summary> /// Returns a <see cref="DataOutput"/> that you may use to write into /// this <see cref="PagedBytes"/> instance. If you do this, you should /// not call the other writing methods (eg, copy); /// results are undefined. /// </summary> public PagedBytesDataOutput GetDataOutput() { if (frozen) { throw new InvalidOperationException("cannot get DataOutput after Freeze()"); } return new PagedBytesDataOutput(this); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.DirectoryServices.Protocols; using System.Linq; using System.Text; using System.Xml; namespace Microsoft.Protocols.TestTools.StackSdk.ActiveDirectory { public class ClaimTransformer { /// <summary> /// constructor /// </summary> /// <param name="dc">DC name or address</param> /// <param name="domain">domain DNS name</param> /// <param name="user">user name for LDAP connection</param> /// <param name="password">password of user</param> public ClaimTransformer(string dc, string domain, string user, string password) { DomainController = dc; DomainDNSName = domain; UserName = user; Password = password; } private LdapConnection connect() { return new LdapConnection(new LdapDirectoryIdentifier(DomainDNSName), new System.Net.NetworkCredential(UserName, Password, DomainDNSName)); } /// <summary> /// user name for connection /// </summary> public string UserName { get; set; } /// <summary> /// password for user /// </summary> public string Password { get; set; } /// <summary> /// DNS name of the domain /// </summary> public string DomainDNSName { get { return domainDNS; } set { domainDNS = value; domainNC = dnsNameToDN(value); } } /// <summary> /// machine name of the DC /// </summary> public string DomainController { get; set; } /// <summary> /// domain DNS name /// </summary> string domainDNS; /// <summary> /// domain NC Distinguished Name /// </summary> string domainNC; /// <summary> /// convert DNS name to Distinguished Name format /// </summary> /// <param name="dns">dns name</param> /// <returns>Distinguished Name</returns> string dnsNameToDN(string dns) { string[] tmps = dns.ToLower().Replace(" ", "").Split(new string[] { ",", "." }, StringSplitOptions.RemoveEmptyEntries); string ret = ""; foreach (string s in tmps) { ret += "DC="; ret += s; ret += ","; } return ret.Remove(ret.Length - 1); } public Win32ErrorCode_32 TransformClaimsOnTrustTraversal(CLAIMS_ARRAY[] input, string trustName, bool fIncomingDirection, out List<CLAIMS_ARRAY> output) { output = null; //found trust SearchRequest search = new SearchRequest( "cn=system," + domainNC, "(cn=" + trustName + ")", SearchScope.OneLevel, new string[] { "*" }); bool hasException = false; SearchResponse response = null; do { try { using (LdapConnection connection = connect()) { response = (SearchResponse)connection.SendRequest(search); } } catch { hasException = true; } } while (hasException); if (response.ResultCode != ResultCode.Success || response.Entries.Count == 0) return Win32ErrorCode_32.ERROR_INVALID_PARAMETER; string xml = null; Win32ErrorCode_32 err = getClaimsTransformationRuleXml(trustName, response.Entries[0].DistinguishedName, fIncomingDirection, out xml); if (err != Win32ErrorCode_32.ERROR_SUCCESS && err != Win32ErrorCode_32.ERROR_INVALID_FUNCTION) return Win32ErrorCode_32.ERROR_SUCCESS; string text = null; if (xml != null) { getTransformRulesText(xml, out text); } output = SimpleCTAEngine.Run(input, text); return Win32ErrorCode_32.ERROR_SUCCESS; } Win32ErrorCode_32 getClaimsTransformationRuleXml(string trustName, string trustObjDN, bool fIncomingDirection, out string ruleXml) { ruleXml = null; SearchRequest search = new SearchRequest( "cn=claims transformation policies,cn=claims configuration,cn=services,cn=configuration," + domainNC, "(objectclass=msds-claimstransformationpolicytype)", SearchScope.OneLevel, new string[] { "*" }); using (LdapConnection connection = connect()) { SearchResponse policiesResponse = (SearchResponse)connection.SendRequest(search); string claimsTransformObject = null; search = new SearchRequest( trustObjDN, "(objectclass=*)", SearchScope.Base, new string[] { "msDS-IngressClaimsTransformationPolicy", "msDS-EgressClaimsTransformationPolicy" }); SearchResponse trustObj = (SearchResponse)connection.SendRequest(search); if (trustObj.ResultCode != ResultCode.Success || trustObj.Entries.Count == 0) return Win32ErrorCode_32.ERROR_INVALID_FUNCTION; if (fIncomingDirection) { if (trustObj.Entries[0].Attributes["msDS-IngressClaimsTransformationPolicy"] == null || trustObj.Entries[0].Attributes["msDS-IngressClaimsTransformationPolicy"].Count == 0) return Win32ErrorCode_32.ERROR_INVALID_FUNCTION; claimsTransformObject = trustObj.Entries[0].Attributes["msDS-IngressClaimsTransformationPolicy"][0].ToString(); } else { if (trustObj.Entries[0].Attributes["msDS-EgressClaimsTransformPolicy"] == null || trustObj.Entries[0].Attributes["msDS-EgressClaimsTransformationPolicy"].Count == 0) return Win32ErrorCode_32.ERROR_INVALID_FUNCTION; claimsTransformObject = trustObj.Entries[0].Attributes["msDS-EgressClaimsTransformationPolicy"][0].ToString(); } foreach (SearchResultEntry entry in policiesResponse.Entries) { if (entry.DistinguishedName.ToLower() == claimsTransformObject.ToLower()) { if (entry.Attributes["msDS-TransformationRules"] != null && entry.Attributes["msDS-TransformationRules"].Count != 0) { ruleXml = entry.Attributes["msDS-TransformationRules"][0].ToString(); return Win32ErrorCode_32.ERROR_SUCCESS; } } } return Win32ErrorCode_32.ERROR_INVALID_PARAMETER; } } Win32ErrorCode_32 getTransformRulesText(string xml, out string text) { text = null; if (xml == null) return Win32ErrorCode_32.ERROR_SUCCESS; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.XmlResolver = null; using (System.IO.StringReader sr = new System.IO.StringReader(xml)) { XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Prohibit; settings.XmlResolver = null; using (System.Xml.XmlReader xmlreader = System.Xml.XmlReader.Create(sr, settings)) { doc.Load(xmlreader); int version = -1; System.Xml.XmlNode ruleNode = null; for (int i = 0; i < doc.ChildNodes.Count; i++) { if (doc.ChildNodes[i].Name == "ClaimsTransformationPolicy") { for (int j = 0; j < doc.ChildNodes[i].ChildNodes.Count; j++) { if (doc.ChildNodes[i].ChildNodes[j].Name == "Rules") { if (doc.ChildNodes[i].ChildNodes[j].Attributes["version"] == null) return Win32ErrorCode_32.ERROR_INVALID_DATA; if (!int.TryParse(doc.ChildNodes[i].ChildNodes[j].Attributes["version"].Value, out version)) return Win32ErrorCode_32.ERROR_INVALID_DATA; ruleNode = doc.ChildNodes[i].ChildNodes[j]; break; } } } } if (version != 1) return Win32ErrorCode_32.ERROR_INVALID_DATA; text = ruleNode.InnerText; return Win32ErrorCode_32.ERROR_SUCCESS; } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Text; using Vinchuca.Utils; using Vinchuca.Workers; namespace Vinchuca.Network.Protocol.Peers { public class PeerList : IEnumerable<PeerInfo> { private readonly IWorkScheduler _worker; private readonly Dictionary<BotIdentifier, PeerInfo> _peers; private static readonly Log Logger = new Log(new TraceSource("List-Manager", SourceLevels.Verbose)); public EventHandler<BrokenBotDetectedEventArgs> BrokenBotDetected; public EventHandler<DesparateModeActivatedEventArgs> DesparadoModeActivated; public PeerList(IWorkScheduler worker) { _worker = worker; _peers = new Dictionary<BotIdentifier, PeerInfo>(); _worker.QueueForever(Check, TimeSpan.FromMinutes(5)); _worker.QueueForever(Purge, TimeSpan.FromSeconds(15)); _worker.QueueForever(Save, TimeSpan.FromMinutes(1)); } private void Check() { Logger.Info("Checking peer list"); if (!IsCritical) return; var bots = new List<PeerInfo>(_peers.Values).ConvertAll(pi => pi.BotId).ToArray(); Events.Raise(DesparadoModeActivated, this, new DesparateModeActivatedEventArgs(bots)); } public bool IsCritical { get { return _peers.Count <= 25; } } public bool TryRegister(PeerInfo peerInfo) { var endpoint = peerInfo.EndPoint; var ip = endpoint.Address; var botId = peerInfo.BotId; if (botId.Equals(BotIdentifier.Id)) { Logger.Verbose("failed attempt for auto-adding"); return false; } if (endpoint.Port <= 30000 || endpoint.Port >= 50000) { Logger.Verbose("failed out-of-range port number ({0}). ", endpoint.Port); return false; } #if !DEBUG var ipMask = IPAddress.Parse("255.255.240.0"); foreach (var info in _peers.Values) { var inSameSubnet = IPAddressUtils.IsInSameSubnet(ip, info.EndPoint.Address, ipMask); if(inSameSubnet) { return false; } } #endif if (_peers.ContainsKey(peerInfo.BotId)) { Logger.Verbose("bot with same ID already exists. Touching it."); var peer = _peers[botId]; peer.EndPoint = endpoint; peer.Touch(); return false; } if (_peers.Count >= 256) { Purge(); } _peers.Add(botId, peerInfo); Logger.Verbose("{0} added", peerInfo); var unknown = BotIdentifier.Unknown; if (!Equals(botId, unknown) && IsRegisteredBot(unknown) && Equals(this[unknown].EndPoint, peerInfo.EndPoint)) { _peers.Remove(unknown); } return true; } public List<PeerInfo> GetPeersEndPoint() { return Recent(); } public void UpdatePeer(BotIdentifier botId) { if (_peers.ContainsKey(botId)) { _peers[botId].Touch(); } } public void Punish(BotIdentifier botId) { if (_peers.ContainsKey(botId)) { _peers[botId].DecreseReputation(); } } public void Save() { try { var sb = new StringBuilder(); foreach (var peerInfo in _peers.Values) { sb.AppendLine(peerInfo.ToString()); } var list = sb.ToString(); File.WriteAllText("peerlist_" + BotIdentifier.Id + ".txt", list); } catch { // ignore if something wrong happened } //RegistryUtils.Write(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\list", list); } public void Load() { //var text = RegistryUtils.Read(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\list"); //var lines = text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries); try { var lines = File.ReadAllLines("peerlist_" + BotIdentifier.Id + ".txt"); foreach (var line in lines) { TryRegister(PeerInfo.Parse(line)); } } catch (FileNotFoundException) { // ignored } } public void Purge() { var peersInfo = new List<PeerInfo>(_peers.Values); foreach (var peerInfo in peersInfo) { if (peerInfo.IsUnknownBot) { Events.Raise(BrokenBotDetected, this, new BrokenBotDetectedEventArgs(peerInfo)); } if (peerInfo.IsLazyBot || peerInfo.IsUnknownBot) { _peers.Remove(peerInfo.BotId); } } } public List<PeerInfo> Recent() { var sortedBy = SortedPeers(); return sortedBy.GetRange(0, Math.Min((int) 8, (int) sortedBy.Count)); } private List<PeerInfo> SortedPeers() { var all = new List<PeerInfo>(_peers.Values); all.Sort((s1, s2) => (int)(s1.LastSeen - s2.LastSeen).TotalSeconds); return all; } public IEnumerator<PeerInfo> GetEnumerator() { return _peers.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } internal bool IsRegisteredBot(BotIdentifier botId) { return _peers.ContainsKey(botId); } public PeerInfo this[BotIdentifier botId] { get { return _peers[botId]; } } public bool TryGet(IPEndPoint endpoint, out PeerInfo peerInfo) { foreach (var pi in _peers.Values) { if (Equals(pi.EndPoint, endpoint)) { peerInfo = pi; return true; } } peerInfo = null; return false; } public void Clear() { _peers.Clear(); } } public class BrokenBotDetectedEventArgs : EventArgs { private readonly PeerInfo _peerInfo; public BrokenBotDetectedEventArgs(PeerInfo peerInfo) { _peerInfo = peerInfo; } public PeerInfo PeerInfo { get { return _peerInfo; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.Examples.SimpleModule { public class MyNpcCharacter : IClientAPI { private uint movementFlag = 0; private short flyState = 0; private Quaternion bodyDirection = Quaternion.Identity; private short count = 0; private short frame = 0; private Scene m_scene; // disable warning: public events, part of the public API #pragma warning disable 67 public event Action<IClientAPI> OnLogout; public event ObjectPermissions OnObjectPermissions; public event MoneyTransferRequest OnMoneyTransferRequest; public event ParcelBuy OnParcelBuy; public event Action<IClientAPI> OnConnectionClosed; public event ImprovedInstantMessage OnInstantMessage; public event ChatMessage OnChatFromClient; public event TextureRequest OnRequestTexture; public event RezObject OnRezObject; public event ModifyTerrain OnModifyTerrain; public event BakeTerrain OnBakeTerrain; public event SetAppearance OnSetAppearance; public event AvatarNowWearing OnAvatarNowWearing; public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv; public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv; public event UUIDNameRequest OnDetachAttachmentIntoInv; public event ObjectAttach OnObjectAttach; public event ObjectDeselect OnObjectDetach; public event ObjectDrop OnObjectDrop; public event StartAnim OnStartAnim; public event StopAnim OnStopAnim; public event LinkObjects OnLinkObjects; public event DelinkObjects OnDelinkObjects; public event RequestMapBlocks OnRequestMapBlocks; public event RequestMapName OnMapNameRequest; public event TeleportLocationRequest OnTeleportLocationRequest; public event TeleportLandmarkRequest OnTeleportLandmarkRequest; public event DisconnectUser OnDisconnectUser; public event RequestAvatarProperties OnRequestAvatarProperties; public event SetAlwaysRun OnSetAlwaysRun; public event DeRezObject OnDeRezObject; public event Action<IClientAPI> OnRegionHandShakeReply; public event GenericCall1 OnRequestWearables; public event GenericCall1 OnCompleteMovementToRegion; public event UpdateAgent OnPreAgentUpdate; public event UpdateAgent OnAgentUpdate; public event AgentRequestSit OnAgentRequestSit; public event AgentSit OnAgentSit; public event AvatarPickerRequest OnAvatarPickerRequest; public event Action<IClientAPI> OnRequestAvatarsData; public event AddNewPrim OnAddPrim; public event RequestGodlikePowers OnRequestGodlikePowers; public event GodKickUser OnGodKickUser; public event ObjectDuplicate OnObjectDuplicate; public event GrabObject OnGrabObject; public event DeGrabObject OnDeGrabObject; public event MoveObject OnGrabUpdate; public event SpinStart OnSpinStart; public event SpinObject OnSpinUpdate; public event SpinStop OnSpinStop; public event ViewerEffectEventHandler OnViewerEffect; public event FetchInventory OnAgentDataUpdateRequest; public event TeleportLocationRequest OnSetStartLocationRequest; public event UpdateShape OnUpdatePrimShape; public event ObjectExtraParams OnUpdateExtraParams; public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily; public event ObjectRequest OnObjectRequest; public event ObjectSelect OnObjectSelect; public event GenericCall7 OnObjectDescription; public event GenericCall7 OnObjectName; public event GenericCall7 OnObjectClickAction; public event GenericCall7 OnObjectMaterial; public event UpdatePrimFlags OnUpdatePrimFlags; public event UpdatePrimTexture OnUpdatePrimTexture; public event UpdateVector OnUpdatePrimGroupPosition; public event UpdateVector OnUpdatePrimSinglePosition; public event UpdatePrimRotation OnUpdatePrimGroupRotation; public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition; public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; public event UpdateVector OnUpdatePrimScale; public event UpdateVector OnUpdatePrimGroupScale; public event StatusChange OnChildAgentStatus; public event GenericCall2 OnStopMovement; public event Action<UUID> OnRemoveAvatar; public event CreateNewInventoryItem OnCreateNewInventoryItem; public event LinkInventoryItem OnLinkInventoryItem; public event CreateInventoryFolder OnCreateNewInventoryFolder; public event UpdateInventoryFolder OnUpdateInventoryFolder; public event MoveInventoryFolder OnMoveInventoryFolder; public event RemoveInventoryFolder OnRemoveInventoryFolder; public event RemoveInventoryItem OnRemoveInventoryItem; public event FetchInventoryDescendents OnFetchInventoryDescendents; public event PurgeInventoryDescendents OnPurgeInventoryDescendents; public event FetchInventory OnFetchInventory; public event RequestTaskInventory OnRequestTaskInventory; public event UpdateInventoryItem OnUpdateInventoryItem; public event CopyInventoryItem OnCopyInventoryItem; public event MoveInventoryItem OnMoveInventoryItem; public event UDPAssetUploadRequest OnAssetUploadRequest; public event RequestTerrain OnRequestTerrain; public event RequestTerrain OnUploadTerrain; public event XferReceive OnXferReceive; public event RequestXfer OnRequestXfer; public event ConfirmXfer OnConfirmXfer; public event AbortXfer OnAbortXfer; public event RezScript OnRezScript; public event UpdateTaskInventory OnUpdateTaskInventory; public event MoveTaskInventory OnMoveTaskItem; public event RemoveTaskInventory OnRemoveTaskItem; public event RequestAsset OnRequestAsset; public event GenericMessage OnGenericMessage; public event UUIDNameRequest OnNameFromUUIDRequest; public event UUIDNameRequest OnUUIDGroupNameRequest; public event ParcelPropertiesRequest OnParcelPropertiesRequest; public event ParcelDivideRequest OnParcelDivideRequest; public event ParcelJoinRequest OnParcelJoinRequest; public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; public event ParcelAbandonRequest OnParcelAbandonRequest; public event ParcelGodForceOwner OnParcelGodForceOwner; public event ParcelReclaim OnParcelReclaim; public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest; public event ParcelAccessListRequest OnParcelAccessListRequest; public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest; public event ParcelSelectObjects OnParcelSelectObjects; public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; public event ParcelDeedToGroup OnParcelDeedToGroup; public event ObjectDeselect OnObjectDeselect; public event RegionInfoRequest OnRegionInfoRequest; public event EstateCovenantRequest OnEstateCovenantRequest; public event EstateChangeInfo OnEstateChangeInfo; public event ObjectDuplicateOnRay OnObjectDuplicateOnRay; public event FriendActionDelegate OnApproveFriendRequest; public event FriendActionDelegate OnDenyFriendRequest; public event FriendshipTermination OnTerminateFriendship; public event GrantUserFriendRights OnGrantUserRights; public event EconomyDataRequest OnEconomyDataRequest; public event MoneyBalanceRequest OnMoneyBalanceRequest; public event UpdateAvatarProperties OnUpdateAvatarProperties; public event ObjectIncludeInSearch OnObjectIncludeInSearch; public event UUIDNameRequest OnTeleportHomeRequest; public event ScriptAnswer OnScriptAnswer; public event RequestPayPrice OnRequestPayPrice; public event ObjectSaleInfo OnObjectSaleInfo; public event ObjectBuy OnObjectBuy; public event BuyObjectInventory OnBuyObjectInventory; public event AgentSit OnUndo; public event AgentSit OnRedo; public event LandUndo OnLandUndo; public event ForceReleaseControls OnForceReleaseControls; public event GodLandStatRequest OnLandStatRequest; public event RequestObjectPropertiesFamily OnObjectGroupRequest; public event DetailedEstateDataRequest OnDetailedEstateDataRequest; public event SetEstateFlagsRequest OnSetEstateFlagsRequest; public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture; public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture; public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights; public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest; public event SetRegionTerrainSettings OnSetRegionTerrainSettings; public event EstateRestartSimRequest OnEstateRestartSimRequest; public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest; public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest; public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest; public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest; public event EstateDebugRegionRequest OnEstateDebugRegionRequest; public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest; public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest; public event ScriptReset OnScriptReset; public event GetScriptRunning OnGetScriptRunning; public event SetScriptRunning OnSetScriptRunning; public event UpdateVector OnAutoPilotGo; public event TerrainUnacked OnUnackedTerrain; public event RegionHandleRequest OnRegionHandleRequest; public event ParcelInfoRequest OnParcelInfoRequest; public event ActivateGesture OnActivateGesture; public event DeactivateGesture OnDeactivateGesture; public event ObjectOwner OnObjectOwner; public event DirPlacesQuery OnDirPlacesQuery; public event DirFindQuery OnDirFindQuery; public event DirLandQuery OnDirLandQuery; public event DirPopularQuery OnDirPopularQuery; public event DirClassifiedQuery OnDirClassifiedQuery; public event EventInfoRequest OnEventInfoRequest; public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime; public event MapItemRequest OnMapItemRequest; public event OfferCallingCard OnOfferCallingCard; public event AcceptCallingCard OnAcceptCallingCard; public event DeclineCallingCard OnDeclineCallingCard; public event SoundTrigger OnSoundTrigger; public event StartLure OnStartLure; public event TeleportLureRequest OnTeleportLureRequest; public event NetworkStats OnNetworkStatsUpdate; public event ClassifiedInfoRequest OnClassifiedInfoRequest; public event ClassifiedInfoUpdate OnClassifiedInfoUpdate; public event ClassifiedDelete OnClassifiedDelete; public event ClassifiedDelete OnClassifiedGodDelete; public event EventNotificationAddRequest OnEventNotificationAddRequest; public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest; public event EventGodDelete OnEventGodDelete; public event ParcelDwellRequest OnParcelDwellRequest; public event UserInfoRequest OnUserInfoRequest; public event UpdateUserInfo OnUpdateUserInfo; public event RetrieveInstantMessages OnRetrieveInstantMessages; public event PickDelete OnPickDelete; public event PickGodDelete OnPickGodDelete; public event PickInfoUpdate OnPickInfoUpdate; public event AvatarNotesUpdate OnAvatarNotesUpdate; public event MuteListRequest OnMuteListRequest; public event AvatarInterestUpdate OnAvatarInterestUpdate; public event PlacesQuery OnPlacesQuery; public event FindAgentUpdate OnFindAgent; public event TrackAgentUpdate OnTrackAgent; public event NewUserReport OnUserReport; public event SaveStateHandler OnSaveState; public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest; public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest; public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest; public event FreezeUserUpdate OnParcelFreezeUser; public event EjectUserUpdate OnParcelEjectUser; public event ParcelBuyPass OnParcelBuyPass; public event ParcelGodMark OnParcelGodMark; public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest; public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest; public event SimWideDeletesDelegate OnSimWideDeletes; public event SendPostcard OnSendPostcard; public event MuteListEntryUpdate OnUpdateMuteListEntry; public event MuteListEntryRemove OnRemoveMuteListEntry; public event GodlikeMessage onGodlikeMessage; public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate; #pragma warning restore 67 private UUID myID = UUID.Random(); public MyNpcCharacter(Scene scene) { // startPos = new Vector3(128, (float)(Util.RandomClass.NextDouble()*100), 2); m_scene = scene; m_scene.EventManager.OnFrame += Update; } private Vector3 startPos = new Vector3(128, 128, 30); public virtual Vector3 StartPos { get { return startPos; } set { } } public virtual UUID AgentId { get { return myID; } } public UUID SessionId { get { return UUID.Zero; } } public UUID SecureSessionId { get { return UUID.Zero; } } public virtual string FirstName { get { return "Only"; } } private string lastName = "Today" + Util.RandomClass.Next(1, 1000); public virtual string LastName { get { return lastName; } } public virtual String Name { get { return FirstName + LastName; } } public bool IsActive { get { return true; } set { } } public bool IsLoggingOut { get { return false; } set { } } public UUID ActiveGroupId { get { return UUID.Zero; } } public string ActiveGroupName { get { return String.Empty; } } public ulong ActiveGroupPowers { get { return 0; } } public bool IsGroupMember(UUID groupID) { return false; } public ulong GetGroupPowers(UUID groupID) { return 0; } public virtual int NextAnimationSequenceNumber { get { return 1; } } public IScene Scene { get { return m_scene; } } public bool SendLogoutPacketWhenClosing { set { } } public virtual void ActivateGesture(UUID assetId, UUID gestureId) { } public virtual void SendWearables(AvatarWearable[] wearables, int serial) { } public virtual void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry) { } public virtual void Kick(string message) { } public virtual void SendStartPingCheck(byte seq) { } public virtual void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data) { } public virtual void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle) { } public virtual void SendKillObject(ulong regionHandle, uint localID) { } public virtual void SetChildAgentThrottle(byte[] throttle) { } public byte[] GetThrottlesPacked(float multiplier) { return new byte[0]; } public virtual void SendAnimations(UUID[] animations, int[] seqs, UUID sourceAgentId, UUID[] objectIDs) { } public virtual void SendChatMessage(string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible) { } public virtual void SendChatMessage(byte[] message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible) { } public void SendInstantMessage(GridInstantMessage im) { } public void SendGenericMessage(string method, List<string> message) { } public void SendGenericMessage(string method, List<byte[]> message) { } public virtual void SendLayerData(float[] map) { } public virtual void SendLayerData(int px, int py, float[] map) { } public virtual void SendLayerData(int px, int py, float[] map, bool track) { } public virtual void SendWindData(Vector2[] windSpeeds) { } public virtual void SendCloudData(float[] cloudCover) { } public virtual void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look) { } public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { } public virtual AgentCircuitData RequestClientInfo() { return new AgentCircuitData(); } public virtual void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL) { } public virtual void SendMapBlock(List<MapBlockData> mapBlocks, uint flag) { } public virtual void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags) { } public virtual void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL) { } public virtual void SendTeleportFailed(string reason) { } public virtual void SendTeleportStart(uint flags) { } public virtual void SendTeleportProgress(uint flags, string message) { } public virtual void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance) { } public virtual void SendPayPrice(UUID objectID, int[] payPrice) { } public virtual void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations) { } public virtual void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels) { } public void SendAvatarDataImmediate(ISceneEntity avatar) { } public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { } public void ReprioritizeUpdates() { } public void FlushPrimUpdates() { } public virtual void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, int version, bool fetchFolders, bool fetchItems) { } public virtual void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item) { } public virtual void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackID) { } public virtual void SendRemoveInventoryItem(UUID itemID) { } public virtual void SendBulkUpdateInventory(InventoryNodeBase node) { } public UUID GetDefaultAnimation(string name) { return UUID.Zero; } public void SendTakeControls(int controls, bool passToAgent, bool TakeControls) { } public virtual void SendTaskInventory(UUID taskID, short serial, byte[] fileName) { } public virtual void SendXferPacket(ulong xferID, uint packet, byte[] data) { } public virtual void SendAbortXferPacket(ulong xferID) { } public virtual void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent) { } public virtual void SendNameReply(UUID profileId, string firstname, string lastname) { } public virtual void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID) { } public virtual void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags) { } public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain) { } public void SendAttachedSoundGainChange(UUID objectID, float gain) { } public void SendAlertMessage(string message) { } public void SendAgentAlertMessage(string message, bool modal) { } public void SendSystemAlertMessage(string message) { } public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { } public virtual void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args) { if (OnRegionHandShakeReply != null) { OnRegionHandShakeReply(this); } if (OnCompleteMovementToRegion != null) { OnCompleteMovementToRegion(this); } } public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) { } public void SendConfirmXfer(ulong xferID, uint PacketID) { } public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName) { } public void SendInitiateDownload(string simFileName, string clientFileName) { } public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec) { } public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData) { } public void SendImageNotFound(UUID imageid) { } public void SendShutdownConnectionNotice() { } public void SendSimStats(SimStats stats) { } public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags) { } public void SendObjectPropertiesReply(ISceneEntity entity) { } public void SendAgentOffline(UUID[] agentIDs) { } public void SendAgentOnline(UUID[] agentIDs) { } public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook) { } public void SendAdminResponse(UUID Token, uint AdminLevel) { } public void SendGroupMembership(GroupMembershipData[] GroupMembership) { } private void Update() { frame++; if (frame > 20) { frame = 0; if (OnAgentUpdate != null) { AgentUpdateArgs pack = new AgentUpdateArgs(); pack.ControlFlags = movementFlag; pack.BodyRotation = bodyDirection; OnAgentUpdate(this, pack); } if (flyState == 0) { movementFlag = (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY | (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG; flyState = 1; } else if (flyState == 1) { movementFlag = (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY | (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS; flyState = 2; } else { movementFlag = (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY; flyState = 0; } if (count >= 10) { if (OnChatFromClient != null) { OSChatMessage args = new OSChatMessage(); args.Message = "Hey You! Get out of my Home. This is my Region"; args.Channel = 0; args.From = FirstName + " " + LastName; args.Scene = m_scene; args.Position = new Vector3(128, 128, 26); args.Sender = this; args.Type = ChatTypeEnum.Shout; OnChatFromClient(this, args); } count = -1; } count++; } } public bool AddMoney(int debit) { return false; } public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong time, uint dlen, uint ylen, float phase) { } public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks) { } public void SendViewerTime(int phase) { } public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] charterMember, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID) { } public void SetDebugPacketLevel(int newDebug) { } public void InPacket(object NewPack) { } public void ProcessInPacket(Packet NewPack) { } public void Close() { } public void Start() { } public void Stop() { } private uint m_circuitCode; public uint CircuitCode { get { return m_circuitCode; } set { m_circuitCode = value; } } public IPEndPoint RemoteEndPoint { get { return new IPEndPoint(IPAddress.Loopback, (ushort)m_circuitCode); } } public void SendBlueBoxMessage(UUID FromAvatarID, String FromAvatarName, String Message) { } public void SendLogoutPacket() { } public void Terminate() { } public EndPoint GetClientEP() { return null; } public ClientInfo GetClientInfo() { return null; } public void SetClientInfo(ClientInfo info) { } public void SendScriptQuestion(UUID objectID, string taskName, string ownerName, UUID itemID, int question) { } public void SendHealth(float health) { } public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID) { } public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID) { } public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args) { } public void SendEstateCovenantInformation(UUID covenant) { } public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner) { } public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, ILandObject lo, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags) { } public void SendLandAccessListData(List<UUID> avatars, uint accessFlag, int localLandID) { } public void SendForceClientSelectObjects(List<uint> objectIDs) { } public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount) { } public void SendCameraConstraint(Vector4 ConstraintPlane) { } public void SendLandParcelOverlay(byte[] data, int sequence_id) { } public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time) { } public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop) { } public void SendGroupNameReply(UUID groupLLUID, string GroupName) { } public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia) { } public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running) { } public void SendAsset(AssetRequestToClient req) { } public void SendTexture(AssetBase TextureAsset) { } public void SendSetFollowCamProperties (UUID objectID, SortedDictionary<int, float> parameters) { } public void SendClearFollowCamProperties (UUID objectID) { } public void SendRegionHandle (UUID regoinID, ulong handle) { } public void SendParcelInfo (RegionInfo info, LandData land, UUID parcelID, uint x, uint y) { } public void SetClientOption(string option, string value) { } public string GetClientOption(string option) { return string.Empty; } public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt) { } public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data) { } public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data) { } public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data) { } public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data) { } public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data) { } public void SendDirLandReply(UUID queryID, DirLandReplyData[] data) { } public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data) { } public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags) { } public void KillEndDone() { } public void SendEventInfoReply (EventData info) { } public void SendOfferCallingCard (UUID destID, UUID transactionID) { } public void SendAcceptCallingCard (UUID transactionID) { } public void SendDeclineCallingCard (UUID transactionID) { } public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data) { } public void SendJoinGroupReply(UUID groupID, bool success) { } public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool succss) { } public void SendLeaveGroupReply(UUID groupID, bool success) { } public void SendTerminateFriend(UUID exFriendID) { } #region IClientAPI Members public bool AddGenericPacketHandler(string MethodName, GenericMessage handler) { return true; } public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name) { } public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price) { } public void SendAgentDropGroup(UUID groupID) { } public void SendAvatarNotesReply(UUID targetID, string text) { } public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks) { } public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds) { } public void SendParcelDwellReply(int localID, UUID parcelID, float dwell) { } public void SendUserInfoReply(bool imViaEmail, bool visible, string email) { } public void SendCreateGroupReply(UUID groupID, bool success, string message) { } public void RefreshGroupMembership() { } public void SendUseCachedMuteList() { } public void SendMuteListUpdate(string filename) { } public void SendPickInfoReply(UUID pickID,UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled) { } #endregion public void SendRebakeAvatarTextures(UUID textureID) { } public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages) { } public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt) { } public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier) { } public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt) { } public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes) { } public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals) { } public void SendChangeUserRights(UUID agentID, UUID friendID, int rights) { } public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId) { } public void StopFlying(ISceneEntity presence) { } public void SendPlacesReply(UUID queryID, UUID transactionID, PlacesReplyData[] data) { } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Provisioning.Cloud.Async.WebJob.Job { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; namespace MVVMBase.Collections { /// <summary> /// This is a Dictionary that supports INotifyCollectionChanged semantics. /// </summary> /// <remarks> /// WARNING: this dictionary is NOT thread-safe! You must still /// provide synchronization to ensure no writes are done while the dictionary is being /// enumerated! This should not be a problem for most bindings as they rely on the /// CollectionChanged information. /// </remarks> /// <typeparam name="TKey">Key</typeparam> /// <typeparam name="TValue">Value type</typeparam> [DebuggerDisplay("Count={Count}")] public class ObservableDictionary<TKey, TValue> : IDictionary<TKey, TValue>, INotifyCollectionChanged, INotifyPropertyChanged { // Internal dictionary that holds values private readonly IDictionary<TKey, TValue> underlyingDictionary; private bool shouldRaiseNotifications; /// <summary> /// Constructor /// </summary> public ObservableDictionary() : this(new Dictionary<TKey, TValue>()) { } /// <summary> /// Constructor that allows different storage initialization /// </summary> public ObservableDictionary(IDictionary<TKey, TValue> store) { if(store == null) { throw new ArgumentNullException("store"); } underlyingDictionary = store; } /// <summary> /// Constructor that takes an equality comparer /// </summary> /// <param name="comparer">Comparison class</param> public ObservableDictionary(IEqualityComparer<TKey> comparer) : this(new Dictionary<TKey, TValue>(comparer)) { } /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </summary> /// <param name="item"> /// The object to add to the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </param> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only. /// </exception> void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { underlyingDictionary.Add(item); OnNotifyAdd(item); } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </summary> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only. /// </exception> public void Clear() { underlyingDictionary.Clear(); OnNotifyReset(); } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1" /> to an /// <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from /// <see cref="T:System.Collections.Generic.ICollection`1" />. The <see cref="T:System.Array" /> must have zero-based /// indexing. /// </param> /// <param name="arrayIndex"> /// The zero-based index in <paramref name="array" /> at which copying begins. /// </param> /// <exception cref="T:System.ArgumentNullException"><paramref name="array" /> is null.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex" /> is less than 0.</exception> public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { underlyingDictionary.CopyTo(array, arrayIndex); } /// <summary> /// Removes the first occurrence of a specific object from the /// <see cref="T:System.Collections.Generic.ICollection`1" />. /// </summary> /// <returns> /// true if <paramref name="item" /> was successfully removed from the /// <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false. This method also returns false if /// <paramref name="item" /> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1" />. /// </returns> /// <param name="item"> /// The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </param> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only. /// </exception> bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { bool flag = underlyingDictionary.Remove(item); if(flag) { OnNotifyRemove(item); } return flag; } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1" /> contains a specific value. /// </summary> /// <returns> /// true if <paramref name="item" /> is found in the <see cref="T:System.Collections.Generic.ICollection`1" />; /// otherwise, false. /// </returns> /// <param name="item"> /// The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </param> bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return underlyingDictionary.Contains(item); } /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </summary> /// <returns> /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </returns> public int Count { get => underlyingDictionary.Count; } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only. /// </summary> /// <returns> /// true if the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only; otherwise, false. /// </returns> public bool IsReadOnly { get => false; } /// <summary> /// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2" />. /// </summary> /// <param name="key"> /// The object to use as the key of the element to add. /// </param> /// <param name="value"> /// The object to use as the value of the element to add. /// </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="key" /> is null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2" />. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.IDictionary`2" /> is read-only. /// </exception> public void Add(TKey key, TValue value) { var item = new KeyValuePair<TKey, TValue>(key, value); underlyingDictionary.Add(item); OnNotifyAdd(item); } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the /// specified key. /// </summary> /// <returns> /// true if the <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the key; otherwise, /// false. /// </returns> /// <param name="key"> /// The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2" />. /// </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="key" /> is null. /// </exception> public bool ContainsKey(TKey key) { return underlyingDictionary.ContainsKey(key); } /// <summary> /// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2" />. /// </summary> /// <returns> /// true if the element is successfully removed; otherwise, false. This method also returns false if /// <paramref name="key" /> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2" />. /// </returns> /// <param name="key"> /// The key of the element to remove. /// </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="key" /> is null. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.IDictionary`2" /> is read-only. /// </exception> public bool Remove(TKey key) { TValue local = underlyingDictionary[key]; bool flag = underlyingDictionary.Remove(key); OnNotifyRemove(new KeyValuePair<TKey, TValue>(key, local)); return flag; } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <returns> /// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element /// with the specified key; otherwise, false. /// </returns> /// <param name="key"> /// The key whose value to get. /// </param> /// <param name="value"> /// When this method returns, the value associated with the specified key, if the key is found; otherwise, the default /// value for the type of the <paramref name="value" /> parameter. This parameter is passed uninitialized. /// </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="key" /> is null. /// </exception> public bool TryGetValue(TKey key, out TValue value) { return underlyingDictionary.TryGetValue(key, out value); } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <returns> /// The element with the specified key. /// </returns> /// <param name="key"> /// The key of the element to get or set. /// </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="key" /> is null. /// </exception> /// <exception cref="T:System.Collections.Generic.KeyNotFoundException"> /// The property is retrieved and <paramref name="key" /> is not found. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The property is set and the <see cref="T:System.Collections.Generic.IDictionary`2" /> is read-only. /// </exception> public TValue this[TKey key] { get => underlyingDictionary[key]; set { if(underlyingDictionary.ContainsKey(key)) { TValue originalValue = underlyingDictionary[key]; underlyingDictionary[key] = value; OnNotifyReplace(new KeyValuePair<TKey, TValue>(key, value), new KeyValuePair<TKey, TValue>(key, originalValue)); } else { underlyingDictionary[key] = value; OnNotifyAdd(new KeyValuePair<TKey, TValue>(key, value)); } } } /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the /// <see cref="T:System.Collections.Generic.IDictionary`2" />. /// </summary> /// <returns> /// An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the object that implements /// <see cref="T:System.Collections.Generic.IDictionary`2" />. /// </returns> public ICollection<TKey> Keys { get => underlyingDictionary.Keys; } /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the /// <see cref="T:System.Collections.Generic.IDictionary`2" />. /// </summary> /// <returns> /// An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the object that implements /// <see cref="T:System.Collections.Generic.IDictionary`2" />. /// </returns> public ICollection<TValue> Values { get => underlyingDictionary.Values; } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. /// </returns> /// <filterpriority>2</filterpriority> IEnumerator IEnumerable.GetEnumerator() { return underlyingDictionary.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection. /// </returns> /// <filterpriority>1</filterpriority> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return underlyingDictionary.GetEnumerator(); } /// <summary> /// Event raised for collection change notification /// </summary> public event NotifyCollectionChangedEventHandler CollectionChanged; /// <summary> /// Event raise for property changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// This method turns off notifications until the returned object /// is Disposed. At that point, the entire dictionary is invalidated. /// </summary> /// <returns>IDisposable</returns> public IDisposable BeginMassUpdate() { return new MassUpdater(this); } /// <summary> /// This is used to notify insertions into the dictionary. /// </summary> /// <param name="item">Item</param> protected void OnNotifyAdd(KeyValuePair<TKey, TValue> item) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item)); OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count))); OnPropertyChanged(new PropertyChangedEventArgs(item.Key.ToString())); } /// <summary> /// This is used to notify removals from the dictionary /// </summary> /// <param name="item">Item</param> protected void OnNotifyRemove(KeyValuePair<TKey, TValue> item) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item)); OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count))); OnPropertyChanged(new PropertyChangedEventArgs(item.Key.ToString())); } /// <summary> /// This is used to notify replacements in the dictionary /// </summary> /// <param name="newItem">New item</param> /// <param name="oldItem">Old item</param> protected void OnNotifyReplace(KeyValuePair<TKey, TValue> newItem, KeyValuePair<TKey, TValue> oldItem) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, newItem, oldItem)); OnPropertyChanged(new PropertyChangedEventArgs(oldItem.Key.ToString())); } /// <summary> /// This is used to notify that the dictionary was completely reset. /// </summary> protected void OnNotifyReset() { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count))); } /// <summary> /// Raises the <see cref="E:System.Collections.ObjectModel.ObservableCollection`1.CollectionChanged" /> event with the /// provided arguments. /// </summary> /// <param name="e">Arguments of the event being raised.</param> protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { if(shouldRaiseNotifications == false) { return; } CollectionChanged?.Invoke(this, e); } /// <summary> /// Raises the property change notification /// </summary> /// <param name="e">Property event args.</param> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { if(shouldRaiseNotifications == false) { return; } PropertyChanged?.Invoke(this, e); } /// <summary> /// IDisposable class which turns off updating /// </summary> private class MassUpdater : IDisposable { private readonly ObservableDictionary<TKey, TValue> parent; public MassUpdater(ObservableDictionary<TKey, TValue> parent) { this.parent = parent; parent.shouldRaiseNotifications = false; } public void Dispose() { parent.shouldRaiseNotifications = true; parent.OnNotifyReset(); } #if DEBUG ~MassUpdater() { Debug.Assert(true, "Did not dispose returned object from ObservableDictionary.BeginMassUpdate!"); } #endif } } }
// // PixbufUtils.cs // // Author: // Ruben Vermeersch <[email protected]> // Larry Ewing <[email protected]> // Stephane Delcroix <[email protected]> // // Copyright (C) 2004-2010 Novell, Inc. // Copyright (C) 2010 Ruben Vermeersch // Copyright (C) 2004-2007 Larry Ewing // Copyright (C) 2006-2009 Stephane Delcroix // // 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.IO; using System.Runtime.InteropServices; using Cairo; using Gdk; using FSpot.Cms; using FSpot.Core; using FSpot.Utils; using FSpot.Imaging; using FSpot.UI.Dialog; using Hyena; using TagLib.Image; using Pinta.Core; using Pinta.Effects; public static class PixbufUtils { static Pixbuf error_pixbuf = null; public static Pixbuf ErrorPixbuf { get { if (error_pixbuf == null) error_pixbuf = GtkUtil.TryLoadIcon (FSpot.Core.Global.IconTheme, "f-spot-question-mark", 256, (Gtk.IconLookupFlags)0); return error_pixbuf; } } public static Pixbuf LoadingPixbuf = PixbufUtils.LoadFromAssembly ("f-spot-loading.png"); public static double Fit (Pixbuf pixbuf, int dest_width, int dest_height, bool upscale_smaller, out int fit_width, out int fit_height) { return Fit (pixbuf.Width, pixbuf.Height, dest_width, dest_height, upscale_smaller, out fit_width, out fit_height); } public static double Fit (int orig_width, int orig_height, int dest_width, int dest_height, bool upscale_smaller, out int fit_width, out int fit_height) { if (orig_width == 0 || orig_height == 0) { fit_width = 0; fit_height = 0; return 0.0; } double scale = Math.Min (dest_width / (double)orig_width, dest_height / (double)orig_height); if (scale > 1.0 && !upscale_smaller) scale = 1.0; fit_width = (int)Math.Round (scale * orig_width); fit_height = (int)Math.Round (scale * orig_height); return scale; } // FIXME: These should be in GTK#. When my patch is committed, these LoadFrom* methods will // go away. public class AspectLoader { Gdk.PixbufLoader loader = new Gdk.PixbufLoader (); int max_width; int max_height; ImageOrientation orientation; public AspectLoader (int max_width, int max_height) { this.max_height = max_height; this.max_width = max_width; loader.SizePrepared += HandleSizePrepared; } private void HandleSizePrepared (object obj, SizePreparedArgs args) { switch (orientation) { case ImageOrientation.LeftTop: case ImageOrientation.LeftBottom: case ImageOrientation.RightTop: case ImageOrientation.RightBottom: int tmp = max_width; max_width = max_height; max_height = tmp; break; default: break; } int scale_width = 0; int scale_height = 0; double scale = Fit (args.Width, args.Height, max_width, max_height, true, out scale_width, out scale_height); if (scale < 1.0) loader.SetSize (scale_width, scale_height); } public Pixbuf Load (System.IO.Stream stream, ImageOrientation orientation) { int count; byte [] data = new byte [8192]; while (((count = stream.Read (data, 0, data.Length)) > 0) && loader.Write (data, (ulong)count)) { ; } loader.Close (); Pixbuf orig = loader.Pixbuf; Gdk.Pixbuf rotated = FSpot.Utils.PixbufUtils.TransformOrientation (orig, orientation); if (orig != rotated) orig.Dispose (); loader.Dispose (); return rotated; } public Pixbuf LoadFromFile (string path) { try { orientation = GetOrientation (new SafeUri (path)); using (FileStream fs = System.IO.File.OpenRead (path)) { return Load (fs, orientation); } } catch (Exception) { Log.ErrorFormat ("Error loading photo {0}", path); return null; } } } public static Pixbuf ScaleToMaxSize (Pixbuf pixbuf, int width, int height, bool upscale = true) { int scale_width = 0; int scale_height = 0; double scale = Fit (pixbuf, width, height, upscale, out scale_width, out scale_height); Gdk.Pixbuf result; if (upscale || (scale < 1.0)) result = pixbuf.ScaleSimple (scale_width, scale_height, (scale_width > 20) ? Gdk.InterpType.Bilinear : Gdk.InterpType.Nearest); else result = pixbuf.Copy (); return result; } static public Pixbuf LoadAtMaxSize (string path, int max_width, int max_height) { PixbufUtils.AspectLoader loader = new AspectLoader (max_width, max_height); return loader.LoadFromFile (path); } public static Pixbuf TagIconFromPixbuf (Pixbuf source) { return IconFromPixbuf (source, (int)Tag.IconSize.Large); } public static Pixbuf IconFromPixbuf (Pixbuf source, int size) { Pixbuf tmp = null; Pixbuf icon = null; if (source.Width > source.Height) source = tmp = new Pixbuf (source, (source.Width - source.Height) / 2, 0, source.Height, source.Height); else if (source.Width < source.Height) source = tmp = new Pixbuf (source, 0, (source.Height - source.Width) / 2, source.Width, source.Width); if (source.Width == source.Height) icon = source.ScaleSimple (size, size, InterpType.Bilinear); else throw new Exception ("Bad logic leads to bad accidents"); if (tmp != null) tmp.Dispose (); return icon; } static Pixbuf LoadFromAssembly (string resource) { try { return new Pixbuf (System.Reflection.Assembly.GetEntryAssembly (), resource); } catch { return null; } } public static Gdk.Pixbuf ScaleToAspect (Gdk.Pixbuf orig, int width, int height) { Gdk.Rectangle pos; double scale = Fit (orig, width, height, false, out pos.Width, out pos.Height); pos.X = (width - pos.Width) / 2; pos.Y = (height - pos.Height) / 2; Pixbuf scaled = new Pixbuf (Colorspace.Rgb, false, 8, width, height); scaled.Fill (0x000000); orig.Composite (scaled, pos.X, pos.Y, pos.Width, pos.Height, pos.X, pos.Y, scale, scale, Gdk.InterpType.Bilinear, 255); return scaled; } public static Pixbuf Flatten (Pixbuf pixbuf) { if (!pixbuf.HasAlpha) return null; Pixbuf flattened = new Pixbuf (Colorspace.Rgb, false, 8, pixbuf.Width, pixbuf.Height); pixbuf.CompositeColor (flattened, 0, 0, pixbuf.Width, pixbuf.Height, 0, 0, 1, 1, InterpType.Bilinear, 255, 0, 0, 2000, 0xffffff, 0xffffff); return flattened; } unsafe public static byte[] Pixbuf_GetRow (byte* pixels, int row, int rowstride, int width, int channels, byte[] dest) { byte* ptr = ((byte*)pixels) + (row * rowstride); Marshal.Copy (((IntPtr)ptr), dest, 0, width * channels); return dest; } unsafe public static void Pixbuf_SetRow (byte* pixels, byte[] dest, int row, int rowstride, int width, int channels) { byte* destPtr = pixels + row * rowstride; for (int i=0; i < width*channels; i++) { destPtr [i] = dest [i]; } } unsafe public static Pixbuf UnsharpMask (Pixbuf src, double radius, double amount, double threshold, ThreadProgressDialog progressDialog) { // Make sure the pixbuf has an alpha channel before we try to blur it src = src.AddAlpha (false, 0, 0, 0); Pixbuf result = Blur (src, (int)radius, progressDialog); int sourceRowstride = src.Rowstride; int sourceHeight = src.Height; int sourceChannels = src.NChannels; int sourceWidth = src.Width; int resultRowstride = result.Rowstride; int resultWidth = result.Width; int resultChannels = result.NChannels; byte[] srcRow = new byte[sourceRowstride]; byte[] destRow = new byte[resultRowstride]; byte* sourcePixels = (byte*)src.Pixels; byte* resultPixels = (byte*)result.Pixels; for (int row=0; row < sourceHeight; row++) { Pixbuf_GetRow (sourcePixels, row, sourceRowstride, sourceWidth, sourceChannels, srcRow); Pixbuf_GetRow (resultPixels, row, resultRowstride, resultWidth, resultChannels, destRow); int diff; for (int i=0; i < sourceWidth*sourceChannels; i++) { diff = srcRow [i] - destRow [i]; if (Math.Abs (2 * diff) < threshold) diff = 0; int val = (int)(srcRow [i] + amount * diff); if (val > 255) val = 255; else if (val < 0) val = 0; destRow [i] = (byte)val; } Pixbuf_SetRow (resultPixels, destRow, row, resultRowstride, resultWidth, resultChannels); // This is the other half of the progress so start and halfway if (progressDialog != null) progressDialog.Fraction = ((double)row / ((double) sourceHeight - 1) ) * 0.25 + 0.75; } return result; } public static Pixbuf Blur (Pixbuf src, int radius, ThreadProgressDialog dialog) { ImageSurface sourceSurface = Hyena.Gui.PixbufImageSurface.Create (src); ImageSurface destinationSurface = new ImageSurface (Cairo.Format.Rgb24, src.Width, src.Height); // If we do it as a bunch of single lines (rectangles of one pixel) then we can give the progress // here instead of going deeper to provide the feedback for (int i=0; i < src.Height; i++) { GaussianBlurEffect.RenderBlurEffect (sourceSurface, destinationSurface, new[] { new Gdk.Rectangle (0, i, src.Width, 1) }, radius); if (dialog != null) { // This only half of the entire process double fraction = ((double)i / (double)(src.Height - 1)) * 0.75; dialog.Fraction = fraction; } } return destinationSurface.ToPixbuf (); } public static ImageSurface Clone (this ImageSurface surf) { ImageSurface newsurf = new ImageSurface (surf.Format, surf.Width, surf.Height); using (Context g = new Context (newsurf)) { g.SetSource (surf); g.Paint (); } return newsurf; } public unsafe static Gdk.Pixbuf RemoveRedeye (Gdk.Pixbuf src, Gdk.Rectangle area) { return RemoveRedeye (src, area, -15); } //threshold, factors and comparisons borrowed from the gimp plugin 'redeye.c' by Robert Merkel public unsafe static Gdk.Pixbuf RemoveRedeye (Gdk.Pixbuf src, Gdk.Rectangle area, int threshold) { Gdk.Pixbuf copy = src.Copy (); Gdk.Pixbuf selection = new Gdk.Pixbuf (copy, area.X, area.Y, area.Width, area.Height); byte * spix = (byte *)selection.Pixels; int h = selection.Height; int w = selection.Width; int channels = src.NChannels; double RED_FACTOR = 0.5133333; double GREEN_FACTOR = 1; double BLUE_FACTOR = 0.1933333; for (int j = 0; j < h; j++) { byte * s = spix; for (int i = 0; i < w; i++) { int adjusted_red = (int)(s [0] * RED_FACTOR); int adjusted_green = (int)(s [1] * GREEN_FACTOR); int adjusted_blue = (int)(s [2] * BLUE_FACTOR); if (adjusted_red >= adjusted_green - threshold && adjusted_red >= adjusted_blue - threshold) s [0] = (byte)(((double)(adjusted_green + adjusted_blue)) / (2.0 * RED_FACTOR)); s += channels; } spix += selection.Rowstride; } return copy; } public static unsafe Pixbuf ColorAdjust (Pixbuf src, double brightness, double contrast, double hue, double saturation, int src_color, int dest_color) { Pixbuf adjusted = new Pixbuf (Colorspace.Rgb, src.HasAlpha, 8, src.Width, src.Height); PixbufUtils.ColorAdjust (src, adjusted, brightness, contrast, hue, saturation, src_color, dest_color); return adjusted; } public static FSpot.Cms.Format PixbufCmsFormat (Pixbuf buf) { return buf.HasAlpha ? FSpot.Cms.Format.Rgba8Planar : FSpot.Cms.Format.Rgb8; } public static unsafe void ColorAdjust (Pixbuf src, Pixbuf dest, double brightness, double contrast, double hue, double saturation, int src_color, int dest_color) { if (src.Width != dest.Width || src.Height != dest.Height) throw new Exception ("Invalid Dimensions"); var srgb = Profile.CreateStandardRgb (); var bchsw = Profile.CreateAbstract (256, 0.0, brightness, contrast, hue, saturation, src_color, dest_color); Profile [] list = { srgb, bchsw, srgb }; var trans = new Transform (list, PixbufCmsFormat (src), PixbufCmsFormat (dest), Intent.Perceptual, 0x0100); ColorAdjust (src, dest, trans); trans.Dispose (); srgb.Dispose (); bchsw.Dispose (); } public static unsafe void ColorAdjust (Gdk.Pixbuf src, Gdk.Pixbuf dest, Transform trans) { int width = src.Width; byte * srcpix = (byte *)src.Pixels; byte * destpix = (byte *)dest.Pixels; for (int row = 0; row < src.Height; row++) { trans.Apply ((IntPtr)(srcpix + row * src.Rowstride), (IntPtr)(destpix + row * dest.Rowstride), (uint)width); } } public static unsafe bool IsGray (Gdk.Pixbuf pixbuf, int max_difference) { int chan = pixbuf.NChannels; byte * pix = (byte *)pixbuf.Pixels; int h = pixbuf.Height; int w = pixbuf.Width; int stride = pixbuf.Rowstride; for (int j = 0; j < h; j++) { byte * p = pix; for (int i = 0; i < w; i++) { if (Math.Abs (p [0] - p [1]) > max_difference || Math.Abs (p [0] - p [2]) > max_difference) return false; p += chan; } pix += stride; } return true; } public static unsafe void ReplaceColor (Gdk.Pixbuf src, Gdk.Pixbuf dest) { if (src.HasAlpha || !dest.HasAlpha || (src.Width != dest.Width) || (src.Height != dest.Height)) throw new ApplicationException ("invalid pixbufs"); byte * dpix = (byte *)dest.Pixels; byte * spix = (byte *)src.Pixels; int h = src.Height; int w = src.Width; for (int j = 0; j < h; j++) { byte * d = dpix; byte * s = spix; for (int i = 0; i < w; i++) { d [0] = s [0]; d [1] = s [1]; d [2] = s [2]; d += 4; s += 3; } dpix += dest.Rowstride; spix += src.Rowstride; } } public static ImageOrientation GetOrientation (SafeUri uri) { using (var img = ImageFile.Create (uri)) { return img.Orientation; } } [DllImport("libgnomethumbnailpixbufutils.dll")] static extern IntPtr gnome_desktop_thumbnail_scale_down_pixbuf (IntPtr pixbuf, int dest_width, int dest_height); public static Gdk.Pixbuf ScaleDown (Gdk.Pixbuf src, int width, int height) { IntPtr raw_ret = gnome_desktop_thumbnail_scale_down_pixbuf (src.Handle, width, height); Gdk.Pixbuf ret; if (raw_ret == IntPtr.Zero) ret = null; else ret = (Gdk.Pixbuf)GLib.Object.GetObject (raw_ret, true); return ret; } public static void CreateDerivedVersion (SafeUri source, SafeUri destination) { CreateDerivedVersion (source, destination, 95); } public static void CreateDerivedVersion (SafeUri source, SafeUri destination, uint jpeg_quality) { if (source.GetExtension () == destination.GetExtension ()) { // Simple copy will do! var file_from = GLib.FileFactory.NewForUri (source); var file_to = GLib.FileFactory.NewForUri (destination); file_from.Copy (file_to, GLib.FileCopyFlags.AllMetadata | GLib.FileCopyFlags.Overwrite, null, null); return; } // Else make a derived copy with metadata copied using (var img = ImageFile.Create (source)) { using (var pixbuf = img.Load ()) { CreateDerivedVersion (source, destination, jpeg_quality, pixbuf); } } } public static void CreateDerivedVersion (SafeUri source, SafeUri destination, uint jpeg_quality, Pixbuf pixbuf) { SaveToSuitableFormat (destination, pixbuf, jpeg_quality); using (var metadata_from = Metadata.Parse (source)) { using (var metadata_to = Metadata.Parse (destination)) { metadata_to.CopyFrom (metadata_from); // Reset orientation to make sure images appear upright. metadata_to.ImageTag.Orientation = ImageOrientation.TopLeft; metadata_to.Save (); } } } private static void SaveToSuitableFormat (SafeUri destination, Pixbuf pixbuf, uint jpeg_quality) { // FIXME: this needs to work on streams rather than filenames. Do that when we switch to // newer GDK. var extension = destination.GetExtension ().ToLower (); if (extension == ".png") pixbuf.Save (destination.LocalPath, "png"); else if (extension == ".jpg" || extension == ".jpeg") pixbuf.Save (destination.LocalPath, "jpeg", jpeg_quality); else throw new NotImplementedException ("Saving this file format is not supported"); } #region Gdk hackery // This hack below is needed because there is no wrapped version of // Save which allows specifying the variable arguments (it's not // possible with p/invoke). [DllImport("libgdk_pixbuf-2.0-0.dll")] static extern bool gdk_pixbuf_save (IntPtr raw, IntPtr filename, IntPtr type, out IntPtr error, IntPtr optlabel1, IntPtr optvalue1, IntPtr dummy); private static bool Save (this Pixbuf pixbuf, string filename, string type, uint jpeg_quality) { IntPtr error = IntPtr.Zero; IntPtr nfilename = GLib.Marshaller.StringToPtrGStrdup (filename); IntPtr ntype = GLib.Marshaller.StringToPtrGStrdup (type); IntPtr optlabel1 = GLib.Marshaller.StringToPtrGStrdup ("quality"); IntPtr optvalue1 = GLib.Marshaller.StringToPtrGStrdup (jpeg_quality.ToString ()); bool ret = gdk_pixbuf_save (pixbuf.Handle, nfilename, ntype, out error, optlabel1, optvalue1, IntPtr.Zero); GLib.Marshaller.Free (nfilename); GLib.Marshaller.Free (ntype); GLib.Marshaller.Free (optlabel1); GLib.Marshaller.Free (optvalue1); if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } #endregion }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Algorithms.Tests { public class IncrementalHashTests { // Some arbitrarily chosen OID segments private static readonly byte[] s_hmacKey = { 2, 5, 29, 54, 1, 2, 84, 113, 54, 91, 1, 1, 2, 5, 29, 10, }; private static readonly byte[] s_inputBytes = ByteUtils.RepeatByte(0xA5, 512); public static IEnumerable<object[]> GetHashAlgorithms() { return new[] { new object[] { MD5.Create(), HashAlgorithmName.MD5 }, new object[] { SHA1.Create(), HashAlgorithmName.SHA1 }, new object[] { SHA256.Create(), HashAlgorithmName.SHA256 }, new object[] { SHA384.Create(), HashAlgorithmName.SHA384 }, new object[] { SHA512.Create(), HashAlgorithmName.SHA512 }, }; } public static IEnumerable<object[]> GetHMACs() { return new[] { new object[] { new HMACMD5(), HashAlgorithmName.MD5 }, new object[] { new HMACSHA1(), HashAlgorithmName.SHA1 }, new object[] { new HMACSHA256(), HashAlgorithmName.SHA256 }, new object[] { new HMACSHA384(), HashAlgorithmName.SHA384 }, new object[] { new HMACSHA512(), HashAlgorithmName.SHA512 }, }; } [Theory] [MemberData("GetHashAlgorithms")] public static void VerifyIncrementalHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm)) { VerifyIncrementalResult(referenceAlgorithm, incrementalHash); } } [Theory] [MemberData("GetHMACs")] public static void VerifyIncrementalHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; VerifyIncrementalResult(referenceAlgorithm, incrementalHash); } } private static void VerifyIncrementalResult(HashAlgorithm referenceAlgorithm, IncrementalHash incrementalHash) { byte[] referenceHash = referenceAlgorithm.ComputeHash(s_inputBytes); const int StepA = 13; const int StepB = 7; int position = 0; while (position < s_inputBytes.Length - StepA) { incrementalHash.AppendData(s_inputBytes, position, StepA); position += StepA; } incrementalHash.AppendData(s_inputBytes, position, s_inputBytes.Length - position); byte[] incrementalA = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalA); // Now try again, verifying both immune to step size behaviors, and that GetHashAndReset resets. position = 0; while (position < s_inputBytes.Length - StepB) { incrementalHash.AppendData(s_inputBytes, position, StepA); position += StepA; } incrementalHash.AppendData(s_inputBytes, position, s_inputBytes.Length - position); byte[] incrementalB = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalB); } [Theory] [MemberData("GetHashAlgorithms")] public static void VerifyEmptyHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm)) { for (int i = 0; i < 10; i++) { incrementalHash.AppendData(Array.Empty<byte>()); } byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Theory] [MemberData("GetHMACs")] public static void VerifyEmptyHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; for (int i = 0; i < 10; i++) { incrementalHash.AppendData(Array.Empty<byte>()); } byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Theory] [MemberData("GetHashAlgorithms")] public static void VerifyTrivialHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm)) { byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Theory] [MemberData("GetHMACs")] public static void VerifyTrivialHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Fact] public static void AppendDataAfterHashClose() { using (IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { byte[] firstHash = hash.GetHashAndReset(); hash.AppendData(Array.Empty<byte>()); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void AppendDataAfterHMACClose() { using (IncrementalHash hash = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, s_hmacKey)) { byte[] firstHash = hash.GetHashAndReset(); hash.AppendData(Array.Empty<byte>()); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void GetHashTwice() { using (IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { byte[] firstHash = hash.GetHashAndReset(); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void GetHMACTwice() { using (IncrementalHash hash = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, s_hmacKey)) { byte[] firstHash = hash.GetHashAndReset(); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void ModifyAfterHashDispose() { using (IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { hash.Dispose(); Assert.Throws<ObjectDisposedException>(() => hash.AppendData(Array.Empty<byte>())); Assert.Throws<ObjectDisposedException>(() => hash.GetHashAndReset()); } } [Fact] public static void ModifyAfterHMACDispose() { using (IncrementalHash hash = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, s_hmacKey)) { hash.Dispose(); Assert.Throws<ObjectDisposedException>(() => hash.AppendData(Array.Empty<byte>())); Assert.Throws<ObjectDisposedException>(() => hash.GetHashAndReset()); } } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Background Operation ///<para>SObject Name: BackgroundOperation</para> ///<para>Custom Object: False</para> ///</summary> public class SfBackgroundOperation : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "BackgroundOperation"; } } ///<summary> /// Background Operation ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Background Operation Name /// <para>Name: Name</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "name")] [Updateable(false), Createable(false)] public string Name { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Submitted /// <para>Name: SubmittedAt</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "submittedAt")] [Updateable(false), Createable(false)] public DateTimeOffset? SubmittedAt { get; set; } ///<summary> /// Status /// <para>Name: Status</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "status")] [Updateable(false), Createable(false)] public string Status { get; set; } ///<summary> /// Execution Group /// <para>Name: ExecutionGroup</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "executionGroup")] [Updateable(false), Createable(false)] public string ExecutionGroup { get; set; } ///<summary> /// Sequence Group /// <para>Name: SequenceGroup</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "sequenceGroup")] [Updateable(false), Createable(false)] public string SequenceGroup { get; set; } ///<summary> /// Sequence Number /// <para>Name: SequenceNumber</para> /// <para>SF Type: int</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "sequenceNumber")] [Updateable(false), Createable(false)] public int? SequenceNumber { get; set; } ///<summary> /// Background Operation ID /// <para>Name: GroupLeaderId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "groupLeaderId")] [Updateable(false), Createable(false)] public string GroupLeaderId { get; set; } ///<summary> /// ReferenceTo: BackgroundOperation /// <para>RelationshipName: GroupLeader</para> ///</summary> [JsonProperty(PropertyName = "groupLeader")] [Updateable(false), Createable(false)] public SfBackgroundOperation GroupLeader { get; set; } ///<summary> /// Started /// <para>Name: StartedAt</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "startedAt")] [Updateable(false), Createable(false)] public DateTimeOffset? StartedAt { get; set; } ///<summary> /// Finished /// <para>Name: FinishedAt</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "finishedAt")] [Updateable(false), Createable(false)] public DateTimeOffset? FinishedAt { get; set; } ///<summary> /// Worker URI /// <para>Name: WorkerUri</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "workerUri")] [Updateable(false), Createable(false)] public string WorkerUri { get; set; } ///<summary> /// Timeout /// <para>Name: Timeout</para> /// <para>SF Type: int</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "timeout")] [Updateable(false), Createable(false)] public int? Timeout { get; set; } ///<summary> /// ExpiresAt /// <para>Name: ExpiresAt</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "expiresAt")] [Updateable(false), Createable(false)] public DateTimeOffset? ExpiresAt { get; set; } ///<summary> /// NumFollowers /// <para>Name: NumFollowers</para> /// <para>SF Type: int</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "numFollowers")] [Updateable(false), Createable(false)] public int? NumFollowers { get; set; } ///<summary> /// ProcessAfter /// <para>Name: ProcessAfter</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "processAfter")] [Updateable(false), Createable(false)] public DateTimeOffset? ProcessAfter { get; set; } ///<summary> /// ParentKey /// <para>Name: ParentKey</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "parentKey")] [Updateable(false), Createable(false)] public string ParentKey { get; set; } ///<summary> /// RetryLimit /// <para>Name: RetryLimit</para> /// <para>SF Type: int</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "retryLimit")] [Updateable(false), Createable(false)] public int? RetryLimit { get; set; } ///<summary> /// RetryCount /// <para>Name: RetryCount</para> /// <para>SF Type: int</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "retryCount")] [Updateable(false), Createable(false)] public int? RetryCount { get; set; } ///<summary> /// RetryBackoff /// <para>Name: RetryBackoff</para> /// <para>SF Type: int</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "retryBackoff")] [Updateable(false), Createable(false)] public int? RetryBackoff { get; set; } ///<summary> /// Error /// <para>Name: Error</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "error")] [Updateable(false), Createable(false)] public string Error { get; set; } } }
using System; using System.Data; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using CslaGenerator; using CslaGenerator.Metadata; using CodeSmith.Engine; namespace CslaGenerator.Util { /// <summary> /// Summary description for VbCslaTemplateHelper. /// </summary> public class VbCslaTemplateHelper : CslaTemplateHelper { public VbCslaTemplateHelper() : base() { } public override string GetInitValue(TypeCodeEx typeCode) { if (typeCode == TypeCodeEx.Int16 || typeCode == TypeCodeEx.Int32 || typeCode == TypeCodeEx.Int64 || typeCode == TypeCodeEx.Double || typeCode == TypeCodeEx.Decimal || typeCode == TypeCodeEx.Single) { return "0"; } else if (typeCode == TypeCodeEx.String) { return "String.Empty"; } else if (typeCode == TypeCodeEx.Boolean) { return "False"; } else if (typeCode == TypeCodeEx.Byte) { return "0"; } else if (typeCode == TypeCodeEx.Object) { return "Nothing"; } else if (typeCode == TypeCodeEx.Guid) { return "Guid.Empty"; } else if (typeCode == TypeCodeEx.SmartDate) { return "New SmartDate(True)"; } else if (typeCode == TypeCodeEx.DateTime) { return "DateTime.Now"; } else if (typeCode == TypeCodeEx.Char) { return "Char.MinValue"; } else if (typeCode == TypeCodeEx.ByteArray) { return "new Byte() {}"; } else { return String.Empty; } } public override string GetInitValue(ValueProperty prop) { if (AllowNull(prop) && prop.PropertyType != TypeCodeEx.SmartDate) return "Nothing"; else return GetInitValue(prop.PropertyType); } public override string GetReaderAssignmentStatement(ValueProperty prop) { return GetReaderAssignmentStatement(prop,false); } public override string GetReaderAssignmentStatement(ValueProperty prop, bool Structure) { string statement; if (Structure) statement = "nfo." + prop.Name; else statement = FormatFieldName(prop.Name); if (PropertyMode == CslaPropertyMode.Managed) if (AllowNull(prop)) { string formatString; if (TypeHelper.IsNullableType(prop.PropertyType)) formatString = "LoadProperty({0}, If(Not dr.IsDBNull(\"{2}\"), New {3}(dr.{1}(\"{2}\")), Nothing))"; else formatString = "LoadProperty({0}, If(Not dr.IsDBNull(\"{2}\"), dr.{1}(\"{2}\"), Nothing))"; return String.Format(formatString, FormatManaged(prop.Name), GetReaderMethod(prop.PropertyType), prop.ParameterName, GetDataType(prop)); } else return String.Format("LoadProperty({0}, dr.{1}(\"{2}\"))", FormatManaged(prop.Name), GetReaderMethod(prop.PropertyType), prop.ParameterName); else return string.Format(GetDataReaderStatement(prop), statement); } public override string GetDataReaderStatement(ValueProperty prop) { bool ternarySupport = (GeneratorController.Current.CurrentUnit.GenerationParams.TargetFramework != TargetFramework.CSLA20 && GeneratorController.Current.CurrentUnit.GenerationParams.TargetFramework != TargetFramework.CSLA10); bool nullable = AllowNull(prop); StringBuilder st = new StringBuilder(); if (nullable && prop.PropertyType != TypeCodeEx.ByteArray) { if (ternarySupport) st.AppendFormat("If(Not dr.IsDBNull(\"{0}\"), ", prop.ParameterName); else st.AppendFormat("If Not dr.IsDBNull(\"{0}\") Then ", prop.ParameterName); } if (ternarySupport) st.Insert(0, "{0} = "); else st.Append("{0} = "); if (nullable && TypeHelper.IsNullableType(prop.PropertyType)) st.AppendFormat("New {0}(", GetDataType(prop)); st.Append("dr."); if (prop.DbBindColumn.ColumnOriginType == ColumnOriginType.None) st.Append(GetReaderMethod(prop.PropertyType)); else st.Append(GetReaderMethod(GetDbType(prop.DbBindColumn), prop.PropertyType)); st.Append("(\"" + prop.ParameterName + "\""); if (prop.PropertyType == TypeCodeEx.SmartDate) st.Append(", true"); st.Append(")"); if (nullable && TypeHelper.IsNullableType(prop.PropertyType)) st.Append(")"); if (nullable && ternarySupport && prop.PropertyType != TypeCodeEx.ByteArray) st.Append(", Nothing)"); if (prop.PropertyType == TypeCodeEx.ByteArray) { st.Remove(0, 6); return "{0} = TryCast(" + st.ToString() + ", Byte())"; } return st.ToString(); } protected override string GetDataType(TypeCodeEx type) { if (type == TypeCodeEx.ByteArray) return "Byte()"; return type.ToString(); } public override string GetDataType(Property prop) { string t = GetDataType(prop.PropertyType); if (AllowNull(prop)) { if (TypeHelper.IsNullableType(prop.PropertyType)) if (CurrentUnit.GenerationParams.TargetFramework == TargetFramework.CSLA10 || CurrentUnit.GenerationParams.TargetFramework == TargetFramework.CSLA20) t = string.Format("Nullable(Of {0})", t); else t += "?"; } return t; } public override string GetParameterSet(Property prop, bool Criteria) { bool nullable = AllowNull(prop); string propName; if (Criteria) propName = "crit." + FormatPascal(prop.Name); else if (PropertyMode == CslaPropertyMode.Managed) propName = String.Format("ReadProperty({0})", FormatManaged(prop.Name)); else propName = FormatFieldName(prop.Name); switch (prop.PropertyType) { case Metadata.TypeCodeEx.SmartDate: return propName + ".DBValue"; case Metadata.TypeCodeEx.Guid: if (nullable) return string.Format("GetNullableParameter(Of {0})({1})", prop.PropertyType.ToString(), propName); else return "IIf (" + propName + ".Equals(Guid.Empty), DBNull.Value, " + propName + ")"; default: if (nullable) { if (TypeHelper.IsNullableType(prop.PropertyType)) return string.Format("GetNullableParameter(Of {0})({1})", prop.PropertyType.ToString(), propName); else return "IIf (" + propName + " Is Nothing, DBNull.Value, " + propName + ")"; } else return propName; } } protected internal override string GetLanguageVariableType(DbType dataType) { switch (dataType) { case DbType.AnsiString: return "String"; case DbType.AnsiStringFixedLength: return "String"; case DbType.Binary: return "Byte()"; case DbType.Boolean: return "Boolean"; case DbType.Byte: return "Byte"; case DbType.Currency: return "Decimal"; case DbType.Date: case DbType.DateTime: return "DateTime"; case DbType.Decimal: return "Decimal"; case DbType.Double: return "Double"; case DbType.Guid: return "Guid"; case DbType.Int16: return "Short"; case DbType.Int32: return "Integer"; case DbType.Int64: return "Long"; case DbType.Object: return "Object"; case DbType.SByte: return "SByte"; case DbType.Single: return "Single"; case DbType.String: return "String"; case DbType.StringFixedLength: return "String"; case DbType.Time: return "TimeSpan"; case DbType.UInt16: return "Short"; case DbType.UInt32: return "Integer"; case DbType.UInt64: return "Long"; case DbType.VarNumeric: return "Decimal"; default: { return "__UNKNOWN__" + dataType.ToString(); } } } public override string GetRelationString(CslaObjectInfo info, ChildProperty child) { string indent = new string('\t', _indentLevel); StringBuilder sb = new StringBuilder(); CslaObjectInfo childInfo = FindChildInfo(info,child.TypeName); string joinColumn = String.Empty; if (child.LoadParameters.Count > 0) { if (IsCollectionType(childInfo.ObjectType)) { joinColumn = child.LoadParameters[0].Property.Name; childInfo = FindChildInfo(info,childInfo.ItemType); } if (joinColumn == String.Empty) { joinColumn = child.LoadParameters[0].Property.Name; } } sb.Append(indent); sb.Append("ds.Relations.Add(\""); sb.Append(info.ObjectName); sb.Append(childInfo.ObjectName); sb.Append("\", ds.Tables("); sb.Append(_resultSetCount.ToString()); sb.Append(").Columns(\""); sb.Append(joinColumn); sb.Append("\"), ds.Tables("); sb.Append((_resultSetCount + 1).ToString()); sb.Append(").Columns(\""); sb.Append(joinColumn); sb.Append("\"), False)"); _resultSetCount++; return sb.ToString(); } public override string GetXmlCommentString(string xmlComment) { string indent = new string('\t', _indentLevel); // add leading indent and comment sign xmlComment = indent + "''' " + xmlComment; return Regex.Replace(xmlComment, "\n", "\n" + indent + "''' ", RegexOptions.Multiline); } public override string GetUsingStatementsString(CslaObjectInfo info) { string[] usingNamespaces = GetNamespaces(info); string result = String.Empty; foreach (string namespaceName in usingNamespaces) { result += "Imports " + namespaceName + "\n"; } return(result); } public override string GetAttributesString(string[] attributes) { if (attributes == null || attributes.Length == 0) return string.Empty; return "<" + string.Join(", ", attributes) + "> _"; } public override string LoadProperty(ValueProperty prop, string value) { string result = base.LoadProperty(prop, value); return result.Substring(0, result.Length - 1); } } }
// // PreferenceDialog.cs // // Author: // Stephane Delcroix <[email protected]> // Ruben Vermeersch <[email protected]> // // Copyright (C) 2006-2010 Novell, Inc. // Copyright (C) 2006-2010 Stephane Delcroix // Copyright (C) 2010 Ruben Vermeersch // // 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.IO; using System.Linq; using FSpot.Settings; using Gtk; using Mono.Unix; using Hyena; namespace FSpot.UI.Dialog { public class PreferenceDialog : BuilderDialog { #pragma warning disable 649 [GtkBeans.Builder.Object] FileChooserButton photosdir_chooser; [GtkBeans.Builder.Object] RadioButton writemetadata_radio; [GtkBeans.Builder.Object] RadioButton dontwrite_radio; [GtkBeans.Builder.Object] CheckButton always_sidecar_check; [GtkBeans.Builder.Object] ComboBox theme_combo; [GtkBeans.Builder.Object] ComboBox screenprofile_combo; [GtkBeans.Builder.Object] ComboBox printprofile_combo; #pragma warning restore 649 #region public API (ctor) public PreferenceDialog (Window parent) : base ("PreferenceDialog.ui", "preference_dialog") { TransientFor = parent; //Photos Folder photosdir_chooser.SetCurrentFolderUri (FSpot.Settings.Global.PhotoUri); SafeUri storage_path = new SafeUri (Preferences.Get<string> (Preferences.STORAGE_PATH)); //If the user has set a photo directory on the commandline then don't let it be changed in Preferences if (storage_path.Equals(FSpot.Settings.Global.PhotoUri)) photosdir_chooser.CurrentFolderChanged += HandlePhotosdirChanged; else photosdir_chooser.Sensitive = false; //Write Metadata LoadPreference (Preferences.METADATA_EMBED_IN_IMAGE); LoadPreference (Preferences.METADATA_ALWAYS_USE_SIDECAR); //Screen profile ListStore sprofiles = new ListStore (typeof (string), typeof (int)); sprofiles.AppendValues (Catalog.GetString ("None"), 0); if (FSpot.ColorManagement.XProfile != null) sprofiles.AppendValues (Catalog.GetString ("System profile"), -1); sprofiles.AppendValues (null, 0); //Pick the display profiles from the full list, avoid _x_profile_ var dprofs = from profile in FSpot.ColorManagement.Profiles where (profile.Value.DeviceClass == Cms.IccProfileClass.Display && profile.Key != "_x_profile_") select profile; foreach (var p in dprofs) sprofiles.AppendValues (p.Key, 1); CellRendererText profilecellrenderer = new CellRendererText (); profilecellrenderer.Ellipsize = Pango.EllipsizeMode.End; screenprofile_combo.Model = sprofiles; screenprofile_combo.PackStart (profilecellrenderer, true); screenprofile_combo.RowSeparatorFunc = ProfileSeparatorFunc; screenprofile_combo.SetCellDataFunc (profilecellrenderer, ProfileCellFunc); LoadPreference (Preferences.COLOR_MANAGEMENT_DISPLAY_PROFILE); //Print profile ListStore pprofiles = new ListStore (typeof (string), typeof (int)); pprofiles.AppendValues (Catalog.GetString ("None"), 0); pprofiles.AppendValues (null, 0); var pprofs = from profile in FSpot.ColorManagement.Profiles where (profile.Value.DeviceClass == Cms.IccProfileClass.Output && profile.Key != "_x_profile_") select profile; foreach (var p in pprofs) pprofiles.AppendValues (p.Key, 1); printprofile_combo.Model = pprofiles; printprofile_combo.PackStart (profilecellrenderer, true); printprofile_combo.RowSeparatorFunc = ProfileSeparatorFunc; printprofile_combo.SetCellDataFunc (profilecellrenderer, ProfileCellFunc); LoadPreference (Preferences.COLOR_MANAGEMENT_OUTPUT_PROFILE); //Theme chooser ListStore themes = new ListStore (typeof (string), typeof (string)); themes.AppendValues (Catalog.GetString ("Standard theme"), null); themes.AppendValues (null, null); //Separator string gtkrc = System.IO.Path.Combine ("gtk-2.0", "gtkrc"); string [] search = {System.IO.Path.Combine (FSpot.Settings.Global.HomeDirectory, ".themes"), "/usr/share/themes"}; foreach (string path in search) if (Directory.Exists (path)) foreach (string dir in Directory.GetDirectories (path)) if (File.Exists (System.IO.Path.Combine (dir, gtkrc))) themes.AppendValues (System.IO.Path.GetFileName (dir), System.IO.Path.Combine (dir, gtkrc)); CellRenderer themecellrenderer = new CellRendererText (); theme_combo.Model = themes; theme_combo.PackStart (themecellrenderer, true); theme_combo.RowSeparatorFunc = ThemeSeparatorFunc; theme_combo.SetCellDataFunc (themecellrenderer, ThemeCellFunc); LoadPreference (Preferences.GTK_RC); ConnectEvents (); } #endregion #region preferences void OnPreferencesChanged (object sender, NotifyEventArgs args) { LoadPreference (args.Key); } void LoadPreference (string key) { string pref; int i; switch (key) { case Preferences.STORAGE_PATH: photosdir_chooser.SetCurrentFolder (Preferences.Get<string> (key)); break; case Preferences.METADATA_EMBED_IN_IMAGE: bool embed_active = Preferences.Get<bool> (key); if (writemetadata_radio.Active != embed_active) { if (embed_active) { writemetadata_radio.Active = true; } else { dontwrite_radio.Active = true; } } always_sidecar_check.Sensitive = embed_active; break; case Preferences.METADATA_ALWAYS_USE_SIDECAR: bool always_use_sidecar = Preferences.Get<bool> (key); always_sidecar_check.Active = always_use_sidecar; break; case Preferences.GTK_RC: pref = Preferences.Get<string> (key); if (string.IsNullOrEmpty (pref)) { theme_combo.Active = 0; break; } i = 0; foreach (object [] row in theme_combo.Model as ListStore) { if (pref == (string)row [1]) { theme_combo.Active = i; break; } i++; } break; case Preferences.COLOR_MANAGEMENT_DISPLAY_PROFILE: pref = Preferences.Get<string> (key); if (string.IsNullOrEmpty (pref)) { screenprofile_combo.Active = 0; break; } if (pref == "_x_profile_" && FSpot.ColorManagement.XProfile != null) { screenprofile_combo.Active = 1; break; } i = 0; foreach (object [] row in screenprofile_combo.Model as ListStore) { if (pref == (string)row [0]) { screenprofile_combo.Active = i; break; } i++; } break; case Preferences.COLOR_MANAGEMENT_OUTPUT_PROFILE: pref = Preferences.Get<string> (key); if (string.IsNullOrEmpty (pref)) { printprofile_combo.Active = 0; break; } i = 0; foreach (object [] row in printprofile_combo.Model as ListStore) { if (pref == (string)row [0]) { printprofile_combo.Active = i; break; } i++; } break; } } #endregion #region event handlers void ConnectEvents () { Preferences.SettingChanged += OnPreferencesChanged; screenprofile_combo.Changed += HandleScreenProfileComboChanged; printprofile_combo.Changed += HandlePrintProfileComboChanged; theme_combo.Changed += HandleThemeComboChanged; writemetadata_radio.Toggled += HandleWritemetadataGroupChanged; always_sidecar_check.Toggled += HandleAlwaysSidecareCheckToggled; } void HandlePhotosdirChanged (object sender, EventArgs args) { photosdir_chooser.CurrentFolderChanged -= HandlePhotosdirChanged; Preferences.Set (Preferences.STORAGE_PATH, photosdir_chooser.Filename); photosdir_chooser.CurrentFolderChanged += HandlePhotosdirChanged; FSpot.Settings.Global.PhotoUri = new SafeUri (photosdir_chooser.Uri, true); } void HandleWritemetadataGroupChanged (object sender, EventArgs args) { Preferences.Set (Preferences.METADATA_EMBED_IN_IMAGE, writemetadata_radio.Active); } void HandleAlwaysSidecareCheckToggled (object sender, EventArgs args) { Preferences.Set (Preferences.METADATA_ALWAYS_USE_SIDECAR, always_sidecar_check.Active); } void HandleThemeComboChanged (object sender, EventArgs e) { ComboBox combo = sender as ComboBox; if (combo == null) return; TreeIter iter; if (combo.GetActiveIter (out iter)) { string gtkrc = (string)combo.Model.GetValue (iter, 1); if (!string.IsNullOrEmpty (gtkrc)) Preferences.Set (Preferences.GTK_RC, gtkrc); else Preferences.Set (Preferences.GTK_RC, string.Empty); } Gtk.Rc.DefaultFiles = FSpot.Settings.Global.DefaultRcFiles; Gtk.Rc.AddDefaultFile (Preferences.Get<string> (Preferences.GTK_RC)); Gtk.Rc.ReparseAllForSettings (Gtk.Settings.Default, true); } void HandleScreenProfileComboChanged (object sender, EventArgs e) { ComboBox combo = sender as ComboBox; if (combo == null) return; TreeIter iter; if (combo.GetActiveIter (out iter)) { switch ((int)combo.Model.GetValue (iter, 1)) { case 0: Preferences.Set (Preferences.COLOR_MANAGEMENT_DISPLAY_PROFILE, string.Empty); break; case -1: Preferences.Set (Preferences.COLOR_MANAGEMENT_DISPLAY_PROFILE, "_x_profile_"); break; case 1: Preferences.Set (Preferences.COLOR_MANAGEMENT_DISPLAY_PROFILE, (string)combo.Model.GetValue (iter, 0)); break; } } } void HandlePrintProfileComboChanged (object sender, EventArgs e) { ComboBox combo = sender as ComboBox; if (combo == null) return; TreeIter iter; if (combo.GetActiveIter (out iter)) { switch ((int)combo.Model.GetValue (iter, 1)) { case 0: Preferences.Set (Preferences.COLOR_MANAGEMENT_OUTPUT_PROFILE, string.Empty); break; case 1: Preferences.Set (Preferences.COLOR_MANAGEMENT_OUTPUT_PROFILE, (string)combo.Model.GetValue (iter, 0)); break; } } } #endregion #region Gtk widgetry void ThemeCellFunc (CellLayout cell_layout, CellRenderer cell, TreeModel tree_model, TreeIter iter) { string name = (string)tree_model.GetValue (iter, 0); (cell as CellRendererText).Text = name; } bool ThemeSeparatorFunc (TreeModel tree_model, TreeIter iter) { return tree_model.GetValue (iter, 0) == null; } void ProfileCellFunc (CellLayout cell_layout, CellRenderer cell, TreeModel tree_model, TreeIter iter) { string name = (string)tree_model.GetValue (iter, 0); (cell as CellRendererText).Text = name; } bool ProfileSeparatorFunc (TreeModel tree_model, TreeIter iter) { return tree_model.GetValue (iter, 0) == null; } #endregion } }
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors #if ENCODER && BLOCK_ENCODER && CODE_ASSEMBLER using Iced.Intel; using Xunit; using static Iced.Intel.AssemblerRegisters; namespace Iced.UnitTests.Intel.AssemblerTests { public class AssemblerRegisterTests { [Fact] public void TestMemoryOperands() { { Assert.NotEqual(st0, st1); Assert.Equal(Register.AL, al); Assert.Equal(Register.CL, cl); Assert.Equal(Register.DL, dl); Assert.Equal(Register.BL, bl); Assert.Equal(Register.AH, ah); Assert.Equal(Register.CH, ch); Assert.Equal(Register.DH, dh); Assert.Equal(Register.BH, bh); Assert.Equal(Register.SPL, spl); Assert.Equal(Register.BPL, bpl); Assert.Equal(Register.SIL, sil); Assert.Equal(Register.DIL, dil); Assert.Equal(Register.R8L, r8b); Assert.Equal(Register.R9L, r9b); Assert.Equal(Register.R10L, r10b); Assert.Equal(Register.R11L, r11b); Assert.Equal(Register.R12L, r12b); Assert.Equal(Register.R13L, r13b); Assert.Equal(Register.R14L, r14b); Assert.Equal(Register.R15L, r15b); Assert.Equal(Register.AX, ax); Assert.Equal(Register.CX, cx); Assert.Equal(Register.DX, dx); Assert.Equal(Register.BX, bx); Assert.Equal(Register.SP, sp); Assert.Equal(Register.BP, bp); Assert.Equal(Register.SI, si); Assert.Equal(Register.DI, di); Assert.Equal(Register.R8W, r8w); Assert.Equal(Register.R9W, r9w); Assert.Equal(Register.R10W, r10w); Assert.Equal(Register.R11W, r11w); Assert.Equal(Register.R12W, r12w); Assert.Equal(Register.R13W, r13w); Assert.Equal(Register.R14W, r14w); Assert.Equal(Register.R15W, r15w); Assert.Equal(Register.EAX, eax); Assert.Equal(Register.ECX, ecx); Assert.Equal(Register.EDX, edx); Assert.Equal(Register.EBX, ebx); Assert.Equal(Register.ESP, esp); Assert.Equal(Register.EBP, ebp); Assert.Equal(Register.ESI, esi); Assert.Equal(Register.EDI, edi); Assert.Equal(Register.R8D, r8d); Assert.Equal(Register.R9D, r9d); Assert.Equal(Register.R10D, r10d); Assert.Equal(Register.R11D, r11d); Assert.Equal(Register.R12D, r12d); Assert.Equal(Register.R13D, r13d); Assert.Equal(Register.R14D, r14d); Assert.Equal(Register.R15D, r15d); Assert.Equal(Register.RAX, rax); Assert.Equal(Register.RCX, rcx); Assert.Equal(Register.RDX, rdx); Assert.Equal(Register.RBX, rbx); Assert.Equal(Register.RSP, rsp); Assert.Equal(Register.RBP, rbp); Assert.Equal(Register.RSI, rsi); Assert.Equal(Register.RDI, rdi); Assert.Equal(Register.R8, r8); Assert.Equal(Register.R9, r9); Assert.Equal(Register.R10, r10); Assert.Equal(Register.R11, r11); Assert.Equal(Register.R12, r12); Assert.Equal(Register.R13, r13); Assert.Equal(Register.R14, r14); Assert.Equal(Register.R15, r15); Assert.Equal(Register.ES, es); Assert.Equal(Register.CS, cs); Assert.Equal(Register.SS, ss); Assert.Equal(Register.DS, ds); Assert.Equal(Register.FS, fs); Assert.Equal(Register.GS, gs); Assert.Equal(Register.XMM0, xmm0); Assert.Equal(Register.XMM1, xmm1); Assert.Equal(Register.XMM2, xmm2); Assert.Equal(Register.XMM3, xmm3); Assert.Equal(Register.XMM4, xmm4); Assert.Equal(Register.XMM5, xmm5); Assert.Equal(Register.XMM6, xmm6); Assert.Equal(Register.XMM7, xmm7); Assert.Equal(Register.XMM8, xmm8); Assert.Equal(Register.XMM9, xmm9); Assert.Equal(Register.XMM10, xmm10); Assert.Equal(Register.XMM11, xmm11); Assert.Equal(Register.XMM12, xmm12); Assert.Equal(Register.XMM13, xmm13); Assert.Equal(Register.XMM14, xmm14); Assert.Equal(Register.XMM15, xmm15); Assert.Equal(Register.XMM16, xmm16); Assert.Equal(Register.XMM17, xmm17); Assert.Equal(Register.XMM18, xmm18); Assert.Equal(Register.XMM19, xmm19); Assert.Equal(Register.XMM20, xmm20); Assert.Equal(Register.XMM21, xmm21); Assert.Equal(Register.XMM22, xmm22); Assert.Equal(Register.XMM23, xmm23); Assert.Equal(Register.XMM24, xmm24); Assert.Equal(Register.XMM25, xmm25); Assert.Equal(Register.XMM26, xmm26); Assert.Equal(Register.XMM27, xmm27); Assert.Equal(Register.XMM28, xmm28); Assert.Equal(Register.XMM29, xmm29); Assert.Equal(Register.XMM30, xmm30); Assert.Equal(Register.XMM31, xmm31); Assert.Equal(Register.YMM0, ymm0); Assert.Equal(Register.YMM1, ymm1); Assert.Equal(Register.YMM2, ymm2); Assert.Equal(Register.YMM3, ymm3); Assert.Equal(Register.YMM4, ymm4); Assert.Equal(Register.YMM5, ymm5); Assert.Equal(Register.YMM6, ymm6); Assert.Equal(Register.YMM7, ymm7); Assert.Equal(Register.YMM8, ymm8); Assert.Equal(Register.YMM9, ymm9); Assert.Equal(Register.YMM10, ymm10); Assert.Equal(Register.YMM11, ymm11); Assert.Equal(Register.YMM12, ymm12); Assert.Equal(Register.YMM13, ymm13); Assert.Equal(Register.YMM14, ymm14); Assert.Equal(Register.YMM15, ymm15); Assert.Equal(Register.YMM16, ymm16); Assert.Equal(Register.YMM17, ymm17); Assert.Equal(Register.YMM18, ymm18); Assert.Equal(Register.YMM19, ymm19); Assert.Equal(Register.YMM20, ymm20); Assert.Equal(Register.YMM21, ymm21); Assert.Equal(Register.YMM22, ymm22); Assert.Equal(Register.YMM23, ymm23); Assert.Equal(Register.YMM24, ymm24); Assert.Equal(Register.YMM25, ymm25); Assert.Equal(Register.YMM26, ymm26); Assert.Equal(Register.YMM27, ymm27); Assert.Equal(Register.YMM28, ymm28); Assert.Equal(Register.YMM29, ymm29); Assert.Equal(Register.YMM30, ymm30); Assert.Equal(Register.YMM31, ymm31); Assert.Equal(Register.ZMM0, zmm0); Assert.Equal(Register.ZMM1, zmm1); Assert.Equal(Register.ZMM2, zmm2); Assert.Equal(Register.ZMM3, zmm3); Assert.Equal(Register.ZMM4, zmm4); Assert.Equal(Register.ZMM5, zmm5); Assert.Equal(Register.ZMM6, zmm6); Assert.Equal(Register.ZMM7, zmm7); Assert.Equal(Register.ZMM8, zmm8); Assert.Equal(Register.ZMM9, zmm9); Assert.Equal(Register.ZMM10, zmm10); Assert.Equal(Register.ZMM11, zmm11); Assert.Equal(Register.ZMM12, zmm12); Assert.Equal(Register.ZMM13, zmm13); Assert.Equal(Register.ZMM14, zmm14); Assert.Equal(Register.ZMM15, zmm15); Assert.Equal(Register.ZMM16, zmm16); Assert.Equal(Register.ZMM17, zmm17); Assert.Equal(Register.ZMM18, zmm18); Assert.Equal(Register.ZMM19, zmm19); Assert.Equal(Register.ZMM20, zmm20); Assert.Equal(Register.ZMM21, zmm21); Assert.Equal(Register.ZMM22, zmm22); Assert.Equal(Register.ZMM23, zmm23); Assert.Equal(Register.ZMM24, zmm24); Assert.Equal(Register.ZMM25, zmm25); Assert.Equal(Register.ZMM26, zmm26); Assert.Equal(Register.ZMM27, zmm27); Assert.Equal(Register.ZMM28, zmm28); Assert.Equal(Register.ZMM29, zmm29); Assert.Equal(Register.ZMM30, zmm30); Assert.Equal(Register.ZMM31, zmm31); Assert.Equal(Register.K0, k0); Assert.Equal(Register.K1, k1); Assert.Equal(Register.K2, k2); Assert.Equal(Register.K3, k3); Assert.Equal(Register.K4, k4); Assert.Equal(Register.K5, k5); Assert.Equal(Register.K6, k6); Assert.Equal(Register.K7, k7); Assert.Equal(Register.BND0, bnd0); Assert.Equal(Register.BND1, bnd1); Assert.Equal(Register.BND2, bnd2); Assert.Equal(Register.BND3, bnd3); Assert.Equal(Register.CR0, cr0); Assert.Equal(Register.CR1, cr1); Assert.Equal(Register.CR2, cr2); Assert.Equal(Register.CR3, cr3); Assert.Equal(Register.CR4, cr4); Assert.Equal(Register.CR5, cr5); Assert.Equal(Register.CR6, cr6); Assert.Equal(Register.CR7, cr7); Assert.Equal(Register.CR8, cr8); Assert.Equal(Register.CR9, cr9); Assert.Equal(Register.CR10, cr10); Assert.Equal(Register.CR11, cr11); Assert.Equal(Register.CR12, cr12); Assert.Equal(Register.CR13, cr13); Assert.Equal(Register.CR14, cr14); Assert.Equal(Register.CR15, cr15); Assert.Equal(Register.DR0, dr0); Assert.Equal(Register.DR1, dr1); Assert.Equal(Register.DR2, dr2); Assert.Equal(Register.DR3, dr3); Assert.Equal(Register.DR4, dr4); Assert.Equal(Register.DR5, dr5); Assert.Equal(Register.DR6, dr6); Assert.Equal(Register.DR7, dr7); Assert.Equal(Register.DR8, dr8); Assert.Equal(Register.DR9, dr9); Assert.Equal(Register.DR10, dr10); Assert.Equal(Register.DR11, dr11); Assert.Equal(Register.DR12, dr12); Assert.Equal(Register.DR13, dr13); Assert.Equal(Register.DR14, dr14); Assert.Equal(Register.DR15, dr15); Assert.Equal(Register.ST0, st0); Assert.Equal(Register.ST1, st1); Assert.Equal(Register.ST2, st2); Assert.Equal(Register.ST3, st3); Assert.Equal(Register.ST4, st4); Assert.Equal(Register.ST5, st5); Assert.Equal(Register.ST6, st6); Assert.Equal(Register.ST7, st7); Assert.Equal(Register.MM0, mm0); Assert.Equal(Register.MM1, mm1); Assert.Equal(Register.MM2, mm2); Assert.Equal(Register.MM3, mm3); Assert.Equal(Register.MM4, mm4); Assert.Equal(Register.MM5, mm5); Assert.Equal(Register.MM6, mm6); Assert.Equal(Register.MM7, mm7); Assert.Equal(Register.TR0, tr0); Assert.Equal(Register.TR1, tr1); Assert.Equal(Register.TR2, tr2); Assert.Equal(Register.TR3, tr3); Assert.Equal(Register.TR4, tr4); Assert.Equal(Register.TR5, tr5); Assert.Equal(Register.TR6, tr6); Assert.Equal(Register.TR7, tr7); } { Assert.Equal(AssemblerOperandFlags.K1, zmm0.k1.Flags); Assert.Equal(AssemblerOperandFlags.K2 | AssemblerOperandFlags.Zeroing, zmm0.k2.z.Flags); Assert.Equal(AssemblerOperandFlags.SuppressAllExceptions, zmm0.sae.Flags); Assert.Equal(AssemblerOperandFlags.RoundToNearest, zmm0.rn_sae.Flags); Assert.Equal(AssemblerOperandFlags.RoundDown, zmm0.rd_sae.Flags); Assert.Equal(AssemblerOperandFlags.RoundUp, zmm0.ru_sae.Flags); Assert.Equal(AssemblerOperandFlags.RoundTowardZero, zmm0.rz_sae.Flags); Assert.NotEqual(zmm0, zmm1); Assert.NotEqual(zmm0, zmm0.k1); Assert.NotEqual(zmm0.GetHashCode(), zmm1.GetHashCode()); Assert.NotEqual(zmm0.GetHashCode(), zmm0.k1.GetHashCode()); } { var m = __.cs[13]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, 13, 8, false, Register.CS), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __.ds[13]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, 13, 8, false, Register.DS), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __.es[13]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, 13, 8, false, Register.ES), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __.fs[13]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, 13, 8, false, Register.FS), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __.gs[13]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, 13, 8, false, Register.GS), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __.ss[13]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, 13, 8, false, Register.SS), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[sbyte.MinValue]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, sbyte.MinValue, 8), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[sbyte.MaxValue]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, sbyte.MaxValue, 8), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[short.MinValue]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, short.MinValue, 8), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[short.MaxValue]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, short.MaxValue, 8), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[int.MinValue]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, int.MinValue, 8), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[int.MaxValue]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, int.MaxValue, 8), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[(long)int.MaxValue + 1]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, unchecked((int)((long)int.MaxValue + 1)), 8), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[ulong.MaxValue]; Assert.Equal(new MemoryOperand(Register.None, Register.None, 1, unchecked((int)(ulong.MaxValue)), 8), m.ToMemoryOperand(64)); Assert.Equal(ulong.MaxValue, (ulong)m.Displacement); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[eax]; Assert.Equal(new MemoryOperand(Register.EAX, Register.None, 1, 0, 0), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[eax + 1]; Assert.Equal(new MemoryOperand(Register.EAX, Register.None, 1, 1, 1), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[eax - 1]; Assert.Equal(new MemoryOperand(Register.EAX, Register.None, 1, -1, 1), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __word_ptr[eax]; Assert.Equal(new MemoryOperand(Register.EAX, Register.None, 1, 0, 0), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.WordPtr, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __dword_ptr[eax]; Assert.Equal(new MemoryOperand(Register.EAX, Register.None, 1, 0, 0), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.DwordPtr, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __qword_ptr[eax]; Assert.Equal(new MemoryOperand(Register.EAX, Register.None, 1, 0, 0), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.QwordPtr, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __xmmword_ptr[eax]; Assert.Equal(new MemoryOperand(Register.EAX, Register.None, 1, 0, 0), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.OwordPtr, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __ymmword_ptr[eax]; Assert.Equal(new MemoryOperand(Register.EAX, Register.None, 1, 0, 0), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.YwordPtr, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __zmmword_ptr[eax]; Assert.Equal(new MemoryOperand(Register.EAX, Register.None, 1, 0, 0), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.ZwordPtr, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[bx + si]; Assert.Equal(new MemoryOperand(Register.BX, Register.SI, 1, 0, 0), m.ToMemoryOperand(16)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[eax + edx]; Assert.Equal(new MemoryOperand(Register.EAX, Register.EDX, 1, 0, 0), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[eax + xmm1]; Assert.Equal(new MemoryOperand(Register.EAX, Register.XMM1, 1, 0, 0), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[eax + ymm1]; Assert.Equal(new MemoryOperand(Register.EAX, Register.YMM1, 1, 0, 0), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[eax + zmm1]; Assert.Equal(new MemoryOperand(Register.EAX, Register.ZMM1, 1, 0, 0), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[rsi + rdi * 2 + 124]; Assert.Equal(new MemoryOperand(Register.RSI, Register.RDI, 2, 124, 1), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[eax + edx * 4 + 8]; Assert.Equal(new MemoryOperand(Register.EAX, Register.EDX, 4, 8, 1), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __[rsi + rdi * 2 + 124]; Assert.Equal(new MemoryOperand(Register.RSI, Register.RDI, 2, 124, 1), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } { var m = __dword_bcst[rsi + rdi * 2 + 124]; Assert.Equal(new MemoryOperand(Register.RSI, Register.RDI, 2, 124, 1, true, Register.None), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.DwordPtr, m.Size); Assert.Equal(AssemblerOperandFlags.Broadcast, m.Flags); } { var m = __dword_bcst[rsi + rdi * 2 - 124]; Assert.Equal(new MemoryOperand(Register.RSI, Register.RDI, 2, -124, 1, true, Register.None), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.DwordPtr, m.Size); Assert.Equal(AssemblerOperandFlags.Broadcast, m.Flags); } { var m = __dword_bcst[(rsi + rdi * 2 - 124) + 1]; Assert.Equal(new MemoryOperand(Register.RSI, Register.RDI, 2, -123, 1, true, Register.None), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.DwordPtr, m.Size); Assert.Equal(AssemblerOperandFlags.Broadcast, m.Flags); } { var m = __dword_bcst[(rsi + rdi * 2 - 124) - 1]; Assert.Equal(new MemoryOperand(Register.RSI, Register.RDI, 2, -125, 1, true, Register.None), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.DwordPtr, m.Size); Assert.Equal(AssemblerOperandFlags.Broadcast, m.Flags); } { var m1 = __qword_bcst[rsi + rdi * 2 + 124]; var m2 = __dword_bcst[rsi + rdi * 2 + 124]; Assert.NotEqual(m1, m2); Assert.Equal(m1.ToMemoryOperand(64), m2.ToMemoryOperand(64)); Assert.NotEqual(m1.GetHashCode(), m2.GetHashCode()); } { var assembler = new Assembler(64); var label = assembler.CreateLabel("Check"); var m = __[label]; Assert.Equal(new MemoryOperand(Register.RIP, Register.None, 1, 1, 1), m.ToMemoryOperand(64)); Assert.Equal(MemoryOperandSize.None, m.Size); Assert.Equal(AssemblerOperandFlags.None, m.Flags); } } } } #endif
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Linq; using System.Text; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.InteractiveWindow; using Microsoft.PythonTools.InteractiveWindow.Shell; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; namespace Microsoft.PythonTools.Repl { [Export(typeof(InteractiveWindowProvider))] [PartCreationPolicy(CreationPolicy.Shared)] class InteractiveWindowProvider { private readonly Dictionary<int, IVsInteractiveWindow> _windows = new Dictionary<int, IVsInteractiveWindow>(); private int _nextId = 1; private readonly List<IVsInteractiveWindow> _mruWindows = new List<IVsInteractiveWindow>(); private readonly Dictionary<string, int> _temporaryWindows = new Dictionary<string, int>(); private readonly IServiceProvider _serviceProvider; private readonly IInteractiveEvaluatorProvider[] _evaluators; private readonly IVsInteractiveWindowFactory _windowFactory; private readonly IContentType _pythonContentType; private static readonly object VsInteractiveWindowKey = new object(); private const string SavedWindowsCategoryBase = "InteractiveWindows\\"; [ImportingConstructor] public InteractiveWindowProvider( [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider, [Import] IVsInteractiveWindowFactory factory, [ImportMany] IInteractiveEvaluatorProvider[] evaluators, [Import] IContentTypeRegistryService contentTypeService ) { _serviceProvider = serviceProvider; _evaluators = evaluators; _windowFactory = factory; _pythonContentType = contentTypeService.GetContentType(PythonCoreConstants.ContentType); } public IEnumerable<IVsInteractiveWindow> AllOpenWindows { get { lock (_windows) { return _windows.Values.ToArray(); } } } private int GetNextId() { lock (_windows) { do { var curId = _nextId++; if (!_windows.ContainsKey(curId)) { return curId; } } while (_nextId < int.MaxValue); } throw new InvalidOperationException("Congratulations, you opened over 2 billion interactive windows this " + "session! Now you need to restart Visual Studio to open any more."); } private bool EnsureInterpretersAvailable() { var registry = _serviceProvider.GetComponentModel().GetService<IInterpreterRegistryService>(); if (registry.Configurations.Any()) { return true; } PythonToolsPackage.OpenNoInterpretersHelpPage(_serviceProvider); return false; } public IVsInteractiveWindow Open(string replId) { EnsureInterpretersAvailable(); lock (_windows) { foreach(var window in _windows.Values) { var eval = window.InteractiveWindow?.Evaluator as SelectableReplEvaluator; if (eval?.CurrentEvaluator == replId) { window.Show(true); return window; } } } return null; } public IVsInteractiveWindow OpenOrCreate(string replId) { EnsureInterpretersAvailable(); IVsInteractiveWindow wnd; lock (_windows) { foreach(var window in _windows.Values) { var eval = window.InteractiveWindow?.Evaluator as SelectableReplEvaluator; if (eval?.CurrentEvaluator == replId) { window.Show(true); return window; } } } wnd = Create(replId); wnd.Show(true); return wnd; } public IVsInteractiveWindow Create(string replId, int curId = -1) { EnsureInterpretersAvailable(); if (curId < 0) { curId = GetNextId(); } var window = CreateInteractiveWindowInternal( new SelectableReplEvaluator(_serviceProvider, _evaluators, replId, curId.ToString()), _pythonContentType, true, curId, Strings.ReplCaptionNoEvaluator, typeof(Navigation.PythonLanguageInfo).GUID, "PythonInteractive" ); lock (_windows) { _windows[curId] = window; } window.InteractiveWindow.TextView.Closed += (s, e) => { lock (_windows) { Debug.Assert(ReferenceEquals(_windows[curId], window)); _windows.Remove(curId); } }; return window; } public IVsInteractiveWindow OpenOrCreateTemporary(string replId, string title) { bool dummy; return OpenOrCreateTemporary(replId, title, out dummy); } public IVsInteractiveWindow OpenOrCreateTemporary(string replId, string title, out bool wasCreated) { EnsureInterpretersAvailable(); IVsInteractiveWindow wnd; lock (_windows) { int curId; if (_temporaryWindows.TryGetValue(replId, out curId)) { if (_windows.TryGetValue(curId, out wnd)) { wnd.Show(true); wasCreated = false; return wnd; } } _temporaryWindows.Remove(replId); } wnd = CreateTemporary(replId, title); wnd.Show(true); wasCreated = true; return wnd; } public IVsInteractiveWindow CreateTemporary(string replId, string title) { EnsureInterpretersAvailable(); int curId = GetNextId(); var window = CreateInteractiveWindowInternal( _evaluators.Select(p => p.GetEvaluator(replId)).FirstOrDefault(e => e != null), _pythonContentType, false, curId, title, typeof(Navigation.PythonLanguageInfo).GUID, replId ); lock (_windows) { _windows[curId] = window; _temporaryWindows[replId] = curId; } window.InteractiveWindow.TextView.Closed += (s, e) => { lock (_windows) { Debug.Assert(ReferenceEquals(_windows[curId], window)); _windows.Remove(curId); _temporaryWindows.Remove(replId); } }; return window; } private IVsInteractiveWindow CreateInteractiveWindowInternal( IInteractiveEvaluator evaluator, IContentType contentType, bool alwaysCreate, int id, string title, Guid languageServiceGuid, string replId ) { var creationFlags = __VSCREATETOOLWIN.CTW_fMultiInstance | __VSCREATETOOLWIN.CTW_fActivateWithProject; if (alwaysCreate) { creationFlags |= __VSCREATETOOLWIN.CTW_fForceCreate; } var replWindow = _windowFactory.Create(GuidList.guidPythonInteractiveWindowGuid, id, title, evaluator, creationFlags); replWindow.InteractiveWindow.Properties[VsInteractiveWindowKey] = replWindow; var toolWindow = replWindow as ToolWindowPane; if (toolWindow != null) { toolWindow.BitmapImageMoniker = KnownMonikers.PYInteractiveWindow; } replWindow.SetLanguage(GuidList.guidPythonLanguageServiceGuid, contentType); replWindow.InteractiveWindow.InitializeAsync(); var selectEval = evaluator as SelectableReplEvaluator; if (selectEval != null) { selectEval.ProvideInteractiveWindowEvents(InteractiveWindowEvents.GetOrCreate(replWindow)); } return replWindow; } internal static IVsInteractiveWindow GetVsInteractiveWindow(IInteractiveWindow window) { IVsInteractiveWindow wnd = null; return (window?.Properties.TryGetProperty(VsInteractiveWindowKey, out wnd) ?? false) ? wnd : null; } internal static void Close(object obj) { var frame = ((obj as ToolWindowPane)?.Frame as IVsWindowFrame); frame?.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } internal static void CloseIfEvaluatorMatches(object obj, string evalId) { var eval = (obj as IVsInteractiveWindow)?.InteractiveWindow.Evaluator as SelectableReplEvaluator; if (eval?.CurrentEvaluator == evalId) { Close(obj); } } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Vevo; using Vevo.DataAccessLib.Cart; using Vevo.Domain; using Vevo.Domain.Users; using Vevo.Shared.DataAccess; public partial class AdminAdvanced_Components_AdminDetails : AdminAdvancedBaseUserControl { private const int ColumnView = 0; private const int ColumnModified = 1; private const int ColumnMenuPageName = 3; private enum Mode { Add, Edit }; private Mode _mode = Mode.Add; private string CurrentAdminID { get { if (!String.IsNullOrEmpty( MainContext.QueryString["AdminID"] )) return MainContext.QueryString["AdminID"]; else return "0"; } } private void ClearInputField() { uxUserName.Text = string.Empty; uxPassword.Text = string.Empty; uxRePassword.Text = string.Empty; uxEmail.Text = string.Empty; } private void PopulateControls() { ClearInputField(); if (CurrentAdminID != null && int.Parse( CurrentAdminID ) >= 0) { Admin admin = DataAccessContext.AdminRepository.GetOne( CurrentAdminID ); uxUserName.Text = admin.UserName; if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal) uxRegisterDateCalendarPopup.SelectedDate = admin.RegisterDate; MembershipUserCollection memberShip = Membership.FindUsersByName( uxUserName.Text ); uxEmail.Text = admin.Email; } } private bool UpdatePassword( out string errorMessage ) { errorMessage = String.Empty; if (uxPassword.Text != "") { if (uxPassword.Text.Trim() != uxRePassword.Text.Trim()) { uxPassword.Text = string.Empty; uxRePassword.Text = string.Empty; errorMessage = Resources.AdminMessage.PasswordNotMatch; return false; } else if (uxOldPassword.Text == "") { errorMessage = Resources.AdminMessage.PasswordEmpty; return false; } else { MembershipUser user = Membership.GetUser( uxUserName.Text ); if (!user.ChangePassword( uxOldPassword.Text, uxPassword.Text )) { errorMessage = Resources.AdminMessage.UpdatePasswordError; return false; } } } return true; } private bool UpdatePermission( out string errorMessage ) { errorMessage = String.Empty; Admin admin = DataAccessContext.AdminRepository.GetOne( CurrentAdminID ); admin = SetUpAdmin( admin ); DataAccessContext.AdminRepository.Save( admin ); if (String.Compare( admin.UserName, "Admin", true ) != 0) { foreach (GridViewRow row in uxGrid.Rows) { CheckBox uxCheckView = (CheckBox) row.FindControl( "uxCheckVeiw" ); CheckBox uxCheckModified = (CheckBox) row.FindControl( "uxCheckModify" ); string menuPageName = uxGrid.DataKeys[row.RowIndex]["MenuPageName"].ToString(); AdminMenuPermissionAccess.Update( CurrentAdminID, menuPageName, uxCheckView.Checked, uxCheckModified.Checked ); } } return true; } private Admin SetUpAdmin( Admin admin ) { admin.UserName = uxUserName.Text.Trim(); admin.Email = uxEmail.Text.Trim(); admin.RegisterDate = uxRegisterDateCalendarPopup.SelectedDate; return admin; } protected void Page_Load( object sender, EventArgs e ) { UpdateMenuInPermission( CurrentAdminID ); } private void Details_RefreshHandler( object sender, EventArgs e ) { PopulateControls(); } private void EnableDisableCheckAllAndRegisterJavascript() { Admin admin = DataAccessContext.AdminRepository.GetOne( CurrentAdminID ); CheckBox SelectAllCheckBoxView = (CheckBox) uxGrid.HeaderRow.FindControl( "SelectAllCheckBoxView" ); SelectAllCheckBoxView.Attributes.Add( "onclick", "SelectAllCheckBoxes(this , 'uxCheckVeiw')" ); CheckBox SelectAllCheckBoxModify = (CheckBox) uxGrid.HeaderRow.FindControl( "SelectAllCheckBoxModify" ); SelectAllCheckBoxModify.Attributes.Add( "onclick", "SelectAllCheckBoxes(this , 'uxCheckModify')" ); if (!admin.IsNull && admin.UserName.ToLower() == "admin") { SelectAllCheckBoxView.Enabled = false; SelectAllCheckBoxModify.Enabled = false; } } protected void Page_PreRender( object sender, EventArgs e ) { if (IsEditMode()) { if (!MainContext.IsPostBack) { PopulateControls(); uxUserName.Enabled = false; uxOldPwd.Visible = true; if (IsAdminModifiable()) { uxUpdateButton.Visible = true; } else { uxUpdateButton.Visible = false; } uxAddButton.Visible = false; } } else { if (IsAdminModifiable()) { lcRegisterDate.Visible = true; uxAddButton.Visible = true; uxUpdateButton.Visible = false; uxOldPwd.Visible = false; uxRegisterDateCalendarPopup.SelectedDate = DateTime.Now; } else { MainContext.RedirectMainControl( "AdminList.ascx" ); } } PopulatePermission(); EnableDisableCheckAllAndRegisterJavascript(); } protected void uxAddButton_Click( object sender, EventArgs e ) { if (Page.IsValid) { string adminID = DataAccessContext.AdminRepository.GetIDFromUserName( uxUserName.Text.Trim() ); if (adminID != "0") { uxUserName.Text = string.Empty; uxMessage.DisplayError( Resources.AdminMessage.DuplicateUserName ); return; } if ((uxPassword.Text.Trim() == "") || (uxRePassword.Text.Trim() == "")) { uxPassword.Text = string.Empty; uxRePassword.Text = string.Empty; uxMessage.DisplayError( Resources.AdminMessage.PasswordEmpty ); return; } if (uxPassword.Text.Trim() != uxRePassword.Text.Trim()) { uxPassword.Text = string.Empty; uxRePassword.Text = string.Empty; uxMessage.DisplayError( Resources.AdminMessage.PasswordNotMatch ); return; } Admin admin = new Admin(); admin = SetUpAdmin( admin ); admin = DataAccessContext.AdminRepository.Save( admin ); Membership.CreateUser( uxUserName.Text.Trim(), uxPassword.Text.Trim(), uxEmail.Text.Trim() ); Roles.AddUserToRole( uxUserName.Text.Trim(), "Administrators" ); foreach (GridViewRow row in uxGrid.Rows) { CheckBox uxCheckView = (CheckBox) row.FindControl( "uxCheckVeiw" ); CheckBox uxCheckModified = (CheckBox) row.FindControl( "uxCheckModify" ); string menuPageName = uxGrid.DataKeys[row.RowIndex]["MenuPageName"].ToString(); string result = AdminMenuPermissionAccess.Create( admin.AdminID, menuPageName, uxCheckView.Checked, uxCheckModified.Checked ); } uxMessage.DisplayMessage( Resources.AdminMessage.AddSuccess ); ClearInputField(); AdminUtilities.ClearAdminCache(); uxStatusHidden.Value = "Added"; } } protected void uxUpdateButton_Click( object sender, EventArgs e ) { try { if (Page.IsValid) { string errorMessage; if (UpdatePassword( out errorMessage ) && UpdatePermission( out errorMessage )) { uxMessage.DisplayMessage( Resources.AdminMessage.UpdateSuccess ); } else { uxMessage.DisplayError( errorMessage ); } PopulateControls(); PopulatePermission(); AdminUtilities.ClearAdminCache(); uxStatusHidden.Value = "Updated"; } } catch (Exception ex) { uxMessage.DisplayException( ex ); } } private void PopulatePermission() { DataTable table = new DataTable(); table = AdminMenuAdvancedPermissionAccess.GetAll( AdminConfig.CurrentCultureID, GridHelper.GetFullSortText(), FlagFilter.ShowTrue ); uxGrid.DataSource = table; uxGrid.DataBind(); if (IsEditMode()) { DataTable adminTable = AdminMenuAdvancedPermissionAccess.GetAllByAdminID( AdminConfig.CurrentCultureID, CurrentAdminID, GridHelper.GetFullSortText(), FlagFilter.ShowTrue ); Admin admin = DataAccessContext.AdminRepository.GetOne( CurrentAdminID ); if (admin.UserName.ToLower() == "admin") { uxMessagePermissionTable.Text = "* Permissions for user 'Admin' cannot be changed." ; } else { uxMessagePermissionTable.Text = ""; } if (adminTable.Rows.Count > 0) { int i = 0; foreach (GridViewRow row in uxGrid.Rows) { CheckBox uxCheckView = (CheckBox) row.FindControl( "uxCheckVeiw" ); CheckBox uxCheckModified = (CheckBox) row.FindControl( "uxCheckModify" ); String menuPageName = uxGrid.DataKeys[row.RowIndex]["MenuPageName"].ToString(); DataRow[] dataRow = adminTable.Select( String.Format( "MenuPagename = '{0}'", menuPageName ), GridHelper.GetFullSortText() ); if (dataRow.Length > 0) { uxCheckView.Checked = Convert.ToBoolean( dataRow[0]["ViewMode"].ToString() ); uxCheckModified.Checked = Convert.ToBoolean( dataRow[0]["ModifyMode"].ToString() ); } if (admin.UserName.ToLower() == "admin") { uxCheckView.Enabled = false; uxCheckModified.Enabled = false; } i += 1; } } } } private void UpdateMenuInPermission( string permissionID ) { DataTable menuTable = AdminMenuAdvancedPermissionAccess.GetAll( AdminConfig.CurrentCultureID, "SortOrder", FlagFilter.ShowTrue ); foreach (DataRow dr in menuTable.Rows) { string menuPageName = dr["MenuPageName"].ToString(); if (!AdminMenuPermissionAccess.IsExistingPermission( permissionID, menuPageName )) { AdminMenuPermissionAccess.Create( permissionID, menuPageName, false, false ); } } } private GridViewHelper GridHelper { get { if (ViewState["GridHelper"] == null) ViewState["GridHelper"] = new GridViewHelper( uxGrid, "SortOrder" ); return (GridViewHelper) ViewState["GridHelper"]; } } protected void uxGrid_Sorting( object sender, GridViewSortEventArgs e ) { GridHelper.SelectSorting( e.SortExpression ); PopulatePermission(); } public bool IsEditMode() { return (_mode == Mode.Edit); } public void SetEditMode() { _mode = Mode.Edit; } }
// 32feet.NET - Personal Area Networking for .NET // // InTheHand.Net.Sockets.BluetoothDeviceInfo // // Copyright (c) 2003-2008 In The Hand Ltd, All rights reserved. // This source code is licensed under the MIT License using System; using InTheHand.Net.Bluetooth; using System.Diagnostics; using InTheHand.Net.Bluetooth.Factory; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace InTheHand.Net.Sockets { /// <summary> /// Provides information about an available device obtained by the client during device discovery. /// </summary> public class BluetoothDeviceInfo : IComparable { readonly IBluetoothDeviceInfo m_impl; //-------- internal BluetoothDeviceInfo(IBluetoothDeviceInfo impl) { m_impl = impl; } // Needed for SdpBrowserCF /// <summary> /// Initializes an instance of the <see cref="T:InTheHand.Net.Sockets.BluetoothDeviceInfo"/> class /// for the device with the given address. /// </summary> /// - /// <param name="address">The <see cref="T:InTheHand.Net.BluetoothAddress"/>.</param> public BluetoothDeviceInfo(BluetoothAddress address) : this(BluetoothFactory.Factory.DoGetBluetoothDeviceInfo(address)) { } //-------- internal void Merge(IBluetoothDeviceInfo other) // used by BluetoothClient.DiscoverDevicesMerge etc { // TODO make this a throw Debug.Assert(this.DeviceAddress.Equals(other.DeviceAddress), "diff.addresses!"); m_impl.Merge(other); } //-------- /// <summary> /// Forces the system to refresh the device information. /// </summary> /// - /// <remarks> /// See <see cref="P:InTheHand.Net.Sockets.BluetoothDeviceInfo.DeviceName"/> /// for one reason why this method is necessary. /// </remarks> public void Refresh() { m_impl.Refresh(); } /// <summary> /// Updates the device name used to display the device, affects the local computer cache. /// </summary> /// <remarks>On Windows CE this only affects devices which are already paired.</remarks> public void Update() { m_impl.Update(); } /// <summary> /// Gets the device identifier. /// </summary> public BluetoothAddress DeviceAddress { [DebuggerStepThrough] get { return m_impl.DeviceAddress; } } /// <summary> /// Gets a name of a device. /// </summary> /// - /// <remarks> /// <para>Note, that due the way in which Bluetooth device discovery works, /// the existence and address of a device is known first, but a separate /// query has to be carried out to find whether the device also has a name. /// This means that if a device is discovered afresh then this property might /// return only a text version of the device&#x2019;s address and not its /// name, one can also see this in the Windows&#x2019; Bluetooth device dialogs /// where the device appears first with its address and the name is later /// updated. To see the name, wait for some time and access this property again /// having called <see cref="M:InTheHand.Net.Sockets.BluetoothDeviceInfo.Refresh"/> /// in the meantime. /// </para> /// </remarks> public string DeviceName { [DebuggerStepThrough] get { return m_impl.DeviceName; } set { m_impl.DeviceName = value; } } /// <summary> /// Returns the Class of Device of the remote device. /// </summary> /// - /// <remarks> /// <para> /// Some CE 4.2 devices such as original PPC2003 devices don't have the native /// API on which this property depends &#x2014; it was added as part of a hotfix. /// The property will always return zero in such a case. On WM/CE we also /// attempt to get the CoD value as part of the discovery process; this is /// of course only works for devices in-range. /// </para> /// </remarks> public ClassOfDevice ClassOfDevice { get { return m_impl.ClassOfDevice; } } /// <summary> /// Returns the signal strength for the Bluetooth connection with the peer device. /// <para><b>Supports only on some platforms.</b></para> /// </summary> /// - /// <value>Valid values for this property are -128 to 128. It returns /// <see cref="F:System.Int32.MinValue">Int32.MinValue</see> on failure. /// </value> /// - /// <remarks> /// <para>Thus there are multiple reasons which this property can return /// the error value (i.e. <see cref="F:System.Int32.MinValue">Int32.MinValue</see>). /// </para> /// <list type="number"> /// <item>On an unsupported platform, e.g. MSFT+Win32, or MSFT+CE/WM on an /// older version. See below. /// </item> /// <item>The remote device is not turned-on or in range. See below. /// </item> /// <item>On Widcomm, there is no connection to the remote device. See below. /// </item> /// </list> /// /// <para>Platform support:</para> /// <list type="bullet"> /// <item>Does <b>not</b> work on Win32 with the Microsoft Bluetooth stack. /// That platform provide no support for RSSI, please contact Microsoft /// to complain. /// </item> /// <item>Works on Windows Mobile 5.0, Windows Embedded CE 6.0, or later /// versions. /// </item> /// <item>Works on Widcomm, both platforms. /// We will <i>not</i> try to connect, see below. /// </item> /// </list> /// <para> /// </para> /// /// <para>Finally, to get an RSSI value Bluetooth requires an open /// connection to the peer device. /// On Widcomm we will <i>not</i> attempt to connect, so the caller must /// ensure that there's a connection -- /// perhaps it could call <see cref="M:InTheHand.Net.Sockets.BluetoothDeviceInfo.GetServiceRecords(System.Guid)"/> /// just before accessing this property. /// On CE/WM if there is no active connection, then we will attempt to /// create one. This of course <i>can</i> be <i>slow</i>, and <i>will</i> /// be slow if the remote device is not in range. /// (Bluetooth 2.1 supports getting the RSSI value at discovery time which /// might provide the solution for many cases. However only the MSFT+Win32 /// stack specifically supports v2.1, and of course it doesn't support RSSI /// at all!) /// </para> /// <para>Note that the Bluetooth specification doesn't require that the /// radio hardware provides any great precision in its RSSI readings. /// The spec says for instance, in v2.1 Volume 2 Part E ("HCI") Section 7.5.4: /// &#x201C;Note: how accurate the dB values will be depends on the Bluetooth hardware. /// The only requirements for the hardware are that the Bluetooth device is able to /// tell whether the RSSI is inside, above or below the Golden Device Power Range.&#x201D; /// </para> /// </remarks> public int Rssi { get { return m_impl.Rssi; } } /// <summary> /// Returns a list of services which are already installed for use on the calling machine. /// </summary> /// <remarks> /// <para>This property returns the services already configured for use. /// Those are the ones that are checked in the &#x201C;Services&#x201D; tab /// of the device&#x2019;s property sheet in the Bluetooth Control panel. /// I presume the behaviour is similar on CE. /// </para> /// <para>Will only return available services for paired devices. /// </para> /// <para>It of course will also only returns standard system services which Windows understands. /// (On desktop Windows this method calls the OS function <c>BluetoothEnumerateInstalledServices</c>). /// </para> /// <para>To see all the services that a device advertises use the /// <see cref="M:InTheHand.Net.Sockets.BluetoothDeviceInfo.GetServiceRecords(System.Guid)"/> /// method. /// </para> /// </remarks> public Guid[] InstalledServices { get { return m_impl.InstalledServices; } } #region SetServiceState /// <summary> /// Enables or disables services for a Bluetooth device. /// </summary> /// <param name="service">The service GUID on the remote device.</param> /// <param name="state">Service state - TRUE to enable the service, FALSE to disable it.</param> /// <remarks> /// When called on Windows CE, the device will require a soft-reset to enabled the settings. /// ///<note> /// <para>The system maintains a mapping of service guids to supported drivers for /// Bluetooth-enabled devices. Enabling a service installs the corresponding /// device driver. Disabling a service removes the corresponding device driver. /// If a non-supported service is enabled, a driver will not be installed. /// </para> /// </note> /// <para>This overload is silent on error; the other overload raises an exception /// if required /// (<see cref="M:InTheHand.Net.Sockets.BluetoothDeviceInfo.SetServiceState(System.Guid,System.Boolean,System.Boolean)"/>). /// </para> /// </remarks> /// - /// <exception cref="T:System.PlatformNotSupportedException"> /// Thrown if this method is called on Windows CE platforms.</exception> public void SetServiceState(Guid service, bool state) { m_impl.SetServiceState(service, state); } /// <summary> /// Enables or disables services for a Bluetooth device. /// </summary> /// <param name="service">The service GUID on the remote device.</param> /// <param name="state">Service state - TRUE to enable the service, FALSE to disable it.</param> /// <param name="throwOnError">Whether the method should raise an exception /// when /// </param> /// <remarks> /// When called on Windows CE, the device will require a soft-reset to enabled the settings. ///<note> /// <para>The system maintains a mapping of service guids to supported drivers for /// Bluetooth-enabled devices. Enabling a service installs the corresponding /// device driver. Disabling a service removes the corresponding device driver. /// If a non-supported service is enabled, a driver will not be installed. /// </para> /// </note> /// </remarks> /// - /// <exception cref="T:System.ComponentModel.Win32Exception">The call failed. /// </exception> public void SetServiceState(Guid service, bool state, bool throwOnError) { m_impl.SetServiceState(service, state, throwOnError); } #endregion #region GetServiceRecords /// <summary> /// Run an SDP query on the device&#x2019;s Service Discovery Database. /// </summary> /// - /// <remarks> /// <para> /// For instance to see whether the device has an an Serial Port service /// search for UUID <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.SerialPort"/>, /// or too find all the services that use RFCOMM use /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.RFCommProtocol"/>, /// or all the services use /// <see cref="F:InTheHand.Net.Bluetooth.BluetoothService.L2CapProtocol"/>. /// </para> /// <para> /// If the device isn&#x2019;t accessible a <see cref="T:System.Net.Sockets.SocketException"/> /// with <see cref="P:System.Net.Sockets.SocketException.ErrorCode"/> /// 10108 (0x277C) occurs. /// </para> /// </remarks> /// - /// <param name="service">The UUID to search for, as a <see cref="T:System.Guid"/>. /// </param> /// - /// <returns>The parsed record as an /// <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/>. /// </returns> /// - /// <example> /// <code lang="VB.NET"> /// Dim bdi As BluetoothDeviceInfo = ... /// Dim records As ServiceRecord() = bdi.GetServiceRecords(BluetoothService.RFCommProtocol) /// ' Dump each to console /// For Each curRecord As ServiceRecord In records /// ServiceRecordUtilities.Dump(Console.Out, curRecord) /// Next /// </code> /// </example> /// /// - /// <exception cref="T:System.Net.Sockets.SocketException"> /// The query failed. /// </exception> public ServiceRecord[] GetServiceRecords(Guid service) { return m_impl.GetServiceRecords(service); } /// <summary> /// Begins an asynchronous Service Record lookup query. /// </summary> /// - /// <param name="service">See <see cref="M:InTheHand.Net.Sockets.BluetoothDeviceInfo.GetServiceRecords(System.Guid)"/>. /// </param> /// <param name="callback">An optional asynchronous callback, to be called /// when the query is complete. /// </param> /// <param name="state">A user-provided object that distinguishes this /// particular asynchronous Service Record lookup query from other requests. /// </param> /// - /// <returns>An <see cref="T:System.IAsyncResult"/> that represents the /// asynchronous Service Record lookup query, which could still be pending. /// </returns> public IAsyncResult BeginGetServiceRecords(Guid service, AsyncCallback callback, object state) { #if !V1 return m_impl.BeginGetServiceRecords(service, callback, state); #else throw new NotSupportedException(); #endif } /// <summary> /// Ends an asynchronous Service Record lookup query. /// </summary> /// - /// <param name="asyncResult">An <see cref="T:System.IAsyncResult"/> /// object that was obtained when the asynchronous operation was started. /// </param> /// - /// <returns>The parsed record as an /// <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/>. /// </returns> public ServiceRecord[] EndGetServiceRecords(IAsyncResult asyncResult) { #if !V1 return m_impl.EndGetServiceRecords(asyncResult); #else throw new NotSupportedException(); #endif } #if FX4 public System.Threading.Tasks.Task<ServiceRecord[]> GetServiceRecordsAsync(Guid service, object state) { return System.Threading.Tasks.Task.Factory.FromAsync<Guid, ServiceRecord[]>( BeginGetServiceRecords, EndGetServiceRecords, service, state); } #endif /// <summary> /// Run an SDP query on the device&#x2019;s Service Discovery Database, /// returning the raw byte rather than a parsed record. /// </summary> /// - /// <remarks> /// If the device isn&#x2019;t accessible a <see cref="T:System.Net.Sockets.SocketException"/> /// with <see cref="P:System.Net.Sockets.SocketException.ErrorCode"/> /// 10108 (0x277C) occurs. /// </remarks> /// - /// <param name="service">The UUID to search for, as a <see cref="T:System.Guid"/>. /// </param> /// - /// <returns>An array of array of <see cref="T:System.Byte"/>.</returns> /// - /// <exception cref="T:System.Net.Sockets.SocketException"> /// The query failed. /// </exception> public byte[][] GetServiceRecordsUnparsed(Guid service) { return m_impl.GetServiceRecordsUnparsed(service); } #endregion /// <summary> /// Gets the radio version and manufacturer information for the device. /// Needs a connection to the device. /// </summary> /// - /// <remarks> /// <para>Includes information such as the LMP versions, supported /// features and the manufacturer of the radio/Bluetooth Controller. /// </para> /// <para>If the device is not connected this information cannot be /// obtained; an error will occur if there is no connection. /// The values will be cached until <see cref="Refresh"/> is called. /// </para> /// <para>This feature is currently supported only on the /// Microsoft Bluetooth stack on both desktop Windows and Windows /// Mobile. However Windows XP does not provide this information. /// Implementation is possible on some of the other Bluetooth stacks /// and will depend on demand/support for the user community. /// </para> /// </remarks> /// - /// <exception cref="System.ComponentModel.Win32Exception"> /// An error occurred, desktop Windows returns error code /// 1167 ERROR_DEVICE_NOT_CONNECTED and Windows Mobile returns error code /// 1168 ERROR_NOT_FOUND. /// Windows XP which does not support this functionality returns error code /// 2 ERROR_FILE_NOT_FOUND. /// </exception> /// <exception cref="System.NotImplementedException"> /// Not yet implemented. /// </exception> /// <exception cref="System.NotSupportedException"> /// This stack does not support getting this information. /// </exception> /// - /// <returns>The radio version etc information as a /// <see cref="RadioVersions"/> instance. /// </returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public RadioVersions GetVersions() { return m_impl.GetVersions(); } /// <summary> /// Specifies whether the device is connected. /// </summary> /// <remarks>Not supported under Windows CE and will always return false.</remarks> /// <seealso cref="Remembered"/> /// <seealso cref="Authenticated"/> public bool Connected { get { return m_impl.Connected; } } /// <summary> /// Specifies whether the device is a remembered device. Not all remembered devices are authenticated. /// </summary> /// - /// <remarks>Now supported under Windows CE &#x2014; will return the same as /// <see cref="P:InTheHand.Net.Sockets.BluetoothDeviceInfo.Authenticated"/>. /// </remarks> /// <seealso cref="Connected"/> /// <seealso cref="Authenticated"/> public bool Remembered { get { return m_impl.Remembered; } } /// <summary> /// Specifies whether the device is authenticated, paired, or bonded. All authenticated devices are remembered. /// </summary> /// <remarks>Is now supported on both CE and XP.</remarks> /// <seealso cref="Connected"/> /// <seealso cref="Remembered"/> public bool Authenticated { get { return m_impl.Authenticated; } } /// <summary> /// Date and Time this device was last seen by the system. /// </summary> /// - /// <remarks><para>Is set by the Inquiry (Device Discovery) process on /// the stacks where we handle Inquiry directly &#x2014; that is /// every platform except the Microsoft stack on Win32 (MSFT+Win32), /// so is supported under MSFT+WM, Widcomm, Bluetopia, etc, etc. /// </para> /// <para>This value is supported on Windows 7 with the Microsoft stack. /// It it not supported on earlier Win32 versions as the native /// API has a bug. The value provided is always simply the current /// time, e.g. after a discovery for every device returned this value has /// the time of the discovery operation. Tracked by workitem /// <see href="http://www.codeplex.com/32feet/WorkItem/View.aspx?WorkItemId=10280">10280</see>. /// </para> /// </remarks> /// - /// <value> /// An instance of <see cref="T:System.DateTime"/> containing the time in UTC, /// or <c>DateTime</c>.<see cref="F:System.DateTime.MinValue"/> /// if there's no value. /// </value> public DateTime LastSeen { get { AssertUtc(m_impl.LastSeen); return m_impl.LastSeen; } } /// <summary> /// Date and Time this device was last used by the system. /// </summary> /// - /// <remarks> /// <para>Not supported on most stacks: Widcomm, Bluetopia, MSFT+WM /// and will return <see cref="F:System.DateTime.MinValue">DateTime.MinValue</see> /// </para> /// <para>Is supported on Windows 7 with the Microsoft stack. Is not /// supported on earlier Win32 versions &#x2014; there it just always /// returns the current time, see <see cref="P:InTheHand.Net.Sockets.BluetoothDeviceInfo.LastSeen"/>. /// </para> /// </remarks> /// - /// <value> /// An instance of <see cref="T:System.DateTime"/> containing the time in UTC, /// or <c>DateTime</c>.<see cref="F:System.DateTime.MinValue"/> /// if there's no value. /// </value> public DateTime LastUsed { get { AssertUtc(m_impl.LastUsed); return m_impl.LastUsed; } } private void AssertUtc(DateTime dateTime) { if (dateTime == DateTime.MinValue) return; Debug.Assert(dateTime.Kind == DateTimeKind.Utc, "Is: " + dateTime.Kind); } /// <summary> /// Displays information about the device. /// </summary> public void ShowDialog() { m_impl.ShowDialog(); } //-------- #region Equals /// <summary> /// Compares two <see cref="BluetoothDeviceInfo"/> instances for equality. /// </summary> /// - /// <param name="obj">The <see cref="BluetoothDeviceInfo"/> /// to compare with the current instance. /// </param> /// - /// <returns><c>true</c> if <paramref name="obj"/> /// is a <see cref="BluetoothDeviceInfo"/> and equal to the current instance; /// otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { //objects are equal if device address matches BluetoothDeviceInfo bdi = obj as BluetoothDeviceInfo; if (bdi != null) { return this.DeviceAddress.Equals(bdi.DeviceAddress); } if (!IsAMsftInternalType(obj)) { Debug.Fail("Who's comparing " + (obj == null ? "<null>" : "'" + obj.GetType().FullName + "'") + " to BDI!"); } return base.Equals(obj); } /// <summary> /// E.g. used internally by WPF. /// </summary> /// <param name="obj"></param> /// <returns></returns> internal static bool IsAMsftInternalType(object obj) { bool msft = obj != null && obj.GetType().FullName.Equals("MS.Internal.NamedObject", StringComparison.Ordinal); return msft; } #endregion #region Auxiliary Equals methods internal static bool EqualsIBDI(IBluetoothDeviceInfo x, IBluetoothDeviceInfo y) { bool eq = x.DeviceAddress.Equals(y.DeviceAddress); return eq; } internal static bool EqualsIBDI(IBluetoothDeviceInfo x, object obj) { IBluetoothDeviceInfo y = obj as IBluetoothDeviceInfo; if (y != null) { return EqualsIBDI(x, y); } Debug.Fail("Who's comparing " + (obj == null ? "<null>" : "'" + obj.GetType().FullName + "'") + " to BDI!"); return object.Equals(x, obj); } internal static int ListIndexOf(System.Collections.Generic.List<IBluetoothDeviceInfo> list, IBluetoothDeviceInfo item) { int idx = list.FindIndex( delegate(IBluetoothDeviceInfo cur) { return item.DeviceAddress.Equals(cur.DeviceAddress); }); return idx; } internal static bool AddUniqueDevice(List<IBluetoothDeviceInfo> list, IBluetoothDeviceInfo bdi) { int idx = BluetoothDeviceInfo.ListIndexOf(list, bdi); AssertManualExistsIf(idx, list, bdi); if (idx == -1) { list.Add(bdi); return true; } else { Debug.WriteLine("Replace device"); // Check the new info versus the previously discovered device. IBluetoothDeviceInfo bdiOld = list[idx]; Debug.Assert(bdiOld.DeviceAddress.Equals(bdi.DeviceAddress)); //Debug.Assert(deviceName != null); //Debug.Assert(deviceName.Length != 0); //Debug.Assert(bdiOld.ClassOfDevice.Equals(bdi.ClassOfDevice)); // Replace list[idx] = bdi; return false; } } [Conditional("DEBUG")] private static void AssertManualExistsIf(int index, List<IBluetoothDeviceInfo> list, IBluetoothDeviceInfo item) { bool found = false; foreach (IBluetoothDeviceInfo cur in list) { if (cur.DeviceAddress == item.DeviceAddress) found = true; } Debug.Assert(found == (index != -1), "manual found != list->object found"); } internal static IBluetoothDeviceInfo[] Intersect(IBluetoothDeviceInfo[] list, List<IBluetoothDeviceInfo> seenDevices) { var copy = new List<IBluetoothDeviceInfo>(list.Length); foreach (var cur in list) { if (-1 != BluetoothDeviceInfo.ListIndexOf(seenDevices, cur)) { copy.Add(cur); } }//for return copy.ToArray(); } #endregion #region Get Hash Code /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A hash code for the current object.</returns> public override int GetHashCode() { return this.DeviceAddress.GetHashCode(); } #endregion #region IComparable Members int IComparable.CompareTo(object obj) { //objects are equal if device address matches BluetoothDeviceInfo bdi = obj as BluetoothDeviceInfo; if (bdi != null) { return ((IComparable)this.DeviceAddress).CompareTo(bdi); } return -1; } #endregion //---- internal static BluetoothDeviceInfo[] Wrap(IBluetoothDeviceInfo[] orig) { // Bah no Array.ConvertAll method in NETCF. BluetoothDeviceInfo[] wrapped = new BluetoothDeviceInfo[orig.Length]; for (int i = 0; i < orig.Length; ++i) { wrapped[i] = new BluetoothDeviceInfo(orig[i]); } return wrapped; } } }
// // Shelf.cs // // Author: // Lluis Sanchez Gual <[email protected]> // // Copyright (c) 2010 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Linq; using System.IO; using System.Collections.Generic; using System.Collections; using System.Text; using Mercurial; using MergeCommandResult = Mercurial.MergeCommand; using PersonIdent = System.String; // maybe ... namespace MonoDevelop.VersionControl.Mercurial { public class Shelf { internal string CommitId { get; private set; } internal string FullLine { get; private set; } internal ShelfCollection ShelfCollection { get; set; } /// <summary> /// Who created the stash /// </summary> public string Author { get; private set; } public string AuthorEmail { get; private set; } /// <summary> /// Timestamp of the stash creation /// </summary> public DateTimeOffset DateTime { get; private set; } /// <summary> /// Shelf comment /// </summary> public string Comment { get; private set; } private Shelf () { } internal Shelf (string prevShelfCommitId, string commitId, string author, string email, string comment) { this.PrevShelfCommitId = prevShelfCommitId; this.CommitId = commitId; this.Author = author; this.AuthorEmail = email; this.DateTime = DateTimeOffset.Now; // Skip "WIP on master: " int i = comment.IndexOf (':'); this.Comment = comment.Substring (i + 2); // Create the text line to be written in the stash log int secs = (int) (this.DateTime - new DateTimeOffset (1970, 1, 1, 0, 0, 0, TimeSpan.Zero)).TotalSeconds; TimeSpan ofs = this.DateTime.Offset; string tz = string.Format ("{0}{1:00}{2:00}", (ofs.Hours >= 0 ? '+':'-'), Math.Abs (ofs.Hours), Math.Abs (ofs.Minutes)); StringBuilder sb = new StringBuilder (); sb.Append (prevShelfCommitId ?? new string ('0', 40)).Append (' '); sb.Append (commitId).Append (' '); sb.Append (author).Append (" <").Append (email).Append ("> "); sb.Append (secs).Append (' ').Append (tz).Append ('\t'); sb.Append (comment); FullLine = sb.ToString (); } string prevShelfCommitId; internal string PrevShelfCommitId { get { return prevShelfCommitId; } set { prevShelfCommitId = value; if (FullLine != null) { if (prevShelfCommitId != null) FullLine = prevShelfCommitId + FullLine.Substring (40); else FullLine = new string ('0', 40) + FullLine.Substring (40); } } } internal static Shelf Parse (string line) { // Parses a stash log line and creates a Shelf object with the information Shelf s = new Shelf (); s.PrevShelfCommitId = line.Substring (0, 40); if (s.PrevShelfCommitId.All (c => c == '0')) // And id will all 0 means no parent (first stash of the stack) s.PrevShelfCommitId = null; s.CommitId = line.Substring (41, 40); string aname = string.Empty; string amail = string.Empty; int i = line.IndexOf ('<'); if (i != -1) { aname = line.Substring (82, i - 82 - 1); i++; int i2 = line.IndexOf ('>', i); if (i2 != -1) amail = line.Substring (i, i2 - i); i2 += 2; i = line.IndexOf (' ', i2); int secs = int.Parse (line.Substring (i2, i - i2)); DateTime t = new DateTime (1970, 1, 1) + TimeSpan.FromSeconds (secs); string st = t.ToString ("yyyy-MM-ddTHH:mm:ss") + line.Substring (i + 1, 3) + ":" + line.Substring (i + 4, 2); s.DateTime = DateTimeOffset.Parse (st); s.Comment = line.Substring (i + 7); i = s.Comment.IndexOf (':'); if (i != -1) s.Comment = s.Comment.Substring (i + 2); } s.Author = aname; s.AuthorEmail = amail; s.FullLine = line; return s; } public global::Mercurial.MergeCommand Apply (MercurialProgressMonitor monitor) { return ShelfCollection.Apply (monitor, this); } } public class ShelfCollection: IEnumerable<Shelf> { global::Mercurial.Repository _repo; internal ShelfCollection (global::Mercurial.Repository repo) { this._repo = repo; } FileInfo ShelfLogFile { get { string stashLog = Path.Combine (_repo.Client.RepositoryPath, "logs"); stashLog = Path.Combine (stashLog, "refs"); return new FileInfo (Path.Combine (stashLog, "stash")); } } FileInfo ShelfRefFile { get { string file = Path.Combine (_repo.Path, "refs"); return new FileInfo (Path.Combine (file, "stash")); } } public Shelf Create (MercurialProgressMonitor monitor) { return Create (monitor, null); } public Shelf Create (MercurialProgressMonitor monitor, string message) { throw new NotImplementedException (); } /* public Shelf Create (MercurialProgressMonitor monitor, string message) { if (monitor != null) { monitor.Start (1); monitor.BeginTask ("Shelving changes", 100); } UserConfig config = _repo.GetConfig ().Get (UserConfig.KEY); RevWalk rw = new RevWalk (_repo); ObjectId headId = _repo.Resolve (Constants.HEAD); var parent = rw.ParseCommit (headId); PersonIdent author = new PersonIdent(config.GetAuthorName () ?? "unknown", config.GetAuthorEmail () ?? "unknown@(none)."); if (string.IsNullOrEmpty (message)) { // Use the commit summary as message message = parent.Abbreviate (7).ToString () + " " + parent.GetShortMessage (); int i = message.IndexOfAny (new char[] { '\r', '\n' }); if (i != -1) message = message.Substring (0, i); } // Create the index tree commit ObjectInserter inserter = _repo.NewObjectInserter (); DirCache dc = _repo.ReadDirCache (); if (monitor != null) monitor.Update (10); var tree_id = dc.WriteTree (inserter); inserter.Release (); if (monitor != null) monitor.Update (10); string commitMsg = "index on " + _repo.GetBranch () + ": " + message; ObjectId indexCommit = GitUtil.CreateCommit (_repo, commitMsg + "\n", new ObjectId[] {headId}, tree_id, author, author); if (monitor != null) monitor.Update (20); // Create the working dir commit tree_id = WriteWorkingDirectoryTree (parent.Tree, dc); commitMsg = "WIP on " + _repo.GetBranch () + ": " + message; var wipCommit = GitUtil.CreateCommit(_repo, commitMsg + "\n", new ObjectId[] { headId, indexCommit }, tree_id, author, author); if (monitor != null) monitor.Update (20); string prevCommit = null; FileInfo sf = ShelfRefFile; if (sf.Exists) prevCommit = File.ReadAllText (sf.FullName).Trim (' ','\t','\r','\n'); Shelf s = new Shelf (prevCommit, wipCommit.Name, author, commitMsg); FileInfo stashLog = ShelfLogFile; File.AppendAllText (stashLog.FullName, s.FullLine + "\n"); File.WriteAllText (sf.FullName, s.CommitId + "\n"); if (monitor != null) monitor.Update (5); // Wipe all local changes GitUtil.HardReset (_repo, Constants.HEAD); monitor.EndTask (); s.ShelfCollection = this; return s; } ObjectId WriteWorkingDirectoryTree (RevTree headTree, DirCache index) { DirCache dc = DirCache.NewInCore (); DirCacheBuilder cb = dc.Builder (); ObjectInserter oi = _repo.NewObjectInserter (); try { TreeWalk tw = new TreeWalk (_repo); tw.Reset (); tw.AddTree (new FileTreeIterator (_repo)); tw.AddTree (headTree); tw.AddTree (new DirCacheIterator (index)); while (tw.Next ()) { // Ignore untracked files if (tw.IsSubtree) tw.EnterSubtree (); else if (tw.GetFileMode (0) != NGit.FileMode.MISSING && (tw.GetFileMode (1) != NGit.FileMode.MISSING || tw.GetFileMode (2) != NGit.FileMode.MISSING)) { WorkingTreeIterator f = tw.GetTree<WorkingTreeIterator>(0); DirCacheIterator dcIter = tw.GetTree<DirCacheIterator>(2); DirCacheEntry currentEntry = dcIter.GetDirCacheEntry (); DirCacheEntry ce = new DirCacheEntry (tw.PathString); if (!f.IsModified (currentEntry, true)) { ce.SetLength (currentEntry.Length); ce.LastModified = currentEntry.LastModified; ce.FileMode = currentEntry.FileMode; ce.SetObjectId (currentEntry.GetObjectId ()); } else { long sz = f.GetEntryLength(); ce.SetLength (sz); ce.LastModified = f.GetEntryLastModified(); ce.FileMode = f.EntryFileMode; var data = f.OpenEntryStream(); try { ce.SetObjectId (oi.Insert (Constants.OBJ_BLOB, sz, data)); } finally { data.Close (); } } cb.Add (ce); } } cb.Finish (); return dc.WriteTree (oi); } finally { oi.Release (); } } */ internal MergeCommandResult Apply (MercurialProgressMonitor monitor, Shelf shelf) { /* monitor.Start (1); monitor.BeginTask ("Applying stash", 100); ObjectId cid = _repo.Resolve (shelf.CommitId); RevWalk rw = new RevWalk (_repo); RevCommit wip = rw.ParseCommit (cid); RevCommit oldHead = wip.Parents.First(); rw.ParseHeaders (oldHead); MergeCommandResult res = GitUtil.MergeTrees (monitor, _repo, oldHead, wip, "Shelf", false); monitor.EndTask (); return res; */ throw new NotImplementedException (); } public void Remove (Shelf s) { List<Shelf> stashes = ReadShelfes (); Remove (stashes, s); } public MergeCommandResult Pop (MercurialProgressMonitor monitor) { List<Shelf> stashes = ReadShelfes (); Shelf last = stashes.Last (); MergeCommandResult res = last.Apply (monitor); if (res.Result == MergeResult.Success) Remove (stashes, last); return res; } public void Clear () { if (ShelfRefFile.Exists) ShelfRefFile.Delete (); if (ShelfLogFile.Exists) ShelfLogFile.Delete (); } void Remove (List<Shelf> stashes, Shelf s) { int i = stashes.FindIndex (st => st.CommitId == s.CommitId); if (i != -1) { stashes.RemoveAt (i); Shelf next = stashes.FirstOrDefault (ns => ns.PrevShelfCommitId == s.CommitId); if (next != null) next.PrevShelfCommitId = s.PrevShelfCommitId; if (stashes.Count == 0) { // No more stashes. The ref and log files can be deleted. ShelfRefFile.Delete (); ShelfLogFile.Delete (); return; } WriteShelfes (stashes); if (i == stashes.Count) { // We deleted the head. Write the new head. File.WriteAllText (ShelfRefFile.FullName, stashes.Last ().CommitId + "\n"); } } } public IEnumerator<Shelf> GetEnumerator () { return ReadShelfes ().GetEnumerator (); } List<Shelf> ReadShelfes () { // Reads the registered stashes // Results are returned from the bottom to the top of the stack List<Shelf> result = new List<Shelf> (); FileInfo logFile = ShelfLogFile; if (!logFile.Exists) return result; Dictionary<string,Shelf> stashes = new Dictionary<string, Shelf> (); Shelf first = null; foreach (string line in File.ReadAllLines (logFile.FullName)) { Shelf s = Shelf.Parse (line); s.ShelfCollection = this; if (s.PrevShelfCommitId == null) first = s; else stashes.Add (s.PrevShelfCommitId, s); } while (first != null) { result.Add (first); stashes.TryGetValue (first.CommitId, out first); } return result; } void WriteShelfes (List<Shelf> list) { StringBuilder sb = new StringBuilder (); foreach (var s in list) { sb.Append (s.FullLine); sb.Append ('\n'); } File.WriteAllText (ShelfLogFile.FullName, sb.ToString ()); } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Drawing; using System.ComponentModel; using System.Globalization; using System.Windows.Forms; using OpenLiveWriter.Api; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Layout; using OpenLiveWriter.Localization; using OpenLiveWriter.Localization.Bidi; using OpenLiveWriter.PostEditor.ContentSources; using OpenLiveWriter.PostEditor.LiveClipboard; //using OpenLiveWriter.SpellChecker; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.ApplicationFramework.Preferences; namespace OpenLiveWriter.PostEditor.LiveClipboard { public class LiveClipboardPreferencesPanel : PreferencesPanel { private System.ComponentModel.IContainer components; private System.Windows.Forms.Label labelInstalledPlugins; private System.Windows.Forms.Label labelCaption; private System.Windows.Forms.Panel panelFormatDetails; private System.Windows.Forms.Label labelNoFormatSelected; private ToolTip2 toolTip; private System.Windows.Forms.Button buttonOptions; private System.Windows.Forms.ListView listViewFormats; private System.Windows.Forms.ImageList imageListFormats; private System.Windows.Forms.LinkLabel linkLabelMoreAboutLiveClipboard; private System.Windows.Forms.GroupBox groupBoxFormatDetails; private System.Windows.Forms.PictureBox pictureBoxLiveClipboardIcon; private System.Windows.Forms.ColumnHeader columnHeaderFormat; private System.Windows.Forms.Button buttonChange; private System.Windows.Forms.ColumnHeader columnHeaderDescription; private System.Windows.Forms.Label labelHandledByCaption; private System.Windows.Forms.Label labelContentSourceName; private System.Windows.Forms.Label labelContentTypeCaption; private System.Windows.Forms.PictureBox pictureBoxContentSource; private System.Windows.Forms.Label labelContentType; private LiveClipboardPreferences _liveClipboardPreferences ; public LiveClipboardPreferencesPanel() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); this.columnHeaderFormat.Text = Res.Get(StringId.LCPrefFormat); this.columnHeaderDescription.Text = Res.Get(StringId.LCPrefDescription); this.labelInstalledPlugins.Text = Res.Get(StringId.LCPrefSupportedFormats); this.labelHandledByCaption.Text = Res.Get(StringId.LCPrefHandledBy); this.buttonChange.Text = Res.Get(StringId.LCPrefChangeButton); this.buttonOptions.Text = Res.Get(StringId.LCPrefOptionsButton); this.labelContentTypeCaption.Text = Res.Get(StringId.LCPrefContentType); this.labelNoFormatSelected.Text = Res.Get(StringId.LCPrefNoFormatSelected); this.linkLabelMoreAboutLiveClipboard.Text = Res.Get(StringId.LCPrefMoreAboutLiveClipboard); this.labelCaption.Text = Res.Get(StringId.LCPrefCaption); this.PanelName = Res.Get(StringId.LCPrefPanelName); // set our bitmap PanelBitmap = ResourceHelper.LoadAssemblyResourceBitmap("LiveClipboard.Images.LiveClipboardSmall.png", true); pictureBoxLiveClipboardIcon.Image = ResourceHelper.LoadAssemblyResourceBitmap("LiveClipboard.Images.LiveClipboardIcon.png", true); // paramaterize caption with product name labelCaption.Text = String.Format(CultureInfo.CurrentCulture, labelCaption.Text, ApplicationEnvironment.ProductName) ; // initialize preferences _liveClipboardPreferences = new LiveClipboardPreferences() ; _liveClipboardPreferences.PreferencesModified += new EventHandler(_liveClipboardPreferences_PreferencesModified) ; // signup for events listViewFormats.SelectedIndexChanged +=new EventHandler(listViewFormats_SelectedIndexChanged); linkLabelMoreAboutLiveClipboard.LinkClicked +=new LinkLabelLinkClickedEventHandler(linkLabelMoreAboutLiveClipboard_LinkClicked); // initialize list of formats PopulateFormatList() ; // select first item if possible if ( listViewFormats.Items.Count > 0 ) listViewFormats.Items[0].Selected = true ; // update the details pane UpdateDetailsPane() ; labelContentType.RightToLeft = System.Windows.Forms.RightToLeft.No; if (BidiHelper.IsRightToLeft) labelContentType.TextAlign = ContentAlignment.MiddleRight; } protected override void OnLoad(EventArgs e) { base.OnLoad (e); if (!DesignMode) { LayoutHelper.NaturalizeHeightAndDistribute(8, Controls); linkLabelMoreAboutLiveClipboard.Top = pictureBoxLiveClipboardIcon.Top + 1; LayoutHelper.EqualizeButtonWidthsVert(AnchorStyles.Right, buttonChange.Width, int.MaxValue, buttonChange, buttonOptions); } } private void PopulateFormatList() { listViewFormats.BeginUpdate(); listViewFormats.Items.Clear(); imageListFormats.Images.Clear(); LiveClipboardFormatHandler[] formatHandlers = LiveClipboardManager.LiveClipboardFormatHandlers ; foreach ( LiveClipboardFormatHandler formatHandler in formatHandlers ) { ListViewItem listViewItem = new ListViewItem(); UpdateListViewItem(listViewItem, formatHandler) ; listViewFormats.Items.Add(listViewItem) ; } listViewFormats.EndUpdate(); } private void UpdateListViewItem( ListViewItem listViewItem, LiveClipboardFormatHandler formatHandler ) { imageListFormats.Images.Add(BidiHelper.Mirror((Bitmap)formatHandler.FormatImage)) ; listViewItem.Tag = formatHandler ; listViewItem.ImageIndex = imageListFormats.Images.Count-1 ; listViewItem.SubItems.Clear(); listViewItem.Text = " " + formatHandler.FormatName ; listViewItem.SubItems.Add( new ListViewItem.ListViewSubItem(listViewItem, formatHandler.FormatDescription)) ; } public override void Save() { if ( _liveClipboardPreferences.IsModified() ) { _liveClipboardPreferences.Save(); } } private void _liveClipboardPreferences_PreferencesModified(object sender, EventArgs e) { OnModified(EventArgs.Empty) ; } private void listViewFormats_SelectedIndexChanged(object sender, EventArgs e) { UpdateDetailsPane() ; } private void listViewFormats_DoubleClick(object sender, System.EventArgs e) { if ( buttonChange.Enabled ) ChangeSelectedFormat(); } private void buttonChange_Click(object sender, System.EventArgs e) { ChangeSelectedFormat(); } private void ChangeSelectedFormat() { if ( listViewFormats.SelectedItems.Count < 1 ) return ; // should never happen ListViewItem selectedItem = listViewFormats.SelectedItems[0] ; LiveClipboardFormatHandler formatHandler = selectedItem.Tag as LiveClipboardFormatHandler ; using ( LiveClipboardChangeHandlerForm changeHandlerForm = new LiveClipboardChangeHandlerForm(formatHandler)) { if ( changeHandlerForm.ShowDialog(FindForm()) == DialogResult.OK ) { LiveClipboardFormatHandler newFormatHandler = changeHandlerForm.FormatHandler ; if ( newFormatHandler != null ) { LiveClipboardManager.SetContentSourceForFormat(newFormatHandler.Format, newFormatHandler.ContentSource.Id); UpdateListViewItem( selectedItem, newFormatHandler ) ; } } } } private void buttonOptions_Click(object sender, System.EventArgs e) { LiveClipboardFormatHandler formatHandler = GetSelectedFormat() ; if ( formatHandler != null ) { if ( formatHandler.ContentSource.WriterPluginHasEditableOptions ) { formatHandler.ContentSource.Instance.EditOptions(FindForm()); } } } private void linkLabelMoreAboutLiveClipboard_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { ShellHelper.LaunchUrl(GLink.Instance.MoreAboutLiveClipboard); } private void UpdateDetailsPane() { LiveClipboardFormatHandler formatHandler = GetSelectedFormat() ; if ( formatHandler != null ) { panelFormatDetails.Visible = true ; labelNoFormatSelected.Visible = false ; groupBoxFormatDetails.Text = String.Format(CultureInfo.CurrentCulture, Res.Get(StringId.LCPrefDetailsGroupBoxFormat), formatHandler.FormatName) ; LiveClipboardComponentDisplay componentDisplay = new LiveClipboardComponentDisplay(formatHandler.ContentSource); pictureBoxContentSource.Image = componentDisplay.Icon ; labelContentSourceName.Text = componentDisplay.Name ; labelContentType.Text = formatHandler.FriendlyContentType ; buttonChange.Enabled = LiveClipboardManager.GetContentSourcesForFormat(formatHandler.Format).Length > 1 ; buttonOptions.Visible = formatHandler.ContentSource.WriterPluginHasEditableOptions; } else { labelNoFormatSelected.Visible = true ; groupBoxFormatDetails.Text = Res.Get(StringId.LCPrefDetails) ; panelFormatDetails.Visible = false ; } } private LiveClipboardFormatHandler GetSelectedFormat() { if ( listViewFormats.SelectedItems.Count > 0 ) return listViewFormats.SelectedItems[0].Tag as LiveClipboardFormatHandler ; else return null ; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { _liveClipboardPreferences.PreferencesModified -= new EventHandler(_liveClipboardPreferences_PreferencesModified); 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.components = new System.ComponentModel.Container(); this.listViewFormats = new System.Windows.Forms.ListView(); this.columnHeaderFormat = new System.Windows.Forms.ColumnHeader(); this.columnHeaderDescription = new System.Windows.Forms.ColumnHeader(); this.imageListFormats = new System.Windows.Forms.ImageList(this.components); this.labelInstalledPlugins = new System.Windows.Forms.Label(); this.groupBoxFormatDetails = new System.Windows.Forms.GroupBox(); this.panelFormatDetails = new System.Windows.Forms.Panel(); this.labelContentType = new System.Windows.Forms.Label(); this.labelHandledByCaption = new System.Windows.Forms.Label(); this.labelContentSourceName = new System.Windows.Forms.Label(); this.buttonChange = new System.Windows.Forms.Button(); this.buttonOptions = new System.Windows.Forms.Button(); this.labelContentTypeCaption = new System.Windows.Forms.Label(); this.pictureBoxContentSource = new System.Windows.Forms.PictureBox(); this.labelNoFormatSelected = new System.Windows.Forms.Label(); this.linkLabelMoreAboutLiveClipboard = new System.Windows.Forms.LinkLabel(); this.labelCaption = new System.Windows.Forms.Label(); this.toolTip = new OpenLiveWriter.Controls.ToolTip2(this.components); this.pictureBoxLiveClipboardIcon = new System.Windows.Forms.PictureBox(); this.groupBoxFormatDetails.SuspendLayout(); this.panelFormatDetails.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxContentSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxLiveClipboardIcon)).BeginInit(); this.SuspendLayout(); // // listViewFormats // this.listViewFormats.AutoArrange = false; this.listViewFormats.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderFormat, this.columnHeaderDescription}); this.listViewFormats.FullRowSelect = true; this.listViewFormats.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.listViewFormats.HideSelection = false; this.listViewFormats.Location = new System.Drawing.Point(8, 84); this.listViewFormats.MultiSelect = false; this.listViewFormats.Name = "listViewFormats"; this.listViewFormats.Size = new System.Drawing.Size(348, 189); this.listViewFormats.SmallImageList = this.imageListFormats; this.listViewFormats.TabIndex = 3; this.listViewFormats.UseCompatibleStateImageBehavior = false; this.listViewFormats.View = System.Windows.Forms.View.Details; this.listViewFormats.DoubleClick += new System.EventHandler(this.listViewFormats_DoubleClick); // // columnHeaderFormat // this.columnHeaderFormat.Text = "Format"; this.columnHeaderFormat.Width = 100; // // columnHeaderDescription // this.columnHeaderDescription.Text = "Description"; this.columnHeaderDescription.Width = 223; // // imageListFormats // this.imageListFormats.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit; this.imageListFormats.ImageSize = new System.Drawing.Size(16, 16); this.imageListFormats.TransparentColor = System.Drawing.Color.Transparent; // // labelInstalledPlugins // this.labelInstalledPlugins.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelInstalledPlugins.Location = new System.Drawing.Point(8, 66); this.labelInstalledPlugins.Name = "labelInstalledPlugins"; this.labelInstalledPlugins.Size = new System.Drawing.Size(341, 15); this.labelInstalledPlugins.TabIndex = 2; this.labelInstalledPlugins.Text = "&Supported formats:"; // // groupBoxFormatDetails // this.groupBoxFormatDetails.Controls.Add(this.panelFormatDetails); this.groupBoxFormatDetails.Controls.Add(this.labelNoFormatSelected); this.groupBoxFormatDetails.FlatStyle = System.Windows.Forms.FlatStyle.System; this.groupBoxFormatDetails.Location = new System.Drawing.Point(8, 282); this.groupBoxFormatDetails.Name = "groupBoxFormatDetails"; this.groupBoxFormatDetails.Size = new System.Drawing.Size(349, 109); this.groupBoxFormatDetails.TabIndex = 4; this.groupBoxFormatDetails.TabStop = false; this.groupBoxFormatDetails.Text = "Details for \'vCalendar\' format"; // // panelFormatDetails // this.panelFormatDetails.Controls.Add(this.labelContentType); this.panelFormatDetails.Controls.Add(this.labelHandledByCaption); this.panelFormatDetails.Controls.Add(this.labelContentSourceName); this.panelFormatDetails.Controls.Add(this.buttonChange); this.panelFormatDetails.Controls.Add(this.buttonOptions); this.panelFormatDetails.Controls.Add(this.labelContentTypeCaption); this.panelFormatDetails.Controls.Add(this.pictureBoxContentSource); this.panelFormatDetails.Location = new System.Drawing.Point(7, 16); this.panelFormatDetails.Name = "panelFormatDetails"; this.panelFormatDetails.Size = new System.Drawing.Size(339, 89); this.panelFormatDetails.TabIndex = 0; // // labelContentType // this.labelContentType.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelContentType.Location = new System.Drawing.Point(2, 67); this.labelContentType.Name = "labelContentType"; this.labelContentType.Size = new System.Drawing.Size(224, 16); this.labelContentType.TabIndex = 5; this.labelContentType.Text = "vcalendar (application/xhtml+xml)"; // // labelHandledByCaption // this.labelHandledByCaption.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelHandledByCaption.Location = new System.Drawing.Point(2, 7); this.labelHandledByCaption.Name = "labelHandledByCaption"; this.labelHandledByCaption.Size = new System.Drawing.Size(186, 15); this.labelHandledByCaption.TabIndex = 0; this.labelHandledByCaption.Text = "Handled by:"; // // labelContentSourceName // this.labelContentSourceName.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelContentSourceName.Location = new System.Drawing.Point(26, 23); this.labelContentSourceName.Name = "labelContentSourceName"; this.labelContentSourceName.Size = new System.Drawing.Size(136, 15); this.labelContentSourceName.TabIndex = 1; this.labelContentSourceName.Text = "Open Live Writer"; // // buttonChange // this.buttonChange.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonChange.Location = new System.Drawing.Point(259, 10); this.buttonChange.Name = "buttonChange"; this.buttonChange.Size = new System.Drawing.Size(75, 23); this.buttonChange.TabIndex = 2; this.buttonChange.Text = "Change..."; this.buttonChange.Click += new System.EventHandler(this.buttonChange_Click); // // buttonOptions // this.buttonOptions.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonOptions.Location = new System.Drawing.Point(259, 40); this.buttonOptions.Name = "buttonOptions"; this.buttonOptions.Size = new System.Drawing.Size(75, 23); this.buttonOptions.TabIndex = 4; this.buttonOptions.Text = "Options..."; this.buttonOptions.Click += new System.EventHandler(this.buttonOptions_Click); // // labelContentTypeCaption // this.labelContentTypeCaption.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelContentTypeCaption.Location = new System.Drawing.Point(2, 51); this.labelContentTypeCaption.Name = "labelContentTypeCaption"; this.labelContentTypeCaption.Size = new System.Drawing.Size(188, 16); this.labelContentTypeCaption.TabIndex = 3; this.labelContentTypeCaption.Text = "Content type:"; // // pictureBoxContentSource // this.pictureBoxContentSource.Location = new System.Drawing.Point(2, 21); this.pictureBoxContentSource.Name = "pictureBoxContentSource"; this.pictureBoxContentSource.Size = new System.Drawing.Size(16, 16); this.pictureBoxContentSource.TabIndex = 0; this.pictureBoxContentSource.TabStop = false; // // labelNoFormatSelected // this.labelNoFormatSelected.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelNoFormatSelected.Location = new System.Drawing.Point(8, 41); this.labelNoFormatSelected.Name = "labelNoFormatSelected"; this.labelNoFormatSelected.Size = new System.Drawing.Size(332, 23); this.labelNoFormatSelected.TabIndex = 1; this.labelNoFormatSelected.Text = "(No format selected)"; this.labelNoFormatSelected.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // linkLabelMoreAboutLiveClipboard // this.linkLabelMoreAboutLiveClipboard.AutoSize = true; this.linkLabelMoreAboutLiveClipboard.FlatStyle = System.Windows.Forms.FlatStyle.System; this.linkLabelMoreAboutLiveClipboard.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.linkLabelMoreAboutLiveClipboard.LinkColor = System.Drawing.SystemColors.HotTrack; this.linkLabelMoreAboutLiveClipboard.Location = new System.Drawing.Point(34, 422); this.linkLabelMoreAboutLiveClipboard.Name = "linkLabelMoreAboutLiveClipboard"; this.linkLabelMoreAboutLiveClipboard.Size = new System.Drawing.Size(144, 13); this.linkLabelMoreAboutLiveClipboard.TabIndex = 5; this.linkLabelMoreAboutLiveClipboard.TabStop = true; this.linkLabelMoreAboutLiveClipboard.Text = "More about Live Clipboard..."; // // labelCaption // this.labelCaption.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelCaption.Location = new System.Drawing.Point(8, 32); this.labelCaption.Name = "labelCaption"; this.labelCaption.Size = new System.Drawing.Size(341, 32); this.labelCaption.TabIndex = 1; this.labelCaption.Text = "You can paste web content that supports the Live Clipboard format into {0}."; // // pictureBoxLiveClipboardIcon // this.pictureBoxLiveClipboardIcon.Location = new System.Drawing.Point(14, 420); this.pictureBoxLiveClipboardIcon.Name = "pictureBoxLiveClipboardIcon"; this.pictureBoxLiveClipboardIcon.Size = new System.Drawing.Size(16, 16); this.pictureBoxLiveClipboardIcon.TabIndex = 6; this.pictureBoxLiveClipboardIcon.TabStop = false; // // LiveClipboardPreferencesPanel // this.AccessibleName = "Live Clipboard"; this.Controls.Add(this.pictureBoxLiveClipboardIcon); this.Controls.Add(this.labelCaption); this.Controls.Add(this.linkLabelMoreAboutLiveClipboard); this.Controls.Add(this.groupBoxFormatDetails); this.Controls.Add(this.labelInstalledPlugins); this.Controls.Add(this.listViewFormats); this.Name = "LiveClipboardPreferencesPanel"; this.PanelName = "Live Clipboard"; this.Size = new System.Drawing.Size(370, 449); this.Controls.SetChildIndex(this.listViewFormats, 0); this.Controls.SetChildIndex(this.labelInstalledPlugins, 0); this.Controls.SetChildIndex(this.groupBoxFormatDetails, 0); this.Controls.SetChildIndex(this.linkLabelMoreAboutLiveClipboard, 0); this.Controls.SetChildIndex(this.labelCaption, 0); this.Controls.SetChildIndex(this.pictureBoxLiveClipboardIcon, 0); this.groupBoxFormatDetails.ResumeLayout(false); this.panelFormatDetails.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxContentSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxLiveClipboardIcon)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Data; using System.IO; using System.IO.Compression; using System.Reflection; using System.Security.Cryptography; using System.Text; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Data; using Npgsql; namespace OpenSim.Data.PGSQL { public class PGSQLXAssetData : IXAssetDataPlugin { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected virtual Assembly Assembly { get { return GetType().Assembly; } } /// <summary> /// Number of days that must pass before we update the access time on an asset when it has been fetched. /// </summary> private const int DaysBetweenAccessTimeUpdates = 30; private bool m_enableCompression = false; private PGSQLManager m_database; private string m_connectionString; private object m_dbLock = new object(); /// <summary> /// We can reuse this for all hashing since all methods are single-threaded through m_dbBLock /// </summary> private HashAlgorithm hasher = new SHA256CryptoServiceProvider(); #region IPlugin Members public string Version { get { return "1.0.0.0"; } } /// <summary> /// <para>Initialises Asset interface</para> /// <para> /// <list type="bullet"> /// <item>Loads and initialises the PGSQL storage plugin.</item> /// <item>Warns and uses the obsolete pgsql_connection.ini if connect string is empty.</item> /// <item>Check for migration</item> /// </list> /// </para> /// </summary> /// <param name="connect">connect string</param> public void Initialise(string connect) { m_log.ErrorFormat("[PGSQL XASSETDATA]: ***********************************************************"); m_log.ErrorFormat("[PGSQL XASSETDATA]: ***********************************************************"); m_log.ErrorFormat("[PGSQL XASSETDATA]: ***********************************************************"); m_log.ErrorFormat("[PGSQL XASSETDATA]: THIS PLUGIN IS STRICTLY EXPERIMENTAL."); m_log.ErrorFormat("[PGSQL XASSETDATA]: DO NOT USE FOR ANY DATA THAT YOU DO NOT MIND LOSING."); m_log.ErrorFormat("[PGSQL XASSETDATA]: DATABASE TABLES CAN CHANGE AT ANY TIME, CAUSING EXISTING DATA TO BE LOST."); m_log.ErrorFormat("[PGSQL XASSETDATA]: ***********************************************************"); m_log.ErrorFormat("[PGSQL XASSETDATA]: ***********************************************************"); m_log.ErrorFormat("[PGSQL XASSETDATA]: ***********************************************************"); m_connectionString = connect; m_database = new PGSQLManager(m_connectionString); using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) { dbcon.Open(); Migration m = new Migration(dbcon, Assembly, "XAssetStore"); m.Update(); } } public void Initialise() { throw new NotImplementedException(); } public void Dispose() { } /// <summary> /// The name of this DB provider /// </summary> public string Name { get { return "PGSQL XAsset storage engine"; } } #endregion #region IAssetDataPlugin Members /// <summary> /// Fetch Asset <paramref name="assetID"/> from database /// </summary> /// <param name="assetID">Asset UUID to fetch</param> /// <returns>Return the asset</returns> /// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks> public AssetBase GetAsset(UUID assetID) { // m_log.DebugFormat("[PGSQL XASSET DATA]: Looking for asset {0}", assetID); AssetBase asset = null; lock (m_dbLock) { using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand( @"SELECT name, description, access_time, ""AssetType"", local, temporary, asset_flags, creatorid, data FROM XAssetsMeta JOIN XAssetsData ON XAssetsMeta.hash = XAssetsData.Hash WHERE id=:ID", dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("ID", assetID)); try { using (NpgsqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { asset = new AssetBase( assetID, (string)dbReader["name"], Convert.ToSByte(dbReader["AssetType"]), dbReader["creatorid"].ToString()); asset.Data = (byte[])dbReader["data"]; asset.Description = (string)dbReader["description"]; string local = dbReader["local"].ToString(); if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase)) asset.Local = true; else asset.Local = false; asset.Temporary = Convert.ToBoolean(dbReader["temporary"]); asset.Flags = (AssetFlags)Convert.ToInt32(dbReader["asset_flags"]); if (m_enableCompression) { using(MemoryStream ms = new MemoryStream(asset.Data)) using(GZipStream decompressionStream = new GZipStream(ms, CompressionMode.Decompress)) { using(MemoryStream outputStream = new MemoryStream()) { decompressionStream.CopyTo(outputStream,int.MaxValue); // int compressedLength = asset.Data.Length; asset.Data = outputStream.ToArray(); } // m_log.DebugFormat( // "[XASSET DB]: Decompressed {0} {1} to {2} bytes from {3}", // asset.ID, asset.Name, asset.Data.Length, compressedLength); } } UpdateAccessTime(asset.Metadata, (int)dbReader["access_time"]); } } } catch (Exception e) { m_log.Error(string.Format("[PGSQL XASSET DATA]: Failure fetching asset {0}", assetID), e); } } } } return asset; } /// <summary> /// Create an asset in database, or update it if existing. /// </summary> /// <param name="asset">Asset UUID to create</param> /// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks> public void StoreAsset(AssetBase asset) { // m_log.DebugFormat("[XASSETS DB]: Storing asset {0} {1}", asset.Name, asset.ID); lock (m_dbLock) { using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) { dbcon.Open(); using (NpgsqlTransaction transaction = dbcon.BeginTransaction()) { string assetName = asset.Name; if (asset.Name.Length > 64) { assetName = asset.Name.Substring(0, 64); m_log.WarnFormat( "[XASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add", asset.Name, asset.ID, asset.Name.Length, assetName.Length); } string assetDescription = asset.Description; if (asset.Description.Length > 64) { assetDescription = asset.Description.Substring(0, 64); m_log.WarnFormat( "[XASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add", asset.Description, asset.ID, asset.Description.Length, assetDescription.Length); } if (m_enableCompression) { MemoryStream outputStream = new MemoryStream(); using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress, false)) { // Console.WriteLine(WebUtil.CopyTo(new MemoryStream(asset.Data), compressionStream, int.MaxValue)); // We have to close the compression stream in order to make sure it writes everything out to the underlying memory output stream. compressionStream.Close(); byte[] compressedData = outputStream.ToArray(); asset.Data = compressedData; } } byte[] hash = hasher.ComputeHash(asset.Data); UUID asset_id; UUID.TryParse(asset.ID, out asset_id); // m_log.DebugFormat( // "[XASSET DB]: Compressed data size for {0} {1}, hash {2} is {3}", // asset.ID, asset.Name, hash, compressedData.Length); try { using (NpgsqlCommand cmd = new NpgsqlCommand( @"insert INTO XAssetsMeta(id, hash, name, description, ""AssetType"", local, temporary, create_time, access_time, asset_flags, creatorid) Select :ID, :Hash, :Name, :Description, :AssetType, :Local, :Temporary, :CreateTime, :AccessTime, :AssetFlags, :CreatorID where not exists( Select id from XAssetsMeta where id = :ID); update XAssetsMeta set id = :ID, hash = :Hash, name = :Name, description = :Description, ""AssetType"" = :AssetType, local = :Local, temporary = :Temporary, create_time = :CreateTime, access_time = :AccessTime, asset_flags = :AssetFlags, creatorid = :CreatorID where id = :ID; ", dbcon)) { // create unix epoch time int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow); cmd.Parameters.Add(m_database.CreateParameter("ID", asset_id)); cmd.Parameters.Add(m_database.CreateParameter("Hash", hash)); cmd.Parameters.Add(m_database.CreateParameter("Name", assetName)); cmd.Parameters.Add(m_database.CreateParameter("Description", assetDescription)); cmd.Parameters.Add(m_database.CreateParameter("AssetType", asset.Type)); cmd.Parameters.Add(m_database.CreateParameter("Local", asset.Local)); cmd.Parameters.Add(m_database.CreateParameter("Temporary", asset.Temporary)); cmd.Parameters.Add(m_database.CreateParameter("CreateTime", now)); cmd.Parameters.Add(m_database.CreateParameter("AccessTime", now)); cmd.Parameters.Add(m_database.CreateParameter("CreatorID", asset.Metadata.CreatorID)); cmd.Parameters.Add(m_database.CreateParameter("AssetFlags", (int)asset.Flags)); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.ErrorFormat("[ASSET DB]: PGSQL failure creating asset metadata {0} with name \"{1}\". Error: {2}", asset.FullID, asset.Name, e.Message); transaction.Rollback(); return; } if (!ExistsData(dbcon, transaction, hash)) { try { using (NpgsqlCommand cmd = new NpgsqlCommand( @"INSERT INTO XAssetsData(hash, data) VALUES(:Hash, :Data)", dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Hash", hash)); cmd.Parameters.Add(m_database.CreateParameter("Data", asset.Data)); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.ErrorFormat("[XASSET DB]: PGSQL failure creating asset data {0} with name \"{1}\". Error: {2}", asset.FullID, asset.Name, e.Message); transaction.Rollback(); return; } } transaction.Commit(); } } } } /// <summary> /// Updates the access time of the asset if it was accessed above a given threshhold amount of time. /// </summary> /// <remarks> /// This gives us some insight into assets which haven't ben accessed for a long period. This is only done /// over the threshold time to avoid excessive database writes as assets are fetched. /// </remarks> /// <param name='asset'></param> /// <param name='accessTime'></param> private void UpdateAccessTime(AssetMetadata assetMetadata, int accessTime) { DateTime now = DateTime.UtcNow; if ((now - Utils.UnixTimeToDateTime(accessTime)).TotalDays < DaysBetweenAccessTimeUpdates) return; lock (m_dbLock) { using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) { dbcon.Open(); NpgsqlCommand cmd = new NpgsqlCommand(@"update XAssetsMeta set access_time=:AccessTime where id=:ID", dbcon); try { UUID asset_id; UUID.TryParse(assetMetadata.ID, out asset_id); using (cmd) { // create unix epoch time cmd.Parameters.Add(m_database.CreateParameter("id", asset_id)); cmd.Parameters.Add(m_database.CreateParameter("access_time", (int)Utils.DateTimeToUnixTime(now))); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.ErrorFormat( "[XASSET PGSQL DB]: Failure updating access_time for asset {0} with name {1} : {2}", assetMetadata.ID, assetMetadata.Name, e.Message); } } } } /// <summary> /// We assume we already have the m_dbLock. /// </summary> /// TODO: need to actually use the transaction. /// <param name="dbcon"></param> /// <param name="transaction"></param> /// <param name="hash"></param> /// <returns></returns> private bool ExistsData(NpgsqlConnection dbcon, NpgsqlTransaction transaction, byte[] hash) { // m_log.DebugFormat("[ASSETS DB]: Checking for asset {0}", uuid); bool exists = false; using (NpgsqlCommand cmd = new NpgsqlCommand(@"SELECT hash FROM XAssetsData WHERE hash=:Hash", dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Hash", hash)); try { using (NpgsqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { // m_log.DebugFormat("[ASSETS DB]: Found asset {0}", uuid); exists = true; } } } catch (Exception e) { m_log.ErrorFormat( "[XASSETS DB]: PGSql failure in ExistsData fetching hash {0}. Exception {1}{2}", hash, e.Message, e.StackTrace); } } return exists; } /// <summary> /// Check if the assets exist in the database. /// </summary> /// <param name="uuids">The assets' IDs</param> /// <returns>For each asset: true if it exists, false otherwise</returns> public bool[] AssetsExist(UUID[] uuids) { if (uuids.Length == 0) return new bool[0]; HashSet<UUID> exist = new HashSet<UUID>(); string ids = "'" + string.Join("','", uuids) + "'"; string sql = string.Format(@"SELECT id FROM XAssetsMeta WHERE id IN ({0})", ids); using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { using (NpgsqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { UUID id = DBGuid.FromDB(reader["id"]); exist.Add(id); } } } } bool[] results = new bool[uuids.Length]; for (int i = 0; i < uuids.Length; i++) results[i] = exist.Contains(uuids[i]); return results; } /// <summary> /// Check if the asset exists in the database /// </summary> /// <param name="uuid">The asset UUID</param> /// <returns>true if it exists, false otherwise.</returns> public bool ExistsAsset(UUID uuid) { // m_log.DebugFormat("[ASSETS DB]: Checking for asset {0}", uuid); bool assetExists = false; lock (m_dbLock) { using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(@"SELECT id FROM XAssetsMeta WHERE id=:ID", dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("id", uuid)); try { using (NpgsqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { // m_log.DebugFormat("[ASSETS DB]: Found asset {0}", uuid); assetExists = true; } } } catch (Exception e) { m_log.Error(string.Format("[XASSETS DB]: PGSql failure fetching asset {0}", uuid), e); } } } } return assetExists; } /// <summary> /// Returns a list of AssetMetadata objects. The list is a subset of /// the entire data set offset by <paramref name="start" /> containing /// <paramref name="count" /> elements. /// </summary> /// <param name="start">The number of results to discard from the total data set.</param> /// <param name="count">The number of rows the returned list should contain.</param> /// <returns>A list of AssetMetadata objects.</returns> public List<AssetMetadata> FetchAssetMetadataSet(int start, int count) { List<AssetMetadata> retList = new List<AssetMetadata>(count); lock (m_dbLock) { using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) { dbcon.Open(); using(NpgsqlCommand cmd = new NpgsqlCommand(@"SELECT name, description, access_time, ""AssetType"", temporary, id, asset_flags, creatorid FROM XAssetsMeta LIMIT :start, :count",dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("start",start)); cmd.Parameters.Add(m_database.CreateParameter("count", count)); try { using (NpgsqlDataReader dbReader = cmd.ExecuteReader()) { while (dbReader.Read()) { AssetMetadata metadata = new AssetMetadata(); metadata.Name = (string)dbReader["name"]; metadata.Description = (string)dbReader["description"]; metadata.Type = Convert.ToSByte(dbReader["AssetType"]); metadata.Temporary = Convert.ToBoolean(dbReader["temporary"]); metadata.Flags = (AssetFlags)Convert.ToInt32(dbReader["asset_flags"]); metadata.FullID = DBGuid.FromDB(dbReader["id"]); metadata.CreatorID = dbReader["creatorid"].ToString(); // We'll ignore this for now - it appears unused! // metadata.SHA1 = dbReader["hash"]); UpdateAccessTime(metadata, (int)dbReader["access_time"]); retList.Add(metadata); } } } catch (Exception e) { m_log.Error("[XASSETS DB]: PGSql failure fetching asset set" + Environment.NewLine + e.ToString()); } } } } return retList; } public bool Delete(string id) { // m_log.DebugFormat("[XASSETS DB]: Deleting asset {0}", id); lock (m_dbLock) { using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(@"delete from XAssetsMeta where id=:ID", dbcon)) { cmd.Parameters.Add(m_database.CreateParameter(id, id)); cmd.ExecuteNonQuery(); } // TODO: How do we deal with data from deleted assets? Probably not easily reapable unless we // keep a reference count (?) } } return true; } #endregion } }
using System; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; using System.Security; using System.Text; using SFML.Window; using SFML.System; namespace SFML { namespace Graphics { //////////////////////////////////////////////////////////// /// <summary> /// Simple wrapper for Window that allows easy /// 2D rendering /// </summary> //////////////////////////////////////////////////////////// public class RenderWindow : SFML.Window.Window, RenderTarget { //////////////////////////////////////////////////////////// /// <summary> /// Create the window with default style and creation settings /// </summary> /// <param name="mode">Video mode to use</param> /// <param name="title">Title of the window</param> //////////////////////////////////////////////////////////// public RenderWindow(VideoMode mode, string title) : this(mode, title, Styles.Default, new ContextSettings(0, 0)) { } //////////////////////////////////////////////////////////// /// <summary> /// Create the window with default creation settings /// </summary> /// <param name="mode">Video mode to use</param> /// <param name="title">Title of the window</param> /// <param name="style">Window style (Resize | Close by default)</param> //////////////////////////////////////////////////////////// public RenderWindow(VideoMode mode, string title, Styles style) : this(mode, title, style, new ContextSettings(0, 0)) { } //////////////////////////////////////////////////////////// /// <summary> /// Create the window /// </summary> /// <param name="mode">Video mode to use</param> /// <param name="title">Title of the window</param> /// <param name="style">Window style (Resize | Close by default)</param> /// <param name="settings">Creation parameters</param> //////////////////////////////////////////////////////////// public RenderWindow(VideoMode mode, string title, Styles style, ContextSettings settings) : base(IntPtr.Zero, 0) { // Copy the string to a null-terminated UTF-32 byte array byte[] titleAsUtf32 = Encoding.UTF32.GetBytes(title + '\0'); unsafe { fixed (byte* titlePtr = titleAsUtf32) { CPointer = sfRenderWindow_createUnicode(mode, (IntPtr)titlePtr, style, ref settings); } } Initialize(); } //////////////////////////////////////////////////////////// /// <summary> /// Create the window from an existing control with default creation settings /// </summary> /// <param name="handle">Platform-specific handle of the control</param> //////////////////////////////////////////////////////////// public RenderWindow(IntPtr handle) : this(handle, new ContextSettings(0, 0)) { } //////////////////////////////////////////////////////////// /// <summary> /// Create the window from an existing control /// </summary> /// <param name="handle">Platform-specific handle of the control</param> /// <param name="settings">Creation parameters</param> //////////////////////////////////////////////////////////// public RenderWindow(IntPtr handle, ContextSettings settings) : base(sfRenderWindow_createFromHandle(handle, ref settings), 0) { Initialize(); } //////////////////////////////////////////////////////////// /// <summary> /// Tell whether or not the window is opened (ie. has been created). /// Note that a hidden window (Show(false)) /// will still return true /// </summary> /// <returns>True if the window is opened</returns> //////////////////////////////////////////////////////////// public override bool IsOpen { get { return sfRenderWindow_isOpen(CPointer); } } //////////////////////////////////////////////////////////// /// <summary> /// Close (destroy) the window. /// The Window instance remains valid and you can call /// Create to recreate the window /// </summary> //////////////////////////////////////////////////////////// public override void Close() { sfRenderWindow_close(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Display the window on screen /// </summary> //////////////////////////////////////////////////////////// public override void Display() { sfRenderWindow_display(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Creation settings of the window /// </summary> //////////////////////////////////////////////////////////// public override ContextSettings Settings { get {return sfRenderWindow_getSettings(CPointer);} } //////////////////////////////////////////////////////////// /// <summary> /// Position of the window /// </summary> //////////////////////////////////////////////////////////// public override Vector2i Position { get { return sfRenderWindow_getPosition(CPointer); } set { sfRenderWindow_setPosition(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Size of the rendering region of the window /// </summary> //////////////////////////////////////////////////////////// public override Vector2u Size { get { return sfRenderWindow_getSize(CPointer); } set { sfRenderWindow_setSize(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Change the title of the window /// </summary> /// <param name="title">New title</param> //////////////////////////////////////////////////////////// public override void SetTitle(string title) { // Copy the title to a null-terminated UTF-32 byte array byte[] titleAsUtf32 = Encoding.UTF32.GetBytes(title + '\0'); unsafe { fixed (byte* titlePtr = titleAsUtf32) { sfRenderWindow_setUnicodeTitle(CPointer, (IntPtr)titlePtr); } } } //////////////////////////////////////////////////////////// /// <summary> /// Change the window's icon /// </summary> /// <param name="width">Icon's width, in pixels</param> /// <param name="height">Icon's height, in pixels</param> /// <param name="pixels">Array of pixels, format must be RGBA 32 bits</param> //////////////////////////////////////////////////////////// public override void SetIcon(uint width, uint height, byte[] pixels) { unsafe { fixed (byte* PixelsPtr = pixels) { sfRenderWindow_setIcon(CPointer, width, height, PixelsPtr); } } } //////////////////////////////////////////////////////////// /// <summary> /// Show or hide the window /// </summary> /// <param name="visible">True to show the window, false to hide it</param> //////////////////////////////////////////////////////////// public override void SetVisible(bool visible) { sfRenderWindow_setVisible(CPointer, visible); } //////////////////////////////////////////////////////////// /// <summary> /// Show or hide the mouse cursor /// </summary> /// <param name="visible">True to show, false to hide</param> //////////////////////////////////////////////////////////// public override void SetMouseCursorVisible(bool visible) { sfRenderWindow_setMouseCursorVisible(CPointer, visible); } //////////////////////////////////////////////////////////// /// <summary> /// Enable / disable vertical synchronization /// </summary> /// <param name="enable">True to enable v-sync, false to deactivate</param> //////////////////////////////////////////////////////////// public override void SetVerticalSyncEnabled(bool enable) { sfRenderWindow_setVerticalSyncEnabled(CPointer, enable); } //////////////////////////////////////////////////////////// /// <summary> /// Enable or disable automatic key-repeat. /// Automatic key-repeat is enabled by default /// </summary> /// <param name="enable">True to enable, false to disable</param> //////////////////////////////////////////////////////////// public override void SetKeyRepeatEnabled(bool enable) { sfRenderWindow_setKeyRepeatEnabled(CPointer, enable); } //////////////////////////////////////////////////////////// /// <summary> /// Activate of deactivate the window as the current target /// for rendering /// </summary> /// <param name="active">True to activate, false to deactivate (true by default)</param> /// <returns>True if operation was successful, false otherwise</returns> //////////////////////////////////////////////////////////// public override bool SetActive(bool active) { return sfRenderWindow_setActive(CPointer, active); } //////////////////////////////////////////////////////////// /// <summary> /// Limit the framerate to a maximum fixed frequency /// </summary> /// <param name="limit">Framerate limit, in frames per seconds (use 0 to disable limit)</param> //////////////////////////////////////////////////////////// public override void SetFramerateLimit(uint limit) { sfRenderWindow_setFramerateLimit(CPointer, limit); } //////////////////////////////////////////////////////////// /// <summary> /// Change the joystick threshold, ie. the value below which /// no move event will be generated /// </summary> /// <param name="threshold">New threshold, in range [0, 100]</param> //////////////////////////////////////////////////////////// public override void SetJoystickThreshold(float threshold) { sfRenderWindow_setJoystickThreshold(CPointer, threshold); } //////////////////////////////////////////////////////////// /// <summary> /// OS-specific handle of the window /// </summary> //////////////////////////////////////////////////////////// public override IntPtr SystemHandle { get {return sfRenderWindow_getSystemHandle(CPointer);} } //////////////////////////////////////////////////////////// /// <summary> /// Default view of the window /// </summary> //////////////////////////////////////////////////////////// public View DefaultView { get { return new View(myDefaultView); } } //////////////////////////////////////////////////////////// /// <summary> /// Return the current active view /// </summary> /// <returns>The current view</returns> //////////////////////////////////////////////////////////// public View GetView() { return new View(sfRenderWindow_getView(CPointer)); } //////////////////////////////////////////////////////////// /// <summary> /// Change the current active view /// </summary> /// <param name="view">New view</param> //////////////////////////////////////////////////////////// public void SetView(View view) { sfRenderWindow_setView(CPointer, view.CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Get the viewport of a view applied to this target /// </summary> /// <param name="view">Target view</param> /// <returns>Viewport rectangle, expressed in pixels in the current target</returns> //////////////////////////////////////////////////////////// public IntRect GetViewport(View view) { return sfRenderWindow_getViewport(CPointer, view.CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Convert a point from target coordinates to world /// coordinates, using the current view /// /// This function is an overload of the MapPixelToCoords /// function that implicitely uses the current view. /// It is equivalent to: /// target.MapPixelToCoords(point, target.GetView()); /// </summary> /// <param name="point">Pixel to convert</param> /// <returns>The converted point, in "world" coordinates</returns> //////////////////////////////////////////////////////////// public Vector2f MapPixelToCoords(Vector2i point) { return MapPixelToCoords(point, GetView()); } //////////////////////////////////////////////////////////// /// <summary> /// Convert a point from target coordinates to world coordinates /// /// This function finds the 2D position that matches the /// given pixel of the render-target. In other words, it does /// the inverse of what the graphics card does, to find the /// initial position of a rendered pixel. /// /// Initially, both coordinate systems (world units and target pixels) /// match perfectly. But if you define a custom view or resize your /// render-target, this assertion is not true anymore, ie. a point /// located at (10, 50) in your render-target may map to the point /// (150, 75) in your 2D world -- if the view is translated by (140, 25). /// /// For render-windows, this function is typically used to find /// which point (or object) is located below the mouse cursor. /// /// This version uses a custom view for calculations, see the other /// overload of the function if you want to use the current view of the /// render-target. /// </summary> /// <param name="point">Pixel to convert</param> /// <param name="view">The view to use for converting the point</param> /// <returns>The converted point, in "world" coordinates</returns> //////////////////////////////////////////////////////////// public Vector2f MapPixelToCoords(Vector2i point, View view) { return sfRenderWindow_mapPixelToCoords(CPointer, point, view != null ? view.CPointer : IntPtr.Zero); } //////////////////////////////////////////////////////////// /// <summary> /// Convert a point from world coordinates to target /// coordinates, using the current view /// /// This function is an overload of the mapCoordsToPixel /// function that implicitely uses the current view. /// It is equivalent to: /// target.MapCoordsToPixel(point, target.GetView()); /// </summary> /// <param name="point">Point to convert</param> /// <returns>The converted point, in target coordinates (pixels)</returns> //////////////////////////////////////////////////////////// public Vector2i MapCoordsToPixel(Vector2f point) { return MapCoordsToPixel(point, GetView()); } //////////////////////////////////////////////////////////// /// <summary> /// Convert a point from world coordinates to target coordinates /// /// This function finds the pixel of the render-target that matches /// the given 2D point. In other words, it goes through the same process /// as the graphics card, to compute the final position of a rendered point. /// /// Initially, both coordinate systems (world units and target pixels) /// match perfectly. But if you define a custom view or resize your /// render-target, this assertion is not true anymore, ie. a point /// located at (150, 75) in your 2D world may map to the pixel /// (10, 50) of your render-target -- if the view is translated by (140, 25). /// /// This version uses a custom view for calculations, see the other /// overload of the function if you want to use the current view of the /// render-target. /// </summary> /// <param name="point">Point to convert</param> /// <param name="view">The view to use for converting the point</param> /// <returns>The converted point, in target coordinates (pixels)</returns> //////////////////////////////////////////////////////////// public Vector2i MapCoordsToPixel(Vector2f point, View view) { return sfRenderWindow_mapCoordsToPixel(CPointer, point, view != null ? view.CPointer : IntPtr.Zero); } //////////////////////////////////////////////////////////// /// <summary> /// Clear the entire window with black color /// </summary> //////////////////////////////////////////////////////////// public void Clear() { sfRenderWindow_clear(CPointer, Color.Black); } //////////////////////////////////////////////////////////// /// <summary> /// Clear the entire window with a single color /// </summary> /// <param name="color">Color to use to clear the window</param> //////////////////////////////////////////////////////////// public void Clear(Color color) { sfRenderWindow_clear(CPointer, color); } //////////////////////////////////////////////////////////// /// <summary> /// Draw a drawable object to the render-target, with default render states /// </summary> /// <param name="drawable">Object to draw</param> //////////////////////////////////////////////////////////// public void Draw(Drawable drawable) { Draw(drawable, RenderStates.Default); } //////////////////////////////////////////////////////////// /// <summary> /// Draw a drawable object to the render-target /// </summary> /// <param name="drawable">Object to draw</param> /// <param name="states">Render states to use for drawing</param> //////////////////////////////////////////////////////////// public void Draw(Drawable drawable, RenderStates states) { drawable.Draw(this, states); } //////////////////////////////////////////////////////////// /// <summary> /// Draw primitives defined by an array of vertices, with default render states /// </summary> /// <param name="vertices">Pointer to the vertices</param> /// <param name="type">Type of primitives to draw</param> //////////////////////////////////////////////////////////// public void Draw(Vertex[] vertices, PrimitiveType type) { Draw(vertices, type, RenderStates.Default); } //////////////////////////////////////////////////////////// /// <summary> /// Draw primitives defined by an array of vertices /// </summary> /// <param name="vertices">Pointer to the vertices</param> /// <param name="type">Type of primitives to draw</param> /// <param name="states">Render states to use for drawing</param> //////////////////////////////////////////////////////////// public void Draw(Vertex[] vertices, PrimitiveType type, RenderStates states) { Draw(vertices, 0, (uint)vertices.Length, type, states); } //////////////////////////////////////////////////////////// /// <summary> /// Draw primitives defined by a sub-array of vertices, with default render states /// </summary> /// <param name="vertices">Array of vertices to draw</param> /// <param name="start">Index of the first vertex to draw in the array</param> /// <param name="count">Number of vertices to draw</param> /// <param name="type">Type of primitives to draw</param> //////////////////////////////////////////////////////////// public void Draw(Vertex[] vertices, uint start, uint count, PrimitiveType type) { Draw(vertices, start, count, type, RenderStates.Default); } //////////////////////////////////////////////////////////// /// <summary> /// Draw primitives defined by a sub-array of vertices /// </summary> /// <param name="vertices">Pointer to the vertices</param> /// <param name="start">Index of the first vertex to use in the array</param> /// <param name="count">Number of vertices to draw</param> /// <param name="type">Type of primitives to draw</param> /// <param name="states">Render states to use for drawing</param> //////////////////////////////////////////////////////////// public void Draw(Vertex[] vertices, uint start, uint count, PrimitiveType type, RenderStates states) { RenderStates.MarshalData marshaledStates = states.Marshal(); unsafe { fixed (Vertex* vertexPtr = vertices) { sfRenderWindow_drawPrimitives(CPointer, vertexPtr + start, count, type, ref marshaledStates); } } } //////////////////////////////////////////////////////////// /// <summary> /// Save the current OpenGL render states and matrices. /// /// This function can be used when you mix SFML drawing /// and direct OpenGL rendering. Combined with PopGLStates, /// it ensures that: /// \li SFML's internal states are not messed up by your OpenGL code /// \li your OpenGL states are not modified by a call to a SFML function /// /// More specifically, it must be used around code that /// calls Draw functions. Example: /// /// // OpenGL code here... /// window.PushGLStates(); /// window.Draw(...); /// window.Draw(...); /// window.PopGLStates(); /// // OpenGL code here... /// /// Note that this function is quite expensive: it saves all the /// possible OpenGL states and matrices, even the ones you /// don't care about. Therefore it should be used wisely. /// It is provided for convenience, but the best results will /// be achieved if you handle OpenGL states yourself (because /// you know which states have really changed, and need to be /// saved and restored). Take a look at the ResetGLStates /// function if you do so. /// </summary> //////////////////////////////////////////////////////////// public void PushGLStates() { sfRenderWindow_pushGLStates(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Restore the previously saved OpenGL render states and matrices. /// /// See the description of PushGLStates to get a detailed /// description of these functions. /// </summary> //////////////////////////////////////////////////////////// public void PopGLStates() { sfRenderWindow_popGLStates(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Reset the internal OpenGL states so that the target is ready for drawing. /// /// This function can be used when you mix SFML drawing /// and direct OpenGL rendering, if you choose not to use /// PushGLStates/PopGLStates. It makes sure that all OpenGL /// states needed by SFML are set, so that subsequent Draw() /// calls will work as expected. /// /// Example: /// /// // OpenGL code here... /// glPushAttrib(...); /// window.ResetGLStates(); /// window.Draw(...); /// window.Draw(...); /// glPopAttrib(...); /// // OpenGL code here... /// </summary> //////////////////////////////////////////////////////////// public void ResetGLStates() { sfRenderWindow_resetGLStates(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Capture the current contents of the window into an image /// </summary> //////////////////////////////////////////////////////////// public Image Capture() { return new Image(sfRenderWindow_capture(CPointer)); } //////////////////////////////////////////////////////////// /// <summary> /// Request the current window to be made the active /// foreground window /// </summary> //////////////////////////////////////////////////////////// public override void RequestFocus() { sfRenderWindow_requestFocus(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Check whether the window has the input focus /// </summary> /// <returns>True if the window has focus, false otherwise</returns> //////////////////////////////////////////////////////////// public override bool HasFocus() { return sfRenderWindow_hasFocus(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Provide a string describing the object /// </summary> /// <returns>String description of the object</returns> //////////////////////////////////////////////////////////// public override string ToString() { return "[RenderWindow]" + " Size(" + Size + ")" + " Position(" + Position + ")" + " Settings(" + Settings + ")" + " DefaultView(" + DefaultView + ")" + " View(" + GetView() + ")"; } //////////////////////////////////////////////////////////// /// <summary> /// Internal function to get the next event /// </summary> /// <param name="eventToFill">Variable to fill with the raw pointer to the event structure</param> /// <returns>True if there was an event, false otherwise</returns> //////////////////////////////////////////////////////////// protected override bool PollEvent(out Event eventToFill) { return sfRenderWindow_pollEvent(CPointer, out eventToFill); } //////////////////////////////////////////////////////////// /// <summary> /// Internal function to get the next event (blocking) /// </summary> /// <param name="eventToFill">Variable to fill with the raw pointer to the event structure</param> /// <returns>False if any error occured</returns> //////////////////////////////////////////////////////////// protected override bool WaitEvent(out Event eventToFill) { return sfRenderWindow_waitEvent(CPointer, out eventToFill); } //////////////////////////////////////////////////////////// /// <summary> /// Internal function to get the mouse position relative to the window. /// This function is public because it is called by another class, /// it is not meant to be called by users. /// </summary> /// <returns>Relative mouse position</returns> //////////////////////////////////////////////////////////// protected override Vector2i InternalGetMousePosition() { return sfMouse_getPositionRenderWindow(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Internal function to set the mouse position relative to the window. /// This function is public because it is called by another class, /// it is not meant to be called by users. /// </summary> /// <param name="position">Relative mouse position</param> //////////////////////////////////////////////////////////// protected override void InternalSetMousePosition(Vector2i position) { sfMouse_setPositionRenderWindow(position, CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Internal function to get the touch position relative to the window. /// This function is protected because it is called by another class of /// another module, it is not meant to be called by users. /// </summary> /// <param name="Finger">Finger index</param> /// <returns>Relative touch position</returns> //////////////////////////////////////////////////////////// protected override Vector2i InternalGetTouchPosition(uint Finger) { return sfTouch_getPositionRenderWindow(Finger, CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Handle the destruction of the object /// </summary> /// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param> //////////////////////////////////////////////////////////// protected override void Destroy(bool disposing) { sfRenderWindow_destroy(CPointer); if (disposing) myDefaultView.Dispose(); } //////////////////////////////////////////////////////////// /// <summary> /// Do common initializations /// </summary> //////////////////////////////////////////////////////////// private void Initialize() { myDefaultView = new View(sfRenderWindow_getDefaultView(CPointer)); GC.SuppressFinalize(myDefaultView); } private View myDefaultView = null; #region Imports [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfRenderWindow_create(VideoMode Mode, string Title, Styles Style, ref ContextSettings Params); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfRenderWindow_createUnicode(VideoMode Mode, IntPtr Title, Styles Style, ref ContextSettings Params); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfRenderWindow_createFromHandle(IntPtr Handle, ref ContextSettings Params); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_destroy(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfRenderWindow_isOpen(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_close(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfRenderWindow_pollEvent(IntPtr CPointer, out Event Evt); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfRenderWindow_waitEvent(IntPtr CPointer, out Event Evt); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_clear(IntPtr CPointer, Color ClearColor); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_display(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern ContextSettings sfRenderWindow_getSettings(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2i sfRenderWindow_getPosition(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_setPosition(IntPtr CPointer, Vector2i position); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2u sfRenderWindow_getSize(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_setSize(IntPtr CPointer, Vector2u size); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_setTitle(IntPtr CPointer, string title); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_setUnicodeTitle(IntPtr CPointer, IntPtr title); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] unsafe static extern void sfRenderWindow_setIcon(IntPtr CPointer, uint Width, uint Height, byte* Pixels); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_setVisible(IntPtr CPointer, bool visible); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_setMouseCursorVisible(IntPtr CPointer, bool visible); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_setVerticalSyncEnabled(IntPtr CPointer, bool Enable); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_setKeyRepeatEnabled(IntPtr CPointer, bool Enable); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfRenderWindow_setActive(IntPtr CPointer, bool Active); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfRenderWindow_saveGLStates(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfRenderWindow_restoreGLStates(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_setFramerateLimit(IntPtr CPointer, uint Limit); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern uint sfRenderWindow_getFrameTime(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_setJoystickThreshold(IntPtr CPointer, float Threshold); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_setView(IntPtr CPointer, IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfRenderWindow_getView(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfRenderWindow_getDefaultView(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntRect sfRenderWindow_getViewport(IntPtr CPointer, IntPtr TargetView); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2i sfRenderWindow_mapCoordsToPixel(IntPtr CPointer, Vector2f point, IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2f sfRenderWindow_mapPixelToCoords(IntPtr CPointer, Vector2i point, IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] unsafe static extern void sfRenderWindow_drawPrimitives(IntPtr CPointer, Vertex* vertexPtr, uint vertexCount, PrimitiveType type, ref RenderStates.MarshalData renderStates); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_pushGLStates(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_popGLStates(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_resetGLStates(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfRenderWindow_getSystemHandle(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfRenderWindow_capture(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_requestFocus(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfRenderWindow_hasFocus(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2i sfMouse_getPositionRenderWindow(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMouse_setPositionRenderWindow(Vector2i position, IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2i sfTouch_getPositionRenderWindow(uint Finger, IntPtr RelativeTo); #endregion } } }
//----------------------------------------------------------------------- // <copyright file="NameValueListBase.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>This is the base class from which readonly name/value</summary> //----------------------------------------------------------------------- using System; using System.ComponentModel; using Csla.Properties; using Csla.Core; using Csla.Serialization.Mobile; namespace Csla { /// <summary> /// This is the base class from which readonly name/value /// collections should be derived. /// </summary> /// <typeparam name="K">Type of the key values.</typeparam> /// <typeparam name="V">Type of the values.</typeparam> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [Serializable] public abstract class NameValueListBase<K, V> : Core.ReadOnlyBindingList<NameValueListBase<K, V>.NameValuePair>, ICloneable, Core.IBusinessObject, Server.IDataPortalTarget { #region Core Implementation /// <summary> /// Returns the value corresponding to the /// specified key. /// </summary> /// <param name="key">Key value for which to retrieve a value.</param> public V Value(K key) { foreach (NameValuePair item in this) if (item.Key.Equals(key)) return item.Value; return default(V); } /// <summary> /// Returns the key corresponding to the /// first occurance of the specified value /// in the list. /// </summary> /// <param name="value">Value for which to retrieve the key.</param> public K Key(V value) { foreach (NameValuePair item in this) if (item.Value.Equals(value)) return item.Key; return default(K); } /// <summary> /// Gets a value indicating whether the list contains the /// specified key. /// </summary> /// <param name="key">Key value for which to search.</param> public bool ContainsKey(K key) { foreach (NameValuePair item in this) if (item.Key.Equals(key)) return true; return false; } /// <summary> /// Gets a value indicating whether the list contains the /// specified value. /// </summary> /// <param name="value">Value for which to search.</param> public bool ContainsValue(V value) { foreach (NameValuePair item in this) if (item.Value.Equals(value)) return true; return false; } /// <summary> /// Get the item for the first matching /// value in the collection. /// </summary> /// <param name="value"> /// Value to search for in the list. /// </param> /// <returns>Item from the list.</returns> public NameValuePair GetItemByValue(V value) { foreach (NameValuePair item in this) { if (item != null && item.Value.Equals(value)) { return item; } } return null; } /// <summary> /// Get the item for the first matching /// key in the collection. /// </summary> /// <param name="key"> /// Key to search for in the list. /// </param> /// <returns>Item from the list.</returns> public NameValuePair GetItemByKey(K key) { foreach (NameValuePair item in this) { if (item != null && item.Key.Equals(key)) { return item; } } return null; } #endregion /// <summary> /// Creates an instance of the object. /// </summary> protected NameValueListBase() { Initialize(); } #region Initialize /// <summary> /// Override this method to set up event handlers so user /// code in a partial class can respond to events raised by /// generated code. /// </summary> protected virtual void Initialize() { /* allows subclass to initialize events before any other activity occurs */ } #endregion #region NameValuePair class /// <summary> /// Contains a key and value pair. /// </summary> [Serializable()] public class NameValuePair : MobileObject { private K _key; private V _value; #if (ANDROID || IOS) || NETFX_CORE /// <summary> /// Creates an instance of the object. /// </summary> public NameValuePair() { } #else private NameValuePair() { } #endif /// <summary> /// The Key or Name value. /// </summary> public K Key { get { return _key; } } /// <summary> /// The Value corresponding to the key/name. /// </summary> public V Value { get { return _value; } } /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public NameValuePair(K key, V value) { _key = key; _value = value; } /// <summary> /// Returns a string representation of the /// value for this item. /// </summary> public override string ToString() { return _value.ToString(); } /// <summary> /// Override this method to manually get custom field /// values from the serialization stream. /// </summary> /// <param name="info">Serialization info.</param> /// <param name="mode">Serialization mode.</param> protected override void OnGetState(SerializationInfo info, StateMode mode) { base.OnGetState(info, mode); info.AddValue("NameValuePair._key", _key); info.AddValue("NameValuePair._value", _value); } /// <summary> /// Override this method to manually set custom field /// values into the serialization stream. /// </summary> /// <param name="info">Serialization info.</param> /// <param name="mode">Serialization mode.</param> protected override void OnSetState(SerializationInfo info, StateMode mode) { base.OnSetState(info, mode); _key = info.GetValue<K>("NameValuePair._key"); _value = info.GetValue<V>("NameValuePair._value"); } } #endregion #region ICloneable object ICloneable.Clone() { return GetClone(); } /// <summary> /// Creates a clone of the object. /// </summary> /// <returns>A new object containing the exact data of the original object.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual object GetClone() { return Core.ObjectCloner.Clone(this); } /// <summary> /// Creates a clone of the object. /// </summary> public NameValueListBase<K, V> Clone() { return (NameValueListBase<K, V>)GetClone(); } #endregion #region Data Access [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")] private void DataPortal_Create(object criteria) { throw new NotSupportedException(Resources.CreateNotSupportedException); } /// <summary> /// Override this method to allow retrieval of an existing business /// object based on data in the database. /// </summary> /// <param name="criteria">An object containing criteria values to identify the object.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] protected virtual void DataPortal_Fetch(object criteria) { throw new NotSupportedException(Resources.FetchNotSupportedException); } private void DataPortal_Update() { throw new NotSupportedException(Resources.UpdateNotSupportedException); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")] private void DataPortal_Delete(object criteria) { throw new NotSupportedException(Resources.DeleteNotSupportedException); } /// <summary> /// Called by the server-side DataPortal prior to calling the /// requested DataPortal_XYZ method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalInvoke(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal after calling the /// requested DataPortal_XYZ method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal if an exception /// occurs during data access. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> /// <param name="ex">The Exception thrown during data access.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex) { } #endregion #region IDataPortalTarget Members void Csla.Server.IDataPortalTarget.CheckRules() { } void Csla.Server.IDataPortalTarget.MarkAsChild() { } void Csla.Server.IDataPortalTarget.MarkNew() { } void Csla.Server.IDataPortalTarget.MarkOld() { } void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvoke(DataPortalEventArgs e) { this.DataPortal_OnDataPortalInvoke(e); } void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e) { this.DataPortal_OnDataPortalInvokeComplete(e); } void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex) { this.DataPortal_OnDataPortalException(e, ex); } void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvoke(DataPortalEventArgs e) { } void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvokeComplete(DataPortalEventArgs e) { } void Csla.Server.IDataPortalTarget.Child_OnDataPortalException(DataPortalEventArgs e, Exception ex) { } #endregion } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Apache License, Version 2.0. // 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.Text; using System.IO; using Common; namespace Randoop { public interface ITestFileWriter { void Move(Randoop.Plan p, Exception exceptionThrown); void MoveNormalTermination(Randoop.Plan p); void Remove(Randoop.Plan p); void WriteTest(Randoop.Plan p); void RemoveTempDir(); } internal class TestWriterHelperMethods { public static void WritePlanToFile(Plan p, string fileName, Type exceptionThrown, string className) { TestCase code; bool writeTest = true; //[email protected] -- added for avoid writing "dummy" code try { code = p.ToTestCase(exceptionThrown, true, className); //[email protected] -- if the middle parameter is set to "true", print plan for debugging } catch (Exception) { code = TestCase.Dummy(className); writeTest = false; } if(writeTest) code.WriteToFile(fileName, true); } } /// <summary> /// A test writer that writes all tests (plans) to the same /// directory. /// </summary> public class SingleDirTestWriter : ITestFileWriter { private DirectoryInfo outputDir; private string testPrefix; public SingleDirTestWriter(DirectoryInfo di, string testPrefix) { this.outputDir = di; if (!this.outputDir.Exists) { this.outputDir.Create(); } if (testPrefix == null) this.testPrefix = "RandoopTest"; else this.testPrefix = testPrefix; } public void Move(Randoop.Plan p, Exception exceptionThrown) { string className = this.testPrefix + p.TestCaseId; string fileName = outputDir + "\\" + className + ".cs"; string savedFileName = fileName + ".saved"; File.Copy(fileName, savedFileName); new FileInfo(fileName).Delete(); TestWriterHelperMethods.WritePlanToFile(p, fileName, exceptionThrown.GetType(), className); new FileInfo(savedFileName).Delete(); } public void MoveNormalTermination(Randoop.Plan p) { // Don't move anywhere. } public void Remove(Randoop.Plan p) { string className = this.testPrefix + p.TestCaseId; string fileName = outputDir + "\\" + className + ".cs"; new FileInfo(fileName).Delete(); } public void WriteTest(Randoop.Plan p) { string className = this.testPrefix + p.TestCaseId; string fileName = outputDir + "\\" + className + ".cs"; TestWriterHelperMethods.WritePlanToFile(p, fileName, null, className); } public void RemoveTempDir() { // No temp dir to remove. } } public class ClassifyingTestFileWriter : ITestFileWriter { private DirectoryInfo outputDir; private int numNormalTerminationPlansWritten; private DirectoryInfo normalTerminationCurrentDir; private string testPrefix; public ClassifyingTestFileWriter(DirectoryInfo di, string testPrefix) { this.outputDir = di; this.numNormalTerminationPlansWritten = 0; DirectoryInfo tempDir = new DirectoryInfo(outputDir + "\\temp"); Console.WriteLine("Creating directory: " + tempDir.FullName); tempDir.Create(); if (testPrefix == null) this.testPrefix = "RandoopTest"; else this.testPrefix = testPrefix; } private void newSubDir() { // Find next index for normaltermination dir. int maxIndex = 0; foreach (DirectoryInfo di in outputDir.GetDirectories("normaltermination*")) { int dirIndex = int.Parse(di.Name.Substring("normaltermination".Length)); if (dirIndex > maxIndex) maxIndex = dirIndex; } this.normalTerminationCurrentDir = new DirectoryInfo( outputDir + "\\" + "normaltermination" + (maxIndex + 1)); Util.Assert(!this.normalTerminationCurrentDir.Exists); this.normalTerminationCurrentDir.Create(); } public void WriteTest(Plan p) { string className = this.testPrefix + p.TestCaseId; string fileName = outputDir + "\\" + "temp" + "\\" + className + ".cs"; TestWriterHelperMethods.WritePlanToFile(p, fileName, null, className); } public void MoveNormalTermination(Plan p) { if (numNormalTerminationPlansWritten % 1000 == 0) newSubDir(); string className = this.testPrefix + p.TestCaseId; string oldTestFileName = outputDir + "\\" + "temp" + "\\" + className + ".cs"; string newTestFileName = normalTerminationCurrentDir + "\\" + className + ".cs"; TestWriterHelperMethods.WritePlanToFile(p, newTestFileName, null, className); new FileInfo(oldTestFileName).Delete(); numNormalTerminationPlansWritten++; } public void Move(Plan p, Exception exceptionThrown) { string dirName; MakeExceptionDirIfNotExists(exceptionThrown, out dirName); string className = this.testPrefix + p.TestCaseId; string oldTestFileName = outputDir + "\\" + "temp" + "\\" + className + ".cs"; string newTestFileName = dirName + "\\" + className + ".cs"; TestWriterHelperMethods.WritePlanToFile(p, newTestFileName, exceptionThrown.GetType(), className); new FileInfo(oldTestFileName).Delete(); } private void MakeExceptionDirIfNotExists(Exception exceptionThrown, out string dirName) { string dirNameBase; if (exceptionThrown.Message.StartsWith("Randoop: an assertion was violated")) { dirNameBase = "AssertionViolations"; } else { dirNameBase = exceptionThrown.GetType().FullName; } dirName = outputDir + "\\" + dirNameBase; DirectoryInfo d = new DirectoryInfo(dirName); if (!d.Exists) d.Create(); } public void Remove(Plan p) { string className = this.testPrefix + p.TestCaseId; string oldTestFileName = outputDir + "\\" + "temp" + "\\" + className + ".cs"; new FileInfo(oldTestFileName).Delete(); } public void RemoveTempDir() { new DirectoryInfo(outputDir + "\\temp").Delete(true); } } }
// 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.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; using System.Threading; using System.Threading.Tasks; namespace System.IO { /* * This class is used to access a contiguous block of memory, likely outside * the GC heap (or pinned in place in the GC heap, but a MemoryStream may * make more sense in those cases). It's great if you have a pointer and * a length for a section of memory mapped in by someone else and you don't * want to copy this into the GC heap. UnmanagedMemoryStream assumes these * two things: * * 1) All the memory in the specified block is readable or writable, * depending on the values you pass to the constructor. * 2) The lifetime of the block of memory is at least as long as the lifetime * of the UnmanagedMemoryStream. * 3) You clean up the memory when appropriate. The UnmanagedMemoryStream * currently will do NOTHING to free this memory. * 4) All calls to Write and WriteByte may not be threadsafe currently. * * It may become necessary to add in some sort of * DeallocationMode enum, specifying whether we unmap a section of memory, * call free, run a user-provided delegate to free the memory, etc etc. * We'll suggest user write a subclass of UnmanagedMemoryStream that uses * a SafeHandle subclass to hold onto the memory. * Check for problems when using this in the negative parts of a * process's address space. We may need to use unsigned longs internally * and change the overflow detection logic. * * -----SECURITY MODEL AND SILVERLIGHT----- * A few key notes about exposing UMS in silverlight: * 1. No ctors are exposed to transparent code. This version of UMS only * supports byte* (not SafeBuffer). Therefore, framework code can create * a UMS and hand it to transparent code. Transparent code can use most * operations on a UMS, but not operations that directly expose a * pointer. * * 2. Scope of "unsafe" and non-CLS compliant operations reduced: The * Whidbey version of this class has CLSCompliant(false) at the class * level and unsafe modifiers at the method level. These were reduced to * only where the unsafe operation is performed -- i.e. immediately * around the pointer manipulation. Note that this brings UMS in line * with recent changes in pu/clr to support SafeBuffer. * * 3. Currently, the only caller that creates a UMS is ResourceManager, * which creates read-only UMSs, and therefore operations that can * change the length will throw because write isn't supported. A * conservative option would be to formalize the concept that _only_ * read-only UMSs can be creates, and enforce this by making WriteX and * SetLength SecurityCritical. However, this is a violation of * security inheritance rules, so we must keep these safe. The * following notes make this acceptable for future use. * a. a race condition in WriteX that could have allowed a thread to * read from unzeroed memory was fixed * b. memory region cannot be expanded beyond _capacity; in other * words, a UMS creator is saying a writeable UMS is safe to * write to anywhere in the memory range up to _capacity, specified * in the ctor. Even if the caller doesn't specify a capacity, then * length is used as the capacity. */ /// <summary> /// Stream over a memory pointer or over a SafeBuffer /// </summary> public class UnmanagedMemoryStream : Stream { [System.Security.SecurityCritical] // auto-generated private SafeBuffer _buffer; [SecurityCritical] private unsafe byte* _mem; private long _length; private long _capacity; private long _position; private long _offset; private FileAccess _access; private bool _isOpen; private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync /// <summary> /// This code is copied from system\buffer.cs in mscorlib /// </summary> /// <param name="src"></param> /// <param name="len"></param> [System.Security.SecurityCritical] // auto-generated private unsafe static void ZeroMemory(byte* src, long len) { while (len-- > 0) *(src + len) = 0; } /// <summary> /// Creates a closed stream. /// </summary> // Needed for subclasses that need to map a file, etc. [System.Security.SecuritySafeCritical] // auto-generated protected UnmanagedMemoryStream() { unsafe { _mem = null; } _isOpen = false; } /// <summary> /// Creates a stream over a SafeBuffer. /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="length"></param> [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) { Initialize(buffer, offset, length, FileAccess.Read, false); } /// <summary> /// Creates a stream over a SafeBuffer. /// </summary> [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) { Initialize(buffer, offset, length, access, false); } /// <summary> /// Subclasses must call this method (or the other overload) to properly initialize all instance fields. /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <param name="access"></param> [System.Security.SecuritySafeCritical] // auto-generated protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) { Initialize(buffer, offset, length, access, false); } [System.Security.SecurityCritical] // auto-generated private void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.ByteLength < (ulong)(offset + length)) { throw new ArgumentException(SR.Argument_InvalidSafeBufferOffLen); } if (access < FileAccess.Read || access > FileAccess.ReadWrite) { throw new ArgumentOutOfRangeException(nameof(access)); } Contract.EndContractBlock(); if (_isOpen) { throw new InvalidOperationException(SR.InvalidOperation_CalledTwice); } // check for wraparound unsafe { byte* pointer = null; try { buffer.AcquirePointer(ref pointer); if ((pointer + offset + length) < pointer) { throw new ArgumentException(SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround); } } finally { if (pointer != null) { buffer.ReleasePointer(); } } } _offset = offset; _buffer = buffer; _length = length; _capacity = length; _access = access; _isOpen = true; } /// <summary> /// Creates a stream over a byte*. /// </summary> [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length) { Initialize(pointer, length, length, FileAccess.Read, false); } /// <summary> /// Creates a stream over a byte*. /// </summary> [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } /// <summary> /// Subclasses must call this method (or the other overload) to properly initialize all instance fields. /// </summary> [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } /// <summary> /// Subclasses must call this method (or the other overload) to properly initialize all instance fields. /// </summary> [System.Security.SecurityCritical] // auto-generated private unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck) { if (pointer == null) throw new ArgumentNullException(nameof(pointer)); if (length < 0 || capacity < 0) throw new ArgumentOutOfRangeException((length < 0) ? "length" : "capacity", SR.ArgumentOutOfRange_NeedNonNegNum); if (length > capacity) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_LengthGreaterThanCapacity); Contract.EndContractBlock(); // Check for wraparound. if (((byte*)((long)pointer + capacity)) < pointer) throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum); if (_isOpen) throw new InvalidOperationException(SR.InvalidOperation_CalledTwice); _mem = pointer; _offset = 0; _length = length; _capacity = capacity; _access = access; _isOpen = true; } /// <summary> /// Returns true if the stream can be read; otherwise returns false. /// </summary> public override bool CanRead { [Pure] get { return _isOpen && (_access & FileAccess.Read) != 0; } } /// <summary> /// Returns true if the stream can seek; otherwise returns false. /// </summary> public override bool CanSeek { [Pure] get { return _isOpen; } } /// <summary> /// Returns true if the stream can be written to; otherwise returns false. /// </summary> public override bool CanWrite { [Pure] get { return _isOpen && (_access & FileAccess.Write) != 0; } } /// <summary> /// Closes the stream. The stream's memory needs to be dealt with separately. /// </summary> /// <param name="disposing"></param> [System.Security.SecuritySafeCritical] // auto-generated protected override void Dispose(bool disposing) { _isOpen = false; unsafe { _mem = null; } // Stream allocates WaitHandles for async calls. So for correctness // call base.Dispose(disposing) for better perf, avoiding waiting // for the finalizers to run on those types. base.Dispose(disposing); } /// <summary> /// Since it's a memory stream, this method does nothing. /// </summary> public override void Flush() { if (!_isOpen) throw Error.GetStreamIsClosed(); } /// <summary> /// Since it's a memory stream, this method does nothing specific. /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Flush(); return Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } /// <summary> /// Number of bytes in the stream. /// </summary> public override long Length { get { if (!_isOpen) throw Error.GetStreamIsClosed(); return Interlocked.Read(ref _length); } } /// <summary> /// Number of bytes that can be written to the stream. /// </summary> public long Capacity { get { if (!_isOpen) throw Error.GetStreamIsClosed(); return _capacity; } } /// <summary> /// ReadByte will read byte at the Position in the stream /// </summary> public override long Position { get { if (!CanSeek) throw Error.GetStreamIsClosed(); Contract.EndContractBlock(); return Interlocked.Read(ref _position); } [System.Security.SecuritySafeCritical] // auto-generated set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); if (!CanSeek) throw Error.GetStreamIsClosed(); Contract.EndContractBlock(); if (IntPtr.Size == 4) { unsafe { // On 32 bit process, ensure we don't wrap around. if (value > (long)Int32.MaxValue || _mem + value < _mem) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } } Interlocked.Exchange(ref _position, value); } } /// <summary> /// Pointer to memory at the current Position in the stream. /// </summary> [CLSCompliant(false)] public unsafe byte* PositionPointer { [System.Security.SecurityCritical] // auto-generated_required get { if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); if (!_isOpen) throw Error.GetStreamIsClosed(); // Use a temp to avoid a race long pos = Interlocked.Read(ref _position); if (pos > _capacity) throw new IndexOutOfRangeException(SR.IndexOutOfRange_UMSPosition); byte* ptr = _mem + pos; return ptr; } [System.Security.SecurityCritical] // auto-generated_required set { if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); if (!_isOpen) throw Error.GetStreamIsClosed(); if (value < _mem) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, value - _mem); } } /// <summary> /// Reads bytes from stream and puts them into the buffer /// </summary> /// <param name="buffer">Buffer to read the bytes to.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Maximum number of bytes to read.</param> /// <returns>Number of bytes actually read.</returns> [System.Security.SecuritySafeCritical] // auto-generated public override int Read([In, Out] byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanRead) throw Error.GetReadNotSupported(); // Use a local variable to avoid a race where another thread // changes our position after we decide we can read some bytes. long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); long n = len - pos; if (n > count) n = count; if (n <= 0) return 0; int nInt = (int)n; // Safe because n <= count, which is an Int32 if (nInt < 0) return 0; // _position could be beyond EOF Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1. unsafe { fixed (byte* pBuffer = buffer) { if (_buffer != null) { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); Buffer.MemoryCopy(source: pointer + pos + _offset, destination: pBuffer + offset, destinationSizeInBytes: nInt, sourceBytesToCopy: nInt); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } else { Buffer.MemoryCopy(source: _mem + pos, destination: pBuffer + offset, destinationSizeInBytes: nInt, sourceBytesToCopy: nInt); } } } Interlocked.Exchange(ref _position, pos + n); return nInt; } /// <summary> /// Reads bytes from stream and puts them into the buffer /// </summary> /// <param name="buffer">Buffer to read the bytes to.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Maximum number of bytes to read.</param> /// <param name="cancellationToken">Token that can be used to cancell this operation.</param> /// <returns>Task that can be used to access the number of bytes actually read.</returns> public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Read(...) if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<Int32>(cancellationToken); try { Int32 n = Read(buffer, offset, count); Task<Int32> t = _lastReadTask; return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n)); } catch (Exception ex) { Debug.Assert(!(ex is OperationCanceledException)); return Task.FromException<Int32>(ex); } } /// <summary> /// Returns the byte at the stream current Position and advances the Position. /// </summary> /// <returns></returns> [System.Security.SecuritySafeCritical] // auto-generated public override int ReadByte() { if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanRead) throw Error.GetReadNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); if (pos >= len) return -1; Interlocked.Exchange(ref _position, pos + 1); int result; if (_buffer != null) { unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); result = *(pointer + pos + _offset); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { result = _mem[pos]; } } return result; } /// <summary> /// Advanced the Position to specifice location in the stream. /// </summary> /// <param name="offset">Offset from the loc parameter.</param> /// <param name="loc">Origin for the offset parameter.</param> /// <returns></returns> public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) throw Error.GetStreamIsClosed(); switch (loc) { case SeekOrigin.Begin: if (offset < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, offset); break; case SeekOrigin.Current: long pos = Interlocked.Read(ref _position); if (offset + pos < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, offset + pos); break; case SeekOrigin.End: long len = Interlocked.Read(ref _length); if (len + offset < 0) throw new IOException(SR.IO_SeekBeforeBegin); Interlocked.Exchange(ref _position, len + offset); break; default: throw new ArgumentException(SR.Argument_InvalidSeekOrigin); } long finalPos = Interlocked.Read(ref _position); Debug.Assert(finalPos >= 0, "_position >= 0"); return finalPos; } /// <summary> /// Sets the Length of the stream. /// </summary> /// <param name="value"></param> [System.Security.SecuritySafeCritical] // auto-generated public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanWrite) throw Error.GetWriteNotSupported(); if (value > _capacity) throw new IOException(SR.IO_FixedCapacity); long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); if (value > len) { unsafe { ZeroMemory(_mem + len, value - len); } } Interlocked.Exchange(ref _length, value); if (pos > value) { Interlocked.Exchange(ref _position, value); } } /// <summary> /// Writes buffer into the stream /// </summary> /// <param name="buffer">Buffer that will be written.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Number of bytes to write.</param> [System.Security.SecuritySafeCritical] // auto-generated public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..) if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanWrite) throw Error.GetWriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + count; // Check for overflow if (n < 0) throw new IOException(SR.IO_StreamTooLong); if (n > _capacity) { throw new NotSupportedException(SR.IO_FixedCapacity); } if (_buffer == null) { // Check to see whether we are now expanding the stream and must // zero any memory in the middle. if (pos > len) { unsafe { ZeroMemory(_mem + len, pos - len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory if (n > len) { Interlocked.Exchange(ref _length, n); } } unsafe { fixed (byte* pBuffer = buffer) { if (_buffer != null) { long bytesLeft = _capacity - pos; if (bytesLeft < count) { throw new ArgumentException(SR.Arg_BufferTooSmall); } byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); Buffer.MemoryCopy(source: pBuffer + offset, destination: pointer + pos + _offset, destinationSizeInBytes: count, sourceBytesToCopy: count); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } else { Buffer.MemoryCopy(source: pBuffer + offset, destination: _mem + pos, destinationSizeInBytes: count, sourceBytesToCopy: count); } } } Interlocked.Exchange(ref _position, n); return; } /// <summary> /// Writes buffer into the stream. The operation completes synchronously. /// </summary> /// <param name="buffer">Buffer that will be written.</param> /// <param name="offset">Starting index in the buffer.</param> /// <param name="count">Number of bytes to write.</param> /// <param name="cancellationToken">Token that can be used to cancell the operation.</param> /// <returns>Task that can be awaited </returns> public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Write(..) if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Write(buffer, offset, count); return Task.CompletedTask; } catch (Exception ex) { Debug.Assert(!(ex is OperationCanceledException)); return Task.FromException(ex); } } /// <summary> /// Writes a byte to the stream and advances the current Position. /// </summary> /// <param name="value"></param> [System.Security.SecuritySafeCritical] // auto-generated public override void WriteByte(byte value) { if (!_isOpen) throw Error.GetStreamIsClosed(); if (!CanWrite) throw Error.GetWriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + 1; if (pos >= len) { // Check for overflow if (n < 0) throw new IOException(SR.IO_StreamTooLong); if (n > _capacity) throw new NotSupportedException(SR.IO_FixedCapacity); // Check to see whether we are now expanding the stream and must // zero any memory in the middle. // don't do if created from SafeBuffer if (_buffer == null) { if (pos > len) { unsafe { ZeroMemory(_mem + len, pos - len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory Interlocked.Exchange(ref _length, n); } } if (_buffer != null) { unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); *(pointer + pos + _offset) = value; } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { _mem[pos] = value; } } Interlocked.Exchange(ref _position, n); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Text { using System; using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] public sealed class DecoderReplacementFallback : DecoderFallback { // Our variables private String strDefault; // Construction. Default replacement fallback uses no best fit and ? replacement string public DecoderReplacementFallback() : this("?") { } public DecoderReplacementFallback(String replacement) { if (replacement == null) throw new ArgumentNullException(nameof(replacement)); Contract.EndContractBlock(); // Make sure it doesn't have bad surrogate pairs bool bFoundHigh=false; for (int i = 0; i < replacement.Length; i++) { // Found a surrogate? if (Char.IsSurrogate(replacement,i)) { // High or Low? if (Char.IsHighSurrogate(replacement, i)) { // if already had a high one, stop if (bFoundHigh) break; // break & throw at the bFoundHIgh below bFoundHigh = true; } else { // Low, did we have a high? if (!bFoundHigh) { // Didn't have one, make if fail when we stop bFoundHigh = true; break; } // Clear flag bFoundHigh = false; } } // If last was high we're in trouble (not surrogate so not low surrogate, so break) else if (bFoundHigh) break; } if (bFoundHigh) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", nameof(replacement))); strDefault = replacement; } public String DefaultString { get { return strDefault; } } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new DecoderReplacementFallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return strDefault.Length; } } public override bool Equals(Object value) { DecoderReplacementFallback that = value as DecoderReplacementFallback; if (that != null) { return (this.strDefault == that.strDefault); } return (false); } public override int GetHashCode() { return strDefault.GetHashCode(); } } public sealed class DecoderReplacementFallbackBuffer : DecoderFallbackBuffer { // Store our default string private String strDefault; int fallbackCount = -1; int fallbackIndex = -1; // Construction public DecoderReplacementFallbackBuffer(DecoderReplacementFallback fallback) { this.strDefault = fallback.DefaultString; } // Fallback Methods public override bool Fallback(byte[] bytesUnknown, int index) { // We expect no previous fallback in our buffer // We can't call recursively but others might (note, we don't test on last char!!!) if (fallbackCount >= 1) { ThrowLastBytesRecursive(bytesUnknown); } // Go ahead and get our fallback if (strDefault.Length == 0) return false; fallbackCount = strDefault.Length; fallbackIndex = -1; return true; } public override char GetNextChar() { // We want it to get < 0 because == 0 means that the current/last character is a fallback // and we need to detect recursion. We could have a flag but we already have this counter. fallbackCount--; fallbackIndex++; // Do we have anything left? 0 is now last fallback char, negative is nothing left if (fallbackCount < 0) return '\0'; // Need to get it out of the buffer. // Make sure it didn't wrap from the fast count-- path if (fallbackCount == int.MaxValue) { fallbackCount = -1; return '\0'; } // Now make sure its in the expected range Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0, "Index exceeds buffer range"); return strDefault[fallbackIndex]; } public override bool MovePrevious() { // Back up one, only if we just processed the last character (or earlier) if (fallbackCount >= -1 && fallbackIndex >= 0) { fallbackIndex--; fallbackCount++; return true; } // Return false 'cause we couldn't do it. return false; } // How many characters left to output? public override int Remaining { get { // Our count is 0 for 1 character left. return (fallbackCount < 0) ? 0 : fallbackCount; } } // Clear the buffer public override unsafe void Reset() { fallbackCount = -1; fallbackIndex = -1; byteStart = null; } // This version just counts the fallback and doesn't actually copy anything. internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* { // return our replacement string Length return strDefault.Length; } } }
// 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.Runtime.CompilerServices; public class Test { [MethodImpl(MethodImplOptions.NoInlining)] static uint rol32(uint value, int amount) { return (value << amount) | (value >> (32 - amount)); } [MethodImpl(MethodImplOptions.NoInlining)] static uint rol32_1(uint value) { return (value << 1) | (value >> (32 - 1)); } [MethodImpl(MethodImplOptions.NoInlining)] static uint rol32_3(uint value) { return (value << 3) | (value >> (32 - 3)); } [MethodImpl(MethodImplOptions.NoInlining)] static uint rol32comm(uint value, int amount) { return (value >> (32 - amount)) | (value << amount); } [MethodImpl(MethodImplOptions.NoInlining)] static bool flag() { return true; } [MethodImpl(MethodImplOptions.NoInlining)] static uint rol32const() { uint value = flag() ? (uint)0x12345678 : (uint)0x12345678; int amount = 16; return (value >> (32 - amount)) | (value << amount); } [MethodImpl(MethodImplOptions.NoInlining)] static uint ror32(uint value, int amount) { return (value << ((32 - amount))) | (value >> amount); } [MethodImpl(MethodImplOptions.NoInlining)] static uint ror32comm(uint value, int amount) { return (value >> amount) | (value << ((32 - amount))); } [MethodImpl(MethodImplOptions.NoInlining)] static uint ror32const() { uint value = flag() ? (uint)0x12345678 : (uint)0x12345678; int amount = flag() ? 12 : 12; return (value >> amount) | (value << ((32 - amount))); } [MethodImpl(MethodImplOptions.NoInlining)] static ulong rol64(ulong value, int amount) { return (value << amount) | (value >> (64 - amount)); } [MethodImpl(MethodImplOptions.NoInlining)] static ulong rol64comm(ulong value, int amount) { return (value >> (64 - amount)) | (value << amount); } [MethodImpl(MethodImplOptions.NoInlining)] static ulong rol64const() { ulong value = flag() ? (ulong)0x123456789abcdef : (ulong)0x123456789abcdef; int amount = 16; return (value >> (64 - amount)) | (value << amount); } [MethodImpl(MethodImplOptions.NoInlining)] static ulong ror64(ulong value, int amount) { return (value << (64 - amount)) | (value >> amount); } [MethodImpl(MethodImplOptions.NoInlining)] static ulong ror64comm(ulong value, int amount) { return (value >> amount) | (value << (64 - amount)); } [MethodImpl(MethodImplOptions.NoInlining)] static ulong ror64const() { ulong value = flag() ? (ulong)0x123456789abcdef : (ulong)0x123456789abcdef; int amount = flag() ? 5 : 5; return (value << (64 - amount)) | (value >> amount); } [MethodImpl(MethodImplOptions.NoInlining)] static uint rol32_call(uint value, int amount) { return (foo(value) << amount) | (foo(value) >> (32 - amount)); } [MethodImpl(MethodImplOptions.NoInlining)] static uint foo(uint value) { return value; } [MethodImpl(MethodImplOptions.NoInlining)] static uint rol32_and(uint value, int amount) { return (value << amount) | (value >> ((32 - amount) & 31)); } [MethodImpl(MethodImplOptions.NoInlining)] static uint two_left_shifts(uint value, int amount) { return (value << amount) | (value << (32 - amount)); } [MethodImpl(MethodImplOptions.NoInlining)] static uint not_rotation(uint value) { return (value >> 10) | (value << 5); } public static int Main() { const int Pass = 100; const int Fail = -1; if (rol32(0x12345678, 16) != 0x56781234) { return Fail; } if (rol32_1(0x12345678) != 0x2468ACF0) { return Fail; } if (rol32_3(0x12345678) != 0x91A2B3C0) { return Fail; } if (rol32comm(0x12345678, 16) != 0x56781234) { return Fail; } if (rol32const() != 0x56781234) { return Fail; } if (ror32(0x12345678, 12) != 0x67812345) { return Fail; } if (ror32comm(0x12345678, 12) != 0x67812345) { return Fail; } if (ror32const() != 0x67812345) { return Fail; } if (rol64(0x123456789abcdef, 32) != 0x89abcdef01234567) { return Fail; } if (rol64comm(0x123456789abcdef, 32) != 0x89abcdef01234567) { return Fail; } if (rol64const() != 0x456789abcdef0123) { return Fail; } if (ror64(0x123456789abcdef, 0) != 0x123456789abcdef) { return Fail; } if (ror64comm(0x123456789abcdef, 0) != 0x123456789abcdef) { return Fail; } if (ror64const() != 0x78091a2b3c4d5e6f) { return Fail; } if (rol32_call(0x12345678, 16) != 0x56781234) { return Fail; } if (rol32_and(0x12345678, 16) != 0x56781234) { return Fail; } if (two_left_shifts(0x12345678, 7) != 0xfa2b3c00) { return Fail; } if (not_rotation(0x87654321) != 0xeca9fd70) { return Fail; } return Pass; } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Runtime.Versioning; using NuGet.Resources; namespace NuGet { public static class PackageRepositoryExtensions { public static IDisposable StartOperation(this IPackageRepository self, string operation, string mainPackageId, string mainPackageVersion) { IOperationAwareRepository repo = self as IOperationAwareRepository; if (repo != null) { return repo.StartOperation(operation, mainPackageId, mainPackageVersion); } return DisposableAction.NoOp; } public static bool Exists(this IPackageRepository repository, IPackageName package) { return repository.Exists(package.Id, package.Version); } public static bool Exists(this IPackageRepository repository, string packageId) { return Exists(repository, packageId, version: null); } public static bool Exists(this IPackageRepository repository, string packageId, SemanticVersion version) { IPackageLookup packageLookup = repository as IPackageLookup; if ((packageLookup != null) && !String.IsNullOrEmpty(packageId) && (version != null)) { return packageLookup.Exists(packageId, version); } return repository.FindPackage(packageId, version) != null; } public static bool TryFindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, out IPackage package) { package = repository.FindPackage(packageId, version); return package != null; } public static IPackage FindPackage(this IPackageRepository repository, string packageId) { return repository.FindPackage(packageId, version: null); } public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version) { // Default allow pre release versions to true here because the caller typically wants to find all packages in this scenario for e.g when checking if a // a package is already installed in the local repository. The same applies to allowUnlisted. return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions: true, allowUnlisted: true); } public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, bool allowPrereleaseVersions, bool allowUnlisted) { return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions, allowUnlisted); } public static IPackage FindPackage( this IPackageRepository repository, string packageId, SemanticVersion version, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool allowUnlisted) { if (repository == null) { throw new ArgumentNullException("repository"); } if (packageId == null) { throw new ArgumentNullException("packageId"); } // if an explicit version is specified, disregard the 'allowUnlisted' argument // and always allow unlisted packages. if (version != null) { allowUnlisted = true; } else if (!allowUnlisted && (constraintProvider == null || constraintProvider == NullConstraintProvider.Instance)) { var packageLatestLookup = repository as ILatestPackageLookup; if (packageLatestLookup != null) { IPackage package; if (packageLatestLookup.TryFindLatestPackageById(packageId, allowPrereleaseVersions, out package)) { return package; } } } // If the repository implements it's own lookup then use that instead. // This is an optimization that we use so we don't have to enumerate packages for // sources that don't need to. var packageLookup = repository as IPackageLookup; if (packageLookup != null && version != null) { return packageLookup.FindPackage(packageId, version); } IEnumerable<IPackage> packages = repository.FindPackagesById(packageId); packages = packages.ToList() .OrderByDescending(p => p.Version); if (!allowUnlisted) { packages = packages.Where(PackageExtensions.IsListed); } if (version != null) { packages = packages.Where(p => p.Version == version); } else if (constraintProvider != null) { packages = FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions); } return packages.FirstOrDefault(); } public static IPackage FindPackage(this IPackageRepository repository, string packageId, IVersionSpec versionSpec, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool allowUnlisted) { var packages = repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted); if (constraintProvider != null) { packages = FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions); } return packages.FirstOrDefault(); } public static IEnumerable<IPackage> FindPackages(this IPackageRepository repository, IEnumerable<string> packageIds) { if (packageIds == null) { throw new ArgumentNullException("packageIds"); } return FindPackages(repository, packageIds, GetFilterExpression); } public static IEnumerable<IPackage> FindPackagesById(this IPackageRepository repository, string packageId) { var serviceBasedRepository = repository as IPackageLookup; if (serviceBasedRepository != null) { return serviceBasedRepository.FindPackagesById(packageId).ToList(); } else { return FindPackagesByIdCore(repository, packageId); } } internal static IEnumerable<IPackage> FindPackagesByIdCore(IPackageRepository repository, string packageId) { var cultureRepository = repository as ICultureAwareRepository; if (cultureRepository != null) { packageId = packageId.ToLower(cultureRepository.Culture); } else { packageId = packageId.ToLower(CultureInfo.CurrentCulture); } return (from p in repository.GetPackages() where p.Id.ToLower() == packageId orderby p.Id select p).ToList(); } /// <summary> /// Since Odata dies when our query for updates is too big. We query for updates 10 packages at a time /// and return the full list of packages. /// </summary> private static IEnumerable<IPackage> FindPackages<T>( this IPackageRepository repository, IEnumerable<T> items, Func<IEnumerable<T>, Expression<Func<IPackage, bool>>> filterSelector) { const int batchSize = 10; while (items.Any()) { IEnumerable<T> currentItems = items.Take(batchSize); Expression<Func<IPackage, bool>> filterExpression = filterSelector(currentItems); var query = repository.GetPackages() .Where(filterExpression) .OrderBy(p => p.Id); foreach (var package in query) { yield return package; } items = items.Skip(batchSize); } } public static IEnumerable<IPackage> FindPackages( this IPackageRepository repository, string packageId, IVersionSpec versionSpec, bool allowPrereleaseVersions, bool allowUnlisted) { if (repository == null) { throw new ArgumentNullException("repository"); } if (packageId == null) { throw new ArgumentNullException("packageId"); } IEnumerable<IPackage> packages = repository.FindPackagesById(packageId) .OrderByDescending(p => p.Version); if (!allowUnlisted) { packages = packages.Where(PackageExtensions.IsListed); } if (versionSpec != null) { packages = packages.FindByVersion(versionSpec); } packages = FilterPackagesByConstraints(NullConstraintProvider.Instance, packages, packageId, allowPrereleaseVersions); return packages; } public static IPackage FindPackage( this IPackageRepository repository, string packageId, IVersionSpec versionSpec, bool allowPrereleaseVersions, bool allowUnlisted) { return repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted).FirstOrDefault(); } public static IEnumerable<IPackage> FindCompatiblePackages(this IPackageRepository repository, IPackageConstraintProvider constraintProvider, IEnumerable<string> packageIds, IPackage package, FrameworkName targetFramework, bool allowPrereleaseVersions) { return (from p in repository.FindPackages(packageIds) where allowPrereleaseVersions || p.IsReleaseVersion() let dependency = p.FindDependency(package.Id, targetFramework) let otherConstaint = constraintProvider.GetConstraint(p.Id) where dependency != null && dependency.VersionSpec.Satisfies(package.Version) && (otherConstaint == null || otherConstaint.Satisfies(package.Version)) select p); } public static PackageDependency FindDependency(this IPackageMetadata package, string packageId, FrameworkName targetFramework) { return (from dependency in package.GetCompatiblePackageDependencies(targetFramework) where dependency.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase) select dependency).FirstOrDefault(); } public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, bool allowPrereleaseVersions) { return Search(repository, searchTerm, targetFrameworks: Enumerable.Empty<string>(), allowPrereleaseVersions: allowPrereleaseVersions); } public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions) { if (targetFrameworks == null) { throw new ArgumentNullException("targetFrameworks"); } var serviceBasedRepository = repository as IServiceBasedRepository; if (serviceBasedRepository != null) { return serviceBasedRepository.Search(searchTerm, targetFrameworks, allowPrereleaseVersions); } // Ignore the target framework if the repository doesn't support searching return repository.GetPackages().Find(searchTerm) .FilterByPrerelease(allowPrereleaseVersions) .AsQueryable(); } public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, bool allowPrereleaseVersions, bool preferListedPackages) { return ResolveDependency(repository, dependency, constraintProvider: null, allowPrereleaseVersions: allowPrereleaseVersions, preferListedPackages: preferListedPackages); } public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool preferListedPackages) { IDependencyResolver dependencyResolver = repository as IDependencyResolver; if (dependencyResolver != null) { return dependencyResolver.ResolveDependency(dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages); } return ResolveDependencyCore(repository, dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages); } internal static IPackage ResolveDependencyCore( this IPackageRepository repository, PackageDependency dependency, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool preferListedPackages) { if (repository == null) { throw new ArgumentNullException("repository"); } if (dependency == null) { throw new ArgumentNullException("dependency"); } IEnumerable<IPackage> packages = repository.FindPackagesById(dependency.Id).ToList(); // Always filter by constraints when looking for dependencies packages = FilterPackagesByConstraints(constraintProvider, packages, dependency.Id, allowPrereleaseVersions); IList<IPackage> candidates = packages.ToList(); if (preferListedPackages) { // pick among Listed packages first IPackage listedSelectedPackage = ResolveDependencyCore(candidates.Where(PackageExtensions.IsListed), dependency); if (listedSelectedPackage != null) { return listedSelectedPackage; } } return ResolveDependencyCore(candidates, dependency); } private static IPackage ResolveDependencyCore(IEnumerable<IPackage> packages, PackageDependency dependency) { // If version info was specified then use it if (dependency.VersionSpec != null) { packages = packages.FindByVersion(dependency.VersionSpec); return packages.OrderBy(p => p.Version).FirstOrDefault(); } else { // BUG 840: If no version info was specified then pick the latest return packages.OrderByDescending(p => p.Version) .FirstOrDefault(); } } /// <summary> /// Returns updates for packages from the repository /// </summary> /// <param name="repository">The repository to search for updates</param> /// <param name="packages">Packages to look for updates</param> /// <param name="includePrerelease">Indicates whether to consider prerelease updates.</param> /// <param name="includeAllVersions">Indicates whether to include all versions of an update as opposed to only including the latest version.</param> public static IEnumerable<IPackage> GetUpdates( this IPackageRepository repository, IEnumerable<IPackageName> packages, bool includePrerelease, bool includeAllVersions, IEnumerable<FrameworkName> targetFrameworks = null, IEnumerable<IVersionSpec> versionConstraints = null) { if (packages.IsEmpty()) { return Enumerable.Empty<IPackage>(); } var serviceBasedRepository = repository as IServiceBasedRepository; return serviceBasedRepository != null ? serviceBasedRepository.GetUpdates(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints) : repository.GetUpdatesCore(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints); } public static IEnumerable<IPackage> GetUpdatesCore( this IPackageRepository repository, IEnumerable<IPackageName> packages, bool includePrerelease, bool includeAllVersions, IEnumerable<FrameworkName> targetFramework, IEnumerable<IVersionSpec> versionConstraints) { List<IPackageName> packageList = packages.ToList(); if (!packageList.Any()) { return Enumerable.Empty<IPackage>(); } IList<IVersionSpec> versionConstraintList; if (versionConstraints == null) { versionConstraintList = new IVersionSpec[packageList.Count]; } else { versionConstraintList = versionConstraints.ToList(); } if (packageList.Count != versionConstraintList.Count) { throw new ArgumentException(NuGetResources.GetUpdatesParameterMismatch); } // These are the packages that we need to look at for potential updates. ILookup<string, IPackage> sourcePackages = GetUpdateCandidates(repository, packageList, includePrerelease) .ToList() .ToLookup(package => package.Id, StringComparer.OrdinalIgnoreCase); var results = new List<IPackage>(); for (int i = 0; i < packageList.Count; i++) { var package = packageList[i]; var constraint = versionConstraintList[i]; var updates = from candidate in sourcePackages[package.Id] where (candidate.Version > package.Version) && SupportsTargetFrameworks(targetFramework, candidate) && (constraint == null || constraint.Satisfies(candidate.Version)) select candidate; results.AddRange(updates); } if (!includeAllVersions) { return results.CollapseById(); } return results; } private static bool SupportsTargetFrameworks(IEnumerable<FrameworkName> targetFramework, IPackage package) { return targetFramework.IsEmpty() || targetFramework.Any(t => VersionUtility.IsCompatible(t, package.GetSupportedFrameworks())); } public static IPackageRepository Clone(this IPackageRepository repository) { var cloneableRepository = repository as ICloneableRepository; if (cloneableRepository != null) { return cloneableRepository.Clone(); } return repository; } /// <summary> /// Since odata dies when our query for updates is too big. We query for updates 10 packages at a time /// and return the full list of candidates for updates. /// </summary> private static IEnumerable<IPackage> GetUpdateCandidates( IPackageRepository repository, IEnumerable<IPackageName> packages, bool includePrerelease) { var query = FindPackages(repository, packages, GetFilterExpression); if (!includePrerelease) { query = query.Where(p => p.IsReleaseVersion()); } // for updates, we never consider unlisted packages query = query.Where(PackageExtensions.IsListed); return query; } /// <summary> /// For the list of input packages generate an expression like: /// p => p.Id == 'package1id' or p.Id == 'package2id' or p.Id == 'package3id'... up to package n /// </summary> private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<IPackageName> packages) { return GetFilterExpression(packages.Select(p => p.Id)); } [SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToLower", Justification = "This is for a linq query")] private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<string> ids) { ParameterExpression parameterExpression = Expression.Parameter(typeof(IPackageName)); Expression expressionBody = ids.Select(id => GetCompareExpression(parameterExpression, id.ToLower())) .Aggregate(Expression.OrElse); return Expression.Lambda<Func<IPackage, bool>>(expressionBody, parameterExpression); } /// <summary> /// Builds the expression: package.Id.ToLower() == "somepackageid" /// </summary> private static Expression GetCompareExpression(Expression parameterExpression, object value) { // package.Id Expression propertyExpression = Expression.Property(parameterExpression, "Id"); // .ToLower() Expression toLowerExpression = Expression.Call(propertyExpression, typeof(string).GetMethod("ToLower", Type.EmptyTypes)); // == localPackage.Id return Expression.Equal(toLowerExpression, Expression.Constant(value)); } private static IEnumerable<IPackage> FilterPackagesByConstraints( IPackageConstraintProvider constraintProvider, IEnumerable<IPackage> packages, string packageId, bool allowPrereleaseVersions) { constraintProvider = constraintProvider ?? NullConstraintProvider.Instance; // Filter packages by this constraint IVersionSpec constraint = constraintProvider.GetConstraint(packageId); if (constraint != null) { packages = packages.FindByVersion(constraint); } if (!allowPrereleaseVersions) { packages = packages.Where(p => p.IsReleaseVersion()); } return packages; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model. */ using System; using Amazon.Runtime; namespace Amazon.ConfigService { /// <summary> /// Constants used for properties of type ChronologicalOrder. /// </summary> public class ChronologicalOrder : ConstantClass { /// <summary> /// Constant Forward for ChronologicalOrder /// </summary> public static readonly ChronologicalOrder Forward = new ChronologicalOrder("Forward"); /// <summary> /// Constant Reverse for ChronologicalOrder /// </summary> public static readonly ChronologicalOrder Reverse = new ChronologicalOrder("Reverse"); /// <summary> /// Default Constructor /// </summary> public ChronologicalOrder(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ChronologicalOrder FindValue(string value) { return FindValue<ChronologicalOrder>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ChronologicalOrder(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ConfigurationItemStatus. /// </summary> public class ConfigurationItemStatus : ConstantClass { /// <summary> /// Constant Deleted for ConfigurationItemStatus /// </summary> public static readonly ConfigurationItemStatus Deleted = new ConfigurationItemStatus("Deleted"); /// <summary> /// Constant Discovered for ConfigurationItemStatus /// </summary> public static readonly ConfigurationItemStatus Discovered = new ConfigurationItemStatus("Discovered"); /// <summary> /// Constant Failed for ConfigurationItemStatus /// </summary> public static readonly ConfigurationItemStatus Failed = new ConfigurationItemStatus("Failed"); /// <summary> /// Constant Ok for ConfigurationItemStatus /// </summary> public static readonly ConfigurationItemStatus Ok = new ConfigurationItemStatus("Ok"); /// <summary> /// Default Constructor /// </summary> public ConfigurationItemStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ConfigurationItemStatus FindValue(string value) { return FindValue<ConfigurationItemStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ConfigurationItemStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type DeliveryStatus. /// </summary> public class DeliveryStatus : ConstantClass { /// <summary> /// Constant Failure for DeliveryStatus /// </summary> public static readonly DeliveryStatus Failure = new DeliveryStatus("Failure"); /// <summary> /// Constant Not_Applicable for DeliveryStatus /// </summary> public static readonly DeliveryStatus Not_Applicable = new DeliveryStatus("Not_Applicable"); /// <summary> /// Constant Success for DeliveryStatus /// </summary> public static readonly DeliveryStatus Success = new DeliveryStatus("Success"); /// <summary> /// Default Constructor /// </summary> public DeliveryStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static DeliveryStatus FindValue(string value) { return FindValue<DeliveryStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator DeliveryStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type RecorderStatus. /// </summary> public class RecorderStatus : ConstantClass { /// <summary> /// Constant Failure for RecorderStatus /// </summary> public static readonly RecorderStatus Failure = new RecorderStatus("Failure"); /// <summary> /// Constant Pending for RecorderStatus /// </summary> public static readonly RecorderStatus Pending = new RecorderStatus("Pending"); /// <summary> /// Constant Success for RecorderStatus /// </summary> public static readonly RecorderStatus Success = new RecorderStatus("Success"); /// <summary> /// Default Constructor /// </summary> public RecorderStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static RecorderStatus FindValue(string value) { return FindValue<RecorderStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator RecorderStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ResourceType. /// </summary> public class ResourceType : ConstantClass { /// <summary> /// Constant AWSCloudTrailTrail for ResourceType /// </summary> public static readonly ResourceType AWSCloudTrailTrail = new ResourceType("AWS::CloudTrail::Trail"); /// <summary> /// Constant AWSEC2CustomerGateway for ResourceType /// </summary> public static readonly ResourceType AWSEC2CustomerGateway = new ResourceType("AWS::EC2::CustomerGateway"); /// <summary> /// Constant AWSEC2EIP for ResourceType /// </summary> public static readonly ResourceType AWSEC2EIP = new ResourceType("AWS::EC2::EIP"); /// <summary> /// Constant AWSEC2Instance for ResourceType /// </summary> public static readonly ResourceType AWSEC2Instance = new ResourceType("AWS::EC2::Instance"); /// <summary> /// Constant AWSEC2InternetGateway for ResourceType /// </summary> public static readonly ResourceType AWSEC2InternetGateway = new ResourceType("AWS::EC2::InternetGateway"); /// <summary> /// Constant AWSEC2NetworkAcl for ResourceType /// </summary> public static readonly ResourceType AWSEC2NetworkAcl = new ResourceType("AWS::EC2::NetworkAcl"); /// <summary> /// Constant AWSEC2NetworkInterface for ResourceType /// </summary> public static readonly ResourceType AWSEC2NetworkInterface = new ResourceType("AWS::EC2::NetworkInterface"); /// <summary> /// Constant AWSEC2RouteTable for ResourceType /// </summary> public static readonly ResourceType AWSEC2RouteTable = new ResourceType("AWS::EC2::RouteTable"); /// <summary> /// Constant AWSEC2SecurityGroup for ResourceType /// </summary> public static readonly ResourceType AWSEC2SecurityGroup = new ResourceType("AWS::EC2::SecurityGroup"); /// <summary> /// Constant AWSEC2Subnet for ResourceType /// </summary> public static readonly ResourceType AWSEC2Subnet = new ResourceType("AWS::EC2::Subnet"); /// <summary> /// Constant AWSEC2Volume for ResourceType /// </summary> public static readonly ResourceType AWSEC2Volume = new ResourceType("AWS::EC2::Volume"); /// <summary> /// Constant AWSEC2VPC for ResourceType /// </summary> public static readonly ResourceType AWSEC2VPC = new ResourceType("AWS::EC2::VPC"); /// <summary> /// Constant AWSEC2VPNConnection for ResourceType /// </summary> public static readonly ResourceType AWSEC2VPNConnection = new ResourceType("AWS::EC2::VPNConnection"); /// <summary> /// Constant AWSEC2VPNGateway for ResourceType /// </summary> public static readonly ResourceType AWSEC2VPNGateway = new ResourceType("AWS::EC2::VPNGateway"); /// <summary> /// Default Constructor /// </summary> public ResourceType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ResourceType FindValue(string value) { return FindValue<ResourceType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ResourceType(string value) { return FindValue(value); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ErrorLogger; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes { public class CodeFixServiceTests { [Fact] public async Task TestGetFirstDiagnosticWithFixAsync() { var diagnosticService = new TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); var fixers = CreateFixers(); var code = @" a "; using (var workspace = await TestWorkspace.CreateCSharpAsync(code)) { var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => workspace.Services.GetService<IErrorLoggerService>())); var fixService = new CodeFixService( diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>()); var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService; // register diagnostic engine to solution crawler var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); var reference = new MockAnalyzerReference(); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); var document = project.Documents.Single(); var unused = await fixService.GetFirstDiagnosticWithFixAsync(document, TextSpan.FromBounds(0, 0), considerSuppressionFixes: false, cancellationToken: CancellationToken.None); var fixer1 = fixers.Single().Value as MockFixer; var fixer2 = reference.Fixer as MockFixer; // check to make sure both of them are called. Assert.True(fixer1.Called); Assert.True(fixer2.Called); } } [Fact] public async Task TestGetCodeFixWithExceptionInRegisterMethod() { await GetFirstDiagnosticWithFixAsync(new ErrorCases.ExceptionInRegisterMethod()); await GetAddedFixesAsync(new ErrorCases.ExceptionInRegisterMethod()); } [Fact] public async Task TestGetCodeFixWithExceptionInRegisterMethodAsync() { await GetFirstDiagnosticWithFixAsync(new ErrorCases.ExceptionInRegisterMethodAsync()); await GetAddedFixesAsync(new ErrorCases.ExceptionInRegisterMethodAsync()); } [Fact] public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds() { await GetDefaultFixesAsync(new ErrorCases.ExceptionInFixableDiagnosticIds()); await GetAddedFixesAsync(new ErrorCases.ExceptionInFixableDiagnosticIds()); } [Fact] public async Task TestGetCodeFixWithExceptionInFixableDiagnosticIds2() { await GetDefaultFixesAsync(new ErrorCases.ExceptionInFixableDiagnosticIds2()); await GetAddedFixesAsync(new ErrorCases.ExceptionInFixableDiagnosticIds2()); } [Fact] public async Task TestGetCodeFixWithExceptionInGetFixAllProvider() { await GetAddedFixesAsync(new ErrorCases.ExceptionInGetFixAllProvider()); } public async Task GetDefaultFixesAsync(CodeFixProvider codefix) { var tuple = await ServiceSetupAsync(codefix); using (var workspace = tuple.Item1) { Document document; EditorLayerExtensionManager.ExtensionManager extensionManager; GetDocumentAndExtensionManager(tuple.Item2, workspace, out document, out extensionManager); var fixes = await tuple.Item3.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeSuppressionFixes: true, cancellationToken: CancellationToken.None); Assert.True(((TestErrorLogger)tuple.Item4).Messages.Count == 1); string message; Assert.True(((TestErrorLogger)tuple.Item4).Messages.TryGetValue(codefix.GetType().Name, out message)); } } public async Task GetAddedFixesAsync(CodeFixProvider codefix) { var tuple = await ServiceSetupAsync(codefix); using (var workspace = tuple.Item1) { Document document; EditorLayerExtensionManager.ExtensionManager extensionManager; GetDocumentAndExtensionManager(tuple.Item2, workspace, out document, out extensionManager); var incrementalAnalyzer = (IIncrementalAnalyzerProvider)tuple.Item2; var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); var reference = new MockAnalyzerReference(codefix); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); document = project.Documents.Single(); var fixes = await tuple.Item3.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeSuppressionFixes: true, cancellationToken: CancellationToken.None); Assert.True(extensionManager.IsDisabled(codefix)); Assert.False(extensionManager.IsIgnored(codefix)); } } public async Task GetFirstDiagnosticWithFixAsync(CodeFixProvider codefix) { var tuple = await ServiceSetupAsync(codefix); using (var workspace = tuple.Item1) { Document document; EditorLayerExtensionManager.ExtensionManager extensionManager; GetDocumentAndExtensionManager(tuple.Item2, workspace, out document, out extensionManager); var unused = await tuple.Item3.GetFirstDiagnosticWithFixAsync(document, TextSpan.FromBounds(0, 0), considerSuppressionFixes: false, cancellationToken: CancellationToken.None); Assert.True(extensionManager.IsDisabled(codefix)); Assert.False(extensionManager.IsIgnored(codefix)); } } private static async Task<Tuple<TestWorkspace, TestDiagnosticAnalyzerService, CodeFixService, IErrorLoggerService>> ServiceSetupAsync(CodeFixProvider codefix) { var diagnosticService = new TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); var fixers = SpecializedCollections.SingletonEnumerable( new Lazy<CodeFixProvider, CodeChangeProviderMetadata>( () => codefix, new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp))); var code = @"class Program { }"; var workspace = await TestWorkspace.CreateCSharpAsync(code); var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => new TestErrorLogger())); var errorLogger = logger.First().Value; var fixService = new CodeFixService( diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>()); return Tuple.Create(workspace, diagnosticService, fixService, errorLogger); } private static void GetDocumentAndExtensionManager(TestDiagnosticAnalyzerService diagnosticService, TestWorkspace workspace, out Document document, out EditorLayerExtensionManager.ExtensionManager extensionManager) { var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService; // register diagnostic engine to solution crawler var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); var reference = new MockAnalyzerReference(); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); document = project.Documents.Single(); extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>() as EditorLayerExtensionManager.ExtensionManager; } private IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> CreateFixers() { return SpecializedCollections.SingletonEnumerable( new Lazy<CodeFixProvider, CodeChangeProviderMetadata>(() => new MockFixer(), new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp))); } internal class MockFixer : CodeFixProvider { public const string Id = "MyDiagnostic"; public bool Called = false; public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(Id); } } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { Called = true; return SpecializedTasks.EmptyTask; } } private class MockAnalyzerReference : AnalyzerReference, ICodeFixProviderFactory { public readonly CodeFixProvider Fixer; public readonly MockDiagnosticAnalyzer Analyzer = new MockDiagnosticAnalyzer(); public MockAnalyzerReference() { Fixer = new MockFixer(); } public MockAnalyzerReference(CodeFixProvider codeFix) { Fixer = codeFix; } public override string Display { get { return "MockAnalyzerReference"; } } public override string FullPath { get { return string.Empty; } } public override object Id { get { return "MockAnalyzerReference"; } } public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language) { return ImmutableArray.Create<DiagnosticAnalyzer>(Analyzer); } public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages() { return ImmutableArray<DiagnosticAnalyzer>.Empty; } public ImmutableArray<CodeFixProvider> GetFixers() { return ImmutableArray.Create<CodeFixProvider>(Fixer); } public class MockDiagnosticAnalyzer : DiagnosticAnalyzer { private DiagnosticDescriptor _descriptor = new DiagnosticDescriptor(MockFixer.Id, "MockDiagnostic", "MockDiagnostic", "InternalCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(_descriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxTreeAction(c => { c.ReportDiagnostic(Diagnostic.Create(_descriptor, c.Tree.GetLocation(TextSpan.FromBounds(0, 0)))); }); } } } internal class TestErrorLogger : IErrorLoggerService { public Dictionary<string, string> Messages = new Dictionary<string, string>(); public void LogException(object source, Exception exception) { Messages.Add(source.GetType().Name, ToLogFormat(exception)); } private static string ToLogFormat(Exception exception) { return exception.Message + Environment.NewLine + exception.StackTrace; } } } }
// <copyright company="Simply Code Ltd."> // Copyright (c) Simply Code Ltd. All rights reserved. // Licensed under the MIT License. // See LICENSE file in the project root for full license information. // </copyright> namespace PackIt.Test.Controllers { using System; using System.Collections.Generic; using System.Net; using Microsoft.AspNetCore.JsonPatch; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using PackIt.Controllers; using PackIt.DTO; using PackIt.Helpers.Enums; using PackIt.Material; /// <summary> (Unit Test Fixture) a controller for handling test materials. </summary> [TestFixture] public class TestMaterialsController { /// <summary> The controller under test. </summary> private MaterialsController controller; /// <summary> Setup for all unit tests here. </summary> [SetUp] public void BeforeTest() { var builder = new DbContextOptionsBuilder<MaterialContext>(); builder.EnableSensitiveDataLogging(); builder.UseInMemoryDatabase("testmaterial"); var context = new MaterialContext(builder.Options); var repository = new MaterialRepository(context); this.controller = new( Mock.Of<ILogger<MaterialsController>>(), repository); Assert.IsNotNull(this.controller); } /// <summary> (Unit Test Method) post this message. </summary> [Test] public void Post() { var item = new Material { MaterialId = Guid.NewGuid().ToString() }; var result = this.controller.Post(item); Assert.IsNotNull(result); Assert.IsInstanceOf<CreatedAtRouteResult>(result); var res = result as CreatedAtRouteResult; Assert.AreEqual((int)HttpStatusCode.Created, res.StatusCode); Assert.IsTrue(res.RouteValues.ContainsKey("id")); Assert.IsInstanceOf<Material>(res.Value); } /// <summary> (Unit Test Method) posts the no data. </summary> [Test] public void PostNoData() { var result = this.controller.Post(null); Assert.IsNotNull(result); Assert.IsInstanceOf<BadRequestResult>(result); Assert.AreEqual((int)HttpStatusCode.BadRequest, (result as BadRequestResult).StatusCode); } /// <summary> (Unit Test Method) posts the already exists. </summary> [Test] public void PostAlreadyExists() { var item = new Material { MaterialId = Guid.NewGuid().ToString() }; var result = this.controller.Post(item); Assert.IsNotNull(result); Assert.IsInstanceOf<CreatedAtRouteResult>(result); var res = result as CreatedAtRouteResult; Assert.AreEqual((int)HttpStatusCode.Created, res.StatusCode); Assert.IsTrue(res.RouteValues.ContainsKey("id")); Assert.IsInstanceOf<Material>(res.Value); result = this.controller.Post(item); Assert.IsNotNull(result); Assert.IsInstanceOf<StatusCodeResult>(result); Assert.AreEqual((int)HttpStatusCode.Conflict, (result as StatusCodeResult).StatusCode); } /// <summary> (Unit Test Method) gets all. </summary> [Test] public void GetAll() { const int ItemsToAdd = 10; var ids = new List<string>(); for (int item = 0; item < ItemsToAdd; ++item) { var id = Guid.NewGuid().ToString(); ids.Add(id); this.controller.Post(new Material { MaterialId = id }); } var result = this.controller.Get(); Assert.IsNotNull(result); Assert.IsInstanceOf<OkObjectResult>(result); var objectResult = result as OkObjectResult; Assert.AreEqual((int)HttpStatusCode.OK, objectResult.StatusCode); Assert.IsInstanceOf<IList<Material>>(objectResult.Value); var items = objectResult.Value as IList<Material>; foreach (var item in items) { if (ids.Contains(item.MaterialId)) { ids.Remove(item.MaterialId); } } Assert.IsEmpty(ids, "IDS not found " + string.Join(",", ids)); } /// <summary> (Unit Test Method) gets this object. </summary> [Test] public void Get() { const string StartName = "A name"; const MaterialType Type = MaterialType.Can; var id = Guid.NewGuid().ToString(); var item = new Material { MaterialId = id, Type = Type, Name = StartName }; var result = this.controller.Post(item); Assert.IsNotNull(result); Assert.IsInstanceOf<CreatedAtRouteResult>(result); var res = result as CreatedAtRouteResult; Assert.AreEqual((int)HttpStatusCode.Created, res.StatusCode); Assert.IsTrue(res.RouteValues.ContainsKey("id")); Assert.IsInstanceOf<Material>(res.Value); result = this.controller.Get(id); Assert.IsNotNull(result); Assert.IsInstanceOf<OkObjectResult>(result); var objectResult = result as OkObjectResult; Assert.AreEqual((int)HttpStatusCode.OK, objectResult.StatusCode); Assert.IsInstanceOf<Material>(objectResult.Value); item = objectResult.Value as Material; Assert.AreEqual(item.MaterialId, id); Assert.AreEqual(item.Type, Type); Assert.AreEqual(item.Name, StartName); } /// <summary> (Unit Test Method) gets not found. </summary> [Test] public void GetNotFound() { var id = Guid.NewGuid().ToString(); var result = this.controller.Get(id); Assert.IsNotNull(result); Assert.IsInstanceOf<NotFoundObjectResult>(result); var notfound = result as NotFoundObjectResult; Assert.AreEqual((int)HttpStatusCode.NotFound, notfound.StatusCode); Assert.AreEqual(id, notfound.Value); } /// <summary> (Unit Test Method) puts this object. </summary> [Test] public void Put() { const string StartName = "A name"; const string PutName = "B name"; const MaterialType Type = MaterialType.Cap; var id = Guid.NewGuid().ToString(); var item = new Material { Type = Type, MaterialId = id, Name = StartName }; var result = this.controller.Post(item); Assert.IsNotNull(result); Assert.IsInstanceOf<CreatedAtRouteResult>(result); var res = result as CreatedAtRouteResult; Assert.AreEqual((int)HttpStatusCode.Created, res.StatusCode); Assert.IsTrue(res.RouteValues.ContainsKey("id")); Assert.IsInstanceOf<Material>(res.Value); item.Name = PutName; result = this.controller.Put(id, item); Assert.IsNotNull(result); Assert.IsInstanceOf<OkResult>(result); Assert.AreEqual((int)HttpStatusCode.OK, (result as OkResult).StatusCode); // Get the material and check the returned object has the new Name result = this.controller.Get(id); Assert.IsInstanceOf<OkObjectResult>(result); var objectResult = result as OkObjectResult; Assert.AreEqual((int)HttpStatusCode.OK, objectResult.StatusCode); Assert.IsInstanceOf<Material>(objectResult.Value); item = objectResult.Value as Material; Assert.AreEqual(item.Type, Type); Assert.AreEqual(item.MaterialId, id); Assert.AreEqual(item.Name, PutName); } /// <summary> (Unit Test Method) puts not found. </summary> [Test] public void PutNotFound() { var id = Guid.NewGuid().ToString(); var item = new Material(); var result = this.controller.Put(id, item); Assert.IsNotNull(result); Assert.IsInstanceOf<NotFoundObjectResult>(result); var notfound = result as NotFoundObjectResult; Assert.AreEqual((int)HttpStatusCode.NotFound, notfound.StatusCode); Assert.AreEqual(id, notfound.Value); } /// <summary> (Unit Test Method) deletes this object. </summary> [Test] public void Delete() { const MaterialType Type = MaterialType.Collar; var id = Guid.NewGuid().ToString(); var item = new Material { MaterialId = id, Type = Type }; var result = this.controller.Post(item); Assert.IsNotNull(result); Assert.IsInstanceOf<CreatedAtRouteResult>(result); var res = result as CreatedAtRouteResult; Assert.AreEqual((int)HttpStatusCode.Created, res.StatusCode); Assert.IsTrue(res.RouteValues.ContainsKey("id")); Assert.IsInstanceOf<Material>(res.Value); result = this.controller.Delete(id); Assert.IsNotNull(result); Assert.IsInstanceOf<OkResult>(result); Assert.AreEqual((int)HttpStatusCode.OK, (result as OkResult).StatusCode); } /// <summary> (Unit Test Method) deletes the not found. </summary> [Test] public void DeleteNotFound() { var id = Guid.NewGuid().ToString(); var result = this.controller.Delete(id); Assert.IsNotNull(result); Assert.IsInstanceOf<NotFoundObjectResult>(result); var notfound = result as NotFoundObjectResult; Assert.AreEqual((int)HttpStatusCode.NotFound, notfound.StatusCode); Assert.AreEqual(id, notfound.Value); } /// <summary> (Unit Test Method) patches this object. </summary> [Test] public void Patch() { const string StartName = "A name"; const string PatchName = "B name"; const MaterialType Type = MaterialType.Crate; var id = Guid.NewGuid().ToString(); var item = new Material { MaterialId = id, Type = Type, Name = StartName }; // Create a new material var result = this.controller.Post(item); Assert.IsNotNull(result); Assert.IsInstanceOf<CreatedAtRouteResult>(result); var res = result as CreatedAtRouteResult; Assert.AreEqual((int)HttpStatusCode.Created, res.StatusCode); Assert.IsTrue(res.RouteValues.ContainsKey("id")); Assert.IsInstanceOf<Material>(res.Value); // Patch the material with a new name var patch = new JsonPatchDocument<Material>(); patch.Replace(e => e.Name, PatchName); result = this.controller.Patch(id, patch); Assert.IsNotNull(result); Assert.IsInstanceOf<OkObjectResult>(result); // Check the returned object from the patch has the same Note but different Name var objectResult = result as OkObjectResult; Assert.AreEqual((int)HttpStatusCode.OK, objectResult.StatusCode); Assert.IsInstanceOf<Material>(objectResult.Value); item = objectResult.Value as Material; Assert.AreEqual(item.Type, Type); Assert.AreEqual(item.MaterialId, id); Assert.AreEqual(item.Name, PatchName); // Get the material and check the returned object has the same Note and new Name result = this.controller.Get(id); Assert.IsInstanceOf<OkObjectResult>(result); objectResult = result as OkObjectResult; Assert.AreEqual((int)HttpStatusCode.OK, objectResult.StatusCode); Assert.IsInstanceOf<Material>(objectResult.Value); item = objectResult.Value as Material; Assert.AreEqual(item.Type, Type); Assert.AreEqual(item.MaterialId, id); Assert.AreEqual(item.Name, PatchName); } /// <summary> (Unit Test Method) patch not found. </summary> [Test] public void PatchNotFound() { const string StartName = "A name"; const string PatchName = "B name"; const MaterialType Type = MaterialType.Crate; var item = new Material { MaterialId = Guid.NewGuid().ToString(), Type = Type, Name = StartName }; var result = this.controller.Post(item); Assert.IsNotNull(result); Assert.IsInstanceOf<CreatedAtRouteResult>(result); var res = result as CreatedAtRouteResult; Assert.AreEqual((int)HttpStatusCode.Created, res.StatusCode); Assert.IsTrue(res.RouteValues.ContainsKey("id")); Assert.IsInstanceOf<Material>(res.Value); var patch = new JsonPatchDocument<Material>(); patch.Replace(e => e.Name, PatchName); var id = Guid.NewGuid().ToString(); result = this.controller.Patch(id, patch); Assert.IsNotNull(result); Assert.IsInstanceOf<NotFoundObjectResult>(result); var notfound = result as NotFoundObjectResult; Assert.AreEqual((int)HttpStatusCode.NotFound, notfound.StatusCode); Assert.AreEqual(id, notfound.Value); } /// <summary> (Unit Test Method) posts the complex material. </summary> [Test] public void PostComplexMaterial() { const MaterialType Type = MaterialType.Crate; var id = Guid.NewGuid().ToString(); // Create a material with a costing var costing = new Costing(); var item = new Material { MaterialId = id, Type = Type }; item.Costings.Add(costing); var result = this.controller.Post(item); Assert.IsNotNull(result); Assert.IsInstanceOf<CreatedAtRouteResult>(result); var res = result as CreatedAtRouteResult; Assert.AreEqual((int)HttpStatusCode.Created, res.StatusCode); Assert.IsTrue(res.RouteValues.ContainsKey("id")); Assert.IsInstanceOf<Material>(res.Value); // Get the material result = this.controller.Get(id); Assert.IsNotNull(result); Assert.IsInstanceOf<OkObjectResult>(result); var objectResult = result as OkObjectResult; Assert.AreEqual((int)HttpStatusCode.OK, objectResult.StatusCode); Assert.IsInstanceOf<Material>(objectResult.Value); // Test the material item = objectResult.Value as Material; Assert.AreEqual(item.Type, Type); Assert.AreEqual(item.MaterialId, id); Assert.AreEqual(item.Costings.Count, 1); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Microsoft.Msagl.Core.Geometry.Curves{ /// <summary> /// A class representing an ellipse. /// </summary> #if TEST_MSAGL [Serializable] #endif public class Ellipse : ICurve{ #if TEST_MSAGL /// <summary> /// </summary> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object[])")] public override string ToString() { return String.Format("{0} {1} from {2} to {3} a0={4} a1={5}", Start, End, ParStart, ParEnd, AxisA, AxisB); } #endif Rectangle box; ParallelogramNodeOverICurve parallelogramNodeOverICurve; /// <summary> /// offsets the curve in the given direction /// </summary> /// <param name="offset">the width of the offset</param> /// <param name="dir">the direction of the offset</param> /// <returns></returns> public ICurve OffsetCurve(double offset, Point dir){ //is dir inside or outside Point d = dir - center; double angle = Point.Angle(aAxis, d); Point s = aAxis*Math.Cos(angle) + bAxis*Math.Sin(angle); if(s.Length < d.Length){ double al = aAxis.Length; double bl = bAxis.Length; return new Ellipse((al + offset)*aAxis.Normalize(), (bl + offset)*bAxis.Normalize(), center); } { double al = aAxis.Length; double bl = bAxis.Length; #if DEBUGCURVES if (al < offset || bl < offset) throw new Exception("wrong parameter for ellipse offset"); #endif return new Ellipse((al - offset)*aAxis.Normalize(), (bl - offset)*bAxis.Normalize(), center); } } /// <summary> /// Reverse the ellipe: not implemented. /// </summary> /// <returns>returns the reversed curve</returns> public ICurve Reverse(){ return null; // throw new Exception("not implemented"); } /// <summary> /// Returns the start point of the curve /// </summary> public Point Start{ get { return this[ParStart]; } } /// <summary> /// Returns the end point of the curve /// </summary> public Point End{ get { return this[ParEnd]; } } /// <summary> /// Trims the curve /// </summary> /// <param name="start">the trim start parameter</param> /// <param name="end">the trim end parameter</param> /// <returns></returns> public ICurve Trim(double start, double end){ Debug.Assert(start<=end); Debug.Assert(start>=ParStart-ApproximateComparer.Tolerance); Debug.Assert(end<=ParEnd+ApproximateComparer.Tolerance); return new Ellipse(Math.Max(start, ParStart), Math.Min(end,ParEnd), AxisA, AxisB, center); } /// <summary> /// Not Implemented: Returns the trimmed curve, wrapping around the end if start is greater than end. /// </summary> /// <param name="start">The starting parameter</param> /// <param name="end">The ending parameter</param> /// <returns>The trimmed curve</returns> public ICurve TrimWithWrap(double start, double end) { throw new NotImplementedException(); } //half x axes Point aAxis; /// <summary> /// the X axis of the ellipse /// </summary> public Point AxisA{ get { return aAxis; } set { aAxis = value; } } Point bAxis; /// <summary> /// the Y axis of the ellipse /// </summary> public Point AxisB{ get { return bAxis; } set { bAxis = value; } } Point center; /// <summary> /// the center of the ellipse /// </summary> public Point Center{ get { return center; } set { center = value; } } /// <summary> /// The bounding box of the ellipse /// </summary> public Rectangle BoundingBox{ get { return box; } } /// <summary> /// Returns the point on the curve corresponding to parameter t /// </summary> /// <param name="t">the parameter of the derivative</param> /// <returns></returns> public Point this[double t]{ get { return center + Math.Cos(t)*aAxis + Math.Sin(t)*bAxis; } } /// <summary> /// first derivative /// </summary> /// <param name="t">the p</param> /// <returns></returns> public Point Derivative(double t){ return -Math.Sin(t)*aAxis + Math.Cos(t)*bAxis; } /// <summary> /// second derivative /// </summary> /// <param name="t"></param> /// <returns></returns> public Point SecondDerivative(double t){ return -Math.Cos(t)*aAxis - Math.Sin(t)*bAxis; } /// <summary> /// third derivative /// </summary> /// <param name="t"></param> /// <returns></returns> public Point ThirdDerivative(double t){ return Math.Sin(t)*aAxis - Math.Cos(t)*bAxis; } /// <summary> /// a tree of ParallelogramNodes covering the edge /// </summary> /// <value></value> public ParallelogramNodeOverICurve ParallelogramNodeOverICurve{ get{ #if PPC lock(this){ #endif if(parallelogramNodeOverICurve != null) return parallelogramNodeOverICurve; return parallelogramNodeOverICurve = CreateParallelogramNodeForCurveSeg(this); #if PPC } #endif } } static ParallelogramNodeOverICurve CreateNodeWithSegmentSplit(double start, double end, Ellipse seg, double eps){ var pBNode = new ParallelogramInternalTreeNode(seg, eps); pBNode.AddChild(CreateParallelogramNodeForCurveSeg(start, 0.5*(start + end), seg, eps)); pBNode.AddChild(CreateParallelogramNodeForCurveSeg(0.5*(start + end), end, seg, eps)); var boxes = new List<Parallelogram>(); boxes.Add(pBNode.Children[0].Parallelogram); boxes.Add(pBNode.Children[1].Parallelogram); pBNode.Parallelogram = Parallelogram.GetParallelogramOfAGroup(boxes); return pBNode; } internal static ParallelogramNodeOverICurve CreateParallelogramNodeForCurveSeg(double start, double end, Ellipse seg, double eps){ bool closedSeg = (start == seg.ParStart && end == seg.ParEnd && ApproximateComparer.Close(seg.Start, seg.End)); if(closedSeg) return CreateNodeWithSegmentSplit(start, end, seg, eps); Point s = seg[start]; Point e = seg[end]; Point w = e - s; Point middle = seg[(start + end) / 2]; if (ParallelogramNodeOverICurve.DistToSegm(middle, s, e) <= ApproximateComparer.IntersectionEpsilon && w * w < Curve.LineSegmentThreshold * Curve.LineSegmentThreshold && end - start < Curve.LineSegmentThreshold) { var ls = new LineSegment(s, e); var leaf = ls.ParallelogramNodeOverICurve as ParallelogramLeaf; leaf.Low = start; leaf.High = end; leaf.Seg = seg; leaf.Chord = ls; return leaf; } bool we = WithinEpsilon(seg, start, end, eps); var box = new Parallelogram(); if(we && CreateParallelogramOnSubSeg(start, end, seg, ref box)){ return new ParallelogramLeaf(start, end, box, seg, eps); } else{ return CreateNodeWithSegmentSplit(start, end, seg, eps); } } internal static bool CreateParallelogramOnSubSeg(double start, double end, Ellipse seg, ref Parallelogram box){ Point tan1 = seg.Derivative(start); Point tan2 = seg.Derivative(end); Point tan2Perp = Point.P(-tan2.Y, tan2.X); Point corner = seg[start]; Point e = seg[end]; Point p = e - corner; double numerator = p*tan2Perp; double denumerator = (tan1*tan2Perp); double x; // = (p * tan2Perp) / (tan1 * tan2Perp); if(Math.Abs(numerator) < ApproximateComparer.DistanceEpsilon) x = 0; else if(Math.Abs(denumerator) < ApproximateComparer.DistanceEpsilon){ //it is degenerated; adjacent sides are parallel, but //since p * tan2Perp is big it does not contain e return false; } else x = numerator/denumerator; tan1 *= x; box = new Parallelogram(corner, tan1, e - corner - tan1); #if DEBUGCURVES if (!box.Contains(seg[end])) { throw new InvalidOperationException();//"the box does not contain the end of the segment"); } #endif return true; } static bool WithinEpsilon(Ellipse seg, double start, double end, double eps){ int n = 3; //hack !!!! but maybe can be proven for Bezier curves and other regular curves double d = (end - start)/n; Point s = seg[start]; Point e = seg[end]; double d0 = ParallelogramNodeOverICurve.DistToSegm(seg[start + d], s, e); if(d0 > eps) return false; double d1 = ParallelogramNodeOverICurve.DistToSegm(seg[start + d*(n - 1)], s, e); //double d1d1 = seg.d1(start) * seg.d1(end); return d1 <= eps; // && d1d1 > 0; } static ParallelogramNodeOverICurve CreateParallelogramNodeForCurveSeg(Ellipse seg) { return CreateParallelogramNodeForCurveSeg(seg.ParStart, seg.ParEnd, seg, ParallelogramNodeOverICurve.DefaultLeafBoxesOffset); } double parStart; /// <summary> /// the start of the parameter domain /// </summary> public double ParStart{ get { return parStart; } set { parStart = value; } } double parEnd; /// <summary> /// the end of the parameter domain /// </summary> public double ParEnd{ get { return parEnd; } set { parEnd = value; } } /// <summary> /// The point on the ellipse corresponding to the parameter t is calculated by /// the formula center + cos(t)*axis0 + sin(t) * axis1. /// To get an ellipse rotating clockwise use, for example, /// axis0=(-1,0) and axis1=(0,1) /// <param name="parStart">start angle in radians</param> /// <param name="parEnd">end angle in radians</param> /// <param name="axis0">x radius</param> /// <param name="axis1">y radius</param> /// <param name="center">the ellipse center</param> /// </summary> public Ellipse(double parStart, double parEnd, Point axis0, Point axis1, Point center){ Debug.Assert(parStart<=parEnd); ParStart = parStart; ParEnd = parEnd; AxisA = axis0; AxisB = axis1; this.center = center; SetBoundingBox(); } void SetBoundingBox() { if (ApproximateComparer.Close(ParStart, 0) && ApproximateComparer.Close(ParEnd, Math.PI * 2)) box = FullBox(); else { //the idea is that the box of an arc staying in one quadrant is just the box of the start and the end point of the arc box = new Rectangle(Start, End); //now Start and End are in the box, we need just add all k*P/2 that are in between double t; for (int i = (int)Math.Ceiling(ParStart / (Math.PI / 2)); (t = i * Math.PI / 2) < ParEnd; i++) if (t > parStart) box.Add(this[t]); } } /// <summary> /// The point on the ellipse corresponding to the parameter t is calculated by /// the formula center + cos(t)*axis0 + sin(t) * axis1. /// To get an ellipse rotating clockwise use, for example, /// axis0=(-1,0) and axis1=(0,1) /// </summary> /// <param name="parStart">start angle in radians</param> /// <param name="parEnd">end angle in radians</param> /// <param name="axis0">the x axis</param> /// <param name="axis1">the y axis</param> /// <param name="centerX">x coordinate of the center</param> /// <param name="centerY">y coordinate of the center</param> public Ellipse(double parStart, double parEnd, Point axis0, Point axis1, double centerX, double centerY) : this(parStart, parEnd, axis0, axis1, new Point(centerX, centerY)){ } /// <summary> /// Construct a full ellipse by two axes /// </summary> /// <param name="axis0">an axis</param> /// <param name="axis1">an axis</param> /// <param name="center"></param> public Ellipse(Point axis0, Point axis1, Point center) : this(0, Math.PI*2, axis0, axis1, center){ } /// <summary> /// Constructs a full ellipse with axes aligned to X and Y directions /// </summary> /// <param name="axisA">the length of the X axis</param> /// <param name="axisB">the length of the Y axis</param> /// <param name="center"></param> public Ellipse(double axisA, double axisB, Point center) : this(0, Math.PI*2, new Point(axisA, 0), new Point(0, axisB), center){ } /// <summary> /// Moves the ellipse to the delta vector /// </summary> public void Translate(Point delta) { this.center += delta; this.box = new Rectangle(center + bAxis + aAxis, center - bAxis - aAxis); parallelogramNodeOverICurve = null; } /// <summary> /// Scales the ellipse by x and by y /// </summary> /// <param name="xScale"></param> /// <param name="yScale"></param> /// <returns>the moved ellipse</returns> public ICurve ScaleFromOrigin(double xScale, double yScale) { return new Ellipse(parStart, parEnd, aAxis * xScale, bAxis * yScale, Point.Scale(xScale, yScale, center)); } /// <summary> /// /// </summary> /// <param name="length"></param> /// <returns></returns> public double GetParameterAtLength(double length) { //todo: slow version! const double eps = 0.001; var l = ParStart; var u = ParEnd; var lenplus = length + eps; var lenminsu = length - eps; while (u - l > ApproximateComparer.DistanceEpsilon) { var m = 0.5*(u + l); var len = LengthPartial(ParStart, m); if(len>lenplus) u=m; else if (len < lenminsu) l = m; else return m; } return (u + l)/2; } /// <summary> /// Transforms the ellipse /// </summary> /// <param name="transformation"></param> /// <returns>the transformed ellipse</returns> public ICurve Transform(PlaneTransformation transformation){ if(transformation != null){ Point ap = transformation*aAxis - transformation.Offset; Point bp = transformation*bAxis - transformation.Offset; return new Ellipse(parStart, parEnd, ap, bp, transformation*center); } return this; } /// <summary> /// returns a parameter t such that the distance between curve[t] and targetPoint is minimal /// and t belongs to the closed segment [low,high] /// </summary> /// <param name="targetPoint">the point to find the closest point</param> /// <param name="high">the upper bound of the parameter</param> /// <param name="low">the low bound of the parameter</param> /// <returns></returns> public double ClosestParameterWithinBounds(Point targetPoint, double low, double high) { const int numberOfTestPoints = 8; double t = (high - low) / (numberOfTestPoints + 1); double closest = low; double minDist = Double.MaxValue; for (int i = 0; i <= numberOfTestPoints; i++) { double par = low + i * t; Point p = targetPoint - this[par]; double d = p * p; if (d < minDist) { minDist = d; closest = par; } } if (closest == 0 && high == Math.PI*2) low = -Math.PI; double ret = ClosestPointOnCurve.ClosestPoint(this, targetPoint, closest, low, high); if (ret < 0) ret += 2 * Math.PI; return ret; } /// <summary> /// return length of the curve segment [start,end] : not implemented /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public double LengthPartial(double start, double end) { return Curve.LengthWithInterpolationAndThreshold(Trim(start, end), Curve.LineSegmentThreshold/100); } /// <summary> /// Return the length of the ellipse curve: not implemented /// </summary> public double Length{ get { return Curve.LengthWithInterpolation(this); } } /// <summary> /// clones the curve. /// </summary> /// <returns>the cloned curve</returns> public ICurve Clone(){ return new Ellipse(parStart, parEnd, aAxis, bAxis, center); } #region ICurve Members /// <summary> /// returns a parameter t such that the distance between curve[t] and a is minimal /// </summary> /// <param name="targetPoint"></param> /// <returns>the parameter of the closest point</returns> public double ClosestParameter(Point targetPoint){ double savedParStart = 0; const int numberOfTestPoints = 8; double t = (ParEnd - ParStart)/(numberOfTestPoints + 1); double closest = ParStart; double minDist = Double.MaxValue; for (int i = 0; i <= numberOfTestPoints; i++){ double par = ParStart + i*t; Point p = targetPoint - this[par]; double d = p*p; if(d < minDist){ minDist = d; closest = par; } } bool parStartWasChanged = false; if(closest == 0 && ParEnd == Math.PI*2){ parStartWasChanged = true; savedParStart = ParStart; ParStart = -Math.PI; } double ret = ClosestPointOnCurve.ClosestPoint(this, targetPoint, closest, ParStart, ParEnd); if(ret<0) ret += 2*Math.PI; if (parStartWasChanged) ParStart = savedParStart; return ret; } /// <summary> /// left derivative at t /// </summary> /// <param name="t">the parameter where the derivative is calculated</param> /// <returns></returns> public Point LeftDerivative(double t){ return Derivative(t); } /// <summary> /// right derivative at t /// </summary> /// <param name="t">the parameter where the derivative is calculated</param> /// <returns></returns> public Point RightDerivative(double t){ return Derivative(t); } #endregion #region ICurve Members /// <summary> /// /// </summary> /// <param name="t"></param> /// <returns></returns> public double Curvature(double t){ throw new NotImplementedException(); } /// <summary> /// /// </summary> /// <param name="t"></param> /// <returns></returns> public double CurvatureDerivative(double t){ throw new NotImplementedException(); } /// <summary> /// /// </summary> /// <param name="t"></param> /// <returns></returns> public double CurvatureSecondDerivative(double t){ throw new NotImplementedException(); } #endregion /// <summary> /// returns true if the ellipse goes counterclockwise /// </summary> /// <returns></returns> public bool OrientedCounterclockwise(){ return AxisA.X*AxisB.Y - AxisB.X*AxisA.Y > 0; } ///<summary> ///returns the box of the ellipse that this ellipse is a part of ///</summary> ///<returns></returns> public Rectangle FullBox() { var del=AxisA + AxisB; return new Rectangle(center + del, center - del); } ///<summary> ///is it a proper circle? ///</summary> public bool IsArc() { return AxisA.X == AxisB.Y && AxisA.Y == -AxisB.X; } } }
// // Encog(tm) Core v3.3 - .Net Version (unit test) // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Encog.Neural.Networks; using Encog.Util.Simple; using Encog.Neural.Networks.Structure; using Encog.Neural.Flat; using Encog.Util; using Encog.ML.Data.Basic; namespace Encog.Neural.Prune { /// <summary> /// Summary description for TestPruneSelective /// </summary> [TestClass] public class TestPruneSelective { public TestPruneSelective() { // // TODO: Add constructor logic here // } private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // // You can use the following additional attributes as you write your tests: // // Use ClassInitialize to run code before running the first test in the class // [ClassInitialize()] // public static void MyClassInitialize(TestContext testContext) { } // // Use ClassCleanup to run code after all tests in a class have run // [ClassCleanup()] // public static void MyClassCleanup() { } // // Use TestInitialize to run code before running each test // [TestInitialize()] // public void MyTestInitialize() { } // // Use TestCleanup to run code after each test has run // [TestCleanup()] // public void MyTestCleanup() { } // #endregion private BasicNetwork ObtainNetwork() { BasicNetwork network = EncogUtility.SimpleFeedForward(2, 3, 0, 4, false); double[] weights = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }; NetworkCODEC.ArrayToNetwork(weights, network); Assert.AreEqual(1.0, network.GetWeight(1, 0, 0), 0.01); Assert.AreEqual(2.0, network.GetWeight(1, 1, 0), 0.01); Assert.AreEqual(3.0, network.GetWeight(1, 2, 0), 0.01); Assert.AreEqual(4.0, network.GetWeight(1, 3, 0), 0.01); Assert.AreEqual(5.0, network.GetWeight(1, 0, 1), 0.01); Assert.AreEqual(6.0, network.GetWeight(1, 1, 1), 0.01); Assert.AreEqual(7.0, network.GetWeight(1, 2, 1), 0.01); Assert.AreEqual(8.0, network.GetWeight(1, 3, 1), 0.01); Assert.AreEqual(9.0, network.GetWeight(1, 0, 2), 0.01); Assert.AreEqual(10.0, network.GetWeight(1, 1, 2), 0.01); Assert.AreEqual(11.0, network.GetWeight(1, 2, 2), 0.01); Assert.AreEqual(12.0, network.GetWeight(1, 3, 2), 0.01); Assert.AreEqual(13.0, network.GetWeight(1, 0, 3), 0.01); Assert.AreEqual(14.0, network.GetWeight(1, 1, 3), 0.01); Assert.AreEqual(15.0, network.GetWeight(1, 2, 3), 0.01); Assert.AreEqual(16.0, network.GetWeight(1, 3, 3), 0.01); Assert.AreEqual(17.0, network.GetWeight(0, 0, 0), 0.01); Assert.AreEqual(18.0, network.GetWeight(0, 1, 0), 0.01); Assert.AreEqual(19.0, network.GetWeight(0, 2, 0), 0.01); Assert.AreEqual(20.0, network.GetWeight(0, 0, 1), 0.01); Assert.AreEqual(21.0, network.GetWeight(0, 1, 1), 0.01); Assert.AreEqual(22.0, network.GetWeight(0, 2, 1), 0.01); Assert.AreEqual(20.0, network.GetWeight(0, 0, 1), 0.01); Assert.AreEqual(21.0, network.GetWeight(0, 1, 1), 0.01); Assert.AreEqual(22.0, network.GetWeight(0, 2, 1), 0.01); Assert.AreEqual(23.0, network.GetWeight(0, 0, 2), 0.01); Assert.AreEqual(24.0, network.GetWeight(0, 1, 2), 0.01); Assert.AreEqual(25.0, network.GetWeight(0, 2, 2), 0.01); return network; } private void CheckWithModel(FlatNetwork model, FlatNetwork pruned) { Assert.AreEqual(model.Weights.Length, pruned.Weights.Length); Assert.AreEqual(model.ContextTargetOffset, pruned.ContextTargetOffset); Assert.AreEqual(model.ContextTargetSize, pruned.ContextTargetSize); Assert.AreEqual(model.LayerCounts, pruned.LayerCounts); Assert.AreEqual(model.LayerFeedCounts, pruned.LayerFeedCounts); Assert.AreEqual(model.LayerIndex, pruned.LayerIndex); Assert.AreEqual(model.LayerOutput.Length, pruned.LayerOutput.Length); Assert.AreEqual(model.WeightIndex, pruned.WeightIndex); } [TestMethod] public void TestPruneNeuronInput() { BasicNetwork network = ObtainNetwork(); Assert.AreEqual(2, network.InputCount); PruneSelective prune = new PruneSelective(network); prune.Prune(0, 1); Assert.AreEqual(22, network.EncodedArrayLength()); Assert.AreEqual(1, network.GetLayerNeuronCount(0)); Assert.AreEqual("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,19,20,22,23,25", network.DumpWeights()); BasicNetwork model = EncogUtility.SimpleFeedForward(1, 3, 0, 4, false); CheckWithModel(model.Structure.Flat, network.Structure.Flat); Assert.AreEqual(1, network.InputCount); } [TestMethod] public void TestPruneNeuronHidden() { BasicNetwork network = ObtainNetwork(); PruneSelective prune = new PruneSelective(network); prune.Prune(1, 1); Assert.AreEqual(18, network.EncodedArrayLength()); Assert.AreEqual(2, network.GetLayerNeuronCount(1)); Assert.AreEqual("1,3,4,5,7,8,9,11,12,13,15,16,17,18,19,23,24,25", network.DumpWeights()); BasicNetwork model = EncogUtility.SimpleFeedForward(2, 2, 0, 4, false); CheckWithModel(model.Structure.Flat, network.Structure.Flat); } [TestMethod] public void TestPruneNeuronOutput() { BasicNetwork network = ObtainNetwork(); Assert.AreEqual(4, network.OutputCount); PruneSelective prune = new PruneSelective(network); prune.Prune(2, 1); Assert.AreEqual(21, network.EncodedArrayLength()); Assert.AreEqual(3, network.GetLayerNeuronCount(2)); Assert.AreEqual("1,2,3,4,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25", network.DumpWeights()); BasicNetwork model = EncogUtility.SimpleFeedForward(2, 3, 0, 3, false); CheckWithModel(model.Structure.Flat, network.Structure.Flat); Assert.AreEqual(3, network.OutputCount); } [TestMethod] public void TestNeuronSignificance() { BasicNetwork network = ObtainNetwork(); PruneSelective prune = new PruneSelective(network); double inputSig = prune.DetermineNeuronSignificance(0, 1); double hiddenSig = prune.DetermineNeuronSignificance(1, 1); double outputSig = prune.DetermineNeuronSignificance(2, 1); Assert.AreEqual(63.0, inputSig, 0.01); Assert.AreEqual(95.0, hiddenSig, 0.01); Assert.AreEqual(26.0, outputSig, 0.01); } [TestMethod] public void TestIncreaseNeuronCountHidden() { BasicNetwork network = XOR.CreateTrainedXOR(); Assert.IsTrue(XOR.VerifyXOR(network, 0.10)); PruneSelective prune = new PruneSelective(network); prune.ChangeNeuronCount(1, 5); BasicNetwork model = EncogUtility.SimpleFeedForward(2, 5, 0, 1, false); CheckWithModel(model.Structure.Flat, network.Structure.Flat); Assert.IsTrue(XOR.VerifyXOR(network, 0.10)); } [TestMethod] public void TestIncreaseNeuronCountHidden2() { BasicNetwork network = EncogUtility.SimpleFeedForward(5, 6, 0, 2, true); PruneSelective prune = new PruneSelective(network); prune.ChangeNeuronCount(1, 60); BasicMLData input = new BasicMLData(5); BasicNetwork model = EncogUtility.SimpleFeedForward(5, 60, 0, 2, true); CheckWithModel(model.Structure.Flat, network.Structure.Flat); model.Compute(input); network.Compute(input); } [TestMethod] public void TestRandomizeNeuronInput() { double[] d = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; BasicNetwork network = EncogUtility.SimpleFeedForward(2, 3, 0, 1, false); NetworkCODEC.ArrayToNetwork(d, network); PruneSelective prune = new PruneSelective(network); prune.RandomizeNeuron(100, 100, 0, 1); Assert.AreEqual("0,0,0,0,0,100,0,0,100,0,0,100,0", network.DumpWeights()); } [TestMethod] public void TestRandomizeNeuronHidden() { double[] d = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; BasicNetwork network = EncogUtility.SimpleFeedForward(2, 3, 0, 1, false); NetworkCODEC.ArrayToNetwork(d, network); PruneSelective prune = new PruneSelective(network); prune.RandomizeNeuron(100, 100, 1, 1); Assert.AreEqual("0,100,0,0,0,0,0,100,100,100,0,0,0", network.DumpWeights()); } [TestMethod] public void TestRandomizeNeuronOutput() { double[] d = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; BasicNetwork network = EncogUtility.SimpleFeedForward(2, 3, 0, 1, false); NetworkCODEC.ArrayToNetwork(d, network); PruneSelective prune = new PruneSelective(network); prune.RandomizeNeuron(100, 100, 2, 0); Assert.AreEqual("100,100,100,100,0,0,0,0,0,0,0,0,0", network.DumpWeights()); } } }
// 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.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Diagnostics.Contracts; using Microsoft.Research.Cloudot.Common; using Microsoft.Research.CodeAnalysis; namespace Microsoft.Research.Cloudot { public class ProcessPool : IDisposable { private const int INITIALPOOLSIZE = 4; #if !TEST static string PathEXE = "C:\\Program Files (x86)\\Microsoft\\Contracts\\Bin\\cccheck.exe"; // TODO:change! #else static string PathEXE = "c:\\cci\\Microsoft.Research\\Clousot\\bin\\Debug\\clousot.exe"; // TODO:change! #endif readonly private Queue<Process> availableWorkers; readonly private List<Process> scheduledWorkers; public ProcessPool(int initialCount = INITIALPOOLSIZE) { Contract.Requires(initialCount >= 0); this.availableWorkers = new Queue<Process>(); this.scheduledWorkers = new List<Process>(); CreateProcessesAndPopulateTheQueue(initialCount); } private void CreateProcessesAndPopulateTheQueue(int initialCount = INITIALPOOLSIZE) { Contract.Requires(initialCount >= 0); lock (this.availableWorkers) { CloudotLogging.WriteLine("Creating {0} workers", initialCount); for (var i = 0; i < initialCount; i++) { var processInfo = SetupProcessInfoToWait(); try { var exe = Process.Start(processInfo); if (exe != null) { this.availableWorkers.Enqueue(exe); } else { CloudotLogging.WriteLine("Failed to create the Clousot process"); } } catch { CloudotLogging.WriteLine("Error in starting the Clousot/cccheck process for the pool"); } } } } public Process GetAProcessFromTheQueue() { lock (this.availableWorkers) { if (this.availableWorkers.Count == 0) { // TODO: This should happen after the dequeue and asyncronously CreateProcessesAndPopulateTheQueue(); } // Get a worker from the worker queue var exe = this.availableWorkers.Dequeue(); // It may be the case the exe was killed somehow if(exe.HasExited) { return GetAProcessFromTheQueue(); } // remember we used this worker this.scheduledWorkers.Add(exe); return exe; } } static private ProcessStartInfo SetupProcessInfo(int whichHalf, ProcessStartInfo processInfo, string[] args) { Contract.Requires(processInfo != null); Contract.Requires(args != null); string half; switch (whichHalf) { case 1: case 2: half = string.Format(" -splitanalysis {0} -usecallgraph=false", whichHalf); break; default: half = ""; break; } processInfo.FileName = PathEXE; processInfo.CreateNoWindow = false; processInfo.UseShellExecute = false; processInfo.WindowStyle = ProcessWindowStyle.Hidden; processInfo.RedirectStandardOutput = true; processInfo.RedirectStandardError = true; processInfo.Arguments = string.Join(" ", args) + half + " " + StringConstants.DoNotUseCloudot; // We use the convention that +cloudot means we should not use the service return processInfo; } static private ProcessStartInfo SetupProcessInfoToWait() { Contract.Ensures(Contract.Result<ProcessStartInfo>() != null); var processInfo = new ProcessStartInfo(); processInfo.FileName = PathEXE; processInfo.CreateNoWindow = false; processInfo.UseShellExecute = false; processInfo.WindowStyle = ProcessWindowStyle.Hidden; processInfo.RedirectStandardOutput = true; processInfo.RedirectStandardError = true; processInfo.Arguments = StringConstants.ClousotWait; // We use the convention that +cloudot means we should not use the service return processInfo; } #region Clean up code for the childs ~ProcessPool() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool Disposing) { // We want to make sure there are no zombie processes left CloudotLogging.WriteLine("Killing all the workers"); foreach (var exe in this.availableWorkers) { try { if (!exe.HasExited) { exe.Kill(); } } catch(Exception e) { CloudotLogging.WriteLine("[Debug] Exception raised while trying to kill the idle process {0} -- We just continue as it means that the OS has already removed the process", exe.Id); CloudotLogging.WriteLine("[Debug] Exception {0}", e); } } foreach (var exe in this.scheduledWorkers) { try { if(!exe.HasExited) { exe.Kill(); } } catch(Exception e) { CloudotLogging.WriteLine("Exception {0} raised while trying to kill an active process -- We just continue as it means that the process was already terminated", e.GetType()); } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Build.Framework; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Microsoft.DotNet.Build.Tasks { /// <summary> /// This task prepares the command line parameters for running a RPM build using FPM tool and also updates the copyright and changelog file tokens. /// If parses various values from the config json by first reading it into a model and then builds the required string for parameters and passes it back. /// /// </summary> public class BuildFPMToolPreReqs : BuildTask { [Required] public string InputDir { get; set; } [Required] public string OutputDir { get; set; } [Required] public string PackageVersion { get; set; } [Required] public string ConfigJsonFile { get; set; } [Output] public string FPMParameters { get; set; } public override bool Execute() { try { if (!File.Exists(ConfigJsonFile)) { throw new FileNotFoundException($"Expected file {ConfigJsonFile} was not found."); } // Open the Config Json and read the values into the model TextReader projectFileReader = File.OpenText(ConfigJsonFile); if (projectFileReader != null) { string jsonFileText = projectFileReader.ReadToEnd(); ConfigJson configJson = JsonConvert.DeserializeObject<ConfigJson>(jsonFileText); // Update the Changelog and Copyright files by replacing tokens with values from config json UpdateChangelog(configJson, PackageVersion); UpdateCopyRight(configJson); // Build the full list of parameters FPMParameters = BuildCmdParameters(configJson, PackageVersion); Log.LogMessage(MessageImportance.Normal, "Generated RPM paramters: " + FPMParameters); } else { throw new IOException($"Could not open the file {ConfigJsonFile} for reading."); } } catch (Exception e) { Log.LogErrorFromException(e, true); } return !Log.HasLoggedErrors; } // Update the tokens in the changelog file from the config Json private void UpdateChangelog(ConfigJson configJson, string package_version) { try { string changelogFile = Path.Combine(InputDir, "templates", "changelog"); if (!File.Exists(changelogFile)) { throw new FileNotFoundException($"Expected file {changelogFile} was not found."); } string str = File.ReadAllText(changelogFile); str = str.Replace("{PACKAGE_NAME}", configJson.Package_Name); str = str.Replace("{PACKAGE_VERSION}", package_version); str = str.Replace("{PACKAGE_REVISION}", configJson.Release.Package_Revision); str = str.Replace("{URGENCY}", configJson.Release.Urgency); str = str.Replace("{CHANGELOG_MESSAGE}", configJson.Release.Changelog_Message); str = str.Replace("{MAINTAINER_NAME}", configJson.Maintainer_Name); str = str.Replace("{MAINTAINER_EMAIL}", configJson.Maintainer_Email); // The date format needs to be like Wed May 17 2017 str = str.Replace("{DATE}", DateTime.UtcNow.ToString("ddd MMM dd yyyy")); File.WriteAllText(changelogFile, str); } catch (Exception e) { Log.LogError("Exception while updating the changelog file: " + e.Message); } } private void UpdateCopyRight(ConfigJson configJson) { try { // Update the tokens in the copyright file from the config Json string copyrightFile = Path.Combine(InputDir, "templates", "copyright"); if (!File.Exists(copyrightFile)) { throw new FileNotFoundException($"Expected file {copyrightFile} was not found."); } string str = File.ReadAllText(copyrightFile); str = str.Replace("{COPYRIGHT_TEXT}", configJson.CopyRight); str = str.Replace("{LICENSE_NAME}", configJson.License.Type); str = str.Replace("{LICENSE_NAME}", configJson.License.Type); str = str.Replace("{LICENSE_TEXT}", configJson.License.Full_Text); File.WriteAllText(copyrightFile, str); } catch (Exception e) { Log.LogError("Exception while updating the copyright file: " + e.Message); } } private string BuildCmdParameters(ConfigJson configJson, string package_version) { // Parameter list that needs to be passed to FPM tool: // -s : is the input source type(dir) --Static // -t : is the type of package(rpm) --Static // -n : is for the name of the package --JSON // -v : is the version to give to the package --ARG // -a : architecture --JSON // -d : is for all dependent packages. This can be used multiple times to specify the dependencies of the package. --JSON // --rpm-os : the operating system to target this rpm --Static // --rpm-changelog : the changelog from FILEPATH contents --ARG // --rpm-summary : it is the RPM summary that shows in the Title --JSON // --description : it is the description for the package --JSON // -p : The actual package name (with path) for your package. --ARG+JSON // --conflicts : Other packages/versions this package conflicts with provided as CSV --JSON // --directories : Recursively add directories as being owned by the package. --JSON // --after-install : FILEPATH to the script to be run after install of the package --JSON // --after-remove : FILEPATH to the script to be run after package removal --JSON // --license : the licensing name for the package. This will include the license type in the meta-data for the package, but will not include the associated license file within the package itself. --JSON // --iteration : the iteration to give to the package. This comes from the package_revision --JSON // --url : url for this package. --JSON // --verbose : Set verbose output for FPM tool --Static // <All folder mappings> : Add all the folder mappings for packge_root, docs, man pages --Static var parameters = new List<string>(); parameters.Add("-s dir"); parameters.Add("-t rpm"); parameters.Add(string.Concat("-n ", configJson.Package_Name)); parameters.Add(string.Concat("-v ", package_version)); parameters.Add(string.Concat("-a ", configJson.Control.Architecture)); // Build the list of dependencies as -d <dep1> -d <dep2> if (configJson.Rpm_Dependencies != null) { IEnumerable<RpmDependency> dependencies; switch (configJson.Rpm_Dependencies) { case JArray dependencyArray: dependencies = dependencyArray.ToObject<RpmDependency[]>(); break; case JObject dependencyDictionary: dependencies = dependencyDictionary .ToObject<Dictionary<string, string>>() .Select(pair => new RpmDependency { Package_Name = pair.Key, Package_Version = pair.Value }); break; default: throw new ArgumentException( "Expected 'rpm_dependencies' to be JArray or JObject, but found " + configJson.Rpm_Dependencies.Type); } foreach (RpmDependency rpmdep in dependencies) { string dependency = ""; if (rpmdep.Package_Name != "") { // If no version is specified then the dependency is just the package without >= check if (rpmdep.Package_Version == "") { dependency = rpmdep.Package_Name; } else { dependency = string.Concat(rpmdep.Package_Name, " >= ", rpmdep.Package_Version); } } if (dependency != "") { parameters.Add(string.Concat("-d ", EscapeArg(dependency))); } } } // Build the list of owned directories if (configJson.Directories != null) { foreach (string dir in configJson.Directories) { if (dir != "") { parameters.Add(string.Concat("--directories ", EscapeArg(dir))); } } } parameters.Add("--rpm-os linux"); parameters.Add(string.Concat("--rpm-changelog ", EscapeArg(Path.Combine(InputDir, "templates", "changelog")))); // Changelog File parameters.Add(string.Concat("--rpm-summary ", EscapeArg(configJson.Short_Description))); parameters.Add(string.Concat("--description ", EscapeArg(configJson.Long_Description))); parameters.Add(string.Concat("--maintainer ", EscapeArg(configJson.Maintainer_Name + " <" + configJson.Maintainer_Email + ">"))); parameters.Add(string.Concat("--vendor ", EscapeArg(configJson.Vendor))); parameters.Add(string.Concat("-p ", Path.Combine(OutputDir, configJson.Package_Name + ".rpm"))); if (configJson.Package_Conflicts != null) parameters.Add(string.Concat("--conflicts ", EscapeArg(string.Join(",", configJson.Package_Conflicts)))); if (configJson.After_Install_Source != null) parameters.Add(string.Concat("--after-install ", Path.Combine(InputDir, EscapeArg(configJson.After_Install_Source)))); if (configJson.After_Remove_Source != null) parameters.Add(string.Concat("--after-remove ", Path.Combine(InputDir, EscapeArg(configJson.After_Remove_Source)))); parameters.Add(string.Concat("--license ", EscapeArg(configJson.License.Type))); parameters.Add(string.Concat("--iteration ", configJson.Release.Package_Revision)); parameters.Add(string.Concat("--url ", "\"", EscapeArg(configJson.Homepage), "\"")); parameters.Add("--verbose"); // Map all the payload directories as they need to install on the system if (configJson.Install_Root != null) parameters.Add(string.Concat(Path.Combine(InputDir, "package_root/="), configJson.Install_Root)); // Package Files if (configJson.Install_Man != null) parameters.Add(string.Concat(Path.Combine(InputDir, "docs", "host/="), configJson.Install_Man)); // Man Pages if (configJson.Install_Doc != null) parameters.Add(string.Concat(Path.Combine(InputDir, "templates", "copyright="), configJson.Install_Doc)); // CopyRight File return string.Join(" ", parameters); } private string EscapeArg(string arg) { var sb = new StringBuilder(); bool quoted = ShouldSurroundWithQuotes(arg); if (quoted) sb.Append("\""); for (int i = 0; i < arg.Length; ++i) { var backslashCount = 0; // Consume All Backslashes while (i < arg.Length && arg[i] == '\\') { backslashCount++; i++; } // Escape any backslashes at the end of the arg // This ensures the outside quote is interpreted as // an argument delimiter if (i == arg.Length) { sb.Append('\\', 2 * backslashCount); } // Escape any preceding backslashes and the quote else if (arg[i] == '"') { sb.Append('\\', (2 * backslashCount) + 1); sb.Append('"'); } // Output any consumed backslashes and the character else { sb.Append('\\', backslashCount); sb.Append(arg[i]); } } if (quoted) sb.Append("\""); return sb.ToString(); } private bool ShouldSurroundWithQuotes(string argument) { // Don't quote already quoted strings if (argument.StartsWith("\"", StringComparison.Ordinal) && argument.EndsWith("\"", StringComparison.Ordinal)) { return false; } // Only quote if whitespace exists in the string if (argument.Contains(" ") || argument.Contains("\t") || argument.Contains("\n")) { return true; } return false; } /// <summary> /// Model classes for reading and storing the JSON. /// </summary> private class ConfigJson { public string Maintainer_Name { get; set; } public string Maintainer_Email { get; set; } public string Vendor { get; set; } public string Package_Name { get; set; } public string Install_Root { get; set; } public string Install_Doc { get; set; } public string Install_Man { get; set; } public string Short_Description { get; set; } public string Long_Description { get; set; } public string Homepage { get; set; } public string CopyRight { get; set; } public Release Release { get; set; } public Control Control { get; set; } public License License { get; set; } public JContainer Rpm_Dependencies { get; set; } public List<string> Package_Conflicts { get; set; } public List<string> Directories { get; set; } public string After_Install_Source { get; set; } public string After_Remove_Source { get; set; } } private class Release { public string Package_Version { get; set; } public string Package_Revision { get; set; } public string Urgency { get; set; } public string Changelog_Message { get; set; } } private class Control { public string Priority { get; set; } public string Section { get; set; } public string Architecture { get; set; } } private class License { public string Type { get; set; } public string Full_Text { get; set; } } private class RpmDependency { public string Package_Name { get; set; } public string Package_Version { get; set; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Sql { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for SyncAgentsOperations. /// </summary> public static partial class SyncAgentsOperationsExtensions { /// <summary> /// Gets a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> public static SyncAgent Get(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName) { return operations.GetAsync(resourceGroupName, serverName, syncAgentName).GetAwaiter().GetResult(); } /// <summary> /// Gets a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SyncAgent> GetAsync(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serverName, syncAgentName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> /// <param name='parameters'> /// The requested sync agent resource state. /// </param> public static SyncAgent CreateOrUpdate(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName, SyncAgent parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, serverName, syncAgentName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> /// <param name='parameters'> /// The requested sync agent resource state. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SyncAgent> CreateOrUpdateAsync(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName, SyncAgent parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, syncAgentName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> public static void Delete(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName) { operations.DeleteAsync(resourceGroupName, serverName, syncAgentName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serverName, syncAgentName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Lists sync agents in a server. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> public static IPage<SyncAgent> ListByServer(this ISyncAgentsOperations operations, string resourceGroupName, string serverName) { return operations.ListByServerAsync(resourceGroupName, serverName).GetAwaiter().GetResult(); } /// <summary> /// Lists sync agents in a server. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SyncAgent>> ListByServerAsync(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByServerWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Generates a sync agent key. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> public static SyncAgentKeyProperties GenerateKey(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName) { return operations.GenerateKeyAsync(resourceGroupName, serverName, syncAgentName).GetAwaiter().GetResult(); } /// <summary> /// Generates a sync agent key. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SyncAgentKeyProperties> GenerateKeyAsync(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GenerateKeyWithHttpMessagesAsync(resourceGroupName, serverName, syncAgentName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists databases linked to a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> public static IPage<SyncAgentLinkedDatabase> ListLinkedDatabases(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName) { return operations.ListLinkedDatabasesAsync(resourceGroupName, serverName, syncAgentName).GetAwaiter().GetResult(); } /// <summary> /// Lists databases linked to a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SyncAgentLinkedDatabase>> ListLinkedDatabasesAsync(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListLinkedDatabasesWithHttpMessagesAsync(resourceGroupName, serverName, syncAgentName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> /// <param name='parameters'> /// The requested sync agent resource state. /// </param> public static SyncAgent BeginCreateOrUpdate(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName, SyncAgent parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, syncAgentName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> /// <param name='parameters'> /// The requested sync agent resource state. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SyncAgent> BeginCreateOrUpdateAsync(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName, SyncAgent parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, syncAgentName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> public static void BeginDelete(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName) { operations.BeginDeleteAsync(resourceGroupName, serverName, syncAgentName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server on which the sync agent is hosted. /// </param> /// <param name='syncAgentName'> /// The name of the sync agent. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this ISyncAgentsOperations operations, string resourceGroupName, string serverName, string syncAgentName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, serverName, syncAgentName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Lists sync agents in a server. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<SyncAgent> ListByServerNext(this ISyncAgentsOperations operations, string nextPageLink) { return operations.ListByServerNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists sync agents in a server. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SyncAgent>> ListByServerNextAsync(this ISyncAgentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByServerNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists databases linked to a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<SyncAgentLinkedDatabase> ListLinkedDatabasesNext(this ISyncAgentsOperations operations, string nextPageLink) { return operations.ListLinkedDatabasesNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists databases linked to a sync agent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SyncAgentLinkedDatabase>> ListLinkedDatabasesNextAsync(this ISyncAgentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListLinkedDatabasesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Template10.Common; using Template10.Services.StateService; using Template10.Utils; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Classic = Template10.Services.NavigationService; using CrossPlat = Template10.Portable.Navigation; namespace Template10.Services.NavigationService { public class OldNavigationStrategy : INavigationStrategy { public INavigationService NavigationService { get; } public OldNavigationStrategy(INavigationService navigationService) { NavigationService = navigationService; } private Windows.Foundation.Collections.IPropertySet PageState(Page page) { if (page == null) { throw new ArgumentNullException(nameof(page)); } return NavigationService.Suspension.GetPageState(page.GetType()).Values; } public async Task SetupViewModelAsync(INavigationService service, INavigable viewmodel) { Services.NavigationService.NavigationService.DebugWrite(); if (viewmodel == null) { return; } viewmodel.NavigationService = service; viewmodel.Dispatcher = service.GetDispatcherWrapper(); viewmodel.SessionState = await Services.StateService.SettingsStateContainer.GetStateAsync(StateService.StateTypes.Session); } public async Task NavedFromAsync(object viewmodel, NavigationMode mode, Page sourcePage, Type sourceType, object sourceParameter, Page targetPage, Type targetType, object targetParameter, bool suspending) { Services.NavigationService.NavigationService.DebugWrite(); if (sourcePage == null) { return; } else if (viewmodel == null) { return; } else if (viewmodel is Classic.INavigatedAwareAsync) { await CallClassicOnNavigatedFrom(viewmodel, sourcePage, suspending); } else if (viewmodel is CrossPlat.INavigatedFromAwareAsync) { await CallPortableOnNavigatedFrom(viewmodel, sourcePage, sourceParameter, suspending); } } public async Task NavedToAsync(object viewmodel, NavigationMode mode, Page sourcePage, Type sourceType, object sourceParameter, Page targetPage, Type targetType, object targetParameter) { Services.NavigationService.NavigationService.DebugWrite(); if (targetPage == null) { throw new ArgumentNullException(nameof(targetPage)); } if (mode == NavigationMode.New) { PageState(targetPage).Clear(); } if (viewmodel == null) { return; } else if (viewmodel is Classic.INavigatedAwareAsync) { await CallClassicOnNavigatedTo(viewmodel, mode, targetPage, targetParameter); } else if (viewmodel is CrossPlat.INavigatedToAwareAsync) { await CallPortableOnNavigatedTo(viewmodel, mode, sourceType, sourceParameter, targetPage, targetType, targetParameter); } UpdateBindings(targetPage); } public async Task<bool> NavingFromCancelsAsync(object viewmodel, NavigationMode mode, Page sourcePage, Type sourceType, object sourceParameter, Page targetPage, Type targetType, object targetParameter, bool suspending) { Services.NavigationService.NavigationService.DebugWrite(); if (sourcePage == null) { return false; } else if (viewmodel == null) { return false; } else if (viewmodel is Classic.INavigatingAwareAsync) { var cancel = await CallClassicOnNavigatingFrom(viewmodel, mode, sourcePage, sourceParameter, targetType, targetParameter, suspending); return cancel; } else if (viewmodel is Portable.Navigation.IConfirmNavigationAsync) { var canNavigate = await CallPortableCanNavigateAsync(viewmodel, mode, sourceType, sourceParameter, targetType, targetParameter, suspending); if (!canNavigate) { return true; } await CallPortableNavigatingFromAsync(viewmodel, mode, sourceType, sourceParameter, targetType, targetParameter, suspending); return false; } else { return true; } } private static void UpdateBindings(Page page) { page.InitializeBindings(); page.UpdateBindings(); } private async Task CallClassicOnNavigatedFrom(object viewmodel, Page sourcePage, bool suspending) { var vm = viewmodel as Classic.INavigatedAwareAsync; await vm?.OnNavigatedFromAsync(PageState(sourcePage), suspending); } private async Task CallClassicOnNavigatedTo(object viewmodel, NavigationMode mode, Page targetPage, object targetParameter) { var vm = viewmodel as Classic.INavigatedAwareAsync; await vm?.OnNavigatedToAsync(targetParameter, mode, PageState(targetPage)); } private static async Task<bool> CallClassicOnNavigatingFrom(object viewmodel, NavigationMode mode, Page sourcePage, object sourceParameter, Type targetType, object targetParameter, bool suspending) { var deferral = new DeferralManager(); var navigatingEventArgs = new Classic.NavigatingEventArgs(deferral) { Page = sourcePage, PageType = sourcePage?.GetType(), Parameter = sourceParameter, NavigationMode = mode, TargetPageType = targetType, TargetPageParameter = targetParameter, Suspending = suspending, }; try { var vm = viewmodel as Classic.INavigatingAwareAsync; if (vm != null) { await vm.OnNavigatingFromAsync(navigatingEventArgs); await deferral.WaitForDeferralsAsync(); } } catch (Exception ex) { Debugger.Break(); } return navigatingEventArgs.Cancel; } private async Task CallPortableOnNavigatedFrom(object viewmodel, Page sourcePage, object sourceParameter, bool suspending) { var vm = viewmodel as CrossPlat.INavigatedFromAwareAsync; var parameters = new NavigatedFromParameters(); parameters.Parameter = sourceParameter; parameters.PageState = PageState(sourcePage); parameters.Suspending = suspending; await vm?.OnNavigatedFromAsync(parameters); } private async Task CallPortableOnNavigatedTo(object viewmodel, NavigationMode mode, Type sourceType, object sourceParameter, Page targetPage, Type targetType, object targetParameter) { var parameters = new NavigatedToParameters(); parameters.PageState = PageState(targetPage); parameters.NavigationMode = mode.ToPortableNavigationMode(); parameters.SourceType = sourceType; parameters.SourceParameter = sourceParameter; parameters.TargetType = targetType; parameters.TargetParameter = targetParameter; var vm = viewmodel as CrossPlat.INavigatedToAwareAsync; await vm?.OnNavigatedToAsync(parameters); } private static async Task<bool> CallPortableCanNavigateAsync(object viewmodel, NavigationMode mode, Type sourceType, object sourceParameter, Type targetType, object targetParameter, bool suspending) { var parameters = new ConfirmNavigationParameters { NavigationMode = mode.ToPortableNavigationMode(), SourceType = sourceType, SourceParameter = sourceParameter, TargetType = targetType, TargetParameter = targetParameter, Suspending = suspending, }; var vm = viewmodel as Portable.Navigation.IConfirmNavigationAsync; var canNavigate = await vm?.CanNavigateAsync(parameters); return canNavigate; } private static async Task CallPortableNavigatingFromAsync(object viewmodel, NavigationMode mode, Type sourceType, object sourceParameter, Type targetType, object targetParameter, bool suspending) { var parameters = new NavigatingFromParameters { NavigationMode = mode.ToPortableNavigationMode(), SourceType = sourceType, SourceParameter = sourceParameter, TargetType = targetType, TargetParameter = targetParameter, Suspending = suspending, }; var vm = viewmodel as Portable.Navigation.INavigatingFromAwareAsync; await vm?.OnNavigatingFromAsync(parameters); } } }
using UnityEngine; //using Windows.Kinect; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.IO; using System.Text; /// <summary> /// Avatar controller is the component that transfers the captured user motion to a humanoid model (avatar). /// </summary> [RequireComponent(typeof(Animator))] public class AvatarController : MonoBehaviour { [Tooltip("Index of the player, tracked by this component. 0 means the 1st player, 1 - the 2nd one, 2 - the 3rd one, etc.")] public int playerIndex = 0; [Tooltip("Whether the avatar is facing the player or not.")] public bool mirroredMovement = false; [Tooltip("Whether the avatar is allowed to move vertically or not.")] public bool verticalMovement = false; [Tooltip("Rate at which the avatar will move through the scene.")] public float moveRate = 1f; [Tooltip("Smooth factor used for avatar movements and joint rotations.")] public float smoothFactor = 5f; [Tooltip("Game object this transform is relative to (optional).")] public GameObject offsetNode; [Tooltip("If specified, makes the initial avatar position relative to this camera, to be equal to the player's position relative to the sensor.")] public Camera posRelativeToCamera; // userId of the player [NonSerialized] public Int64 playerId = 0; // The body root node protected Transform bodyRoot; // Variable to hold all them bones. It will initialize the same size as initialRotations. protected Transform[] bones; // Rotations of the bones when the Kinect tracking starts. protected Quaternion[] initialRotations; // Initial position and rotation of the transform protected Vector3 initialPosition; protected Quaternion initialRotation; protected Vector3 offsetNodePos; protected Quaternion offsetNodeRot; protected Vector3 bodyRootPosition; // Calibration Offset Variables for Character Position. protected bool offsetCalibrated = false; protected float xOffset, yOffset, zOffset; //private Quaternion originalRotation; // whether the parent transform obeys physics protected bool isRigidBody = false; // private instance of the KinectManager protected KinectManager kinectManager; // returns the number of bone transforms (array length) public int GetBoneTransformCount() { return bones != null ? bones.Length : 0; } // returns the bone transform by index public Transform GetBoneTransform(int index) { if(index >= 0 && index < bones.Length) { return bones[index]; } return null; } // returns bone index by the joint type public int GetBoneIndexByJoint(KinectInterop.JointType joint, bool bMirrored) { int boneIndex = -1; if(jointMap2boneIndex.ContainsKey(joint)) { boneIndex = !bMirrored ? jointMap2boneIndex[joint] : mirrorJointMap2boneIndex[joint]; } return boneIndex; } // transform caching gives performance boost since Unity calls GetComponent<Transform>() each time you call transform private Transform _transformCache; public new Transform transform { get { if (!_transformCache) _transformCache = base.transform; return _transformCache; } } public void Awake() { // check for double start if(bones != null) return; if(!gameObject.activeInHierarchy) return; // Set model's arms to be in T-pose, if needed SetModelArmsInTpose(); // inits the bones array bones = new Transform[27]; // Initial rotations and directions of the bones. initialRotations = new Quaternion[bones.Length]; // Map bones to the points the Kinect tracks MapBones(); // Get initial bone rotations GetInitialRotations(); // if parent transform uses physics isRigidBody = gameObject.GetComponent<Rigidbody>(); } // Update the avatar each frame. public void UpdateAvatar(Int64 UserID) { if(!gameObject.activeInHierarchy) return; // Get the KinectManager instance if(kinectManager == null) { kinectManager = KinectManager.Instance; } // move the avatar to its Kinect position MoveAvatar(UserID); for (var boneIndex = 0; boneIndex < bones.Length; boneIndex++) { if (!bones[boneIndex]) continue; if(boneIndex2JointMap.ContainsKey(boneIndex)) { KinectInterop.JointType joint = !mirroredMovement ? boneIndex2JointMap[boneIndex] : boneIndex2MirrorJointMap[boneIndex]; TransformBone(UserID, joint, boneIndex, !mirroredMovement); } else if(specIndex2JointMap.ContainsKey(boneIndex)) { // special bones (clavicles) List<KinectInterop.JointType> alJoints = !mirroredMovement ? specIndex2JointMap[boneIndex] : specIndex2MirrorJointMap[boneIndex]; if(alJoints.Count >= 2) { //Debug.Log(alJoints[0].ToString()); Vector3 baseDir = alJoints[0].ToString().EndsWith("Left") ? Vector3.left : Vector3.right; TransformSpecialBone(UserID, alJoints[0], alJoints[1], boneIndex, baseDir, !mirroredMovement); } } } } // Set bones to their initial positions and rotations. public void ResetToInitialPosition() { playerId = 0; if(bones == null) return; // For each bone that was defined, reset to initial position. transform.rotation = Quaternion.identity; for(int pass = 0; pass < 2; pass++) // 2 passes because clavicles are at the end { for(int i = 0; i < bones.Length; i++) { if(bones[i] != null) { bones[i].rotation = initialRotations[i]; } } } // if(bodyRoot != null) // { // bodyRoot.localPosition = Vector3.zero; // bodyRoot.localRotation = Quaternion.identity; // } // Restore the offset's position and rotation if(offsetNode != null) { offsetNode.transform.position = offsetNodePos; offsetNode.transform.rotation = offsetNodeRot; } transform.position = initialPosition; transform.rotation = initialRotation; } // Invoked on the successful calibration of a player. public void SuccessfulCalibration(Int64 userId) { playerId = userId; // reset the models position if(offsetNode != null) { offsetNode.transform.position = offsetNodePos; offsetNode.transform.rotation = offsetNodeRot; } transform.position = initialPosition; transform.rotation = initialRotation; // re-calibrate the position offset offsetCalibrated = false; } // Apply the rotations tracked by kinect to the joints. protected void TransformBone(Int64 userId, KinectInterop.JointType joint, int boneIndex, bool flip) { Transform boneTransform = bones[boneIndex]; if(boneTransform == null || kinectManager == null) return; int iJoint = (int)joint; if(iJoint < 0 || !kinectManager.IsJointTracked(userId, iJoint)) return; // Get Kinect joint orientation Quaternion jointRotation = kinectManager.GetJointOrientation(userId, iJoint, flip); if(jointRotation == Quaternion.identity) return; // Smoothly transition to the new rotation Quaternion newRotation = Kinect2AvatarRot(jointRotation, boneIndex); if(smoothFactor != 0f) boneTransform.rotation = Quaternion.Slerp(boneTransform.rotation, newRotation, smoothFactor * Time.deltaTime); else boneTransform.rotation = newRotation; } // Apply the rotations tracked by kinect to a special joint protected void TransformSpecialBone(Int64 userId, KinectInterop.JointType joint, KinectInterop.JointType jointParent, int boneIndex, Vector3 baseDir, bool flip) { Transform boneTransform = bones[boneIndex]; if(boneTransform == null || kinectManager == null) return; if(!kinectManager.IsJointTracked(userId, (int)joint) || !kinectManager.IsJointTracked(userId, (int)jointParent)) { return; } Vector3 jointDir = kinectManager.GetJointDirection(userId, (int)joint, false, true); Quaternion jointRotation = jointDir != Vector3.zero ? Quaternion.FromToRotation(baseDir, jointDir) : Quaternion.identity; if(!flip) { Vector3 mirroredAngles = jointRotation.eulerAngles; mirroredAngles.y = -mirroredAngles.y; mirroredAngles.z = -mirroredAngles.z; jointRotation = Quaternion.Euler(mirroredAngles); } if(jointRotation != Quaternion.identity) { // Smoothly transition to the new rotation Quaternion newRotation = Kinect2AvatarRot(jointRotation, boneIndex); if(smoothFactor != 0f) boneTransform.rotation = Quaternion.Slerp(boneTransform.rotation, newRotation, smoothFactor * Time.deltaTime); else boneTransform.rotation = newRotation; } } // Moves the avatar in 3D space - pulls the tracked position of the user and applies it to root. protected void MoveAvatar(Int64 UserID) { if(!kinectManager || !kinectManager.IsJointTracked(UserID, (int)KinectInterop.JointType.SpineBase)) return; // Get the position of the body and store it. Vector3 trans = kinectManager.GetUserPosition(UserID); // If this is the first time we're moving the avatar, set the offset. Otherwise ignore it. if (!offsetCalibrated) { offsetCalibrated = true; xOffset = trans.x; // !mirroredMovement ? trans.x * moveRate : -trans.x * moveRate; yOffset = trans.y; // trans.y * moveRate; zOffset = !mirroredMovement ? -trans.z : trans.z; // -trans.z * moveRate; if(posRelativeToCamera) { Vector3 cameraPos = posRelativeToCamera.transform.position; Vector3 bodyRootPos = bodyRoot != null ? bodyRoot.position : transform.position; Vector3 hipCenterPos = bodyRoot != null ? bodyRoot.position : bones[0].position; float yRelToAvatar = 0f; if(verticalMovement) { yRelToAvatar = (trans.y - cameraPos.y) - (hipCenterPos - bodyRootPos).magnitude; } else { yRelToAvatar = bodyRootPos.y - cameraPos.y; } Vector3 relativePos = new Vector3(trans.x, yRelToAvatar, trans.z); Vector3 newBodyRootPos = cameraPos + relativePos; // if(offsetNode != null) // { // newBodyRootPos += offsetNode.transform.position; // } if(bodyRoot != null) { bodyRoot.position = newBodyRootPos; } else { transform.position = newBodyRootPos; } bodyRootPosition = newBodyRootPos; } } // Smoothly transition to the new position Vector3 targetPos = bodyRootPosition + Kinect2AvatarPos(trans, verticalMovement); if(isRigidBody && !verticalMovement) { // workaround for obeying the physics (e.g. gravity falling) targetPos.y = bodyRoot != null ? bodyRoot.position.y : transform.position.y; } if(bodyRoot != null) { bodyRoot.position = smoothFactor != 0f ? Vector3.Lerp(bodyRoot.position, targetPos, smoothFactor * Time.deltaTime) : targetPos; } else { transform.position = smoothFactor != 0f ? Vector3.Lerp(transform.position, targetPos, smoothFactor * Time.deltaTime) : targetPos; } } // Set model's arms to be in T-pose protected void SetModelArmsInTpose() { Vector3 vTposeLeftDir = transform.TransformDirection(Vector3.left); Vector3 vTposeRightDir = transform.TransformDirection(Vector3.right); Animator animator = GetComponent<Animator>(); Transform transLeftUarm = animator.GetBoneTransform(HumanBodyBones.LeftUpperArm); Transform transLeftLarm = animator.GetBoneTransform(HumanBodyBones.LeftLowerArm); Transform transLeftHand = animator.GetBoneTransform(HumanBodyBones.LeftHand); if(transLeftUarm != null && transLeftLarm != null) { Vector3 vUarmLeftDir = transLeftLarm.position - transLeftUarm.position; float fUarmLeftAngle = Vector3.Angle(vUarmLeftDir, vTposeLeftDir); if(Mathf.Abs(fUarmLeftAngle) >= 5f) { Quaternion vFixRotation = Quaternion.FromToRotation(vUarmLeftDir, vTposeLeftDir); transLeftUarm.rotation = vFixRotation * transLeftUarm.rotation; } if(transLeftHand != null) { Vector3 vLarmLeftDir = transLeftHand.position - transLeftLarm.position; float fLarmLeftAngle = Vector3.Angle(vLarmLeftDir, vTposeLeftDir); if(Mathf.Abs(fLarmLeftAngle) >= 5f) { Quaternion vFixRotation = Quaternion.FromToRotation(vLarmLeftDir, vTposeLeftDir); transLeftLarm.rotation = vFixRotation * transLeftLarm.rotation; } } } Transform transRightUarm = animator.GetBoneTransform(HumanBodyBones.RightUpperArm); Transform transRightLarm = animator.GetBoneTransform(HumanBodyBones.RightLowerArm); Transform transRightHand = animator.GetBoneTransform(HumanBodyBones.RightHand); if(transRightUarm != null && transRightLarm != null) { Vector3 vUarmRightDir = transRightLarm.position - transRightUarm.position; float fUarmRightAngle = Vector3.Angle(vUarmRightDir, vTposeRightDir); if(Mathf.Abs(fUarmRightAngle) >= 5f) { Quaternion vFixRotation = Quaternion.FromToRotation(vUarmRightDir, vTposeRightDir); transRightUarm.rotation = vFixRotation * transRightUarm.rotation; } if(transRightHand != null) { Vector3 vLarmRightDir = transRightHand.position - transRightLarm.position; float fLarmRightAngle = Vector3.Angle(vLarmRightDir, vTposeRightDir); if(Mathf.Abs(fLarmRightAngle) >= 5f) { Quaternion vFixRotation = Quaternion.FromToRotation(vLarmRightDir, vTposeRightDir); transRightLarm.rotation = vFixRotation * transRightLarm.rotation; } } } } // If the bones to be mapped have been declared, map that bone to the model. protected virtual void MapBones() { // // make OffsetNode as a parent of model transform. // offsetNode = new GameObject(name + "Ctrl") { layer = transform.gameObject.layer, tag = transform.gameObject.tag }; // offsetNode.transform.position = transform.position; // offsetNode.transform.rotation = transform.rotation; // offsetNode.transform.parent = transform.parent; // // take model transform as body root // transform.parent = offsetNode.transform; // transform.localPosition = Vector3.zero; // transform.localRotation = Quaternion.identity; //bodyRoot = transform; // get bone transforms from the animator component Animator animatorComponent = GetComponent<Animator>(); for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++) { if (!boneIndex2MecanimMap.ContainsKey(boneIndex)) continue; bones[boneIndex] = animatorComponent.GetBoneTransform(boneIndex2MecanimMap[boneIndex]); } } // Capture the initial rotations of the bones protected void GetInitialRotations() { // save the initial rotation if(offsetNode != null) { offsetNodePos = offsetNode.transform.position; offsetNodeRot = offsetNode.transform.rotation; } initialPosition = transform.position; initialRotation = transform.rotation; // if(offsetNode != null) // { // initialRotation = Quaternion.Inverse(offsetNodeRot) * initialRotation; // } transform.rotation = Quaternion.identity; // save the body root initial position if(bodyRoot != null) { bodyRootPosition = bodyRoot.position; } else { bodyRootPosition = transform.position; } if(offsetNode != null) { bodyRootPosition = bodyRootPosition - offsetNodePos; } // save the initial bone rotations for (int i = 0; i < bones.Length; i++) { if (bones[i] != null) { initialRotations[i] = bones[i].rotation; } } // Restore the initial rotation transform.rotation = initialRotation; } // Converts kinect joint rotation to avatar joint rotation, depending on joint initial rotation and offset rotation protected Quaternion Kinect2AvatarRot(Quaternion jointRotation, int boneIndex) { Quaternion newRotation = jointRotation * initialRotations[boneIndex]; //newRotation = initialRotation * newRotation; if(offsetNode != null) { newRotation = offsetNode.transform.rotation * newRotation; } else { newRotation = initialRotation * newRotation; } return newRotation; } // Converts Kinect position to avatar skeleton position, depending on initial position, mirroring and move rate protected Vector3 Kinect2AvatarPos(Vector3 jointPosition, bool bMoveVertically) { float xPos; // if(!mirroredMovement) xPos = (jointPosition.x - xOffset) * moveRate; // else // xPos = (-jointPosition.x - xOffset) * moveRate; float yPos = (jointPosition.y - yOffset) * moveRate; //float zPos = (-jointPosition.z - zOffset) * moveRate; float zPos = !mirroredMovement ? (-jointPosition.z - zOffset) * moveRate : (jointPosition.z - zOffset) * moveRate; Vector3 newPosition = new Vector3(xPos, bMoveVertically ? yPos : 0f, zPos); if(offsetNode != null) { newPosition += offsetNode.transform.position; } return newPosition; } // protected void OnCollisionEnter(Collision col) // { // Debug.Log("Collision entered"); // } // // protected void OnCollisionExit(Collision col) // { // Debug.Log("Collision exited"); // } // dictionaries to speed up bones' processing // the author of the terrific idea for kinect-joints to mecanim-bones mapping // along with its initial implementation, including following dictionary is // Mikhail Korchun ([email protected]). Big thanks to this guy! private readonly Dictionary<int, HumanBodyBones> boneIndex2MecanimMap = new Dictionary<int, HumanBodyBones> { {0, HumanBodyBones.Hips}, {1, HumanBodyBones.Spine}, // {2, HumanBodyBones.Chest}, {3, HumanBodyBones.Neck}, // {4, HumanBodyBones.Head}, {5, HumanBodyBones.LeftUpperArm}, {6, HumanBodyBones.LeftLowerArm}, {7, HumanBodyBones.LeftHand}, {8, HumanBodyBones.LeftIndexProximal}, // {9, HumanBodyBones.LeftIndexIntermediate}, // {10, HumanBodyBones.LeftThumbProximal}, {11, HumanBodyBones.RightUpperArm}, {12, HumanBodyBones.RightLowerArm}, {13, HumanBodyBones.RightHand}, {14, HumanBodyBones.RightIndexProximal}, // {15, HumanBodyBones.RightIndexIntermediate}, // {16, HumanBodyBones.RightThumbProximal}, {17, HumanBodyBones.LeftUpperLeg}, {18, HumanBodyBones.LeftLowerLeg}, {19, HumanBodyBones.LeftFoot}, // {20, HumanBodyBones.LeftToes}, {21, HumanBodyBones.RightUpperLeg}, {22, HumanBodyBones.RightLowerLeg}, {23, HumanBodyBones.RightFoot}, // {24, HumanBodyBones.RightToes}, {25, HumanBodyBones.LeftShoulder}, {26, HumanBodyBones.RightShoulder}, }; protected readonly Dictionary<int, KinectInterop.JointType> boneIndex2JointMap = new Dictionary<int, KinectInterop.JointType> { {0, KinectInterop.JointType.SpineBase}, {1, KinectInterop.JointType.SpineMid}, {2, KinectInterop.JointType.SpineShoulder}, {3, KinectInterop.JointType.Neck}, {4, KinectInterop.JointType.Head}, {5, KinectInterop.JointType.ShoulderLeft}, {6, KinectInterop.JointType.ElbowLeft}, {7, KinectInterop.JointType.WristLeft}, {8, KinectInterop.JointType.HandLeft}, {9, KinectInterop.JointType.HandTipLeft}, {10, KinectInterop.JointType.ThumbLeft}, {11, KinectInterop.JointType.ShoulderRight}, {12, KinectInterop.JointType.ElbowRight}, {13, KinectInterop.JointType.WristRight}, {14, KinectInterop.JointType.HandRight}, {15, KinectInterop.JointType.HandTipRight}, {16, KinectInterop.JointType.ThumbRight}, {17, KinectInterop.JointType.HipLeft}, {18, KinectInterop.JointType.KneeLeft}, {19, KinectInterop.JointType.AnkleLeft}, {20, KinectInterop.JointType.FootLeft}, {21, KinectInterop.JointType.HipRight}, {22, KinectInterop.JointType.KneeRight}, {23, KinectInterop.JointType.AnkleRight}, {24, KinectInterop.JointType.FootRight}, }; protected readonly Dictionary<int, List<KinectInterop.JointType>> specIndex2JointMap = new Dictionary<int, List<KinectInterop.JointType>> { {25, new List<KinectInterop.JointType> {KinectInterop.JointType.ShoulderLeft, KinectInterop.JointType.SpineShoulder} }, {26, new List<KinectInterop.JointType> {KinectInterop.JointType.ShoulderRight, KinectInterop.JointType.SpineShoulder} }, }; protected readonly Dictionary<int, KinectInterop.JointType> boneIndex2MirrorJointMap = new Dictionary<int, KinectInterop.JointType> { {0, KinectInterop.JointType.SpineBase}, {1, KinectInterop.JointType.SpineMid}, {2, KinectInterop.JointType.SpineShoulder}, {3, KinectInterop.JointType.Neck}, {4, KinectInterop.JointType.Head}, {5, KinectInterop.JointType.ShoulderRight}, {6, KinectInterop.JointType.ElbowRight}, {7, KinectInterop.JointType.WristRight}, {8, KinectInterop.JointType.HandRight}, {9, KinectInterop.JointType.HandTipRight}, {10, KinectInterop.JointType.ThumbRight}, {11, KinectInterop.JointType.ShoulderLeft}, {12, KinectInterop.JointType.ElbowLeft}, {13, KinectInterop.JointType.WristLeft}, {14, KinectInterop.JointType.HandLeft}, {15, KinectInterop.JointType.HandTipLeft}, {16, KinectInterop.JointType.ThumbLeft}, {17, KinectInterop.JointType.HipRight}, {18, KinectInterop.JointType.KneeRight}, {19, KinectInterop.JointType.AnkleRight}, {20, KinectInterop.JointType.FootRight}, {21, KinectInterop.JointType.HipLeft}, {22, KinectInterop.JointType.KneeLeft}, {23, KinectInterop.JointType.AnkleLeft}, {24, KinectInterop.JointType.FootLeft}, }; protected readonly Dictionary<int, List<KinectInterop.JointType>> specIndex2MirrorJointMap = new Dictionary<int, List<KinectInterop.JointType>> { {25, new List<KinectInterop.JointType> {KinectInterop.JointType.ShoulderRight, KinectInterop.JointType.SpineShoulder} }, {26, new List<KinectInterop.JointType> {KinectInterop.JointType.ShoulderLeft, KinectInterop.JointType.SpineShoulder} }, }; protected readonly Dictionary<KinectInterop.JointType, int> jointMap2boneIndex = new Dictionary<KinectInterop.JointType, int> { {KinectInterop.JointType.SpineBase, 0}, {KinectInterop.JointType.SpineMid, 1}, {KinectInterop.JointType.SpineShoulder, 2}, {KinectInterop.JointType.Neck, 3}, {KinectInterop.JointType.Head, 4}, {KinectInterop.JointType.ShoulderLeft, 5}, {KinectInterop.JointType.ElbowLeft, 6}, {KinectInterop.JointType.WristLeft, 7}, {KinectInterop.JointType.HandLeft, 8}, {KinectInterop.JointType.HandTipLeft, 9}, {KinectInterop.JointType.ThumbLeft, 10}, {KinectInterop.JointType.ShoulderRight, 11}, {KinectInterop.JointType.ElbowRight, 12}, {KinectInterop.JointType.WristRight, 13}, {KinectInterop.JointType.HandRight, 14}, {KinectInterop.JointType.HandTipRight, 15}, {KinectInterop.JointType.ThumbRight, 16}, {KinectInterop.JointType.HipLeft, 17}, {KinectInterop.JointType.KneeLeft, 18}, {KinectInterop.JointType.AnkleLeft, 19}, {KinectInterop.JointType.FootLeft, 20}, {KinectInterop.JointType.HipRight, 21}, {KinectInterop.JointType.KneeRight, 22}, {KinectInterop.JointType.AnkleRight, 23}, {KinectInterop.JointType.FootRight, 24}, }; protected readonly Dictionary<KinectInterop.JointType, int> mirrorJointMap2boneIndex = new Dictionary<KinectInterop.JointType, int> { {KinectInterop.JointType.SpineBase, 0}, {KinectInterop.JointType.SpineMid, 1}, {KinectInterop.JointType.SpineShoulder, 2}, {KinectInterop.JointType.Neck, 3}, {KinectInterop.JointType.Head, 4}, {KinectInterop.JointType.ShoulderRight, 5}, {KinectInterop.JointType.ElbowRight, 6}, {KinectInterop.JointType.WristRight, 7}, {KinectInterop.JointType.HandRight, 8}, {KinectInterop.JointType.HandTipRight, 9}, {KinectInterop.JointType.ThumbRight, 10}, {KinectInterop.JointType.ShoulderLeft, 11}, {KinectInterop.JointType.ElbowLeft, 12}, {KinectInterop.JointType.WristLeft, 13}, {KinectInterop.JointType.HandLeft, 14}, {KinectInterop.JointType.HandTipLeft, 15}, {KinectInterop.JointType.ThumbLeft, 16}, {KinectInterop.JointType.HipRight, 17}, {KinectInterop.JointType.KneeRight, 18}, {KinectInterop.JointType.AnkleRight, 19}, {KinectInterop.JointType.FootRight, 20}, {KinectInterop.JointType.HipLeft, 21}, {KinectInterop.JointType.KneeLeft, 22}, {KinectInterop.JointType.AnkleLeft, 23}, {KinectInterop.JointType.FootLeft, 24}, }; }
// Copyright (C) 2011-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.Collections.Generic; using System.Diagnostics; namespace OpenGL.Objects.State { /// <summary> /// A set of GraphicsState. /// </summary> /// <remarks> /// <para> /// This class collects <see cref="GraphicsState"/> instances to specify a set of parameters that affect drawing /// operations. Each <see cref="GraphicsState"/> instance is applied, replacing the previous state having the same /// type (<see cref="IGraphicsState.StateIdentifier"/>). /// </para> /// <para> /// Usually rendering operations are ordered by the state they requires, and the order is meant to /// minimize the state changes. The state is applied only if the actually one is different to the one /// to be applied. This operation is performed using Merge method. /// </para> /// </remarks> [DebuggerDisplay("GraphicsStateSet: States={_RenderStates.Count}")] public class GraphicsStateSet { #region Constructors /// <summary> /// Static constructor. /// </summary> static GraphicsStateSet() { int index; index = ViewportState.StateSetIndex; index = PixelAlignmentState.StateSetIndex; index = PrimitiveRestartState.StateSetIndex; index = TransformState.StateSetIndex; index = CullFaceState.StateSetIndex; index = BlendState.StateSetIndex; index = DepthTestState.StateSetIndex; index = PolygonModeState.StateSetIndex; index = PolygonOffsetState.StateSetIndex; index = ShaderUniformState.StateSetIndex; index = LightsState.StateSetIndex; index = MaterialState.StateSetIndex; index = ShadowsState.StateSetIndex; index = WriteMaskState.StateSetIndex; } #endregion #region State Factory /// <summary> /// Factory method for getting the default render state set. /// </summary> /// <returns> /// It returns a GraphicsStateSet representing the default state set. /// </returns> public static GraphicsStateSet GetDefaultSet() { GraphicsStateSet renderStateSet = new GraphicsStateSet(); // Instantiate all context-bound states renderStateSet.DefineState(PixelAlignmentState.DefaultState); renderStateSet.DefineState(TransformState.DefaultState); renderStateSet.DefineState(DepthTestState.DefaultState); renderStateSet.DefineState(BlendState.DefaultState); renderStateSet.DefineState(CullFaceState.DefaultState); renderStateSet.DefineState(PolygonOffsetState.DefaultState); return (renderStateSet); } /// <summary> /// Factory method for getting the current render state set. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> defining the state vector. /// </param> /// <returns> /// It returns a GraphicsStateSet representing the currently active state vector. /// </returns> public static GraphicsStateSet GetCurrentStateSet(GraphicsContext ctx) { if (ctx == null) throw new ArgumentNullException("ctx"); if (ctx.IsCurrent == false) throw new ArgumentException("not current", "ctx"); GraphicsStateSet renderStateSet = new GraphicsStateSet(); // Instantiate all context-bound states renderStateSet.DefineState(new PolygonModeState(ctx)); renderStateSet.DefineState(new BlendState(ctx)); renderStateSet.DefineState(new DepthTestState(ctx)); renderStateSet.DefineState(new CullFaceState(ctx)); //renderStateSet.DefineState(new RenderBufferState(ctx)); //renderStateSet.DefineState(new ViewportState(ctx)); //renderStateSet.DefineState(new TransformState(ctx)); return (renderStateSet); } #endregion #region Set Definition /// <summary> /// Define/override a state. /// </summary> /// <param name="renderState"> /// A <see cref="IGraphicsState"/> that specify how the render state is modified. /// </param> public void DefineState(IGraphicsState renderState) { if (renderState == null) throw new ArgumentNullException("renderState"); if (renderState.StateIndex >= _RenderStates.Length) throw new ArgumentException(renderState.GetType() + " not registered", "renderState"); // Reference the new state, loose the previous one _RenderStates[renderState.StateIndex] = renderState; } /// <summary> /// Undefine a state. /// </summary> /// <param name="stateId"> /// A <see cref="String"/> that identify a specific state to undefine. /// </param> public void UndefineState(int stateIndex) { if (stateIndex >= _RenderStates.Length) throw new ArgumentOutOfRangeException("stateIndex"); // Remove state _RenderStates[stateIndex] = null; } /// <summary> /// Determine whether a specific state is defined in this set. /// </summary> /// <param name="stateId"> /// A <see cref="String"/> that identify a specific state. /// </param> /// <returns> /// It returns a boolean value indicating whether a state is defined in this GraphicsStateSet. /// </returns> public bool IsDefinedState(int stateIndex) { if (stateIndex >= _RenderStates.Length) throw new ArgumentOutOfRangeException("stateIndex"); return (_RenderStates[stateIndex] != null); } /// <summary> /// /// </summary> /// <param name="stateId"></param> /// <returns></returns> public IGraphicsState this[int stateIndex] { get { // Defensive Debug.Assert(stateIndex < _RenderStates.Length); if (stateIndex >= _RenderStates.Length) return (null); return (_RenderStates[stateIndex]); } set { if (value == null) throw new InvalidOperationException("null state not allowed"); DefineState(value); } } /// <summary> /// An enumerable of the states collected by this GraphicsStateSet. /// </summary> public IEnumerable<IGraphicsState> States { get { return (_RenderStates); } } /// <summary> /// The set of GraphicsState. /// </summary> private readonly IGraphicsState[] _RenderStates = new IGraphicsState[GraphicsState.GetStateCount()]; #endregion #region Application public void Create(GraphicsContext ctx, ShaderProgram shaderProgram) { foreach (IGraphicsState state in _RenderStates) if (state != null) state.Create(ctx, shaderProgram); } public void Delete() { foreach (IGraphicsState state in _RenderStates) if (state != null) state.Delete(); } /// <summary> /// Apply the set of GraphicsState collected by this instance. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> defining the state vector. /// </param> public void Apply(GraphicsContext ctx) { Apply(ctx, null); } /// <summary> /// Apply the set of GraphicsState collected by this instance. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> defining the state vector. /// </param> /// <param name="program"> /// A <see cref="ShaderProgram"/> defining the uniform state. This value can be null. /// </param> public void Apply(GraphicsContext ctx, ShaderProgram program) { if (ctx == null) throw new ArgumentNullException("ctx"); // Apply known states foreach (IGraphicsState state in _RenderStates) { if (state == null) continue; // Apply state if: // - the state is context-bound, or // - the state is program-bound and a shader program is currently in use if (state.IsContextBound || (state.IsProgramBound && program != null)) state.Apply(ctx, program); } } #endregion #region Stack Support /// <summary> /// Clone this GraphicsStateSet. /// </summary> /// <returns> /// It returns a deep copy of this GraphicsStateSet. /// </returns> public GraphicsStateSet Push() { GraphicsStateSet clone = new GraphicsStateSet(); foreach (IGraphicsState state in _RenderStates) if (state != null) clone.DefineState(state.Push()); return (clone); } /// <summary> /// Merge this state set with another one. /// </summary> /// <param name="stateSet"> /// A <see cref="GraphicsStateSet"/> to be merged with this GraphicsStateSet. /// </param> /// <remarks> /// <para> /// After a call to this routine, this GraphicsStateSet store the union of the previous information /// and of the information of <paramref name="stateSet"/>. /// </para> /// <para> /// The semantic of the merge result is dependent by each <see cref="IGraphicsState"/> defined in both /// state sets. /// </para> /// <para> /// In the case a kind of GraphicsState is defined only in this GraphicsStateSet, the specific state remains /// unchanged, except when the state is not inheritable; in this case the specific state will be undefined. /// </para> /// <para> /// In the case a kind of GraphicsState is defined only in <paramref name="stateSet"/>, that state will be /// defined equally in this GraphicsStateSet. /// </para> /// <para> /// In the case a kind of GraphicsState is defined by both state sets, the state defined in this GraphicsStateSet /// will be merged with the one defined in <paramref name="stateSet"/>, by calling <see cref="IGraphicsState.Merge"/>. /// </para> /// </remarks> public void Merge(GraphicsStateSet stateSet) { if (stateSet == null) throw new ArgumentNullException("stateSet"); for (int i = 0; i < _RenderStates.Length; i++) { IGraphicsState currentState = _RenderStates[i]; IGraphicsState otherState = stateSet[i]; if (currentState != null && otherState != null) _RenderStates[i].Merge(otherState); else if (currentState == null && otherState != null) _RenderStates[i] = otherState.Push(); } } #endregion } }
using System.Text.RegularExpressions; using System.Diagnostics; using System; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Collections; using System.Drawing; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using WeifenLuo.WinFormsUI; using Microsoft.Win32; using WeifenLuo; using System.ComponentModel; using System.Globalization; using System.Threading; namespace SoftLogik.Win { namespace UI { public partial class SPTextBox { #region Enumerations public enum TextStyleEnum { General, Numeric, Alphabetic, Accounting, EmailAddress, Phone } #endregion #region Members private TextStyleEnum m_enmTextStyle; private string m_strFormatString; private bool m_boolMinusSign; private bool m_boolPeriod; private bool m_boolTrimSpaces; //** Storage for property settings private bool m_boolHighlight; private bool m_boolThousandsSeparator; //** Locale aware keystrokes private string mtDecimal; private string mtMinus; private string mtSeparator; //** String Constants private const string mtLOWER_A = "a"; private const string mtUPPER_A = "A"; private const string mtLOWER_Z = "z"; private const string mtUPPER_Z = "Z"; private const string mtZERO = "0"; private const string mtNINE = "9"; private const string mtDASH = "-"; private const string mtLEFT_PAREN = "("; private const string mtRIGHT_PAREN = ")"; private const string mtSPACE = " "; //** Integer Constants private const int miKEY_BACKSPACE = 8; private const int miKEY_ENTER = 13; //** Flow control and cultural sensitivity private bool mbIgnoreKeystroke = false; private KeyPressed meLastKeystroke; private enum KeyPressed { NumberPadDecimal = 0, SpaceBar = 1, NothingSpecial = 2 } #endregion #region Constructor public SPTextBox() { //--------------------------------------------------------------------------------- // Default settings for boolean properties //--------------------------------------------------------------------------------- m_boolPeriod = true; m_boolHighlight = true; m_boolMinusSign = true; m_boolThousandsSeparator = true; m_boolTrimSpaces = false; //--------------------------------------------------------------------------------- // Set the characters to be used for the locale aware minus sign, thousands // separator and decimal point //--------------------------------------------------------------------------------- CultureInfo ci = new CultureInfo(Thread.CurrentThread.CurrentCulture.ToString()); mtDecimal = ci.NumberFormat.NumberDecimalSeparator; mtSeparator = ci.NumberFormat.NumberGroupSeparator; mtMinus = ci.NumberFormat.NegativeSign; ci = null; } #endregion #region Public Properties [Description("Returns or Sets the Style of Text in the TextBox")]public TextStyleEnum TextStyle { get { return m_enmTextStyle; } set { m_enmTextStyle = value; } } [Description("Returns or Sets the Formatting String of the TextBox")]public string FormatString { get { return m_strFormatString; } set { m_strFormatString = value; } } [Description("Returns or Sets whether or not a minus sign is " + "accepted in the first character position when the" + " TextStyle property is set to Numeric")]public bool MinusSign { get { return m_boolMinusSign; } set { m_boolMinusSign = value; } } [Description("Returns or Sets whether or not a period is " + "accepted in the TextBox when the " + " TextStyle property is set to Numeric")]public bool Period { get { return m_boolPeriod; } set { m_boolPeriod = value; } } [Description("Return or Sets whether or not leading and trailing " + "spaces are removed from the Text when the TextBox loses the focus")]public bool TrimSpaces { get { bool returnValue; returnValue = m_boolTrimSpaces; return returnValue; } set { m_boolTrimSpaces = value; } } [Description("Return or Sets whether or not text in the TextBox " + "is higlighted when the TextBox gets focus")]public bool Highlight { get { return m_boolHighlight; } set { m_boolHighlight = value; } } [Description("")]public bool ThousandsSeparator { get { return m_boolThousandsSeparator; } set { m_boolThousandsSeparator = value; } } #endregion #region SPTextBox Events protected override void OnGotFocus(System.EventArgs e) { base.OnGotFocus(e); SPTextBox with_1 = this; if (m_boolHighlight) { //** Highlight any text and place the cursor at the end of that text with_1.SelectionStart = 0; with_1.SelectionLength = with_1.Text.Length; } else { //** Place the cursor at the end of any text without highlighting with_1.SelectionLength = 0; with_1.SelectionStart = with_1.Text.Length; } } protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e) { base.OnKeyDown(e); //--------------------------------------------------------------------------------- // Detect when the decimal point on the keypad, or the space bar is pressed //--------------------------------------------------------------------------------- switch (e.KeyCode.ToString().ToLower()) { case "decimal": meLastKeystroke = KeyPressed.NumberPadDecimal; break; case "space": meLastKeystroke = KeyPressed.SpaceBar; break; default: meLastKeystroke = KeyPressed.NothingSpecial; break; } } protected override void OnKeypress(System.Windows.Forms.KeyPressEventArgs e) { base.OnKeyPress(e); switch (Strings.Asc(e.KeyChar)) { case miKEY_BACKSPACE: case miKEY_ENTER: break; //Navigation or edit keystroke ... fall through default: //Test all other characters switch (m_enmTextStyle) { case TextStyleEnum.General: break; //All keystrokes are allowed ... fall through case TextStyleEnum.Alphabetic: AllowLettersOnly(e); break; case TextStyleEnum.Numeric: case TextStyleEnum.Accounting: AllowNumbersOnly(e); break; case TextStyleEnum.Phone: AllowPhoneChar(e); break; } break; } } protected override void OnLeave(System.EventArgs e) { base.OnLeave(e); if (m_boolTrimSpaces) { //Remove all leading and trailing spaces from the text this.Text = this.Text.Trim(); } } protected override void OnTextChanged(System.EventArgs e) { base.OnTextChanged(e); FormatText(); } #endregion #region Procedures private void AllowLettersOnly(System.Windows.Forms.KeyPressEventArgs e) { //--------------------------------------------------------------------------------- // Accept a-z, A-Z, and space //--------------------------------------------------------------------------------- // Date Developer Comments // ---------- -------------------- ----------------------------------------------- // 09/12/2005 G Gilbert Original code //--------------------------------------------------------------------------------- System.Windows.Forms.KeyPressEventArgs with_1 = e; if ((with_1.KeyChar >= mtLOWER_A && with_1.KeyChar <= mtLOWER_Z) || (with_1.KeyChar >= mtUPPER_A && with_1.KeyChar <= mtUPPER_Z) || with_1.KeyChar == mtSPACE) { //** The keystroke is allowed ... fall through } else { //** The keystroke is not allowed ... dump it DumpKeystroke(e, true); } } private void AllowNumbersOnly(System.Windows.Forms.KeyPressEventArgs e) { //--------------------------------------------------------------------------------- // Accept 0-9 plus allowed number related special characters (minus sign, decimal // point, thousands separator) //--------------------------------------------------------------------------------- // Date Developer Comments // ---------- -------------------- ----------------------------------------------- // 09/12/2005 G Gilbert Original code // 04/27/2006 G Gilbert Added correct handling of a decimal keystroke // on the number pad when the decimal is // something other than a period; and the // space bar when the thousands separator // is a space //--------------------------------------------------------------------------------- //--------------------------------------------------------------------------------- // If a substitute keystroke was sent below, ignore it //--------------------------------------------------------------------------------- if (mbIgnoreKeystroke) { mbIgnoreKeystroke = false; return; } //--------------------------------------------------------------------------------- // When the decimal point on the number pad is pressed, ensure the keystroke // is interpreted correctly per the region settings. Also ensure that the space // bar can be used for a thousands separator when called for by the region setting. //--------------------------------------------------------------------------------- bool sendChar; string keystroke; //** Default to neither a decimal or the space bar keystroke = e.KeyChar; sendChar = false; //** Override the default with a culturally correct decimal or space switch (meLastKeystroke) { case KeyPressed.NumberPadDecimal: //** Convert the number pad decimal point to the culturally correct //** character keystroke = mtDecimal; sendChar = true; break; case KeyPressed.SpaceBar: //** When the thousands separator is a space, convert the space bar //** character (ASCII 32) to the culturally correct character (ASCII 160) if (Strings.Asc(mtSeparator) == 160) { keystroke = mtSeparator; sendChar = true; } break; } //--------------------------------------------------------------------------------- // Determine whether or not the keystroke can be accepted //--------------------------------------------------------------------------------- bool KeyRejected = false; switch (keystroke) { case mtMinus: if (m_boolMinusSign) { //** The insertion cursor must be at the start of the text if (this.SelectionStart > 0) { //** The minus sign would not be the first character KeyRejected = true; } } else { //** A minus sign is not allowed KeyRejected = true; } break; case mtDecimal: if (m_boolPeriod) { if (this.Text.IndexOf(System.Convert.ToChar(mtDecimal)) > - 1) { //** Only one decimal point is permitted KeyRejected = true; } else { //** This is the first decimal point entered. Check if //** the character is to be changed to the one that //** agrees with the region setting. if (sendChar) { //** Dump the keystroke entered by the user DumpKeystroke(e, false); //** Prevent this Sub from processing the keystroke //** being substituted mbIgnoreKeystroke = true; //** Send the culturally correct substitute character SendKeys.Send(mtDecimal); } } } else { //** A decimal point is not allowed KeyRejected = true; } break; case mtSeparator: if (m_boolThousandsSeparator) { //** Check if the character is to be changed to the one //** that agrees with the region setting if (sendChar) { //** Dump the keystroke entered by the user DumpKeystroke(e, false); //** Prevent this Sub from processing the keystroke //** being substituted mbIgnoreKeystroke = true; //** Send the culturally correct substitute character SendKeys.Send(mtSeparator); } } else { //** Thousands separators are not allowed KeyRejected = true; } break; default: //** Check for numbers if (e.KeyChar < mtZERO || e.KeyChar > mtNINE) { //** The keystroke is not allowed KeyRejected = true; } break; } if (KeyRejected) { //** The keystroke is not allowed ... dump it DumpKeystroke(e, true); } } private void AllowNoSpecialChar(System.Windows.Forms.KeyPressEventArgs e) { //--------------------------------------------------------------------------------- // Accept a-z, A-Z, 0-9, and space //--------------------------------------------------------------------------------- // Date Developer Comments // ---------- -------------------- ----------------------------------------------- // 09/12/2005 G Gilbert Original code //--------------------------------------------------------------------------------- System.Windows.Forms.KeyPressEventArgs with_1 = e; if ((with_1.KeyChar >= mtLOWER_A && with_1.KeyChar <= mtLOWER_Z) || (with_1.KeyChar >= mtUPPER_A && with_1.KeyChar <= mtUPPER_Z) || (with_1.KeyChar >= mtZERO && with_1.KeyChar <= mtNINE) || with_1.KeyChar == mtSPACE) { //** The keystroke is allowed ... fall through } else { //** The keystroke is not allowed ... dump it DumpKeystroke(e, true); } } private void AllowPhoneChar(System.Windows.Forms.KeyPressEventArgs e) { //--------------------------------------------------------------------------------- // Allow 0-9, -, (), and space //--------------------------------------------------------------------------------- // Date Developer Comments // ---------- -------------------- ----------------------------------------------- // 09/12/2005 G Gilbert Original code //--------------------------------------------------------------------------------- System.Windows.Forms.KeyPressEventArgs with_1 = e; if ((with_1.KeyChar >= mtZERO && with_1.KeyChar <= mtNINE) || with_1.KeyChar == mtDASH || with_1.KeyChar == mtLEFT_PAREN || with_1.KeyChar == mtRIGHT_PAREN || with_1.KeyChar == mtSPACE) { //** The keystroke is allowed ... fall through } else { //** The keystroke is not allowed ... dump it DumpKeystroke(e, true); } } private void DumpKeystroke(System.Windows.Forms.KeyPressEventArgs e, bool soundBeep) { e.Handled = true; if (soundBeep) { Interaction.Beep(); } } private void FormatText() { this.Font = new Font(this.Font, FontStyle.Regular); this.ForeColor = SystemColors.ControlText; switch (TextStyle) { case TextStyleEnum.General: this.TextAlign = HorizontalAlignment.Left; break; case TextStyleEnum.Alphabetic: this.TextAlign = HorizontalAlignment.Left; break; case TextStyleEnum.Accounting: this.TextAlign = HorizontalAlignment.Right; this.Text = Strings.Format(this.Text, My.Settings.Default.MoneyFormat); break; case TextStyleEnum.Numeric: break; case TextStyleEnum.Phone: break; case TextStyleEnum.EmailAddress: this.TextAlign = HorizontalAlignment.Left; if (StringSupport.IsValidEmail(this.Text)) { Font newFont = (Font) (this.Font.Clone()); this.Font = new Font(newFont, FontStyle.Underline); this.ForeColor = SystemColors.HotTrack; newFont.Dispose(); } break; default: break; } } #endregion } } }
#region File Description //----------------------------------------------------------------------------- // Level.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using System.Xml.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input.Touch; using Microsoft.Xna.Framework.Graphics; #endregion namespace MemoryMadness { class Level : DrawableGameComponent { public int levelNumber; LinkedList<ButtonColors[]> sequence; LinkedListNode<ButtonColors[]> currentSequenceItem; public LevelState CurrentState; public bool IsActive; /// <summary> /// The amount of moves correctly performed by the user so far /// </summary> public int MovesPerformed { get; set; } // Sequence demonstration delays are multiplied by this each level const float DifficultyFactor = 0.75f; // Define the delay between flashes when the current set of moves is // demonstrated to the player TimeSpan delayFlashOn = TimeSpan.FromSeconds(1); TimeSpan delayFlashOff = TimeSpan.FromSeconds(0.5); // Define the allowed delay between two user inputs TimeSpan delayBetweenInputs = TimeSpan.FromSeconds(5); // Define the delay per move which will be used to calculate the overall time // the player has to input the sample. For example, if this delay is 4 and the // current level has 5 steps, the user will have 20 seconds overall to complete // the level. readonly TimeSpan DelayOverallPerInput = TimeSpan.FromSeconds(4); // The display period for the user's own input (feedback) readonly TimeSpan InputFlashDuration = TimeSpan.FromSeconds(0.75); TimeSpan delayPeriod; TimeSpan inputFlashPeriod; TimeSpan elapsedPatternInput; TimeSpan overallAllowedInputPeriod; bool flashOn; bool drawUserInput; ButtonColors?[] currentTouchSampleColors = new ButtonColors?[4]; // Define spheres covering the various buttons BoundingSphere redShpere; BoundingSphere blueShpere; BoundingSphere greenShpere; BoundingSphere yellowShpere; // Rendering members SpriteBatch spriteBatch; Texture2D buttonsTexture; public Level(Game game, SpriteBatch spriteBatch, int levelNumber, int movesPerformed, Texture2D buttonsTexture) : base(game) { this.levelNumber = levelNumber; this.spriteBatch = spriteBatch; CurrentState = LevelState.NotReady; this.buttonsTexture = buttonsTexture; MovesPerformed = movesPerformed; } public Level(Game game, SpriteBatch spriteBatch, int levelNumber, Texture2D buttonsTexture) : this(game, spriteBatch, levelNumber, 0, buttonsTexture) { } public override void Initialize() { //Update delays to match level difficulty UpdateDelays(); // Define button bounding spheres DefineBoundingSpheres(); // Load sequences for current level from definitions XML LoadLevelSequences(); } /// <summary> /// Load sequences for current level from definitions XML /// </summary> private void LoadLevelSequences() { XDocument doc = XDocument.Load(@"Content\Gameplay\LevelDefinitions.xml"); var definitions = doc.Document.Descendants(XName.Get("Level")); XElement levelDefinition = null; foreach (var definition in definitions) { if (int.Parse( definition.Attribute(XName.Get("Number")).Value) == levelNumber) { levelDefinition = definition; break; } } // Used to skip moves if we are resuming a level mid-play int skipMoves = 0; // If definitions are found, create a sequences if (null != levelDefinition) { sequence = new LinkedList<ButtonColors[]>(); foreach (var pattern in levelDefinition.Descendants(XName.Get("Pattern"))) { if (skipMoves < MovesPerformed) { skipMoves++; continue; } string[] values = pattern.Value.Split(','); ButtonColors[] colors = new ButtonColors[values.Length]; // Add each color to a sequence for (int i = 0; i < values.Length; i++) { colors[i] = (ButtonColors)Enum.Parse( typeof(ButtonColors), values[i], true); } // Add each sequence to the sequence list sequence.AddLast(colors); } if (MovesPerformed == 0) { CurrentState = LevelState.Ready; delayPeriod = TimeSpan.Zero; } else { InitializeUserInputStage(); } } } /// <summary> /// Define button bounding spheres /// </summary> private void DefineBoundingSpheres() { redShpere = new BoundingSphere( new Vector3( Settings.RedButtonPosition.X + Settings.ButtonSize.X / 2, Settings.RedButtonPosition.Y + Settings.ButtonSize.Y / 2, 0), Settings.ButtonSize.X / 2); blueShpere = new BoundingSphere( new Vector3( Settings.BlueButtonPosition.X + Settings.ButtonSize.X / 2, Settings.BlueButtonPosition.Y + Settings.ButtonSize.Y / 2, 0), Settings.ButtonSize.X / 2); greenShpere = new BoundingSphere( new Vector3( Settings.GreenButtonPosition.X + Settings.ButtonSize.X / 2, Settings.GreenButtonPosition.Y + Settings.ButtonSize.Y / 2, 0), Settings.ButtonSize.X / 2); yellowShpere = new BoundingSphere( new Vector3( Settings.YellowButtonPosition.X + Settings.ButtonSize.X / 2, Settings.YellowButtonPosition.Y + Settings.ButtonSize.Y / 2, 0), Settings.ButtonSize.X / 2); } /// <summary> /// Update delays to match level difficulty /// </summary> private void UpdateDelays() { delayFlashOn = TimeSpan.FromTicks( (long)(delayFlashOn.Ticks * Math.Pow(DifficultyFactor, levelNumber - 1))); delayFlashOff = TimeSpan.FromTicks( (long)(delayFlashOff.Ticks * Math.Pow(DifficultyFactor, levelNumber - 1))); } /// <summary> /// Sets various members to allow the user to supply input. /// </summary> private void InitializeUserInputStage() { elapsedPatternInput = TimeSpan.Zero; overallAllowedInputPeriod = TimeSpan.Zero; CurrentState = LevelState.Started; drawUserInput = false; // Calculate total allowed timeout period for the entire level overallAllowedInputPeriod = TimeSpan.FromSeconds( DelayOverallPerInput.TotalSeconds * sequence.Count); } public override void Update(GameTime gameTime) { if (!IsActive) { base.Update(gameTime); return; } switch (CurrentState) { case LevelState.NotReady: // Nothing to update in this state break; case LevelState.Ready: // Wait for a while before demonstrating the level's move set delayPeriod += gameTime.ElapsedGameTime; if (delayPeriod >= delayFlashOn) { // Initiate flashing sequence currentSequenceItem = sequence.First; //TODO #5 CurrentState = LevelState.Flashing; delayPeriod = TimeSpan.Zero; flashOn = true; } break; case LevelState.Flashing: // Display the level's move set. When done, start accepting // user input delayPeriod += gameTime.ElapsedGameTime; if ((delayPeriod >= delayFlashOn) && (flashOn)) { delayPeriod = TimeSpan.Zero; flashOn = false; } if ((delayPeriod >= delayFlashOff) && (!flashOn)) { delayPeriod = TimeSpan.Zero; currentSequenceItem = currentSequenceItem.Next; //TODO #6 flashOn = true; } if (currentSequenceItem == null) { InitializeUserInputStage(); } break; case LevelState.Started: case LevelState.InProcess: delayPeriod += gameTime.ElapsedGameTime; inputFlashPeriod += gameTime.ElapsedGameTime; elapsedPatternInput += gameTime.ElapsedGameTime; if ((delayPeriod >= delayBetweenInputs) || (elapsedPatternInput >= overallAllowedInputPeriod)) { // The user was not quick enough inputFlashPeriod = TimeSpan.Zero; CurrentState = LevelState.Fault; } if (inputFlashPeriod >= InputFlashDuration) { drawUserInput = false; } break; case LevelState.Fault: inputFlashPeriod += gameTime.ElapsedGameTime; if (inputFlashPeriod >= InputFlashDuration) { drawUserInput = false; CurrentState = LevelState.FinishedFail; } break; case LevelState.Success: inputFlashPeriod += gameTime.ElapsedGameTime; if (inputFlashPeriod >= InputFlashDuration) { drawUserInput = false; CurrentState = LevelState.FinishedOk; } break; case LevelState.FinishedOk: // Gameplay screen will advance the level break; case LevelState.FinishedFail: // Gameplay screen will reset the level break; default: break; } base.Update(gameTime); } public override void Draw(GameTime gameTime) { if (IsActive) { spriteBatch.Begin(); Rectangle redButtonRectangle = Settings.RedButtonDim; Rectangle greenButtonRectangle = Settings.GreenButtonDim; Rectangle blueButtonRectangle = Settings.BlueButtonDim; Rectangle yellowButtonRectangle = Settings.YellowButtonDim; // Draw the darkened buttons DrawDarkenedButtons(redButtonRectangle, greenButtonRectangle, blueButtonRectangle, yellowButtonRectangle); switch (CurrentState) { case LevelState.NotReady: case LevelState.Ready: // Nothing extra to draw break; case LevelState.Flashing: if ((currentSequenceItem != null) && (flashOn)) { ButtonColors[] toDraw = currentSequenceItem.Value; DrawLitButtons(toDraw); } break; case LevelState.Started: case LevelState.InProcess: case LevelState.Fault: case LevelState.Success: if (drawUserInput) { List<ButtonColors> toDraw = new List<ButtonColors>(currentTouchSampleColors.Length); foreach (var touchColor in currentTouchSampleColors) { if (touchColor.HasValue) { toDraw.Add(touchColor.Value); } } DrawLitButtons(toDraw.ToArray()); } break; case LevelState.FinishedOk: break; case LevelState.FinishedFail: break; default: break; } spriteBatch.End(); } base.Draw(gameTime); } private void DrawDarkenedButtons(Rectangle redButtonRectangle, Rectangle greenButtonRectangle, Rectangle blueButtonRectangle, Rectangle yellowButtonRectangle) { spriteBatch.Draw(buttonsTexture, Settings.RedButtonPosition, redButtonRectangle, Color.White); spriteBatch.Draw(buttonsTexture, Settings.GreenButtonPosition, greenButtonRectangle, Color.White); spriteBatch.Draw(buttonsTexture, Settings.BlueButtonPosition, blueButtonRectangle, Color.White); spriteBatch.Draw(buttonsTexture, Settings.YellowButtonPosition, yellowButtonRectangle, Color.White); } private void DrawLitButtons(ButtonColors[] toDraw) { Vector2 position = Vector2.Zero; Rectangle rectangle = Rectangle.Empty; for (int i = 0; i < toDraw.Length; i++) { switch (toDraw[i]) { case ButtonColors.Red: position = Settings.RedButtonPosition; rectangle = Settings.RedButtonLit; break; case ButtonColors.Yellow: position = Settings.YellowButtonPosition; rectangle = Settings.YellowButtonLit; break; case ButtonColors.Blue: position = Settings.BlueButtonPosition; rectangle = Settings.BlueButtonLit; break; case ButtonColors.Green: position = Settings.GreenButtonPosition; rectangle = Settings.GreenButtonLit; break; } spriteBatch.Draw(buttonsTexture, position, rectangle, Color.White); } } public void RegisterTouch(List<TouchLocation> touchPoints) { if ((CurrentState == LevelState.Started || CurrentState == LevelState.InProcess)) { ButtonColors[] stepColors = sequence.First.Value; bool validTouchRegistered = false; if (touchPoints.Count > 0) { // Reset current touch sample for (int i = 0; i < Settings.ButtonAmount; i++) { currentTouchSampleColors[i] = null; } // Go over the touch points and populate the current touch sample for (int i = 0; i < touchPoints.Count; i++) { var gestureBox = new BoundingBox( new Vector3(touchPoints[i].Position.X - 5, touchPoints[i].Position.Y - 5, 0), new Vector3(touchPoints[i].Position.X + 10, touchPoints[i].Position.Y + 10, 0)); if (redShpere.Intersects(gestureBox)) { currentTouchSampleColors[i] = ButtonColors.Red; // TODO #1 } else if (yellowShpere.Intersects(gestureBox)) { currentTouchSampleColors[i] = ButtonColors.Yellow; // TODO #2 } else if (blueShpere.Intersects(gestureBox)) { currentTouchSampleColors[i] = ButtonColors.Blue; // TODO #3 } else if (greenShpere.Intersects(gestureBox)) { currentTouchSampleColors[i] = ButtonColors.Green; // TODO #4 } CurrentState = LevelState.InProcess; } List<ButtonColors> colorsHit = new List<ButtonColors>(currentTouchSampleColors.Length); // Check if the user pressed at least one of the colored buttons foreach (var hitColor in currentTouchSampleColors) { if (hitColor.HasValue) { validTouchRegistered = true; colorsHit.Add(hitColor.Value); } } // Find the buttons which the user failed to touch List<ButtonColors> missedColors = new List<ButtonColors>(stepColors.Length); foreach (var stepColor in stepColors) { if (!colorsHit.Contains(stepColor)) { missedColors.Add(stepColor); } } // If the user failed to performe the current move, fail the level // Do nothing if no buttons were touched if (((missedColors.Count > 0) || (touchPoints.Count != stepColors.Length)) && validTouchRegistered) CurrentState = LevelState.Fault; if (validTouchRegistered) { // Show user pressed buttons, reset timeout period // for button flash drawUserInput = true; inputFlashPeriod = TimeSpan.Zero; MovesPerformed++; sequence.Remove(stepColors); if ((sequence.Count == 0) && (CurrentState != LevelState.Fault)) { CurrentState = LevelState.Success; } } } } } } }
// Zlib.cs // ------------------------------------------------------------------ // // Copyright (c) 2009-2011 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // Last Saved: <2011-August-03 19:52:28> // // ------------------------------------------------------------------ // // This module defines classes for ZLIB compression and // decompression. This code is derived from the jzlib implementation of // zlib, but significantly modified. The object model is not the same, // and many of the behaviors are new or different. Nonetheless, in // keeping with the license for jzlib, the copyright to that code is // included below. // // ------------------------------------------------------------------ // // The following notice applies to jzlib: // // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the distribution. // // 3. The names of the authors may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. // // ----------------------------------------------------------------------- // // jzlib is based on zlib-1.1.3. // // The following notice applies to zlib: // // ----------------------------------------------------------------------- // // Copyright (C) 1995-2004 Jean-loup Gailly and Mark Adler // // The ZLIB software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // // Jean-loup Gailly [email protected] // Mark Adler [email protected] // // ----------------------------------------------------------------------- using Interop=System.Runtime.InteropServices; namespace Ionic.Zlib { /// <summary> /// Describes how to flush the current deflate operation. /// </summary> /// <remarks> /// The different FlushType values are useful when using a Deflate in a streaming application. /// </remarks> internal enum FlushType { /// <summary>No flush at all.</summary> None = 0, /// <summary>Closes the current block, but doesn't flush it to /// the output. Used internally only in hypothetical /// scenarios. This was supposed to be removed by Zlib, but it is /// still in use in some edge cases. /// </summary> Partial, /// <summary> /// Use this during compression to specify that all pending output should be /// flushed to the output buffer and the output should be aligned on a byte /// boundary. You might use this in a streaming communication scenario, so that /// the decompressor can get all input data available so far. When using this /// with a ZlibCodec, <c>AvailableBytesIn</c> will be zero after the call if /// enough output space has been provided before the call. Flushing will /// degrade compression and so it should be used only when necessary. /// </summary> Sync, /// <summary> /// Use this during compression to specify that all output should be flushed, as /// with <c>FlushType.Sync</c>, but also, the compression state should be reset /// so that decompression can restart from this point if previous compressed /// data has been damaged or if random access is desired. Using /// <c>FlushType.Full</c> too often can significantly degrade the compression. /// </summary> Full, /// <summary>Signals the end of the compression/decompression stream.</summary> Finish, } /// <summary> /// The compression level to be used when using a DeflateStream or ZlibStream with CompressionMode.Compress. /// </summary> internal enum CompressionLevel { /// <summary> /// None means that the data will be simply stored, with no change at all. /// If you are producing ZIPs for use on Mac OSX, be aware that archives produced with CompressionLevel.None /// cannot be opened with the default zip reader. Use a different CompressionLevel. /// </summary> None= 0, /// <summary> /// Same as None. /// </summary> Level0 = 0, /// <summary> /// The fastest but least effective compression. /// </summary> BestSpeed = 1, /// <summary> /// A synonym for BestSpeed. /// </summary> Level1 = 1, /// <summary> /// A little slower, but better, than level 1. /// </summary> Level2 = 2, /// <summary> /// A little slower, but better, than level 2. /// </summary> Level3 = 3, /// <summary> /// A little slower, but better, than level 3. /// </summary> Level4 = 4, /// <summary> /// A little slower than level 4, but with better compression. /// </summary> Level5 = 5, /// <summary> /// The default compression level, with a good balance of speed and compression efficiency. /// </summary> Default = 6, /// <summary> /// A synonym for Default. /// </summary> Level6 = 6, /// <summary> /// Pretty good compression! /// </summary> Level7 = 7, /// <summary> /// Better compression than Level7! /// </summary> Level8 = 8, /// <summary> /// The "best" compression, where best means greatest reduction in size of the input data stream. /// This is also the slowest compression. /// </summary> BestCompression = 9, /// <summary> /// A synonym for BestCompression. /// </summary> Level9 = 9, } /// <summary> /// Describes options for how the compression algorithm is executed. Different strategies /// work better on different sorts of data. The strategy parameter can affect the compression /// ratio and the speed of compression but not the correctness of the compresssion. /// </summary> internal enum CompressionStrategy { /// <summary> /// The default strategy is probably the best for normal data. /// </summary> Default = 0, /// <summary> /// The <c>Filtered</c> strategy is intended to be used most effectively with data produced by a /// filter or predictor. By this definition, filtered data consists mostly of small /// values with a somewhat random distribution. In this case, the compression algorithm /// is tuned to compress them better. The effect of <c>Filtered</c> is to force more Huffman /// coding and less string matching; it is a half-step between <c>Default</c> and <c>HuffmanOnly</c>. /// </summary> Filtered = 1, /// <summary> /// Using <c>HuffmanOnly</c> will force the compressor to do Huffman encoding only, with no /// string matching. /// </summary> HuffmanOnly = 2, } /// <summary> /// An enum to specify the direction of transcoding - whether to compress or decompress. /// </summary> internal enum CompressionMode { /// <summary> /// Used to specify that the stream should compress the data. /// </summary> Compress= 0, /// <summary> /// Used to specify that the stream should decompress the data. /// </summary> Decompress = 1, } /// <summary> /// A general purpose exception class for exceptions in the Zlib library. /// </summary> #if !PCL [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")] [Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000E")] #endif internal class ZlibException : System.Exception { /// <summary> /// The ZlibException class captures exception information generated /// by the Zlib library. /// </summary> public ZlibException() : base() { } /// <summary> /// This ctor collects a message attached to the exception. /// </summary> /// <param name="s">the message for the exception.</param> public ZlibException(System.String s) : base(s) { } } internal class SharedUtils { /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static int URShift(int number, int bits) { return (int)((uint)number >> bits); } #if NOT /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static long URShift(long number, int bits) { return (long) ((UInt64)number >> bits); } #endif /// <summary> /// Reads a number of characters from the current source TextReader and writes /// the data to the target array at the specified index. /// </summary> /// /// <param name="sourceTextReader">The source TextReader to read from</param> /// <param name="target">Contains the array of characteres read from the source TextReader.</param> /// <param name="start">The starting index of the target array.</param> /// <param name="count">The maximum number of characters to read from the source TextReader.</param> /// /// <returns> /// The number of characters read. The number will be less than or equal to /// count depending on the data available in the source TextReader. Returns -1 /// if the end of the stream is reached. /// </returns> public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count) { // Returns 0 bytes if not enough space in target if (target.Length == 0) return 0; char[] charArray = new char[target.Length]; int bytesRead = sourceTextReader.Read(charArray, start, count); // Returns -1 if EOF if (bytesRead == 0) return -1; for (int index = start; index < start + bytesRead; index++) target[index] = (byte)charArray[index]; return bytesRead; } internal static byte[] ToByteArray(System.String sourceString) { return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString); } internal static char[] ToCharArray(byte[] byteArray) { return System.Text.UTF8Encoding.UTF8.GetChars(byteArray); } } internal static class InternalConstants { internal static readonly int MAX_BITS = 15; internal static readonly int BL_CODES = 19; internal static readonly int D_CODES = 30; internal static readonly int LITERALS = 256; internal static readonly int LENGTH_CODES = 29; internal static readonly int L_CODES = (LITERALS + 1 + LENGTH_CODES); // Bit length codes must not exceed MAX_BL_BITS bits internal static readonly int MAX_BL_BITS = 7; // repeat previous bit length 3-6 times (2 bits of repeat count) internal static readonly int REP_3_6 = 16; // repeat a zero length 3-10 times (3 bits of repeat count) internal static readonly int REPZ_3_10 = 17; // repeat a zero length 11-138 times (7 bits of repeat count) internal static readonly int REPZ_11_138 = 18; } internal sealed class StaticTree { internal static readonly short[] lengthAndLiteralsTreeCodes = new short[] { 12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8, 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8 }; internal static readonly short[] distTreeCodes = new short[] { 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 }; internal static readonly StaticTree Literals; internal static readonly StaticTree Distances; internal static readonly StaticTree BitLengths; internal short[] treeCodes; // static tree or null internal int[] extraBits; // extra bits for each code or null internal int extraBase; // base index for extra_bits internal int elems; // max number of elements in the tree internal int maxLength; // max bit length for the codes private StaticTree(short[] treeCodes, int[] extraBits, int extraBase, int elems, int maxLength) { this.treeCodes = treeCodes; this.extraBits = extraBits; this.extraBase = extraBase; this.elems = elems; this.maxLength = maxLength; } static StaticTree() { Literals = new StaticTree(lengthAndLiteralsTreeCodes, Tree.ExtraLengthBits, InternalConstants.LITERALS + 1, InternalConstants.L_CODES, InternalConstants.MAX_BITS); Distances = new StaticTree(distTreeCodes, Tree.ExtraDistanceBits, 0, InternalConstants.D_CODES, InternalConstants.MAX_BITS); BitLengths = new StaticTree(null, Tree.extra_blbits, 0, InternalConstants.BL_CODES, InternalConstants.MAX_BL_BITS); } } /// <summary> /// Computes an Adler-32 checksum. /// </summary> /// <remarks> /// The Adler checksum is similar to a CRC checksum, but faster to compute, though less /// reliable. It is used in producing RFC1950 compressed streams. The Adler checksum /// is a required part of the "ZLIB" standard. Applications will almost never need to /// use this class directly. /// </remarks> /// /// <exclude/> internal sealed class Adler { // largest prime smaller than 65536 private static readonly uint BASE = 65521; // NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 private static readonly int NMAX = 5552; #pragma warning disable 3001 #pragma warning disable 3002 /// <summary> /// Calculates the Adler32 checksum. /// </summary> /// <remarks> /// <para> /// This is used within ZLIB. You probably don't need to use this directly. /// </para> /// </remarks> /// <example> /// To compute an Adler32 checksum on a byte array: /// <code> /// var adler = Adler.Adler32(0, null, 0, 0); /// adler = Adler.Adler32(adler, buffer, index, length); /// </code> /// </example> public static uint Adler32(uint adler, byte[] buf, int index, int len) { if (buf == null) return 1; uint s1 = (uint) (adler & 0xffff); uint s2 = (uint) ((adler >> 16) & 0xffff); while (len > 0) { int k = len < NMAX ? len : NMAX; len -= k; while (k >= 16) { //s1 += (buf[index++] & 0xff); s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; k -= 16; } if (k != 0) { do { s1 += buf[index++]; s2 += s1; } while (--k != 0); } s1 %= BASE; s2 %= BASE; } return (uint)((s2 << 16) | s1); } #pragma warning restore 3001 #pragma warning restore 3002 } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using OpenMetaverse; using OpenMetaverse.StructuredData; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; namespace Aurora.ScriptEngine.AuroraDotNetEngine.Plugins { public class SensorRepeatPlugin : IScriptPlugin { private const int AGENT = 1; private const int AGENT_BY_USERNAME = 0x10; private const int ACTIVE = 2; private const int PASSIVE = 4; private const int SCRIPTED = 8; private readonly Object SenseLock = new Object(); private readonly object SenseRepeatListLock = new object(); private List<SenseRepeatClass> SenseRepeaters = new List<SenseRepeatClass>(); public ScriptEngine m_ScriptEngine; private double maximumRange = 96.0; private int maximumToReturn = 16; private bool usemaximumRange = true; private bool usemaximumToReturn = true; #region IScriptPlugin Members public void Initialize(ScriptEngine engine) { m_ScriptEngine = engine; maximumRange = engine.Config.GetDouble("SensorMaxRange", 512.0d); usemaximumRange = engine.Config.GetBoolean("UseSensorMaxRange", true); maximumToReturn = engine.Config.GetInt("SensorMaxResults", 32); usemaximumToReturn = engine.Config.GetBoolean("UseSensorMaxResults", true); } public void AddRegion(IScene scene) { } // // SenseRepeater and Sensors // public void RemoveScript(UUID objectID, UUID m_itemID) { // Remove from timer lock (SenseRepeatListLock) { #if (!ISWIN) List<SenseRepeatClass> NewSensors = new List<SenseRepeatClass>(); foreach (SenseRepeatClass ts in SenseRepeaters) { if (ts.objectID != objectID && ts.itemID != m_itemID) NewSensors.Add(ts); } #else List<SenseRepeatClass> NewSensors = SenseRepeaters.Where(ts => ts.objectID != objectID && ts.itemID != m_itemID).ToList(); #endif SenseRepeaters.Clear(); SenseRepeaters = NewSensors; } } public bool Check() { // Nothing to do here? if (SenseRepeaters.Count == 0) return false; lock (SenseRepeatListLock) { // Go through all timers DateTime UniversalTime = DateTime.Now.ToUniversalTime(); #if (!ISWIN) foreach (SenseRepeatClass ts in SenseRepeaters) { if (ts.next.ToUniversalTime() < UniversalTime) { SensorSweep(ts); // set next interval ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval); } } #else foreach (SenseRepeatClass ts in SenseRepeaters.Where(ts => ts.next.ToUniversalTime() < UniversalTime)) { SensorSweep(ts); // set next interval ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval); } #endif } // lock return SenseRepeaters.Count > 0; } public OSD GetSerializationData(UUID itemID, UUID primID) { OSDMap data = new OSDMap(); #if(!ISWIN) lock (SenseRepeatListLock) { foreach (SenseRepeatClass ts in SenseRepeaters) { if (ts.itemID == itemID) { OSDMap map = new OSDMap(); map.Add("Interval", ts.interval); map.Add("Name", ts.name); map.Add("ID", ts.keyID); map.Add("Type", ts.type); map.Add("Range", ts.range); map.Add("Arc", ts.arc); data[itemID.ToString()] = map; } } } #else lock (SenseRepeatListLock) { foreach (OSDMap map in from ts in SenseRepeaters where ts.itemID == itemID select new OSDMap { {"Interval", ts.interval}, {"Name", ts.name}, {"ID", ts.keyID}, {"Type", ts.type}, {"Range", ts.range}, {"Arc", ts.arc} }) { data[itemID.ToString()] = map; } } #endif return data; } public void CreateFromData(UUID itemID, UUID objectID, OSD data) { IScene scene = findPrimsScene(objectID); if (scene == null) return; ISceneChildEntity part = scene.GetSceneObjectPart( objectID); if (part == null) return; OSDMap save = (OSDMap)data; foreach (KeyValuePair<string, OSD> kvp in save) { OSDMap map = (OSDMap)kvp.Value; SenseRepeatClass ts = new SenseRepeatClass { objectID = objectID, itemID = itemID, interval = map["Interval"].AsLong(), name = map["Name"].AsString(), keyID = map["ID"].AsUUID(), type = map["Type"].AsInteger(), range = map["Range"].AsReal(), arc = map["Arc"].AsReal(), host = part }; ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval); lock (SenseRepeatListLock) SenseRepeaters.Add(ts); } //Make sure that the cmd handler thread is running m_ScriptEngine.MaintenanceThread.PokeThreads(UUID.Zero); } public string Name { get { return "SensorRepeat"; } } #endregion public void SetSenseRepeatEvent(UUID objectID, UUID m_itemID, string name, UUID keyID, int type, double range, double arc, double sec, ISceneChildEntity host) { // Always remove first, in case this is a re-set RemoveScript(objectID, m_itemID); if (sec == 0) // Disabling timer return; // Add to timer SenseRepeatClass ts = new SenseRepeatClass { objectID = objectID, itemID = m_itemID, interval = sec, name = name, keyID = keyID, type = type }; if (range > maximumRange && usemaximumRange) ts.range = maximumRange; else ts.range = range; ts.arc = arc; ts.host = host; ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval); lock (SenseRepeatListLock) { SenseRepeaters.Add(ts); } //Make sure that the cmd handler thread is running m_ScriptEngine.MaintenanceThread.PokeThreads(ts.itemID); } public void SenseOnce(UUID objectID, UUID m_itemID, string name, UUID keyID, int type, double range, double arc, ISceneChildEntity host) { // Add to timer SenseRepeatClass ts = new SenseRepeatClass { objectID = objectID, itemID = m_itemID, interval = 0, name = name, keyID = keyID, type = type }; if (range > maximumRange && usemaximumRange) ts.range = maximumRange; else ts.range = range; ts.arc = arc; ts.host = host; SensorSweep(ts); //Make sure that the cmd handler thread is running m_ScriptEngine.MaintenanceThread.PokeThreads(ts.itemID); } private void SensorSweep(SenseRepeatClass ts) { if (ts.host == null) { return; } List<SensedEntity> sensedEntities = new List<SensedEntity>(); // Is the sensor type is AGENT and not SCRIPTED then include agents if ((ts.type & (AGENT | AGENT_BY_USERNAME)) != 0 && (ts.type & SCRIPTED) == 0) { sensedEntities.AddRange(doAgentSensor(ts)); } // If SCRIPTED or PASSIVE or ACTIVE check objects if ((ts.type & SCRIPTED) != 0 || (ts.type & PASSIVE) != 0 || (ts.type & ACTIVE) != 0) { sensedEntities.AddRange(doObjectSensor(ts)); } lock (SenseLock) { if (sensedEntities.Count == 0) { // send a "no_sensor" // Add it to queue m_ScriptEngine.PostScriptEvent(ts.itemID, ts.objectID, new EventParams("no_sensor", new Object[0], new DetectParams[0]), EventPriority.Suspended); } else { // Sort the list to get everything ordered by distance sensedEntities.Sort(); int count = sensedEntities.Count; int idx; List<DetectParams> detected = new List<DetectParams>(); for (idx = 0; idx < count; idx++) { if (ts.host != null && ts.host.ParentEntity != null && ts.host.ParentEntity.Scene != null) { DetectParams detect = new DetectParams { Key = sensedEntities[idx].itemID }; detect.Populate(ts.host.ParentEntity.Scene); detected.Add(detect); if (detected.Count == maximumToReturn && usemaximumToReturn) break; } } if (detected.Count == 0) { // To get here with zero in the list there must have been some sort of problem // like the object being deleted or the avatar leaving to have caused some // difficulty during the Populate above so fire a no_sensor event m_ScriptEngine.PostScriptEvent(ts.itemID, ts.objectID, new EventParams("no_sensor", new Object[0], new DetectParams[0]), EventPriority.Suspended); } else { m_ScriptEngine.PostScriptEvent(ts.itemID, ts.objectID, new EventParams("sensor", new Object[] { new LSL_Types.LSLInteger(detected.Count) }, detected.ToArray()), EventPriority.Suspended); } } } } private List<SensedEntity> doObjectSensor(SenseRepeatClass ts) { List<ISceneEntity> Entities; List<SensedEntity> sensedEntities = new List<SensedEntity>(); ISceneChildEntity SensePoint = ts.host; Vector3 fromRegionPos = SensePoint.AbsolutePosition; // If this is an object sense by key try to get it directly // rather than getting a list to scan through if (ts.keyID != UUID.Zero) { IEntity e = null; ts.host.ParentEntity.Scene.Entities.TryGetValue(ts.keyID, out e); if (e == null || !(e is ISceneEntity)) return sensedEntities; Entities = new List<ISceneEntity> { e as ISceneEntity }; } else { Entities = new List<ISceneEntity>(ts.host.ParentEntity.Scene.Entities.GetEntities(fromRegionPos, (float)ts.range)); } // pre define some things to avoid repeated definitions in the loop body Vector3 toRegionPos; double dis; int objtype; ISceneChildEntity part; float dx; float dy; float dz; Quaternion q = SensePoint.RotationOffset; if (SensePoint.ParentEntity.RootChild.IsAttachment) { // In attachments, the sensor cone always orients with the // avatar rotation. This may include a nonzero elevation if // in mouselook. IScenePresence avatar = ts.host.ParentEntity.Scene.GetScenePresence(SensePoint.ParentEntity.RootChild.AttachedAvatar); q = avatar.Rotation; } LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W); LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r); double mag_fwd = LSL_Types.Vector3.Mag(forward_dir); Vector3 ZeroVector = new Vector3(0, 0, 0); bool nameSearch = !string.IsNullOrEmpty(ts.name); foreach (ISceneEntity ent in Entities) { bool keep = true; if (nameSearch && ent.Name != ts.name) // Wrong name and it is a named search continue; if (ent.IsDeleted) // taken so long to do this it has gone from the scene continue; if (!(ent is ISceneEntity)) // dont bother if it is a pesky avatar continue; toRegionPos = ent.AbsolutePosition; // Calculation is in line for speed dx = toRegionPos.X - fromRegionPos.X; dy = toRegionPos.Y - fromRegionPos.Y; dz = toRegionPos.Z - fromRegionPos.Z; // Weed out those that will not fit in a cube the size of the range // no point calculating if they are within a sphere the size of the range // if they arent even in the cube if (Math.Abs(dx) > ts.range || Math.Abs(dy) > ts.range || Math.Abs(dz) > ts.range) dis = ts.range + 1.0; else dis = Math.Sqrt(dx * dx + dy * dy + dz * dz); if (keep && dis <= ts.range && ts.host.UUID != ent.UUID) { // In Range and not the object containing the script, is it the right Type ? objtype = 0; part = (ent).RootChild; if (part.AttachmentPoint != 0) // Attached so ignore continue; if (part.Inventory.ContainsScripts()) { objtype |= ACTIVE | SCRIPTED; // Scripted and active. It COULD have one hidden ... } else { if (ent.Velocity.Equals(ZeroVector)) { objtype |= PASSIVE; // Passive non-moving } else { objtype |= ACTIVE; // moving so active } } // If any of the objects attributes match any in the requested scan type if (((ts.type & objtype) != 0)) { // Right type too, what about the other params , key and name ? if (ts.arc < Math.PI) { // not omni-directional. Can you see it ? // vec forward_dir = llRot2Fwd(llGetRot()) // vec obj_dir = toRegionPos-fromRegionPos // dot=dot(forward_dir,obj_dir) // mag_fwd = mag(forward_dir) // mag_obj = mag(obj_dir) // ang = acos(dot /(mag_fwd*mag_obj)) double ang_obj = 0; try { Vector3 diff = toRegionPos - fromRegionPos; LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3(diff.X, diff.Y, diff.Z); double dot = LSL_Types.Vector3.Dot(forward_dir, obj_dir); double mag_obj = LSL_Types.Vector3.Mag(obj_dir); ang_obj = Math.Acos(dot / (mag_fwd * mag_obj)); } catch { } if (ang_obj > ts.arc) keep = false; } if (keep) { // add distance for sorting purposes later sensedEntities.Add(new SensedEntity(dis, ent.UUID)); } } } } return sensedEntities; } private List<SensedEntity> doAgentSensor(SenseRepeatClass ts) { List<SensedEntity> sensedEntities = new List<SensedEntity>(); // If nobody about quit fast IEntityCountModule entityCountModule = ts.host.ParentEntity.Scene.RequestModuleInterface<IEntityCountModule>(); if (entityCountModule != null && entityCountModule.RootAgents == 0) return sensedEntities; ISceneChildEntity SensePoint = ts.host; Vector3 fromRegionPos = SensePoint.AbsolutePosition; Quaternion q = SensePoint.RotationOffset; LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W); LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r); double mag_fwd = LSL_Types.Vector3.Mag(forward_dir); bool attached = (SensePoint.AttachmentPoint != 0); Vector3 toRegionPos; double dis; Action<IScenePresence> senseEntity = delegate(IScenePresence presence) { if (presence.IsDeleted || presence.IsChildAgent || presence.GodLevel > 0.0) return; // if the object the script is in is attached and the avatar is the owner // then this one is not wanted if (attached && presence.UUID == SensePoint.OwnerID) return; toRegionPos = presence.AbsolutePosition; dis = Math.Abs(Util.GetDistanceTo(toRegionPos, fromRegionPos)); // are they in range if (dis <= ts.range) { // Are they in the required angle of view if (ts.arc < Math.PI) { // not omni-directional. Can you see it ? // vec forward_dir = llRot2Fwd(llGetRot()) // vec obj_dir = toRegionPos-fromRegionPos // dot=dot(forward_dir,obj_dir) // mag_fwd = mag(forward_dir) // mag_obj = mag(obj_dir) // ang = acos(dot /(mag_fwd*mag_obj)) double ang_obj = 0; try { Vector3 diff = toRegionPos - fromRegionPos; LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3(diff.X, diff.Y, diff.Z); double dot = LSL_Types.Vector3.Dot(forward_dir, obj_dir); double mag_obj = LSL_Types.Vector3.Mag(obj_dir); ang_obj = Math.Acos(dot / (mag_fwd * mag_obj)); } catch { } if (ang_obj <= ts.arc) { sensedEntities.Add(new SensedEntity(dis, presence.UUID)); } } else { sensedEntities.Add(new SensedEntity(dis, presence.UUID)); } } }; // If this is an avatar sense by key try to get them directly // rather than getting a list to scan through if (ts.keyID != UUID.Zero) { IScenePresence sp; // Try direct lookup by UUID if (!ts.host.ParentEntity.Scene.TryGetScenePresence(ts.keyID, out sp)) return sensedEntities; senseEntity(sp); } else if (!string.IsNullOrEmpty(ts.name)) { IScenePresence sp; // Try lookup by name will return if/when found if (!ts.host.ParentEntity.Scene.TryGetAvatarByName(ts.name, out sp)) return sensedEntities; if (((ts.type & AGENT) != 0) && ts.host.ParentEntity.Scene.TryGetAvatarByName(ts.name, out sp)) senseEntity(sp); if ((ts.type & AGENT_BY_USERNAME) != 0) { ts.host.ParentEntity.Scene.ForEachScenePresence( delegate(IScenePresence ssp) { if (ssp.Lastname == "Resident") { if (ssp.Firstname.ToLower() == ts.name) senseEntity(ssp); return; } if (ssp.Name.Replace(" ", ".").ToLower() == ts.name) senseEntity(ssp); } ); } } else { ts.host.ParentEntity.Scene.ForEachScenePresence(senseEntity); } return sensedEntities; } public IScene findPrimsScene(UUID objectID) { foreach (IScene s in m_ScriptEngine.Worlds) { ISceneChildEntity part = s.GetSceneObjectPart(objectID); if (part != null) { return s; } } return null; } public IScene findPrimsScene(uint localID) { foreach (IScene s in m_ScriptEngine.Worlds) { ISceneChildEntity part = s.GetSceneObjectPart(localID); if (part != null) { return s; } } return null; } public void Dispose() { } #region Nested type: SenseRepeatClass private class SenseRepeatClass { public double arc; public ISceneChildEntity host; public double interval; public UUID itemID; public UUID keyID; public string name; public DateTime next; public UUID objectID; public double range; public int type; } #endregion // // Sensed entity // #region Nested type: SensedEntity private class SensedEntity : IComparable { public readonly double distance; public readonly UUID itemID; public SensedEntity(double detectedDistance, UUID detectedID) { distance = detectedDistance; itemID = detectedID; } #region IComparable Members public int CompareTo(object obj) { if (!(obj is SensedEntity)) throw new InvalidOperationException(); SensedEntity ent = (SensedEntity)obj; if (ent == null || ent.distance < distance) return 1; if (ent.distance > distance) return -1; return 0; } #endregion } #endregion } }
using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Reflection; namespace Imms.Abstract { /// <summary> /// Parent of all unordered collections containing distinct values, which can efficiently determine membership. /// </summary> /// <typeparam name="TElem"> </typeparam> /// <typeparam name="TSet"> </typeparam> public abstract partial class AbstractSet<TElem, TSet> : AbstractIterable<TElem, TSet, ISetBuilder<TElem, TSet>> where TSet : AbstractSet<TElem, TSet> { /// <summary> /// Returns true if the item is contained in the set. /// </summary> /// <param name="item"></param> /// <returns></returns> public virtual bool Contains(TElem item) { return TryGet(item).IsSome; } /// <summary> /// Returns true if the item is contained in this set. /// </summary> /// <param name="item"></param> /// <returns></returns> public bool this[TElem item] { get { return Contains(item); } } /// <summary> /// Identical to <see cref="Union(IEnumerable{TElem})"/>. /// </summary> /// <param name="items"></param> /// <returns></returns> public TSet AddRange(IEnumerable<TElem> items) { return Union(items); } /// <summary> /// Returns the set-theoretic relation between this set and a sequence of elements. This member is optimized depending on the /// actual type of the input. /// </summary> /// <param name="other">A sequence of values. This operation is much faster if it's a set compatible with this one.</param> /// <returns></returns> public SetRelation RelatesTo(IEnumerable<TElem> other) { other.CheckNotNull("other"); TSet set = other as TSet; if (set != null && IsCompatibleWith(set)) return RelatesTo(set); if (ReferenceEquals(this, other)) return IsEmpty ? SetRelation.Disjoint | SetRelation.Equal : SetRelation.Equal; var total = 0; var intersectSize = other.Count(x => { total += 1; return Contains(x); }); if (IsEmpty) { if (total == 0) return SetRelation.Equal | SetRelation.Disjoint; if (total != 0) return SetRelation.ProperSubsetOf | SetRelation.Disjoint; } else if (total == 0) { return SetRelation.ProperSupersetOf | SetRelation.Disjoint; } if (intersectSize == 0) return SetRelation.Disjoint; var otherContainsThis = intersectSize == Length; var thisContainsOther = intersectSize == total; if (thisContainsOther && otherContainsThis) return SetRelation.Equal; if (thisContainsOther) return SetRelation.ProperSupersetOf; if (otherContainsThis) return SetRelation.ProperSubsetOf; return SetRelation.None; } /// <summary> /// Adds a new item to the set, or does nothing if the item already exists. /// </summary> /// <param name="item">The item to add.</param> /// <returns></returns> public abstract TSet Add(TElem item); /// <summary> /// Removes an item from the set, or does nothing if the item does not exist. /// </summary> /// <param name="item">The item to remove.</param> /// <returns></returns> public abstract TSet Remove(TElem item); /// <summary> /// Returns the instance of the specified element, as it appears in this set, or None if no such instance exists. /// </summary> /// <param name="item"></param> /// <returns></returns> protected abstract Optional<TElem> TryGet(TElem item); /// <summary> /// Returns if this set is set equal to a sequence of elements (using the current set's membership semantics). /// </summary> /// <param name="other">A sequence of values. This operation is much faster if it's a set compatible with this one.</param> /// <returns></returns> public virtual bool SetEquals(IEnumerable<TElem> other) { other.CheckNotNull("other"); var set = other as TSet; if (set != null && IsCompatibleWith(set)) { return set.Length == Length && IsSupersetOf(set); } var guessLength = other.TryGuessLength(); if (guessLength.IsSome && guessLength.Value < Length) { return false; } set = this.ToIterable(other); return set.Length == Length && IsSupersetOf(set); } /// <summary> /// Returns true if this set is a superset of a sequence of elements. Uses the current set's membership semantics. /// </summary> /// <param name="other">A sequence of values. This operation is much faster if it's a set compatible with this one.</param> /// <returns></returns> public bool IsSupersetOf(IEnumerable<TElem> other) { other.CheckNotNull("other"); var set = other as TSet; if (set != null && IsCompatibleWith(set)) { return set.Length <= Length && IsSupersetOf(set); } return other.ForEachWhile(Contains); } /// <summary> /// Returns true if this set is a proper superset of the other set. /// </summary> /// <param name="other">A sequence of values. This operation is much faster if it's a set compatible with this one.</param> /// <returns></returns> public bool IsProperSupersetOf(IEnumerable<TElem> other) { other.CheckNotNull("other"); TSet set = other as TSet; if (set != null && IsCompatibleWith(set)) { return set.Length < Length && IsSupersetOf(set); } set = this.ToIterable(other); return set.Length < Length && IsSupersetOf(set); } /// <summary> /// Returns true if this set is a proper subset of the other set. /// </summary> /// <param name="other">A sequence of values. This operation is much faster if it's a set compatible with this one.</param> /// <returns></returns> public bool IsProperSubsetOf(IEnumerable<TElem> other) { other.CheckNotNull("other"); var set = other as TSet; if (set != null && IsCompatibleWith(set)) { return set.IsProperSupersetOf(this); } var guessLength = other.TryGuessLength(); if (guessLength.IsSome && guessLength.Value <= Length) { return false; } var tSet = this.ToIterable(other); return tSet.IsProperSupersetOf(this); } /// <summary> /// Returns true if this set is a subset of the other set. /// </summary> /// <param name="other">A sequence of values. This operation is much faster if it's a set compatible with this one.</param> /// <returns></returns> public bool IsSubsetOf(IEnumerable<TElem> other) { other.CheckNotNull("other"); TSet set = other as TSet; if (set != null && IsCompatibleWith(set)) { return set.IsSupersetOf(this); } var guessLength = other.TryGuessLength(); if (guessLength.IsSome && guessLength.Value < Length) { return false; } var tSet = this.ToIterable(other); return tSet.IsProperSupersetOf(this); } /// <summary> /// Override this to provide an efficient implementation for the operation. /// </summary> /// <param name="other"></param> /// <returns></returns> protected virtual TSet Difference(TSet other) { other.CheckNotNull("other"); var ex1 = Except(other); var ex2 = other.Except(this); return ex1.Union(ex2); } /// <summary> /// Applies a symmetric difference/XOR between a set, and a set-like collection. /// </summary> /// <param name="other">A sequence of values. This operation is much faster if it's a set compatible with this one.</param> /// <returns></returns> public virtual TSet Difference(IEnumerable<TElem> other) { other.CheckNotNull("other"); if (ReferenceEquals(this, other)) { return Empty; } TSet set = other as TSet; if (set != null && IsCompatibleWith(set)) return Difference(set); set = this.ToIterable(other); return Difference(set); } /// <summary> /// Applies an inverse except operation, essentially other - this. /// </summary> /// <param name="other">A sequence of values. This operation is much faster if it's a set compatible with this one.</param> /// <returns></returns> public TSet ExceptInverse(IEnumerable<TElem> other) { other.CheckNotNull("other"); if (ReferenceEquals(this, other)) return Empty; TSet set = other as TSet; if (set != null && IsCompatibleWith(set)) return set.Except(this); using (var builder = EmptyBuilder) { other.ForEach(item => { if (!Contains(item)) { builder.Add(item); } }); return builder.Produce(); } } /// <summary> /// Checks if this set is compatible with (e.g. same equality semantics) with another set. /// </summary> /// <param name="other"></param> /// <returns></returns> protected abstract bool IsCompatibleWith(TSet other); /// <summary> /// Override this to provide an efficient implementation for the operation. /// </summary> /// <param name="other"></param> /// <returns></returns> protected virtual TSet Except(TSet other) { other.CheckNotNull("other"); return Unchecked_Except(other); } /// <summary> /// Performs the set-theoretic Except operation (non-symmetric difference) with the other collection. /// </summary> /// <param name="other">A sequence of values. This operation is much faster if it's a set compatible with this one.</param> /// <returns></returns> public virtual TSet Except(IEnumerable<TElem> other) { other.CheckNotNull("other"); if (ReferenceEquals(this, other)) return Empty; TSet set = other as TSet; if (set != null && IsCompatibleWith(set)) return Except(set); return Unchecked_Except(other); } TSet Unchecked_Except(IEnumerable<TElem> other) { using (var builder = BuilderFrom(this)) { var len = Length; other.ForEachWhile(x => { if (builder.Remove(x)) { len--; } return len > 0; }); return builder.Produce(); } } /// <summary> /// Applies the set-theoretic Intersect operation. /// </summary> /// <param name="other">A sequence of values. This operation is much faster if it's a set compatible with this one.</param> /// <returns></returns> public virtual TSet Intersect(IEnumerable<TElem> other) { other.CheckNotNull("other"); if (ReferenceEquals(this, other)) return this; TSet set = other as TSet; if (set != null && IsCompatibleWith(set)) return Intersect(set); int total = 0; int len = Length; using (var builder = EmptyBuilder) { other.ForEachWhile(item => { var myKey = TryGet(item); if (myKey.IsSome) { builder.Add(myKey.Value); total++; } return total < len; }); return builder.Produce(); } } /// <summary> /// Override this to provide an efficient implementation for the operation. /// </summary> /// <param name="other"></param> /// <returns></returns> protected virtual TSet Intersect(TSet other) { other.CheckNotNull("other"); using (var builder = EmptyBuilder) { var thisIsShorter = Length <= other.Length; var shorterSet = thisIsShorter ? this : (AbstractSet<TElem, TSet>) other; var longerSet = thisIsShorter ? (AbstractSet<TElem, TSet>) other : this; shorterSet.ForEach(x => { if (thisIsShorter) { if (longerSet.Contains(x)) builder.Add(x); } else { var myKey = shorterSet.TryGet(x); if (myKey.IsSome) { builder.Add(myKey.Value); } } }); return builder.Produce(); } } /// <summary> /// Returns true if this set is disjoint (shares no elements with) 'other'. The empty set is disjoint with all sets. /// </summary> /// <param name="other"></param> /// <returns></returns> public bool IsDisjointWith(IEnumerable<TElem> other) { other.CheckNotNull("other"); if (ReferenceEquals(this, other)) return IsEmpty; TSet set = other as TSet; if (set != null && IsCompatibleWith(set)) return IsDisjointWith(set); return !other.Any(Contains); } /// <summary> /// Override this to provide an efficient implementation for the operation. /// </summary> /// <param name="other"></param> /// <returns></returns> protected virtual bool IsSupersetOf(TSet other) { return other.Length <= Length && other.All(Contains); } /// <summary> /// Override this to provide an efficient implementation for the operation. /// </summary> /// <param name="other"></param> /// <returns></returns> protected virtual bool IsDisjointWith(TSet other) { if (Length < other.Length) return !Any(other.Contains); return !other.Any(Contains); } /// <summary> /// Override this to provide an efficient implementation for the operation. /// </summary> /// <param name="other"></param> /// <returns></returns> protected virtual SetRelation RelatesTo(TSet other) { if (ReferenceEquals(this, other)) return IsEmpty ? SetRelation.Disjoint | SetRelation.Equal : SetRelation.Equal; if (IsEmpty && other.IsEmpty) return SetRelation.Equal | SetRelation.Disjoint; if (IsEmpty && !other.IsEmpty) return SetRelation.ProperSubsetOf | SetRelation.Disjoint; if (!IsEmpty && other.IsEmpty) return SetRelation.ProperSupersetOf | SetRelation.Disjoint; var driver = Length > other.Length ? other : (TSet)this; var checker = driver == this ? other : (TSet)this; var intersectCount = driver.Count(checker.Contains); if (intersectCount == 0) return SetRelation.Disjoint; var otherContainsThis = intersectCount == Length; var thisContainsOther = intersectCount == other.Length; if (otherContainsThis && thisContainsOther) return SetRelation.Equal; if (thisContainsOther) return SetRelation.ProperSupersetOf; if (otherContainsThis) return SetRelation.ProperSubsetOf; return SetRelation.None; } /// <summary> /// Override this to provide an efficient implementation for the operation. /// </summary> /// <param name="other"></param> /// <returns></returns> protected virtual TSet Union(TSet other) { return Union_Unchecked(other); } TSet Union_Unchecked(IEnumerable<TElem> other) { if (ReferenceEquals(this, other)) return this; using (var builder = BuilderFrom(this)) { builder.AddRange(other); return builder.Produce(); } } /// <summary> /// Returns the set-theoretic union between this set and a set-like collection. /// </summary> /// <param name="other">A sequence of values. This operation is much faster if it's a set compatible with this one.</param> /// <returns></returns> public virtual TSet Union(IEnumerable<TElem> other) { other.CheckNotNull("other"); if (ReferenceEquals(other, this)) return this; TSet set = other as TSet; if (set != null && IsCompatibleWith(set)) return Union(set); return Union_Unchecked(other); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Apache.Geode.Client; namespace Apache.Geode.Client.Tests { public class PositionPdx : IPdxSerializable { #region Private members private long m_avg20DaysVol; private string m_bondRating; private double m_convRatio; private string m_country; private double m_delta; private long m_industry; private long m_issuer; private double m_mktValue; private double m_qty; private string m_secId; private string m_secLinks; private string m_secType; private int m_sharesOutstanding; private string m_underlyer; private long m_volatility; private int m_pid; private static int m_count = 0; #endregion #region Private methods private void Init() { m_avg20DaysVol = 0; m_bondRating = null; m_convRatio = 0.0; m_country = null; m_delta = 0.0; m_industry = 0; m_issuer = 0; m_mktValue = 0.0; m_qty = 0.0; m_secId = null; m_secLinks = null; m_secType = null; m_sharesOutstanding = 0; m_underlyer = null; m_volatility = 0; m_pid = 0; } private UInt64 GetObjectSize(ISerializable obj) { return (obj == null ? 0 : obj.ObjectSize); } #endregion #region Public accessors public string secId { get { return m_secId; } } public int Id { get { return m_pid; } } public int getSharesOutstanding { get { return m_sharesOutstanding; } } public static int Count { get { return m_count; } set { m_count = value; } } public override string ToString() { return "Position [secId=" + m_secId + " sharesOutstanding=" + m_sharesOutstanding + " type=" + m_secType + " id=" + m_pid + "]"; } #endregion #region Constructors public PositionPdx() { Init(); } //This ctor is for a data validation test public PositionPdx(Int32 iForExactVal) { Init(); char[] id = new char[iForExactVal + 1]; for (int i = 0; i <= iForExactVal; i++) { id[i] = 'a'; } m_secId = new string(id); m_qty = iForExactVal % 2 == 0 ? 1000 : 100; m_mktValue = m_qty * 2; m_sharesOutstanding = iForExactVal; m_secType = "a"; m_pid = iForExactVal; } public PositionPdx(string id, int shares) { Init(); m_secId = id; m_qty = shares * (m_count % 2 == 0 ? 10.0 : 100.0); m_mktValue = m_qty * 1.2345998; m_sharesOutstanding = shares; m_secType = "a"; m_pid = m_count++; } #endregion public static IPdxSerializable CreateDeserializable() { return new PositionPdx(); } #region IPdxSerializable Members public void FromData(IPdxReader reader) { m_avg20DaysVol = reader.ReadLong("avg20DaysVol"); m_bondRating = reader.ReadString("bondRating"); m_convRatio = reader.ReadDouble("convRatio"); m_country = reader.ReadString("country"); m_delta = reader.ReadDouble("delta"); m_industry = reader.ReadLong("industry"); m_issuer = reader.ReadLong("issuer"); m_mktValue = reader.ReadDouble("mktValue"); m_qty = reader.ReadDouble("qty"); m_secId = reader.ReadString("secId"); m_secLinks = reader.ReadString("secLinks"); m_secType = reader.ReadString("secType"); m_sharesOutstanding = reader.ReadInt("sharesOutstanding"); m_underlyer = reader.ReadString("underlyer"); m_volatility = reader.ReadLong("volatility"); m_pid = reader.ReadInt("pid"); } public void ToData(IPdxWriter writer) { writer.WriteLong("avg20DaysVol", m_avg20DaysVol) .MarkIdentityField("avg20DaysVol") .WriteString("bondRating", m_bondRating) .MarkIdentityField("bondRating") .WriteDouble("convRatio", m_convRatio) .MarkIdentityField("convRatio") .WriteString("country", m_country) .MarkIdentityField("country") .WriteDouble("delta", m_delta) .MarkIdentityField("delta") .WriteLong("industry", m_industry) .MarkIdentityField("industry") .WriteLong("issuer", m_issuer) .MarkIdentityField("issuer") .WriteDouble("mktValue", m_mktValue) .MarkIdentityField("mktValue") .WriteDouble("qty", m_qty) .MarkIdentityField("qty") .WriteString("secId", m_secId) .MarkIdentityField("secId") .WriteString("secLinks", m_secLinks) .MarkIdentityField("secLinks") .WriteString("secType", m_secType) .MarkIdentityField("secType") .WriteInt("sharesOutstanding", m_sharesOutstanding) .MarkIdentityField("sharesOutstanding") .WriteString("underlyer", m_underlyer) .MarkIdentityField("underlyer") .WriteLong("volatility", m_volatility) .MarkIdentityField("volatility") .WriteInt("pid", m_pid) .MarkIdentityField("pid"); //identity field //writer.MarkIdentityField("pid"); } #endregion } }
using System; using System.Linq; using GoogleApi.Entities.Translate.Common.Enums; using GoogleApi.Entities.Translate.Common.Enums.Extensions; using GoogleApi.Entities.Translate.Translate.Request; using GoogleApi.Entities.Translate.Translate.Request.Enums; using NUnit.Framework; namespace GoogleApi.UnitTests.Translate.Translate { [TestFixture] public class TranslateRequestTests { [Test] public void ConstructorDefaultTest() { var request = new TranslateRequest(); Assert.IsNull(request.Source); Assert.IsNull(request.Target); Assert.AreEqual(Model.Base, request.Model); Assert.AreEqual(Format.Html, request.Format); } [Test] public void GetQueryStringParametersTest() { var request = new TranslateRequest { Key = "key", Target = Language.Afrikaans, Qs = new[] { "query" } }; var queryStringParameters = request.GetQueryStringParameters(); Assert.IsNotNull(queryStringParameters); var key = queryStringParameters.FirstOrDefault(x => x.Key == "key"); var keyExpected = request.Key; Assert.IsNotNull(key); Assert.AreEqual(keyExpected, key.Value); var target = queryStringParameters.FirstOrDefault(x => x.Key == "target"); var targetExpected = request.Target.GetValueOrDefault().ToCode(); Assert.IsNotNull(target); Assert.AreEqual(targetExpected, target.Value); var qs = queryStringParameters.FirstOrDefault(x => x.Key == "q"); var qsExpected = request.Qs.FirstOrDefault(); Assert.IsNotNull(qs); Assert.AreEqual(qsExpected, qs.Value); var model = queryStringParameters.FirstOrDefault(x => x.Key == "model"); var modelExpected = request.Model.ToString().ToLower(); Assert.IsNotNull(model); Assert.AreEqual(modelExpected, model.Value); var format = queryStringParameters.FirstOrDefault(x => x.Key == "format"); var formatExpected = request.Format.ToString().ToLower(); Assert.IsNotNull(format); Assert.AreEqual(formatExpected, format.Value); } [Test] public void GetQueryStringParametersWhenKeyIsNullTest() { var request = new TranslateRequest { Key = null }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "'Key' is required"); } [Test] public void GetQueryStringParametersWhenKeyIsStringEmptyTest() { var request = new TranslateRequest { Key = string.Empty }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "'Key' is required"); } [Test] public void GetQueryStringParametersWhenTargetIsNullTest() { var request = new TranslateRequest { Key = "key", Target = null }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "'Target' is required"); } [Test] public void GetQueryStringParametersWhenQsIsNullTest() { var request = new TranslateRequest { Key = "key", Target = Language.Danish, Qs = null }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "'Qs' is required"); } [Test] public void GetQueryStringParametersWhenQsIsEmptyTest() { var request = new TranslateRequest { Key = "key", Target = Language.Danish, Qs = new string[0] }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "'Qs' is required"); } [Test] public void GetQueryStringParametersWhenSourceIsNotValidNmtTest() { var request = new TranslateRequest { Key = "key", Source = Language.Amharic, Target = Language.English, Qs = new[] { "Hej Verden" }, Model = Model.Nmt }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "'Source' is not compatible with model 'Nmt'"); } [Test] public void GetQueryStringParametersWhenTargetIsNotValidNmtTest() { var request = new TranslateRequest { Key = "key", Source = Language.English, Target = Language.Amharic, Qs = new[] { "Hej Verden" }, Model = Model.Nmt }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "'Target' is not compatible with model 'Nmt'"); } [Test] public void GetQueryStringParametersWhenModelIsNmtAndSourceOrTargetIsNotEnglishTest() { var request = new TranslateRequest { Key = "key", Source = Language.Danish, Target = Language.Danish, Model = Model.Nmt, Qs = new[] { "Hej Verden" } }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "'Source' or 'Target' must be english"); } } }
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; /// This is the main GVR audio class that communicates with the native code implementation of /// the audio system. Native functions of the system can only be called through this class to /// preserve the internal system functionality. Public function calls are *not* thread-safe. public static class GvrAudio { /// Audio system rendering quality. public enum Quality { Stereo = 0, ///< Stereo-only rendering Low = 1, ///< Low quality binaural rendering (first-order HRTF) High = 2 ///< High quality binaural rendering (third-order HRTF) } /// Native audio spatializer effect data. public enum SpatializerData { Id = 0, /// ID. Type = 1, /// Spatializer type. NumChannels = 2, /// Number of input channels. ChannelSet = 3, /// Soundfield channel set. Gain = 4, /// Gain. DistanceAttenuation = 5, /// Computed distance attenuation. MinDistance = 6, /// Minimum distance for distance-based attenuation. ZeroOutput = 7, /// Should zero out the output buffer? } /// Native audio spatializer type. public enum SpatializerType { Source = 0, /// 3D sound object. Soundfield = 1 /// First-order ambisonic soundfield. } /// System sampling rate. public static int SampleRate { get { return sampleRate; } } private static int sampleRate = -1; /// System number of output channels. public static int NumChannels { get { return numChannels; } } private static int numChannels = -1; /// System number of frames per buffer. public static int FramesPerBuffer { get { return framesPerBuffer; } } private static int framesPerBuffer = -1; /// Initializes the audio system with the current audio configuration. /// @note This should only be called from the main Unity thread. public static void Initialize (GvrAudioListener listener, Quality quality) { if (!initialized) { // Initialize the audio system. AudioConfiguration config = AudioSettings.GetConfiguration(); sampleRate = config.sampleRate; numChannels = (int)config.speakerMode; framesPerBuffer = config.dspBufferSize; if (numChannels != (int)AudioSpeakerMode.Stereo) { Debug.LogError("Only 'Stereo' speaker mode is supported by GVR Audio."); return; } Initialize(quality, sampleRate, numChannels, framesPerBuffer); listenerTransform = listener.transform; initialized = true; } else if (listener.transform != listenerTransform) { Debug.LogError("Only one GvrAudioListener component is allowed in the scene."); GvrAudioListener.Destroy(listener); } } /// Shuts down the audio system. /// @note This should only be called from the main Unity thread. public static void Shutdown (GvrAudioListener listener) { if (initialized && listener.transform == listenerTransform) { initialized = false; Shutdown(); sampleRate = -1; numChannels = -1; framesPerBuffer = -1; listenerTransform = null; } } /// Updates the audio listener. /// @note This should only be called from the main Unity thread. public static void UpdateAudioListener (float globalGainDb, LayerMask occlusionMask) { if (initialized) { occlusionMaskValue = occlusionMask.value; SetListenerGain(ConvertAmplitudeFromDb(globalGainDb)); } } /// Creates a new first-order ambisonic soundfield with a unique id. /// @note This should only be called from the main Unity thread. public static int CreateAudioSoundfield () { int soundfieldId = -1; if (initialized) { soundfieldId = CreateSoundfield(numFoaChannels); } return soundfieldId; } /// Destroys the soundfield with given |id|. /// @note This should only be called from the main Unity thread. public static void DestroyAudioSoundfield (int id) { if (initialized) { DestroySoundfield(id); } } /// Creates a new audio source with a unique id. /// @note This should only be called from the main Unity thread. public static int CreateAudioSource (bool hrtfEnabled) { int sourceId = -1; if (initialized) { sourceId = CreateSource(hrtfEnabled); } return sourceId; } /// Destroys the audio source with given |id|. /// @note This should only be called from the main Unity thread. public static void DestroyAudioSource (int id) { if (initialized) { DestroySource(id); } } /// Updates the audio |source| with given |id| and its properties. /// @note This should only be called from the main Unity thread. public static void UpdateAudioSource (int id, GvrAudioSource source, float currentOcclusion) { if (initialized) { SetSourceBypassRoomEffects(id, source.bypassRoomEffects); SetSourceDirectivity(id, source.directivityAlpha, source.directivitySharpness); SetSourceListenerDirectivity(id, source.listenerDirectivityAlpha, source.listenerDirectivitySharpness); SetSourceOcclusionIntensity(id, currentOcclusion); } } /// Updates the room effects of the environment with given |room| properties. /// @note This should only be called from the main Unity thread. public static void UpdateAudioRoom(GvrAudioRoom room, bool roomEnabled) { // Update the enabled rooms list. if (roomEnabled) { if (!enabledRooms.Contains(room)) { enabledRooms.Add(room); } } else { enabledRooms.Remove(room); } // Update the current room effects to be applied. if(initialized) { if (enabledRooms.Count > 0) { GvrAudioRoom currentRoom = enabledRooms[enabledRooms.Count - 1]; RoomProperties roomProperties = GetRoomProperties(currentRoom); // Pass the room properties into a pointer. IntPtr roomPropertiesPtr = Marshal.AllocHGlobal(Marshal.SizeOf(roomProperties)); Marshal.StructureToPtr(roomProperties, roomPropertiesPtr, false); SetRoomProperties(roomPropertiesPtr); Marshal.FreeHGlobal(roomPropertiesPtr); } else { // Set the room properties to null, which will effectively disable the room effects. SetRoomProperties(IntPtr.Zero); } } } /// Computes the occlusion intensity of a given |source| using point source detection. /// @note This should only be called from the main Unity thread. public static float ComputeOcclusion (Transform sourceTransform) { float occlusion = 0.0f; if (initialized) { Vector3 listenerPosition = listenerTransform.position; Vector3 sourceFromListener = sourceTransform.position - listenerPosition; RaycastHit[] hits = Physics.RaycastAll(listenerPosition, sourceFromListener, sourceFromListener.magnitude, occlusionMaskValue); foreach (RaycastHit hit in hits) { if (hit.transform != listenerTransform && hit.transform != sourceTransform) { occlusion += 1.0f; } } } return occlusion; } /// Converts given |db| value to its amplitude equivalent where 'dB = 20 * log10(amplitude)'. public static float ConvertAmplitudeFromDb (float db) { return Mathf.Pow(10.0f, 0.05f * db); } /// Generates a set of points to draw a 2D polar pattern. public static Vector2[] Generate2dPolarPattern (float alpha, float order, int resolution) { Vector2[] points = new Vector2[resolution]; float interval = 2.0f * Mathf.PI / resolution; for (int i = 0; i < resolution; ++i) { float theta = i * interval; // Magnitude |r| for |theta| in radians. float r = Mathf.Pow(Mathf.Abs((1 - alpha) + alpha * Mathf.Cos(theta)), order); points[i] = new Vector2(r * Mathf.Sin(theta), r * Mathf.Cos(theta)); } return points; } /// Returns whether the listener is currently inside the given |room| boundaries. public static bool IsListenerInsideRoom(GvrAudioRoom room) { bool isInside = false; if(initialized) { Vector3 relativePosition = listenerTransform.position - room.transform.position; Quaternion rotationInverse = Quaternion.Inverse(room.transform.rotation); bounds.size = Vector3.Scale(room.transform.lossyScale, room.size); isInside = bounds.Contains(rotationInverse * relativePosition); } return isInside; } /// Listener directivity GUI color. public static readonly Color listenerDirectivityColor = 0.65f * Color.magenta; /// Source directivity GUI color. public static readonly Color sourceDirectivityColor = 0.65f * Color.blue; /// Minimum distance threshold between |minDistance| and |maxDistance|. public const float distanceEpsilon = 0.01f; /// Max distance limit that can be set for volume rolloff. public const float maxDistanceLimit = 1000000.0f; /// Min distance limit that can be set for volume rolloff. public const float minDistanceLimit = 990099.0f; /// Maximum allowed gain value in decibels. public const float maxGainDb = 24.0f; /// Minimum allowed gain value in decibels. public const float minGainDb = -24.0f; /// Maximum allowed reverb brightness modifier value. public const float maxReverbBrightness = 1.0f; /// Minimum allowed reverb brightness modifier value. public const float minReverbBrightness = -1.0f; /// Maximum allowed reverb time modifier value. public const float maxReverbTime = 3.0f; /// Maximum allowed reflectivity multiplier of a room surface material. public const float maxReflectivity = 2.0f; /// Source occlusion detection rate in seconds. public const float occlusionDetectionInterval = 0.2f; // Number of first-order ambisonic input channels. public const int numFoaChannels = 4; [StructLayout(LayoutKind.Sequential)] private struct RoomProperties { // Center position of the room in world space. public float positionX; public float positionY; public float positionZ; // Rotation (quaternion) of the room in world space. public float rotationX; public float rotationY; public float rotationZ; public float rotationW; // Size of the shoebox room in world space. public float dimensionsX; public float dimensionsY; public float dimensionsZ; // Material name of each surface of the shoebox room. public GvrAudioRoom.SurfaceMaterial materialLeft; public GvrAudioRoom.SurfaceMaterial materialRight; public GvrAudioRoom.SurfaceMaterial materialBottom; public GvrAudioRoom.SurfaceMaterial materialTop; public GvrAudioRoom.SurfaceMaterial materialFront; public GvrAudioRoom.SurfaceMaterial materialBack; // User defined uniform scaling factor for reflectivity. This parameter has no effect when set // to 1.0f. public float reflectionScalar; // User defined reverb tail gain multiplier. This parameter has no effect when set to 0.0f. public float reverbGain; // Parameter which allows the reverberation time across all frequency bands to be increased or // decreased. This parameter has no effect when set to 1.0f. public float reverbTime; // Parameter which allows the ratio of high frequncy reverb components to low frequency reverb // components to be adjusted. This parameter has no effect when set to 0.0f. public float reverbBrightness; }; // Converts given |position| and |rotation| from Unity space to audio space. private static void ConvertAudioTransformFromUnity (ref Vector3 position, ref Quaternion rotation) { pose.SetRightHanded(Matrix4x4.TRS(position, rotation, Vector3.one)); position = pose.Position; rotation = pose.Orientation; } // Returns room properties of the given |room|. private static RoomProperties GetRoomProperties(GvrAudioRoom room) { RoomProperties roomProperties; Vector3 position = room.transform.position; Quaternion rotation = room.transform.rotation; Vector3 scale = Vector3.Scale(room.transform.lossyScale, room.size); ConvertAudioTransformFromUnity(ref position, ref rotation); roomProperties.positionX = position.x; roomProperties.positionY = position.y; roomProperties.positionZ = position.z; roomProperties.rotationX = rotation.x; roomProperties.rotationY = rotation.y; roomProperties.rotationZ = rotation.z; roomProperties.rotationW = rotation.w; roomProperties.dimensionsX = scale.x; roomProperties.dimensionsY = scale.y; roomProperties.dimensionsZ = scale.z; roomProperties.materialLeft = room.leftWall; roomProperties.materialRight = room.rightWall; roomProperties.materialBottom = room.floor; roomProperties.materialTop = room.ceiling; roomProperties.materialFront = room.frontWall; roomProperties.materialBack = room.backWall; roomProperties.reverbGain = ConvertAmplitudeFromDb(room.reverbGainDb); roomProperties.reverbTime = room.reverbTime; roomProperties.reverbBrightness = room.reverbBrightness; roomProperties.reflectionScalar = room.reflectivity; return roomProperties; } // Boundaries instance to be used in room detection logic. private static Bounds bounds = new Bounds(Vector3.zero, Vector3.zero); // Container to store the currently active rooms in the scene. private static List<GvrAudioRoom> enabledRooms = new List<GvrAudioRoom>(); // Denotes whether the system is initialized properly. private static bool initialized = false; // Listener transform. private static Transform listenerTransform = null; // Occlusion layer mask. private static int occlusionMaskValue = -1; // 3D pose instance to be used in transform space conversion. private static MutablePose3D pose = new MutablePose3D(); #if UNITY_IOS private const string pluginName = "__Internal"; #else private const string pluginName = "audioplugingvrunity"; #endif // Listener handlers. [DllImport(pluginName)] private static extern void SetListenerGain (float gain); // Soundfield handlers. [DllImport(pluginName)] private static extern int CreateSoundfield (int numChannels); [DllImport(pluginName)] private static extern void DestroySoundfield (int soundfieldId); // Source handlers. [DllImport(pluginName)] private static extern int CreateSource (bool enableHrtf); [DllImport(pluginName)] private static extern void DestroySource (int sourceId); [DllImport(pluginName)] private static extern void SetSourceBypassRoomEffects (int sourceId, bool bypassRoomEffects); [DllImport(pluginName)] private static extern void SetSourceDirectivity (int sourceId, float alpha, float order); [DllImport(pluginName)] private static extern void SetSourceListenerDirectivity (int sourceId, float alpha, float order); [DllImport(pluginName)] private static extern void SetSourceOcclusionIntensity (int sourceId, float intensity); // Room handlers. [DllImport(pluginName)] private static extern void SetRoomProperties (IntPtr roomProperties); // System handlers. [DllImport(pluginName)] private static extern void Initialize (Quality quality, int sampleRate, int numChannels, int framesPerBuffer); [DllImport(pluginName)] private static extern void Shutdown (); }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; namespace Orleans.Runtime.Scheduler { [DebuggerDisplay("OrleansTaskScheduler RunQueueLength={" + nameof(RunQueueLength) + "}")] internal class OrleansTaskScheduler : TaskScheduler, ITaskScheduler, IHealthCheckParticipant { private readonly ILogger logger; private readonly ILoggerFactory loggerFactory; private readonly SchedulerStatisticsGroup schedulerStatistics; private readonly IOptions<StatisticsOptions> statisticsOptions; private readonly ILogger taskWorkItemLogger; private readonly ConcurrentDictionary<ISchedulingContext, WorkItemGroup> workgroupDirectory; private bool applicationTurnsStopped; private readonly CancellationTokenSource cancellationTokenSource; private readonly OrleansSchedulerAsynchAgent systemAgent; private readonly OrleansSchedulerAsynchAgent mainAgent; private readonly int maximumConcurrencyLevel; internal static TimeSpan TurnWarningLengthThreshold { get; set; } // This is the maximum number of pending work items for a single activation before we write a warning log. internal int MaxPendingItemsSoftLimit { get; private set; } public int RunQueueLength => systemAgent.Count + mainAgent.Count; public OrleansTaskScheduler( IOptions<SchedulingOptions> options, ExecutorService executorService, ILoggerFactory loggerFactory, SchedulerStatisticsGroup schedulerStatistics, IOptions<StatisticsOptions> statisticsOptions) { this.loggerFactory = loggerFactory; this.schedulerStatistics = schedulerStatistics; this.statisticsOptions = statisticsOptions; this.logger = loggerFactory.CreateLogger<OrleansTaskScheduler>(); cancellationTokenSource = new CancellationTokenSource(); this.SchedulingOptions = options.Value; applicationTurnsStopped = false; TurnWarningLengthThreshold = options.Value.TurnWarningLengthThreshold; this.MaxPendingItemsSoftLimit = options.Value.MaxPendingWorkItemsSoftLimit; this.StoppedWorkItemGroupWarningInterval = options.Value.StoppedActivationWarningInterval; workgroupDirectory = new ConcurrentDictionary<ISchedulingContext, WorkItemGroup>(); const int maxSystemThreads = 2; var maxActiveThreads = options.Value.MaxActiveThreads; maximumConcurrencyLevel = maxActiveThreads + maxSystemThreads; OrleansSchedulerAsynchAgent CreateSchedulerAsynchAgent(string agentName, bool drainAfterCancel, int degreeOfParallelism) { return new OrleansSchedulerAsynchAgent( agentName, executorService, degreeOfParallelism, options.Value.DelayWarningThreshold, options.Value.TurnWarningLengthThreshold, drainAfterCancel, loggerFactory); } mainAgent = CreateSchedulerAsynchAgent("Scheduler.LevelOne.MainQueue", false, maxActiveThreads); systemAgent = CreateSchedulerAsynchAgent("Scheduler.LevelOne.SystemQueue", true, maxSystemThreads); this.taskWorkItemLogger = loggerFactory.CreateLogger<TaskWorkItem>(); logger.Info("Starting OrleansTaskScheduler with {0} Max Active application Threads and 2 system thread.", maxActiveThreads); IntValueStatistic.FindOrCreate(StatisticNames.SCHEDULER_WORKITEMGROUP_COUNT, () => WorkItemGroupCount); IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_INSTANTANEOUS_PER_QUEUE, "Scheduler.LevelOne"), () => RunQueueLength); if (!schedulerStatistics.CollectShedulerQueuesStats) return; FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageRunQueueLengthLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageEnqueuedLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageArrivalRateLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumRunQueueLengthLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumEnqueuedLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumArrivalRateLevelTwo); } public int WorkItemGroupCount => workgroupDirectory.Count; public TimeSpan StoppedWorkItemGroupWarningInterval { get; } public SchedulingOptions SchedulingOptions { get; } private float AverageRunQueueLengthLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght) / (float)workgroupDirectory.Values.Count; } } private float AverageEnqueuedLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests) / (float)workgroupDirectory.Values.Count; } } private float AverageArrivalRateLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate) / (float)workgroupDirectory.Values.Count; } } private float SumRunQueueLengthLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght); } } private float SumEnqueuedLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests); } } private float SumArrivalRateLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate); } } public void StopApplicationTurns() { #if DEBUG logger.Debug("StopApplicationTurns"); #endif // Do not RunDown the application run queue, since it is still used by low priority system targets. applicationTurnsStopped = true; foreach (var group in workgroupDirectory.Values) { if (!group.IsSystemGroup) group.Stop(); } } public void Start() { systemAgent.Start(); mainAgent.Start(); } public void Stop() { cancellationTokenSource.Cancel(); mainAgent.Stop(); systemAgent.Stop(); } protected override IEnumerable<Task> GetScheduledTasks() { return Array.Empty<Task>(); } protected override void QueueTask(Task task) { var contextObj = task.AsyncState; #if DEBUG if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("QueueTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current); #endif var context = contextObj as ISchedulingContext; var workItemGroup = GetWorkItemGroup(context); if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystemGroup) { // Drop the task on the floor if it's an application work item and application turns are stopped logger.Warn(ErrorCode.SchedulerAppTurnsStopped_2, string.Format("Dropping Task {0} because application turns are stopped", task)); return; } if (workItemGroup == null) { var todo = new TaskWorkItem(this, task, context, this.taskWorkItemLogger); ScheduleExecution(todo); } else { var error = String.Format("QueueTask was called on OrleansTaskScheduler for task {0} on Context {1}." + " Should only call OrleansTaskScheduler.QueueTask with tasks on the null context.", task.Id, context); logger.Error(ErrorCode.SchedulerQueueTaskWrongCall, error); throw new InvalidOperationException(error); } } public void ScheduleExecution(IWorkItem workItem) { if (workItem.IsSystemPriority) { systemAgent.QueueRequest(workItem); } else { mainAgent.QueueRequest(workItem); } } // Enqueue a work item to a given context public void QueueWorkItem(IWorkItem workItem, ISchedulingContext context) { #if DEBUG if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("QueueWorkItem " + context); #endif if (workItem is TaskWorkItem) { var error = String.Format("QueueWorkItem was called on OrleansTaskScheduler for TaskWorkItem {0} on Context {1}." + " Should only call OrleansTaskScheduler.QueueWorkItem on WorkItems that are NOT TaskWorkItem. Tasks should be queued to the scheduler via QueueTask call.", workItem.ToString(), context); logger.Error(ErrorCode.SchedulerQueueWorkItemWrongCall, error); throw new InvalidOperationException(error); } var workItemGroup = GetWorkItemGroup(context); if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystemGroup) { // Drop the task on the floor if it's an application work item and application turns are stopped var msg = string.Format("Dropping work item {0} because application turns are stopped", workItem); logger.Warn(ErrorCode.SchedulerAppTurnsStopped_1, msg); return; } workItem.SchedulingContext = context; // We must wrap any work item in Task and enqueue it as a task to the right scheduler via Task.Start. Task t = TaskSchedulerUtils.WrapWorkItemAsTask(workItem); // This will make sure the TaskScheduler.Current is set correctly on any task that is created implicitly in the execution of this workItem. if (workItemGroup == null) { t.Start(this); } else { t.Start(workItemGroup.TaskScheduler); } } // Only required if you have work groups flagged by a context that is not a WorkGroupingContext public WorkItemGroup RegisterWorkContext(ISchedulingContext context) { if (context == null) return null; var wg = new WorkItemGroup( this, context, this.loggerFactory, this.cancellationTokenSource.Token, this.schedulerStatistics, this.statisticsOptions); workgroupDirectory.TryAdd(context, wg); return wg; } // Only required if you have work groups flagged by a context that is not a WorkGroupingContext public void UnregisterWorkContext(ISchedulingContext context) { if (context == null) return; WorkItemGroup workGroup; if (workgroupDirectory.TryRemove(context, out workGroup)) workGroup.Stop(); } // public for testing only -- should be private, otherwise public WorkItemGroup GetWorkItemGroup(ISchedulingContext context) { if (context == null) return null; WorkItemGroup workGroup; if(workgroupDirectory.TryGetValue(context, out workGroup)) return workGroup; var error = String.Format("QueueWorkItem was called on a non-null context {0} but there is no valid WorkItemGroup for it.", context); logger.Error(ErrorCode.SchedulerQueueWorkItemWrongContext, error); throw new InvalidSchedulingContextException(error); } internal void CheckSchedulingContextValidity(ISchedulingContext context) { if (context == null) { throw new InvalidSchedulingContextException( "CheckSchedulingContextValidity was called on a null SchedulingContext." + "Please make sure you are not trying to create a Timer from outside Orleans Task Scheduler, " + "which will be the case if you create it inside Task.Run."); } GetWorkItemGroup(context); // GetWorkItemGroup throws for Invalid context } public override int MaximumConcurrencyLevel => maximumConcurrencyLevel; protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { //bool canExecuteInline = WorkerPoolThread.CurrentContext != null; var ctx = RuntimeContext.Current; bool canExecuteInline = ctx == null || ctx.ActivationContext==null; #if DEBUG if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace("TryExecuteTaskInline Id={0} with Status={1} PreviouslyQueued={2} CanExecute={3}", task.Id, task.Status, taskWasPreviouslyQueued, canExecuteInline); } #endif if (!canExecuteInline) return false; if (taskWasPreviouslyQueued) canExecuteInline = TryDequeue(task); if (!canExecuteInline) return false; // We can't execute tasks in-line on non-worker pool threads // We are on a worker pool thread, so can execute this task bool done = TryExecuteTask(task); if (!done) { logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete1, "TryExecuteTaskInline: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}", task.Id, task.Status); } return done; } /// <summary> /// Run the specified task synchronously on the current thread /// </summary> /// <param name="task"><c>Task</c> to be executed</param> public void RunTask(Task task) { #if DEBUG if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("RunTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current); #endif var context = RuntimeContext.CurrentActivationContext; var workItemGroup = GetWorkItemGroup(context); if (workItemGroup == null) { RuntimeContext.SetExecutionContext(null); bool done = TryExecuteTask(task); if (!done) logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete2, "RunTask: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}", task.Id, task.Status); } else { var error = String.Format("RunTask was called on OrleansTaskScheduler for task {0} on Context {1}. Should only call OrleansTaskScheduler.RunTask on tasks queued on a null context.", task.Id, context); logger.Error(ErrorCode.SchedulerTaskRunningOnWrongScheduler1, error); throw new InvalidOperationException(error); } #if DEBUG if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("RunTask: Completed Id={0} with Status={1} task.AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current); #endif } // Returns true if healthy, false if not public bool CheckHealth(DateTime lastCheckTime) { return mainAgent.CheckHealth(lastCheckTime) && systemAgent.CheckHealth(lastCheckTime); } internal void PrintStatistics() { if (!logger.IsEnabled(LogLevel.Information)) return; var stats = Utils.EnumerableToString(workgroupDirectory.Values.OrderBy(wg => wg.Name), wg => string.Format("--{0}", wg.DumpStatus()), Environment.NewLine); if (stats.Length > 0) logger.Info(ErrorCode.SchedulerStatistics, "OrleansTaskScheduler.PrintStatistics(): RunQueue={0}, WorkItems={1}, Directory:" + Environment.NewLine + "{2}", RunQueueLength, WorkItemGroupCount, stats); } internal void DumpSchedulerStatus(bool alwaysOutput = true) { if (!logger.IsEnabled(LogLevel.Debug) && !alwaysOutput) return; PrintStatistics(); var sb = new StringBuilder(); sb.AppendLine("Dump of current OrleansTaskScheduler status:"); sb.AppendFormat("CPUs={0} RunQueue={1}, WorkItems={2} {3}", Environment.ProcessorCount, RunQueueLength, workgroupDirectory.Count, applicationTurnsStopped ? "STOPPING" : "").AppendLine(); // todo: either remove or support. At the time of writting is being used only in tests // sb.AppendLine("RunQueue:"); // RunQueue.DumpStatus(sb); - woun't work without additional costs // Pool.DumpStatus(sb); foreach (var workgroup in workgroupDirectory.Values) sb.AppendLine(workgroup.DumpStatus()); logger.Info(ErrorCode.SchedulerStatus, sb.ToString()); } } }
// // KeyPairPersistence.cs: Keypair persistence // // Author: // Sebastien Pouliot <[email protected]> // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using Mono.Xml; namespace Mono.Security.Cryptography { /* File name * [type][unique name][key number].xml * * where * type CspParameters.ProviderType * unique name A unique name for the keypair, which is * a. default (for a provider default keypair) * b. a GUID derived from * i. random if no container name was * specified at generation time * ii. the MD5 hash of the container * name (CspParameters.KeyContainerName) * key number CspParameters.KeyNumber * * File format * <KeyPair> * <Properties> * <Provider Name="" Type=""/> * <Container Name=""/> * </Properties> * <KeyValue Id=""> * RSAKeyValue, DSAKeyValue ... * </KeyValue> * </KeyPair> */ /* NOTES * * - There's NO confidentiality / integrity built in this * persistance mechanism. The container directories (both user and * machine) are created with restrited ACL. The ACL is also checked * when a key is accessed (so totally public keys won't be used). * see /mono/mono/metadata/security.c for implementation * * - As we do not use CSP we limit ourselves to provider types (not * names). This means that for a same type and container type, but * two different provider names) will return the same keypair. This * should work as CspParameters always requires a csp type in its * constructors. * * - Assert (CAS) are used so only the OS permission will limit access * to the keypair files. I.e. this will work even in high-security * scenarios where users do not have access to file system (e.g. web * application). We can allow this because the filename used is * TOTALLY under our control (no direct user input is used). * * - You CAN'T changes properties of the keypair once it's been * created (saved). You must remove the container than save it * back. This is the same behaviour as CSP under Windows. */ #if INSIDE_CORLIB internal #else public #endif class KeyPairPersistence { private static bool _userPathExists = false; // check at 1st use private static string _userPath; private static bool _machinePathExists = false; // check at 1st use private static string _machinePath; private CspParameters _params; private string _keyvalue; private string _filename; private string _container; // constructors public KeyPairPersistence (CspParameters parameters) : this (parameters, null) { } public KeyPairPersistence (CspParameters parameters, string keyPair) { if (parameters == null) throw new ArgumentNullException ("parameters"); _params = Copy (parameters); _keyvalue = keyPair; } // properties public string Filename { get { if (_filename == null) { _filename = String.Format (CultureInfo.InvariantCulture, "[{0}][{1}][{2}].xml", _params.ProviderType, this.ContainerName, _params.KeyNumber); if (UseMachineKeyStore) _filename = Path.Combine (MachinePath, _filename); else _filename = Path.Combine (UserPath, _filename); } return _filename; } } public string KeyValue { get { return _keyvalue; } set { if (this.CanChange) _keyvalue = value; } } // return a (read-only) copy public CspParameters Parameters { get { return Copy (_params); } } // methods public bool Load () { // see NOTES // FIXME new FileIOPermission (FileIOPermissionAccess.Read, this.Filename).Assert (); bool result = File.Exists (this.Filename); if (result) { using (StreamReader sr = File.OpenText (this.Filename)) { FromXml (sr.ReadToEnd ()); } } return result; } public void Save () { // see NOTES // FIXME new FileIOPermission (FileIOPermissionAccess.Write, this.Filename).Assert (); using (FileStream fs = File.Open (this.Filename, FileMode.Create)) { StreamWriter sw = new StreamWriter (fs, Encoding.UTF8); sw.Write (this.ToXml ()); sw.Close (); } // apply protection to newly created files if (UseMachineKeyStore) ProtectMachine (Filename); else ProtectUser (Filename); } public void Remove () { // see NOTES // FIXME new FileIOPermission (FileIOPermissionAccess.Write, this.Filename).Assert (); File.Delete (this.Filename); // it's now possible to change the keypair un the container } // private static stuff static object lockobj = new object (); private static string UserPath { get { lock (lockobj) { if ((_userPath == null) || (!_userPathExists)) { _userPath = Path.Combine ( Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), ".mono"); _userPath = Path.Combine (_userPath, "keypairs"); _userPathExists = Directory.Exists (_userPath); if (!_userPathExists) { try { Directory.CreateDirectory (_userPath); ProtectUser (_userPath); _userPathExists = true; } catch (Exception e) { string msg = Locale.GetText ("Could not create user key store '{0}'."); throw new CryptographicException (String.Format (msg, _userPath), e); } } } } // is it properly protected ? if (!IsUserProtected (_userPath)) { string msg = Locale.GetText ("Improperly protected user's key pairs in '{0}'."); throw new CryptographicException (String.Format (msg, _userPath)); } return _userPath; } } private static string MachinePath { get { lock (lockobj) { if ((_machinePath == null) || (!_machinePathExists)) { _machinePath = Path.Combine ( Environment.GetFolderPath (Environment.SpecialFolder.CommonApplicationData), ".mono"); _machinePath = Path.Combine (_machinePath, "keypairs"); _machinePathExists = Directory.Exists (_machinePath); if (!_machinePathExists) { try { Directory.CreateDirectory (_machinePath); ProtectMachine (_machinePath); _machinePathExists = true; } catch (Exception e) { string msg = Locale.GetText ("Could not create machine key store '{0}'."); throw new CryptographicException (String.Format (msg, _machinePath), e); } } } } // is it properly protected ? if (!IsMachineProtected (_machinePath)) { string msg = Locale.GetText ("Improperly protected machine's key pairs in '{0}'."); throw new CryptographicException (String.Format (msg, _machinePath)); } return _machinePath; } } #if INSIDE_CORLIB [MethodImplAttribute (MethodImplOptions.InternalCall)] internal static extern bool _CanSecure (string root); [MethodImplAttribute (MethodImplOptions.InternalCall)] internal static extern bool _ProtectUser (string path); [MethodImplAttribute (MethodImplOptions.InternalCall)] internal static extern bool _ProtectMachine (string path); [MethodImplAttribute (MethodImplOptions.InternalCall)] internal static extern bool _IsUserProtected (string path); [MethodImplAttribute (MethodImplOptions.InternalCall)] internal static extern bool _IsMachineProtected (string path); #else // Mono.Security.dll assembly can't use the internal // call (and still run with other runtimes) // Note: Class is only available in Mono.Security.dll as // a management helper (e.g. build a GUI app) internal static bool _CanSecure (string root) { return true; } internal static bool _ProtectUser (string path) { return true; } internal static bool _ProtectMachine (string path) { return true; } internal static bool _IsUserProtected (string path) { return true; } internal static bool _IsMachineProtected (string path) { return true; } #endif // private stuff private static bool CanSecure (string path) { // we assume POSIX filesystems can always be secured // check for Unix platforms - see FAQ for more details // http://www.mono-project.com/FAQ:_Technical#How_to_detect_the_execution_platform_.3F int platform = (int) Environment.OSVersion.Platform; if ((platform == 4) || (platform == 128)) return true; // while we ask the runtime for Windows OS return _CanSecure (Path.GetPathRoot (path)); } private static bool ProtectUser (string path) { // we cannot protect on some filsystem (like FAT) if (CanSecure (path)) { return _ProtectUser (path); } // but Mono still needs to run on them :( return true; } private static bool ProtectMachine (string path) { // we cannot protect on some filsystem (like FAT) if (CanSecure (path)) { return _ProtectMachine (path); } // but Mono still needs to run on them :( return true; } private static bool IsUserProtected (string path) { // we cannot protect on some filsystem (like FAT) if (CanSecure (path)) { return _IsUserProtected (path); } // but Mono still needs to run on them :( return true; } private static bool IsMachineProtected (string path) { // we cannot protect on some filsystem (like FAT) if (CanSecure (path)) { return _IsMachineProtected (path); } // but Mono still needs to run on them :( return true; } private bool CanChange { get { return (_keyvalue == null); } } private bool UseDefaultKeyContainer { get { return ((_params.Flags & CspProviderFlags.UseDefaultKeyContainer) == CspProviderFlags.UseDefaultKeyContainer); } } private bool UseMachineKeyStore { get { return ((_params.Flags & CspProviderFlags.UseMachineKeyStore) == CspProviderFlags.UseMachineKeyStore); } } private string ContainerName { get { if (_container == null) { if (UseDefaultKeyContainer) { // easy to spot _container = "default"; } else if ((_params.KeyContainerName == null) || (_params.KeyContainerName.Length == 0)) { _container = Guid.NewGuid ().ToString (); } else { // we don't want to trust the key container name as we don't control it // anyway some characters may not be compatible with the file system byte[] data = Encoding.UTF8.GetBytes (_params.KeyContainerName); // Note: We use MD5 as it is faster than SHA1 and has the same length // as a GUID. Recent problems found in MD5 (like collisions) aren't a // problem in this case. MD5 hash = MD5.Create (); byte[] result = hash.ComputeHash (data); _container = new Guid (result).ToString (); } } return _container; } } // we do not want any changes after receiving the csp informations private CspParameters Copy (CspParameters p) { CspParameters copy = new CspParameters (p.ProviderType, p.ProviderName, p.KeyContainerName); copy.KeyNumber = p.KeyNumber; copy.Flags = p.Flags; return copy; } private void FromXml (string xml) { SecurityParser sp = new SecurityParser (); sp.LoadXml (xml); SecurityElement root = sp.ToXml (); if (root.Tag == "KeyPair") { //SecurityElement prop = root.SearchForChildByTag ("Properties"); SecurityElement keyv = root.SearchForChildByTag ("KeyValue"); if (keyv.Children.Count > 0) _keyvalue = keyv.Children [0].ToString (); // Note: we do not read other stuff because // it can't be changed after key creation } } private string ToXml () { // note: we do not use SecurityElement here because the // keypair is a XML string (requiring parsing) StringBuilder xml = new StringBuilder (); xml.AppendFormat ("<KeyPair>{0}\t<Properties>{0}\t\t<Provider ", Environment.NewLine); if ((_params.ProviderName != null) && (_params.ProviderName.Length != 0)) { xml.AppendFormat ("Name=\"{0}\" ", _params.ProviderName); } xml.AppendFormat ("Type=\"{0}\" />{1}\t\t<Container ", _params.ProviderType, Environment.NewLine); xml.AppendFormat ("Name=\"{0}\" />{1}\t</Properties>{1}\t<KeyValue", this.ContainerName, Environment.NewLine); if (_params.KeyNumber != -1) { xml.AppendFormat (" Id=\"{0}\" ", _params.KeyNumber); } xml.AppendFormat (">{1}\t\t{0}{1}\t</KeyValue>{1}</KeyPair>{1}", this.KeyValue, Environment.NewLine); return xml.ToString (); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Drawing.Imaging; using System.Drawing.Internal; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Permissions; namespace System.Drawing { /// <summary> /// An abstract base class that provides functionality for 'Bitmap', 'Icon', 'Cursor', and 'Metafile' descended classes. /// </summary> [ImmutableObject(true)] [ComVisible(true)] public abstract partial class Image : MarshalByRefObject, ICloneable, IDisposable { #if FINALIZATION_WATCH private string allocationSite = Graphics.GetAllocationStack(); #endif // The signature of this delegate is incorrect. The signature of the corresponding // native callback function is: // extern "C" { // typedef BOOL (CALLBACK * ImageAbort)(VOID *); // typedef ImageAbort DrawImageAbort; // typedef ImageAbort GetThumbnailImageAbort; // } // However, as this delegate is not used in both GDI 1.0 and 1.1, we choose not // to modify it, in order to preserve compatibility. public delegate bool GetThumbnailImageAbort(); internal IntPtr nativeImage; // used to work around lack of animated gif encoder... rarely set... private byte[] _rawData; //userData : so that user can use TAGS with IMAGES.. private object _userData; internal Image() { } [ Localizable(false), DefaultValue(null), ] public object Tag { get { return _userData; } set { _userData = value; } } /// <summary> /// Creates an <see cref='Image'/> from the specified file. /// </summary> public static Image FromFile(String filename) { return Image.FromFile(filename, false); } public static Image FromFile(String filename, bool useEmbeddedColorManagement) { if (!File.Exists(filename)) { throw new FileNotFoundException(filename); } // GDI+ will read this file multiple times. Get the fully qualified path // so if our app changes default directory we won't get an error filename = Path.GetFullPath(filename); IntPtr image = IntPtr.Zero; int status; if (useEmbeddedColorManagement) { status = SafeNativeMethods.Gdip.GdipLoadImageFromFileICM(filename, out image); } else { status = SafeNativeMethods.Gdip.GdipLoadImageFromFile(filename, out image); } if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); status = SafeNativeMethods.Gdip.GdipImageForceValidation(new HandleRef(null, image)); if (status != SafeNativeMethods.Gdip.Ok) { SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(null, image)); throw SafeNativeMethods.Gdip.StatusException(status); } Image img = CreateImageObject(image); EnsureSave(img, filename, null); return img; } /// <summary> /// Creates an <see cref='Image'/> from the specified data stream. /// </summary> public static Image FromStream(Stream stream) { return Image.FromStream(stream, false); } public static Image FromStream(Stream stream, bool useEmbeddedColorManagement) { return FromStream(stream, useEmbeddedColorManagement, true); } public static Image FromStream(Stream stream, bool useEmbeddedColorManagement, bool validateImageData) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } IntPtr image = IntPtr.Zero; int status; if (useEmbeddedColorManagement) { status = SafeNativeMethods.Gdip.GdipLoadImageFromStreamICM(new GPStream(stream), out image); } else { status = SafeNativeMethods.Gdip.GdipLoadImageFromStream(new GPStream(stream), out image); } if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } if (validateImageData) { status = SafeNativeMethods.Gdip.GdipImageForceValidation(new HandleRef(null, image)); if (status != SafeNativeMethods.Gdip.Ok) { SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(null, image)); throw SafeNativeMethods.Gdip.StatusException(status); } } Image img = CreateImageObject(image); EnsureSave(img, null, stream); return img; } // Used for serialization private void InitializeFromStream(Stream stream) { IntPtr image = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipLoadImageFromStream(new GPStream(stream), out image); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); status = SafeNativeMethods.Gdip.GdipImageForceValidation(new HandleRef(null, image)); if (status != SafeNativeMethods.Gdip.Ok) { SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(null, image)); throw SafeNativeMethods.Gdip.StatusException(status); } nativeImage = image; int type = -1; status = SafeNativeMethods.Gdip.GdipGetImageType(new HandleRef(this, nativeImage), out type); EnsureSave(this, null, stream); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } internal Image(IntPtr nativeImage) { SetNativeImage(nativeImage); } /// <summary> /// Creates an exact copy of this <see cref='Image'/>. /// </summary> public object Clone() { IntPtr cloneImage = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCloneImage(new HandleRef(this, nativeImage), out cloneImage); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); status = SafeNativeMethods.Gdip.GdipImageForceValidation(new HandleRef(null, cloneImage)); if (status != SafeNativeMethods.Gdip.Ok) { SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(null, cloneImage)); throw SafeNativeMethods.Gdip.StatusException(status); } return CreateImageObject(cloneImage); } /// <summary> /// Cleans up Windows resources for this <see cref='Image'/>. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { #if FINALIZATION_WATCH if (!disposing && nativeImage != IntPtr.Zero) Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite); #endif if (nativeImage != IntPtr.Zero) { try { #if DEBUG int status = #endif SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(this, nativeImage)); #if DEBUG Debug.Assert(status == SafeNativeMethods.Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); #endif } catch (Exception ex) { if (ClientUtils.IsSecurityOrCriticalException(ex)) { throw; } Debug.Fail("Exception thrown during Dispose: " + ex.ToString()); } finally { nativeImage = IntPtr.Zero; } } } /// <summary> /// Cleans up Windows resources for this <see cref='Image'/>. /// </summary> ~Image() { Dispose(false); } internal static void EnsureSave(Image image, string filename, Stream dataStream) { if (image.RawFormat.Equals(ImageFormat.Gif)) { bool animatedGif = false; Guid[] dimensions = image.FrameDimensionsList; foreach (Guid guid in dimensions) { FrameDimension dimension = new FrameDimension(guid); if (dimension.Equals(FrameDimension.Time)) { animatedGif = image.GetFrameCount(FrameDimension.Time) > 1; break; } } if (animatedGif) { try { Stream created = null; long lastPos = 0; if (dataStream != null) { lastPos = dataStream.Position; dataStream.Position = 0; } try { if (dataStream == null) { created = dataStream = File.OpenRead(filename); } image._rawData = new byte[(int)dataStream.Length]; dataStream.Read(image._rawData, 0, (int)dataStream.Length); } finally { if (created != null) { created.Close(); } else { dataStream.Position = lastPos; } } } // possible exceptions for reading the filename catch (UnauthorizedAccessException) { } catch (DirectoryNotFoundException) { } catch (IOException) { } // possible exceptions for setting/getting the position inside dataStream catch (NotSupportedException) { } catch (ObjectDisposedException) { } // possible exception when reading stuff into dataStream catch (ArgumentException) { } } } } private enum ImageTypeEnum { Bitmap = 1, Metafile = 2, } internal static Image CreateImageObject(IntPtr nativeImage) { Image image; int type = -1; int status = SafeNativeMethods.Gdip.GdipGetImageType(new HandleRef(null, nativeImage), out type); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); switch ((ImageTypeEnum)type) { case ImageTypeEnum.Bitmap: image = Bitmap.FromGDIplus(nativeImage); break; case ImageTypeEnum.Metafile: image = Metafile.FromGDIplus(nativeImage); break; default: throw new ArgumentException(SR.Format(SR.InvalidImage)); } return image; } /// <summary> /// Returns information about the codecs used for this <see cref='Image'/>. /// </summary> public EncoderParameters GetEncoderParameterList(Guid encoder) { EncoderParameters p; int size; int status = SafeNativeMethods.Gdip.GdipGetEncoderParameterListSize(new HandleRef(this, nativeImage), ref encoder, out size); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); if (size <= 0) return null; IntPtr buffer = Marshal.AllocHGlobal(size); try { status = SafeNativeMethods.Gdip.GdipGetEncoderParameterList(new HandleRef(this, nativeImage), ref encoder, size, buffer); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } p = EncoderParameters.ConvertFromMemory(buffer); } finally { Marshal.FreeHGlobal(buffer); } return p; } /// <summary> /// Saves this <see cref='Image'/> to the specified file. /// </summary> public void Save(string filename) { Save(filename, RawFormat); } /// <summary> /// Saves this <see cref='Image'/> to the specified file in the specified format. /// </summary> public void Save(string filename, ImageFormat format) { if (format == null) throw new ArgumentNullException("format"); ImageCodecInfo codec = format.FindEncoder(); if (codec == null) codec = ImageFormat.Png.FindEncoder(); Save(filename, codec, null); } /// <summary> /// Saves this <see cref='Image'/> to the specified file in the specified format and with the specified encoder parameters. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public void Save(string filename, ImageCodecInfo encoder, EncoderParameters encoderParams) { if (filename == null) throw new ArgumentNullException("filename"); if (encoder == null) throw new ArgumentNullException("encoder"); IntPtr encoderParamsMemory = IntPtr.Zero; if (encoderParams != null) { _rawData = null; encoderParamsMemory = encoderParams.ConvertToMemory(); } int status = SafeNativeMethods.Gdip.Ok; try { Guid g = encoder.Clsid; bool saved = false; if (_rawData != null) { ImageCodecInfo rawEncoder = RawFormat.FindEncoder(); if (rawEncoder != null && rawEncoder.Clsid == g) { using (FileStream fs = File.OpenWrite(filename)) { fs.Write(_rawData, 0, _rawData.Length); saved = true; } } } if (!saved) { status = SafeNativeMethods.Gdip.GdipSaveImageToFile(new HandleRef(this, nativeImage), filename, ref g, new HandleRef(encoderParams, encoderParamsMemory)); } } finally { if (encoderParamsMemory != IntPtr.Zero) { Marshal.FreeHGlobal(encoderParamsMemory); } } if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } internal void Save(MemoryStream stream) { // Jpeg loses data, so we don't want to use it to serialize... ImageFormat dest = RawFormat; if (dest == ImageFormat.Jpeg) { dest = ImageFormat.Png; } ImageCodecInfo codec = dest.FindEncoder(); // If we don't find an Encoder (for things like Icon), we // just switch back to PNG... if (codec == null) { codec = ImageFormat.Png.FindEncoder(); } Save(stream, codec, null); } /// <summary> /// Saves this <see cref='Image'/> to the specified stream in the specified format. /// </summary> public void Save(Stream stream, ImageFormat format) { if (format == null) throw new ArgumentNullException("format"); ImageCodecInfo codec = format.FindEncoder(); Save(stream, codec, null); } /// <summary> /// Saves this <see cref='Image'/> to the specified stream in the specified format. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public void Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) { if (stream == null) { throw new ArgumentNullException("stream"); } if (encoder == null) { throw new ArgumentNullException("encoder"); } IntPtr encoderParamsMemory = IntPtr.Zero; if (encoderParams != null) { _rawData = null; encoderParamsMemory = encoderParams.ConvertToMemory(); } int status = SafeNativeMethods.Gdip.Ok; try { Guid g = encoder.Clsid; bool saved = false; if (_rawData != null) { ImageCodecInfo rawEncoder = RawFormat.FindEncoder(); if (rawEncoder != null && rawEncoder.Clsid == g) { stream.Write(_rawData, 0, _rawData.Length); saved = true; } } if (!saved) { status = SafeNativeMethods.Gdip.GdipSaveImageToStream(new HandleRef(this, nativeImage), new UnsafeNativeMethods.ComStreamFromDataStream(stream), ref g, new HandleRef(encoderParams, encoderParamsMemory)); } } finally { if (encoderParamsMemory != IntPtr.Zero) { Marshal.FreeHGlobal(encoderParamsMemory); } } if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } /// <summary> /// Adds an <see cref='EncoderParameters'/> to this <see cref='Image'/>. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public void SaveAdd(EncoderParameters encoderParams) { IntPtr encoder = IntPtr.Zero; if (encoderParams != null) { encoder = encoderParams.ConvertToMemory(); } _rawData = null; int status = SafeNativeMethods.Gdip.GdipSaveAdd(new HandleRef(this, nativeImage), new HandleRef(encoderParams, encoder)); if (encoder != IntPtr.Zero) { Marshal.FreeHGlobal(encoder); } if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } /// <summary> /// Adds an <see cref='EncoderParameters'/> to the specified <see cref='Image'/>. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public void SaveAdd(Image image, EncoderParameters encoderParams) { IntPtr encoder = IntPtr.Zero; if (image == null) { throw new ArgumentNullException("image"); } if (encoderParams != null) { encoder = encoderParams.ConvertToMemory(); } _rawData = null; int status = SafeNativeMethods.Gdip.GdipSaveAddImage(new HandleRef(this, nativeImage), new HandleRef(image, image.nativeImage), new HandleRef(encoderParams, encoder)); if (encoder != IntPtr.Zero) { Marshal.FreeHGlobal(encoder); } if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } private SizeF _GetPhysicalDimension() { float width; float height; int status = SafeNativeMethods.Gdip.GdipGetImageDimension(new HandleRef(this, nativeImage), out width, out height); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return new SizeF(width, height); } /// <summary> /// Gets the width and height of this <see cref='Image'/>. /// </summary> public SizeF PhysicalDimension { get { return _GetPhysicalDimension(); } } /// <summary> /// Gets the width and height of this <see cref='Image'/>. /// </summary> public Size Size { get { return new Size(Width, Height); } } /// <summary> /// Gets the width of this <see cref='Image'/>. /// </summary> [ DefaultValue(false), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public int Width { get { int width; int status = SafeNativeMethods.Gdip.GdipGetImageWidth(new HandleRef(this, nativeImage), out width); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return width; } } /// <summary> /// Gets the height of this <see cref='Image'/>. /// </summary> [ DefaultValue(false), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public int Height { get { int height; int status = SafeNativeMethods.Gdip.GdipGetImageHeight(new HandleRef(this, nativeImage), out height); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return height; } } /// <summary> /// Gets the horizontal resolution, in pixels-per-inch, of this <see cref='Image'/>. /// </summary> public float HorizontalResolution { get { float horzRes; int status = SafeNativeMethods.Gdip.GdipGetImageHorizontalResolution(new HandleRef(this, nativeImage), out horzRes); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return horzRes; } } /// <summary> /// Gets the vertical resolution, in pixels-per-inch, of this <see cref='Image'/>. /// </summary> public float VerticalResolution { get { float vertRes; int status = SafeNativeMethods.Gdip.GdipGetImageVerticalResolution(new HandleRef(this, nativeImage), out vertRes); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return vertRes; } } /// <summary> /// Gets attribute flags for this <see cref='Image'/>. /// </summary> [Browsable(false)] public int Flags { get { int flags; int status = SafeNativeMethods.Gdip.GdipGetImageFlags(new HandleRef(this, nativeImage), out flags); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return flags; } } /// <summary> /// Gets the format of this <see cref='Image'/>. /// </summary> public ImageFormat RawFormat { get { Guid guid = new Guid(); int status = SafeNativeMethods.Gdip.GdipGetImageRawFormat(new HandleRef(this, nativeImage), ref guid); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return new ImageFormat(guid); } } /// <summary> /// Gets the pixel format for this <see cref='Image'/>. /// </summary> public PixelFormat PixelFormat { get { int format; int status = SafeNativeMethods.Gdip.GdipGetImagePixelFormat(new HandleRef(this, nativeImage), out format); if (status != SafeNativeMethods.Gdip.Ok) return PixelFormat.Undefined; else return (PixelFormat)format; } } /// <summary> /// Gets a bounding rectangle in the specified units for this <see cref='Image'/>. /// </summary> public RectangleF GetBounds(ref GraphicsUnit pageUnit) { GPRECTF gprectf = new GPRECTF(); int status = SafeNativeMethods.Gdip.GdipGetImageBounds(new HandleRef(this, nativeImage), ref gprectf, out pageUnit); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return gprectf.ToRectangleF(); } private ColorPalette _GetColorPalette() { int size = -1; int status = SafeNativeMethods.Gdip.GdipGetImagePaletteSize(new HandleRef(this, nativeImage), out size); // "size" is total byte size: // sizeof(ColorPalette) + (pal->Count-1)*sizeof(ARGB) if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } ColorPalette palette = new ColorPalette(size); // Memory layout is: // UINT Flags // UINT Count // ARGB Entries[size] IntPtr memory = Marshal.AllocHGlobal(size); try { status = SafeNativeMethods.Gdip.GdipGetImagePalette(new HandleRef(this, nativeImage), memory, size); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } palette.ConvertFromMemory(memory); } finally { Marshal.FreeHGlobal(memory); } return palette; } private void _SetColorPalette(ColorPalette palette) { IntPtr memory = palette.ConvertToMemory(); int status = SafeNativeMethods.Gdip.GdipSetImagePalette(new HandleRef(this, nativeImage), memory); if (memory != IntPtr.Zero) { Marshal.FreeHGlobal(memory); } if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } /// <summary> /// Gets or sets the color palette used for this <see cref='Image'/>. /// </summary> [Browsable(false)] public ColorPalette Palette { get { return _GetColorPalette(); } set { _SetColorPalette(value); } } // Thumbnail support /// <summary> /// Returns the thumbnail for this <see cref='Image'/>. /// </summary> public Image GetThumbnailImage(int thumbWidth, int thumbHeight, GetThumbnailImageAbort callback, IntPtr callbackData) { IntPtr thumbImage = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipGetImageThumbnail(new HandleRef(this, nativeImage), thumbWidth, thumbHeight, out thumbImage, callback, callbackData); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return CreateImageObject(thumbImage); } // Multi-frame support /// <summary> /// Gets an array of GUIDs that represent the dimensions of frames within this <see cref='Image'/>. /// </summary> [Browsable(false)] public Guid[] FrameDimensionsList { get { int count; int status = SafeNativeMethods.Gdip.GdipImageGetFrameDimensionsCount(new HandleRef(this, nativeImage), out count); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } Debug.Assert(count >= 0, "FrameDimensionsList returns bad count"); if (count <= 0) { return new Guid[0]; } int size = (int)Marshal.SizeOf(typeof(Guid)); IntPtr buffer = Marshal.AllocHGlobal(checked(size * count)); if (buffer == IntPtr.Zero) { throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory); } status = SafeNativeMethods.Gdip.GdipImageGetFrameDimensionsList(new HandleRef(this, nativeImage), buffer, count); if (status != SafeNativeMethods.Gdip.Ok) { Marshal.FreeHGlobal(buffer); throw SafeNativeMethods.Gdip.StatusException(status); } Guid[] guids = new Guid[count]; try { for (int i = 0; i < count; i++) { guids[i] = (Guid)UnsafeNativeMethods.PtrToStructure((IntPtr)((long)buffer + size * i), typeof(Guid)); } } finally { Marshal.FreeHGlobal(buffer); } return guids; } } /// <summary> /// Returns the number of frames of the given dimension. /// </summary> public int GetFrameCount(FrameDimension dimension) { int[] count = new int[] { 0 }; Guid dimensionID = dimension.Guid; int status = SafeNativeMethods.Gdip.GdipImageGetFrameCount(new HandleRef(this, nativeImage), ref dimensionID, count); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return count[0]; } /// <summary> /// Selects the frame specified by the given dimension and index. /// </summary> public int SelectActiveFrame(FrameDimension dimension, int frameIndex) { int[] count = new int[] { 0 }; Guid dimensionID = dimension.Guid; int status = SafeNativeMethods.Gdip.GdipImageSelectActiveFrame(new HandleRef(this, nativeImage), ref dimensionID, frameIndex); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return count[0]; } public void RotateFlip(RotateFlipType rotateFlipType) { int status = SafeNativeMethods.Gdip.GdipImageRotateFlip(new HandleRef(this, nativeImage), unchecked((int)rotateFlipType)); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <summary> /// Gets an array of the property IDs stored in this <see cref='Image'/>. /// </summary> [Browsable(false)] public int[] PropertyIdList { get { int count; int status = SafeNativeMethods.Gdip.GdipGetPropertyCount(new HandleRef(this, nativeImage), out count); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); int[] propid = new int[count]; //if we have a 0 count, just return our empty array if (count == 0) return propid; status = SafeNativeMethods.Gdip.GdipGetPropertyIdList(new HandleRef(this, nativeImage), count, propid); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return propid; } } /// <summary> /// Gets the specified property item from this <see cref='Image'/>. /// </summary> public PropertyItem GetPropertyItem(int propid) { PropertyItem propitem; int size; int status = SafeNativeMethods.Gdip.GdipGetPropertyItemSize(new HandleRef(this, nativeImage), propid, out size); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); if (size == 0) return null; IntPtr propdata = Marshal.AllocHGlobal(size); if (propdata == IntPtr.Zero) throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory); try { status = SafeNativeMethods.Gdip.GdipGetPropertyItem(new HandleRef(this, nativeImage), propid, size, propdata); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } propitem = PropertyItemInternal.ConvertFromMemory(propdata, 1)[0]; } finally { Marshal.FreeHGlobal(propdata); } return propitem; } /// <summary> /// Removes the specified property item from this <see cref='Image'/>. /// </summary> public void RemovePropertyItem(int propid) { int status = SafeNativeMethods.Gdip.GdipRemovePropertyItem(new HandleRef(this, nativeImage), propid); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <summary> /// Sets the specified property item to the specified value. /// </summary> public void SetPropertyItem(PropertyItem propitem) { PropertyItemInternal propItemInternal = PropertyItemInternal.ConvertFromPropertyItem(propitem); using (propItemInternal) { int status = SafeNativeMethods.Gdip.GdipSetPropertyItem(new HandleRef(this, nativeImage), propItemInternal); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } } /// <summary> /// Gets an array of <see cref='PropertyItem'/> objects that describe this <see cref='Image'/>. /// </summary> [Browsable(false)] public PropertyItem[] PropertyItems { get { int size; int count; int status = SafeNativeMethods.Gdip.GdipGetPropertyCount(new HandleRef(this, nativeImage), out count); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); status = SafeNativeMethods.Gdip.GdipGetPropertySize(new HandleRef(this, nativeImage), out size, ref count); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); if (size == 0 || count == 0) return new PropertyItem[0]; IntPtr propdata = Marshal.AllocHGlobal(size); try { status = SafeNativeMethods.Gdip.GdipGetAllPropertyItems(new HandleRef(this, nativeImage), size, count, propdata); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } return PropertyItemInternal.ConvertFromMemory(propdata, count); } finally { Marshal.FreeHGlobal(propdata); } } } internal void SetNativeImage(IntPtr handle) { if (handle == IntPtr.Zero) throw new ArgumentException(SR.Format(SR.NativeHandle0), "handle"); nativeImage = handle; } /// <summary> /// Creates a <see cref='Bitmap'/> from a Windows handle. /// </summary> public static Bitmap FromHbitmap(IntPtr hbitmap) { return FromHbitmap(hbitmap, IntPtr.Zero); } /// <summary> /// Creates a <see cref='Bitmap'/> from the specified Windows handle with the specified color palette. /// </summary> public static Bitmap FromHbitmap(IntPtr hbitmap, IntPtr hpalette) { IntPtr bitmap = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateBitmapFromHBITMAP(new HandleRef(null, hbitmap), new HandleRef(null, hpalette), out bitmap); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return Bitmap.FromGDIplus(bitmap); } /// <summary> /// Returns the size of the specified pixel format. /// </summary> public static int GetPixelFormatSize(PixelFormat pixfmt) { return (unchecked((int)pixfmt) >> 8) & 0xFF; } /// <summary> /// Returns a value indicating whether the pixel format contains alpha information. /// </summary> public static bool IsAlphaPixelFormat(PixelFormat pixfmt) { return (pixfmt & PixelFormat.Alpha) != 0; } /// <summary> /// Returns a value indicating whether the pixel format is extended. /// </summary> public static bool IsExtendedPixelFormat(PixelFormat pixfmt) { return (pixfmt & PixelFormat.Extended) != 0; } /* * Determine if the pixel format is canonical format: * PixelFormat32bppARGB * PixelFormat32bppPARGB * PixelFormat64bppARGB * PixelFormat64bppPARGB */ /// <summary> /// Returns a value indicating whether the pixel format is canonical. /// </summary> public static bool IsCanonicalPixelFormat(PixelFormat pixfmt) { return (pixfmt & PixelFormat.Canonical) != 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using OLEDB.Test.ModuleCore; using System.IO; using XmlCoreTest.Common; namespace System.Xml.Tests { public abstract partial class XmlWriterTestCaseBase : CTestCase { public static string nl = Environment.NewLine; public XmlWriterTestCaseBase() : base() { } public override int Init(object o) { return base.Init(o); } public XmlWriterTestModule XmlWriterTestModule { get { return (XmlWriterTestModule)this.TestModule; } } public WriterType WriterType { get { return this.XmlWriterTestModule.WriterFactory.WriterType; } } public string BaselinePath { get { return this.XmlWriterTestModule.BaselinePath; } } public string FullPath(string fileName) { if (fileName == null || fileName == String.Empty) return fileName; return BaselinePath + fileName; } public virtual XmlWriter CreateWriter() { return this.XmlWriterTestModule.WriterFactory.CreateWriter(); } public virtual XmlWriter CreateWriter(XmlWriterSettings s) { return this.XmlWriterTestModule.WriterFactory.CreateWriter(s); } public virtual XmlReader GetReader() { return this.XmlWriterTestModule.WriterFactory.GetReader(); } public bool CompareReader(string strExpected) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CheckCharacters = false; readerSettings.CloseInput = true; readerSettings.ConformanceLevel = ConformanceLevel.Auto; StringReader sr = new StringReader(strExpected); XmlReader xrExpected = XmlReader.Create(sr, readerSettings); return this.XmlWriterTestModule.WriterFactory.CompareReader(xrExpected); } public bool CompareString(string strExpected) { CError.WriteLine(this.XmlWriterTestModule.WriterFactory.GetString()); if (strExpected.Contains("~")) return this.XmlWriterTestModule.WriterFactory.CompareStringWithPrefixes(strExpected); return this.XmlWriterTestModule.WriterFactory.CompareString(strExpected); } public string RemoveSpaceInDocType(string xml) { int docPos = xml.IndexOf("<!DOCTYPE"); if (docPos < 0) return xml; int spacePos = xml.IndexOf(' ', docPos + "<!DOCTYPE".Length + 1); int subsetPos = xml.IndexOf('[', docPos + "<!DOCTYPE".Length + 1); int closePos = xml.IndexOf('>', docPos + "<!DOCTYPE".Length + 1); if (spacePos + 1 == subsetPos || spacePos + 1 == closePos) xml = xml.Remove(spacePos, 1); return xml; } public bool IsIndent() { return (WriterType == WriterType.UTF8WriterIndent || WriterType == WriterType.UnicodeWriterIndent) ? true : false; } public void CheckErrorState(WriteState ws) { if (WriterType == WriterType.CharCheckingWriter) return; CError.Compare(ws, WriteState.Error, "WriteState should be Error"); } public void CheckElementState(WriteState ws) { CError.Compare(ws, WriteState.Element, "WriteState should be Element"); } public bool CompareBaseline(string baselineFile) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CloseInput = true; XmlReader xrExpected = XmlReader.Create(FilePathUtil.getStream(FullPath(baselineFile)), readerSettings); return this.XmlWriterTestModule.WriterFactory.CompareReader(xrExpected); } public bool CompareBaseline2(string baselineFile) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CloseInput = true; XmlReader xrExpected = XmlReader.Create(FilePathUtil.getStream(baselineFile), readerSettings); return this.XmlWriterTestModule.WriterFactory.CompareReader(xrExpected); } public void RaiseError(String strErrorMsg) { Exception e = new Exception(strErrorMsg); throw (e); } } public abstract partial class XmlFactoryWriterTestCaseBase : XmlWriterTestCaseBase { public XmlFactoryWriterTestCaseBase() : base() { } public virtual string GetString() { return this.XmlWriterTestModule.WriterFactory.GetString(); } public virtual XmlWriter CreateWriter(ConformanceLevel cl) { return this.XmlWriterTestModule.WriterFactory.CreateWriter(cl); } public override XmlWriter CreateWriter(XmlWriterSettings wSettings) { return this.XmlWriterTestModule.WriterFactory.CreateWriter(wSettings); } } public abstract partial class TCWriteBuffer : XmlWriterTestCaseBase { public int VerifyInvalidWrite(string methodName, int iBufferSize, int iIndex, int iCount, Type exceptionType) { byte[] byteBuffer = new byte[iBufferSize]; for (int i = 0; i < iBufferSize; i++) byteBuffer[i] = (byte)(i + '0'); char[] charBuffer = new char[iBufferSize]; for (int i = 0; i < iBufferSize; i++) charBuffer[i] = (char)(i + '0'); XmlWriter w = CreateWriter(); w.WriteStartElement("root"); try { switch (methodName) { case "WriteBase64": w.WriteBase64(byteBuffer, iIndex, iCount); break; case "WriteRaw": w.WriteRaw(charBuffer, iIndex, iCount); break; case "WriteBinHex": w.WriteBinHex(byteBuffer, iIndex, iCount); break; case "WriteChars": w.WriteChars(charBuffer, iIndex, iCount); break; default: CError.Compare(false, "Unexpected method name " + methodName); break; } } catch (Exception e) { CError.WriteLineIgnore("Exception: " + e.ToString()); if (exceptionType.FullName.Equals(e.GetType().FullName)) { return TEST_PASS; } else { CError.WriteLine("Did not throw exception of type {0}", exceptionType); } } w.Flush(); return TEST_FAIL; } public byte[] StringToByteArray(string src) { byte[] base64 = new byte[src.Length * 2]; for (int i = 0; i < src.Length; i++) { byte[] temp = System.BitConverter.GetBytes(src[i]); base64[2 * i] = temp[0]; base64[2 * i + 1] = temp[1]; } return base64; } public static void ensureSpace(ref byte[] buffer, int len) { if (len >= buffer.Length) { int originalLen = buffer.Length; byte[] newBuffer = new byte[(int)(len * 2)]; for (int i = 0; i < originalLen; newBuffer[i] = buffer[i++]) { // Intentionally Empty } buffer = newBuffer; } } public static void WriteToBuffer(ref byte[] destBuff, ref int len, byte srcByte) { ensureSpace(ref destBuff, len); destBuff[len++] = srcByte; } public static void WriteToBuffer(ref byte[] destBuff, ref int len, byte[] srcBuff) { int srcArrayLen = srcBuff.Length; WriteToBuffer(ref destBuff, ref len, srcBuff, 0, (int)srcArrayLen); } public static void WriteToBuffer(ref byte[] destBuff, ref int destStart, byte[] srcBuff, int srcStart, int count) { ensureSpace(ref destBuff, destStart + count - 1); for (int i = srcStart; i < srcStart + count; i++) { destBuff[destStart++] = srcBuff[i]; } } public static void WriteToBuffer(ref byte[] destBuffer, ref int destBuffLen, String strValue) { for (int i = 0; i < strValue.Length; i++) { WriteToBuffer(ref destBuffer, ref destBuffLen, System.BitConverter.GetBytes(strValue[i])); } WriteToBuffer(ref destBuffer, ref destBuffLen, System.BitConverter.GetBytes('\0')); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Lime.Messaging.Resources; using Lime.Protocol; using NSubstitute; using Serilog; using Shouldly; using Take.Blip.Client.Extensions.Contacts; using Take.Blip.Client.Extensions.Directory; using Take.Blip.Client.Receivers; using Xunit; namespace Take.Blip.Client.UnitTests.Receivers { public class ContactMessageReceiverBaseTests : TestsBase { public ContactMessageReceiverBaseTests() { ContactExtension = Substitute.For<IContactExtension>(); DirectoryExtension = Substitute.For<IDirectoryExtension>(); CacheExpiration = TimeSpan.FromMilliseconds(250); } public IContactExtension ContactExtension { get; } public IDirectoryExtension DirectoryExtension { get; set; } public bool CacheLocally { get; set; } public TimeSpan CacheExpiration { get; set; } public TestContactMessageReceiver GetTarget() { return new TestContactMessageReceiver( ContactExtension, DirectoryExtension, Substitute.For<ILogger>(), CacheLocally, CacheExpiration ); } [Fact] public async Task ReceiveMessageShouldGetContactFromContacts() { // Arrange var message = Dummy.CreateMessage(); var identity = message.From.ToIdentity(); var contact = Dummy.CreateContact(); contact.Identity = identity; ContactExtension .GetAsync(identity, Arg.Any<CancellationToken>()) .Returns(contact); var target = GetTarget(); // Act await target.ReceiveAsync(message, CancellationToken); // Assert target.ReceivedItems.Count.ShouldBe(1); target.ReceivedItems[0].message.ShouldBe(message); var actualContact = target.ReceivedItems[0].contact; actualContact.ShouldNotBeNull(); foreach (var property in typeof(Contact).GetProperties()) { property .GetValue(actualContact) .ShouldBe( property.GetValue(contact)); } } [Fact] public async Task ReceiveMessageShouldGetContactFromDirectoryWhenNotInContacts() { // Arrange var message = Dummy.CreateMessage(); var identity = message.From.ToIdentity(); var account = Dummy.CreateAccount(); account.Identity = identity; DirectoryExtension .GetDirectoryAccountAsync(identity, Arg.Any<CancellationToken>()) .Returns(account); var target = GetTarget(); // Act await target.ReceiveAsync(message, CancellationToken); // Assert target.ReceivedItems.Count.ShouldBe(1); target.ReceivedItems[0].message.ShouldBe(message); var actualContact = target.ReceivedItems[0].contact; actualContact.ShouldNotBeNull(); actualContact.Name.ShouldBe(account.FullName); foreach (var property in typeof(ContactDocument).GetProperties()) { property .GetValue(actualContact) .ShouldBe( property.GetValue(account)); } } [Fact] public async Task ReceiveMessageTwiceShouldGetContactFromCacheOnSecondTime() { // Arrange CacheLocally = true; var message = Dummy.CreateMessage(); var identity = message.From.ToIdentity(); var contact = Dummy.CreateContact(); contact.Identity = identity; ContactExtension .GetAsync(identity, Arg.Any<CancellationToken>()) .Returns(contact); var target = GetTarget(); // Act await target.ReceiveAsync(message, CancellationToken); await target.ReceiveAsync(message, CancellationToken); // Assert ContactExtension.Received(1).GetAsync(identity, CancellationToken); } [Fact] public async Task ReceiveMessageTwiceShouldGetContactFromContactsTwiceWhenCaseIsDisabled() { // Arrange CacheLocally = false; var message = Dummy.CreateMessage(); var identity = message.From.ToIdentity(); var contact = Dummy.CreateContact(); contact.Identity = identity; ContactExtension .GetAsync(identity, Arg.Any<CancellationToken>()) .Returns(contact); var target = GetTarget(); // Act await target.ReceiveAsync(message, CancellationToken); await target.ReceiveAsync(message, CancellationToken); // Assert ContactExtension.Received(2).GetAsync(identity, CancellationToken); } [Fact] public async Task ReceiveMessageTwiceShouldGetContactFromContactsTwiceWhenCaseExpires() { // Arrange CacheLocally = true; var message = Dummy.CreateMessage(); var identity = message.From.ToIdentity(); var contact = Dummy.CreateContact(); contact.Identity = identity; ContactExtension .GetAsync(identity, Arg.Any<CancellationToken>()) .Returns(contact); var target = GetTarget(); // Act await target.ReceiveAsync(message, CancellationToken); await Task.Delay(CacheExpiration + CacheExpiration); await target.ReceiveAsync(message, CancellationToken); // Assert ContactExtension.Received(2).GetAsync(identity, CancellationToken); } } public class TestContactMessageReceiver : ContactMessageReceiverBase { public TestContactMessageReceiver( IContactExtension contactExtension, IDirectoryExtension directoryExtension, ILogger logger, bool cacheLocally = true, TimeSpan cacheExpiration = default) : base(contactExtension, directoryExtension, logger, cacheLocally, cacheExpiration) { ReceivedItems = new List<(Message, Contact)>(); } public List<(Message message, Contact contact)> ReceivedItems { get; } protected override Task ReceiveAsync(Message message, Contact contact, CancellationToken cancellationToken = default(CancellationToken)) { ReceivedItems.Add((message, contact)); return Task.CompletedTask; } } }
// ReSharper disable All using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Account.DataAccess; using Frapid.Account.Api.Fakes; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Xunit; namespace Frapid.Account.Api.Tests { public class LoginTests { public static LoginController Fixture() { LoginController controller = new LoginController(new LoginRepository()); return controller; } [Fact] [Conditional("Debug")] public void CountEntityColumns() { EntityView entityView = Fixture().GetEntityView(); Assert.Null(entityView.Columns); } [Fact] [Conditional("Debug")] public void Count() { long count = Fixture().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetAll() { int count = Fixture().GetAll().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Export() { int count = Fixture().Export().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Get() { Frapid.Account.Entities.Login login = Fixture().Get(0); Assert.NotNull(login); } [Fact] [Conditional("Debug")] public void First() { Frapid.Account.Entities.Login login = Fixture().GetFirst(); Assert.NotNull(login); } [Fact] [Conditional("Debug")] public void Previous() { Frapid.Account.Entities.Login login = Fixture().GetPrevious(0); Assert.NotNull(login); } [Fact] [Conditional("Debug")] public void Next() { Frapid.Account.Entities.Login login = Fixture().GetNext(0); Assert.NotNull(login); } [Fact] [Conditional("Debug")] public void Last() { Frapid.Account.Entities.Login login = Fixture().GetLast(); Assert.NotNull(login); } [Fact] [Conditional("Debug")] public void GetMultiple() { IEnumerable<Frapid.Account.Entities.Login> logins = Fixture().Get(new long[] { }); Assert.NotNull(logins); } [Fact] [Conditional("Debug")] public void GetPaginatedResult() { int count = Fixture().GetPaginatedResult().Count(); Assert.Equal(1, count); count = Fixture().GetPaginatedResult(1).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountWhere() { long count = Fixture().CountWhere(new JArray()); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetWhere() { int count = Fixture().GetWhere(1, new JArray()).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountFiltered() { long count = Fixture().CountFiltered(""); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetFiltered() { int count = Fixture().GetFiltered(1, "").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetDisplayFields() { int count = Fixture().GetDisplayFields().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetCustomFields() { int count = Fixture().GetCustomFields().Count(); Assert.Equal(1, count); count = Fixture().GetCustomFields("").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void AddOrEdit() { try { var form = new JArray { null, null }; Fixture().AddOrEdit(form); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Add() { try { Fixture().Add(null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Edit() { try { Fixture().Edit(0, null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void BulkImport() { var collection = new JArray { null, null, null, null }; var actual = Fixture().BulkImport(collection); Assert.NotNull(actual); } [Fact] [Conditional("Debug")] public void Delete() { try { Fixture().Delete(0); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using RaptorDB.Common; using fastJSON; namespace fastBinaryJSON { internal sealed class BJsonParser { readonly byte[] json; int index; bool _useUTC = true; internal BJsonParser(byte[] json, bool useUTC) { this.json = json; _useUTC = useUTC; } public object Decode() { bool b = false; return ParseValue(out b); } private Dictionary<string, object> ParseObject() { Dictionary<string, object> dic = new Dictionary<string, object>(); bool breakparse = false; while (!breakparse) { byte t = GetToken(); if (t == TOKENS.COMMA) continue; if (t == TOKENS.DOC_END) break; string key = ""; if (t != TOKENS.NAME) throw new Exception("excpecting a name field"); key = ParseName(); t = GetToken(); if (t != TOKENS.COLON) throw new Exception("expecting a colon"); object val = ParseValue(out breakparse); if (breakparse == false) { dic.Add(key, val); } } return dic; } private string ParseName() { byte c = json[index++]; string s = Reflection.Instance.utf8.GetString(json, index, c); index += c; return s; } private List<object> ParseArray() { List<object> array = new List<object>(); bool breakparse = false; while (!breakparse) { object o = ParseValue(out breakparse); byte t = 0; if (breakparse == false) { array.Add(o); t = GetToken(); } else t = (byte)o; if (t == TOKENS.COMMA) continue; if (t == TOKENS.ARRAY_END) break; } return array; } private object ParseValue(out bool breakparse) { byte t = GetToken(); breakparse = false; switch (t) { case TOKENS.BYTE: return ParseByte(); case TOKENS.BYTEARRAY: return ParseByteArray(); case TOKENS.CHAR: return ParseChar(); case TOKENS.DATETIME: return ParseDateTime(); case TOKENS.DECIMAL: return ParseDecimal(); case TOKENS.DOUBLE: return ParseDouble(); case TOKENS.FLOAT: return ParseFloat(); case TOKENS.GUID: return ParseGuid(); case TOKENS.INT: return ParseInt(); case TOKENS.LONG: return ParseLong(); case TOKENS.SHORT: return ParseShort(); //case TOKENS.SINGLE: // return ParseSingle(); case TOKENS.UINT: return ParseUint(); case TOKENS.ULONG: return ParseULong(); case TOKENS.USHORT: return ParseUShort(); case TOKENS.UNICODE_STRING: return ParseUnicodeString(); case TOKENS.STRING: return ParseString(); case TOKENS.DOC_START: return ParseObject(); case TOKENS.ARRAY_START: return ParseArray(); case TOKENS.TRUE: return true; case TOKENS.FALSE: return false; case TOKENS.NULL: return null; case TOKENS.ARRAY_END: breakparse = true; return TOKENS.ARRAY_END; case TOKENS.DOC_END: breakparse = true; return TOKENS.DOC_END; case TOKENS.COMMA: breakparse = true; return TOKENS.COMMA; } throw new Exception("Unrecognized token at index = " + index); } private object ParseChar() { short u = (short)Helper.ToInt16(json, index); index += 2; return u; } private Guid ParseGuid() { byte[] b = new byte[16]; Buffer.BlockCopy(json, index, b, 0, 16); index += 16; return new Guid(b); } private float ParseFloat() { float f = BitConverter.ToSingle(json, index); index += 4; return f; } private ushort ParseUShort() { ushort u = (ushort)Helper.ToInt16(json, index); index += 2; return u; } private ulong ParseULong() { ulong u = (ulong)Helper.ToInt64(json, index); index += 8; return u; } private uint ParseUint() { uint u = (uint)Helper.ToInt32(json, index); index += 4; return u; } private short ParseShort() { short u = (short)Helper.ToInt16(json, index); index += 2; return u; } private long ParseLong() { long u = (long)Helper.ToInt64(json, index); index += 8; return u; } private int ParseInt() { int u = (int)Helper.ToInt32(json, index); index += 4; return u; } private double ParseDouble() { double d = BitConverter.ToDouble(json, index); index += 8; return d; } private object ParseUnicodeString() { int c = Helper.ToInt32(json, index); index += 4; string s = Reflection.Instance.unicode.GetString(json, index, c); index += c; return s; } private string ParseString() { int c = Helper.ToInt32(json, index); index += 4; string s = Reflection.Instance.utf8.GetString(json, index, c); index += c; return s; } private decimal ParseDecimal() { int[] i = new int[4]; i[0] = Helper.ToInt32(json, index); index += 4; i[1] = Helper.ToInt32(json, index); index += 4; i[2] = Helper.ToInt32(json, index); index += 4; i[3] = Helper.ToInt32(json, index); index += 4; return new decimal(i); } private DateTime ParseDateTime() { long l = Helper.ToInt64(json, index); index += 8; DateTime dt = new DateTime(l); if (_useUTC) dt = dt.ToLocalTime(); // to local time return dt; } private byte[] ParseByteArray() { int c = Helper.ToInt32(json, index); index += 4; byte[] b = new byte[c]; Buffer.BlockCopy(json, index, b, 0, c); index += c; return b; } private byte ParseByte() { return json[index++]; } private byte GetToken() { byte b = json[index++]; return b; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Xml; #pragma warning disable 618 namespace Apache.Geode.Client.FwkLib { using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; [Serializable] public enum DataKind { String, List, Region, Range, Pool } [Serializable] public class FwkLocalFile { private string m_name; private bool m_append; private string m_description; private string m_content; #region Public accessors public string Name { get { return m_name; } } public bool Append { get { return m_append; } } public string Description { get { return m_description; } } public string Content { get { return m_content; } } #endregion public FwkLocalFile(string name, bool append, string description, string content) { m_name = name; m_append = append; m_description = description; m_content = content; } public static void LoadLocalFileNodes(XmlNode node) { XmlNodeList xmlNodes = node.SelectNodes("localFile"); if (xmlNodes != null) { foreach (XmlNode lf in xmlNodes) { XmlAttributeCollection attrcoll = lf.Attributes; string name = null; bool append = false; ; string description = null; foreach (XmlAttribute attr in attrcoll) { // Console.WriteLine("attr name " + attr.Name); if (attr.Name == "name") { name = attr.Name; } else if (attr.Name == "append") { if (attr.Value == "true") { append = true; } else { append = false; } } else if (attr.Name == "description") { description = attr.Value; } else { throw new IllegalArgException("Local file data format incorrect"); } } FwkLocalFile lfobj = new FwkLocalFile(name, append, description, lf.InnerText); Util.BBSet(string.Empty, name, lfobj); } } } } [Serializable] public class FwkData { #region Private members private object m_data1; private object m_data2; private DataKind m_kind; #endregion #region Public accessors public DataKind Kind { get { return m_kind; } } public object Data1 { get { return m_data1; } set { m_data1 = value; } } public object Data2 { get { return m_data2; } set { m_data2 = null; } } #endregion public FwkData(object data1, object data2, DataKind kind) { m_data1 = data1; m_data2 = data2; m_kind = kind; } public static Dictionary<string, FwkData> ReadDataNodes(XmlNode node) { throw new Exception(); } public static void SetThisAttribute(string name, XmlNode node, Apache.Geode.Client.RegionAttributesFactory<string, string> regionAttributesFactory) { string value = node.Value; switch (name) { case "caching-enabled": if (value == "true") { regionAttributesFactory.SetCachingEnabled(true); } else { regionAttributesFactory.SetCachingEnabled(false); } break; case "load-factor": float lf = float.Parse(value); regionAttributesFactory.SetLoadFactor(lf); break; case "concurrency-level": int cl = int.Parse(value); regionAttributesFactory.SetConcurrencyLevel(cl); break; case "lru-entries-limit": uint lel = uint.Parse(value); regionAttributesFactory.SetLruEntriesLimit(lel); break; case "initial-capacity": int ic = int.Parse(value); regionAttributesFactory.SetInitialCapacity(ic); break; case "disk-policy": if (value == "none") { regionAttributesFactory.SetDiskPolicy(Apache.Geode.Client.DiskPolicyType.None); } else if (value == "overflows") { regionAttributesFactory.SetDiskPolicy(Apache.Geode.Client.DiskPolicyType.Overflows); } else { throw new IllegalArgException("Unknown disk policy"); } break; case "pool-name": if (value.Length != 0) { regionAttributesFactory.SetPoolName(value); } else { regionAttributesFactory.SetPoolName(value); } break; case "client-notification": break; case "region-time-to-live": XmlNode nlrttl = node.FirstChild; if (nlrttl.Name == "expiration-attributes") { XmlAttributeCollection exAttrColl = nlrttl.Attributes; Apache.Geode.Client.ExpirationAction action = StrToExpirationAction(exAttrColl["action"].Value); string rttl = exAttrColl["timeout"].Value; regionAttributesFactory.SetRegionTimeToLive(action, TimeSpan.FromSeconds(uint.Parse(rttl))); } else { throw new IllegalArgException("The xml file passed has an unknowk format"); } break; case "region-idle-time": XmlNode nlrit = node.FirstChild; if (nlrit.Name == "expiration-attributes") { XmlAttributeCollection exAttrColl = nlrit.Attributes; Apache.Geode.Client.ExpirationAction action = StrToExpirationAction(exAttrColl["action"].Value); string rit = exAttrColl["timeout"].Value; regionAttributesFactory.SetRegionIdleTimeout(action, TimeSpan.FromSeconds(uint.Parse(rit))); } else { throw new IllegalArgException("The xml file passed has an unknowk format"); } break; case "entry-time-to-live": XmlNode nlettl = node.FirstChild; if (nlettl.Name == "expiration-attributes") { XmlAttributeCollection exAttrColl = nlettl.Attributes; Apache.Geode.Client.ExpirationAction action = StrToExpirationAction(exAttrColl["action"].Value); string ettl = exAttrColl["timeout"].Value; regionAttributesFactory.SetEntryTimeToLive(action, TimeSpan.FromSeconds(uint.Parse(ettl))); } else { throw new IllegalArgException("The xml file passed has an unknowk format"); } break; case "entry-idle-time": XmlNode nleit = node.FirstChild; if (nleit.Name == "expiration-attributes") { XmlAttributeCollection exAttrColl = nleit.Attributes; Apache.Geode.Client.ExpirationAction action = StrToExpirationAction(exAttrColl["action"].Value); string eit = exAttrColl["timeout"].Value; regionAttributesFactory.SetEntryIdleTimeout(action, TimeSpan.FromSeconds(uint.Parse(eit))); } else { throw new IllegalArgException("The xml file passed has an unknowk format"); } break; case "cache-loader": XmlAttributeCollection loaderattrs = node.Attributes; string loaderlibrary = null; string loaderfunction = null; foreach(XmlAttribute tmpattr in loaderattrs) { if (tmpattr.Name == "library") { loaderlibrary = tmpattr.Value; } else if (tmpattr.Name == "function") { loaderfunction = tmpattr.Value; } else { throw new IllegalArgException("cahe-loader attributes in improper format"); } } if (loaderlibrary != null && loaderfunction != null) { if (loaderfunction.IndexOf('.') < 0) { Type myType = typeof(FwkData); loaderfunction = myType.Namespace + '.' + loaderlibrary + '.' + loaderfunction; loaderlibrary = "FwkLib"; } regionAttributesFactory.SetCacheLoader(loaderlibrary, loaderfunction); } break; case "cache-listener": XmlAttributeCollection listenerattrs = node.Attributes; string listenerlibrary = null; string listenerfunction = null; foreach (XmlAttribute tmpattr in listenerattrs) { if (tmpattr.Name == "library") { listenerlibrary = tmpattr.Value; } else if (tmpattr.Name == "function") { listenerfunction = tmpattr.Value; } else { throw new IllegalArgException("cahe-loader attributes in improper format"); } } if (listenerlibrary != null && listenerfunction != null) { if (listenerfunction.IndexOf('.') < 0) { Type myType = typeof(FwkData); listenerfunction = myType.Namespace + '.' + listenerlibrary + '.' + listenerfunction; listenerlibrary = "FwkLib"; } regionAttributesFactory.SetCacheListener(listenerlibrary, listenerfunction); } break; case "cache-writer": XmlAttributeCollection writerattrs = node.Attributes; string writerlibrary = null; string writerfunction = null; foreach (XmlAttribute tmpattr in writerattrs) { if (tmpattr.Name == "library") { writerlibrary = tmpattr.Value; } else if (tmpattr.Name == "function") { writerfunction = tmpattr.Value; } else { throw new IllegalArgException("cahe-loader attributes in improper format"); } } if (writerlibrary != null && writerfunction != null) { if (writerfunction.IndexOf('.') < 0) { Type myType = typeof(FwkData); writerfunction = myType.Namespace + '.' + writerlibrary + '.' + writerfunction; writerlibrary = "FwkLib"; } regionAttributesFactory.SetCacheWriter(writerlibrary, writerfunction); } break; case "persistence-manager": string pmlibrary = null; string pmfunction = null; Apache.Geode.Client.Properties<string, string> prop = new Apache.Geode.Client.Properties<string, string>(); XmlAttributeCollection pmattrs = node.Attributes; foreach (XmlAttribute attr in pmattrs) { if (attr.Name == "library") { pmlibrary = attr.Value; } else if (attr.Name == "function") { pmfunction = attr.Value; } else { throw new IllegalArgException("Persistence Manager attributes in wrong format: " + attr.Name); } } if (node.FirstChild.Name == "properties") { XmlNodeList pmpropnodes = node.FirstChild.ChildNodes; foreach (XmlNode propnode in pmpropnodes) { if (propnode.Name == "property") { XmlAttributeCollection keyval = propnode.Attributes; XmlAttribute keynode = keyval["name"]; XmlAttribute valnode = keyval["value"]; if (keynode.Value == "PersistenceDirectory" || keynode.Value == "EnvironmentDirectory") { prop.Insert(keynode.Value, valnode.Value); } else if (keynode.Value == "CacheSizeGb" || keynode.Value == "CacheSizeMb" || keynode.Value == "PageSize" || keynode.Value == "MaxFileSize") { prop.Insert(keynode.Value, valnode.Value); } } } } regionAttributesFactory.SetPersistenceManager(pmlibrary, pmfunction, prop); break; } } private static Apache.Geode.Client.ExpirationAction StrToExpirationAction(string str) { return (Apache.Geode.Client.ExpirationAction)Enum.Parse(typeof(Apache.Geode.Client.ExpirationAction), str.Replace("-", string.Empty), true); } } /// <summary> /// Reader class for <see cref="FwkData"/> /// </summary> public class FwkReadData : MarshalByRefObject { #region Private members private Dictionary<string, FwkData> m_dataMap = new Dictionary<string, FwkData>(); private Dictionary<string, int> m_dataIndexMap = new Dictionary<string, int>(); private Stack<string> m_taskNames = new Stack<string>(); #endregion #region Private methods private FwkData ReadData(string key) { FwkData data; lock (((ICollection)m_dataMap).SyncRoot) { if (m_dataMap.ContainsKey(key)) { data = m_dataMap[key]; } else { try { // First search the task specific data (which overrides the global // data) and then search in global data for the key. data = Util.BBGet(TaskName, key) as FwkData; } catch (KeyNotFoundException) { data = null; } if (data == null) { try { data = Util.BBGet(string.Empty, key) as FwkData; } catch (KeyNotFoundException) { data = null; } } m_dataMap[key] = data; } } return data; } #endregion #region Public accessors and constants public const string TestRunNumKey = "TestRunNum"; public const string HostGroupKey = "HostGroup"; public string TaskName { get { return (m_taskNames.Count > 0 ? m_taskNames.Peek() : null); } } #endregion #region Public methods public void PushTaskName(string taskName) { m_taskNames.Push(taskName); Util.Log("FWKLIB:: Setting the taskname to [{0}]", taskName); } public void PopTaskName() { Util.Log("FWKLIB:: Removing taskname [{0}]", TaskName); m_taskNames.Pop(); string oldTaskName = TaskName; if (oldTaskName != null) { Util.Log("FWKLIB:: Setting the taskname back to [{0}]", oldTaskName); } } /// <summary> /// Read the value of an object as a string from the server /// for the given key. /// </summary> /// <remarks> /// For the case when the key corresponds to a list, this function /// gives a random value if the list has 'oneOf' attribute, /// else gives the values from the list in sequential order. /// </remarks> /// <param name="key">The key of the string to read.</param> /// <returns> /// The string value with the given key; null if not found. /// </returns> public string GetStringValue(string key) { FwkData data = ReadData(key); string res = null; if (data != null) { if (data.Kind == DataKind.String) { lock (((ICollection)m_dataIndexMap).SyncRoot) { int currentIndex; if (!m_dataIndexMap.TryGetValue(key, out currentIndex)) { currentIndex = 0; } if (currentIndex == 0) { res = data.Data1 as string; m_dataIndexMap[key] = 1; } } } else if (data.Kind == DataKind.List) { int len; List<string> dataList = data.Data1 as List<string>; if (dataList != null && (len = dataList.Count) > 0) { bool oneOf = false; if (data.Data2 != null && data.Data2 is bool) { oneOf = (bool)data.Data2; } if (oneOf) { res = dataList[Util.Rand(len)]; } else { lock (((ICollection)m_dataIndexMap).SyncRoot) { int currentIndex; if (!m_dataIndexMap.TryGetValue(key, out currentIndex)) { currentIndex = 0; } if (currentIndex < len) { res = dataList[currentIndex]; m_dataIndexMap[key] = currentIndex + 1; } } } } } // TODO: Deal with Range here. } return res; } /// <summary> /// Read the value of an object as an integer from the server /// for the given key. /// </summary> /// <remarks> /// The value is assumed to be an unsigned integer. /// For the case when the key corresponds to a list, this function /// gives a random value if the list has 'oneOf' attribute, /// else gives the values from the list in sequential order. /// </remarks> /// <param name="key">The key of the string to read.</param> /// <returns> /// The integer value with the given key; -1 if not found. /// </returns> public int GetUIntValue(string key) { string str = GetStringValue(key); if (str == null) { return -1; } try { return int.Parse(str); } catch { return -1; } } /// <summary> /// Read the value of an object as time in seconds from the server /// for the given key. /// </summary> /// <remarks> /// If the value contains 'h' or 'm' then it is assumed to be in /// hours and minutes respectively. /// </remarks> /// <param name="key">The key of the value to read.</param> /// <returns> /// The integer value with the given key; -1 if not found. /// </returns> public int GetTimeValue(string key) { return XmlNodeReaderWriter.String2Seconds(GetStringValue(key), -1); } /// <summary> /// Read the value of an object as a boolean value for the given key. /// </summary> /// <remarks> /// If the key is not defined the default value returned is false. /// </remarks> /// <param name="key">The key of the boolean to read.</param> /// <returns> /// The boolean value with the given key; /// false if not found or in incorrect format. /// </returns> public bool GetBoolValue(string key) { string str = GetStringValue(key); if (str == null) return false; try { return bool.Parse(str); } catch { } return false; } /// <summary> /// Read the name of the region for the given key. /// </summary> /// <param name="key">The key of the region to read.</param> /// <returns>The name of the region.</returns> public string GetRegionName(string key) { FwkData data = ReadData(key); if (data != null && data.Kind == DataKind.Region) { return data.Data1 as string; } return null; } /// <summary> /// Reset a key to the start. /// </summary> /// <param name="key">The key to remove.</param> public void ResetKey(string key) { lock (((ICollection)m_dataIndexMap).SyncRoot) { if (m_dataIndexMap.ContainsKey(key)) { m_dataIndexMap.Remove(key); } } } /// <summary> /// Clear all the keys from the local map. /// </summary> public void ClearCachedKeys() { lock (((ICollection)m_dataMap).SyncRoot) { m_dataMap.Clear(); } lock (((ICollection)m_dataIndexMap).SyncRoot) { m_dataIndexMap.Clear(); } } #endregion } }
using System; using System.IO; using System.Text; using ChainUtils.BouncyCastle.Utilities; using ChainUtils.BouncyCastle.Utilities.Encoders; namespace ChainUtils.BouncyCastle.Asn1.Utilities { public sealed class Asn1Dump { private static readonly string NewLine = Platform.NewLine; private Asn1Dump() { } private const string Tab = " "; private const int SampleSize = 32; /** * dump a Der object as a formatted string with indentation * * @param obj the Asn1Object to be dumped out. */ private static void AsString( string indent, bool verbose, Asn1Object obj, StringBuilder buf) { if (obj is Asn1Sequence) { var tab = indent + Tab; buf.Append(indent); if (obj is BerSequence) { buf.Append("BER Sequence"); } else if (obj is DerSequence) { buf.Append("DER Sequence"); } else { buf.Append("Sequence"); } buf.Append(NewLine); foreach (Asn1Encodable o in ((Asn1Sequence)obj)) { if (o == null || o is Asn1Null) { buf.Append(tab); buf.Append("NULL"); buf.Append(NewLine); } else { AsString(tab, verbose, o.ToAsn1Object(), buf); } } } else if (obj is DerTaggedObject) { var tab = indent + Tab; buf.Append(indent); if (obj is BerTaggedObject) { buf.Append("BER Tagged ["); } else { buf.Append("Tagged ["); } var o = (DerTaggedObject)obj; buf.Append(((int)o.TagNo).ToString()); buf.Append(']'); if (!o.IsExplicit()) { buf.Append(" IMPLICIT "); } buf.Append(NewLine); if (o.IsEmpty()) { buf.Append(tab); buf.Append("EMPTY"); buf.Append(NewLine); } else { AsString(tab, verbose, o.GetObject(), buf); } } else if (obj is BerSet) { var tab = indent + Tab; buf.Append(indent); buf.Append("BER Set"); buf.Append(NewLine); foreach (Asn1Encodable o in ((Asn1Set)obj)) { if (o == null) { buf.Append(tab); buf.Append("NULL"); buf.Append(NewLine); } else { AsString(tab, verbose, o.ToAsn1Object(), buf); } } } else if (obj is DerSet) { var tab = indent + Tab; buf.Append(indent); buf.Append("DER Set"); buf.Append(NewLine); foreach (Asn1Encodable o in ((Asn1Set)obj)) { if (o == null) { buf.Append(tab); buf.Append("NULL"); buf.Append(NewLine); } else { AsString(tab, verbose, o.ToAsn1Object(), buf); } } } else if (obj is DerObjectIdentifier) { buf.Append(indent + "ObjectIdentifier(" + ((DerObjectIdentifier)obj).Id + ")" + NewLine); } else if (obj is DerBoolean) { buf.Append(indent + "Boolean(" + ((DerBoolean)obj).IsTrue + ")" + NewLine); } else if (obj is DerInteger) { buf.Append(indent + "Integer(" + ((DerInteger)obj).Value + ")" + NewLine); } else if (obj is BerOctetString) { var octets = ((Asn1OctetString)obj).GetOctets(); var extra = verbose ? dumpBinaryDataAsString(indent, octets) : ""; buf.Append(indent + "BER Octet String" + "[" + octets.Length + "] " + extra + NewLine); } else if (obj is DerOctetString) { var octets = ((Asn1OctetString)obj).GetOctets(); var extra = verbose ? dumpBinaryDataAsString(indent, octets) : ""; buf.Append(indent + "DER Octet String" + "[" + octets.Length + "] " + extra + NewLine); } else if (obj is DerBitString) { var bt = (DerBitString)obj; var bytes = bt.GetBytes(); var extra = verbose ? dumpBinaryDataAsString(indent, bytes) : ""; buf.Append(indent + "DER Bit String" + "[" + bytes.Length + ", " + bt.PadBits + "] " + extra + NewLine); } else if (obj is DerIA5String) { buf.Append(indent + "IA5String(" + ((DerIA5String)obj).GetString() + ") " + NewLine); } else if (obj is DerUtf8String) { buf.Append(indent + "UTF8String(" + ((DerUtf8String)obj).GetString() + ") " + NewLine); } else if (obj is DerPrintableString) { buf.Append(indent + "PrintableString(" + ((DerPrintableString)obj).GetString() + ") " + NewLine); } else if (obj is DerVisibleString) { buf.Append(indent + "VisibleString(" + ((DerVisibleString)obj).GetString() + ") " + NewLine); } else if (obj is DerBmpString) { buf.Append(indent + "BMPString(" + ((DerBmpString)obj).GetString() + ") " + NewLine); } else if (obj is DerT61String) { buf.Append(indent + "T61String(" + ((DerT61String)obj).GetString() + ") " + NewLine); } else if (obj is DerUtcTime) { buf.Append(indent + "UTCTime(" + ((DerUtcTime)obj).TimeString + ") " + NewLine); } else if (obj is DerGeneralizedTime) { buf.Append(indent + "GeneralizedTime(" + ((DerGeneralizedTime)obj).GetTime() + ") " + NewLine); } else if (obj is BerApplicationSpecific) { buf.Append(outputApplicationSpecific("BER", indent, verbose, (BerApplicationSpecific)obj)); } else if (obj is DerApplicationSpecific) { buf.Append(outputApplicationSpecific("DER", indent, verbose, (DerApplicationSpecific)obj)); } else if (obj is DerEnumerated) { var en = (DerEnumerated)obj; buf.Append(indent + "DER Enumerated(" + en.Value + ")" + NewLine); } else if (obj is DerExternal) { var ext = (DerExternal)obj; buf.Append(indent + "External " + NewLine); var tab = indent + Tab; if (ext.DirectReference != null) { buf.Append(tab + "Direct Reference: " + ext.DirectReference.Id + NewLine); } if (ext.IndirectReference != null) { buf.Append(tab + "Indirect Reference: " + ext.IndirectReference.ToString() + NewLine); } if (ext.DataValueDescriptor != null) { AsString(tab, verbose, ext.DataValueDescriptor, buf); } buf.Append(tab + "Encoding: " + ext.Encoding + NewLine); AsString(tab, verbose, ext.ExternalContent, buf); } else { buf.Append(indent + obj.ToString() + NewLine); } } private static string outputApplicationSpecific( string type, string indent, bool verbose, DerApplicationSpecific app) { var buf = new StringBuilder(); if (app.IsConstructed()) { try { var s = Asn1Sequence.GetInstance(app.GetObject(Asn1Tags.Sequence)); buf.Append(indent + type + " ApplicationSpecific[" + app.ApplicationTag + "]" + NewLine); foreach (Asn1Encodable ae in s) { AsString(indent + Tab, verbose, ae.ToAsn1Object(), buf); } } catch (IOException e) { buf.Append(e); } return buf.ToString(); } return indent + type + " ApplicationSpecific[" + app.ApplicationTag + "] (" + Hex.ToHexString(app.GetContents()) + ")" + NewLine; } [Obsolete("Use version accepting Asn1Encodable")] public static string DumpAsString( object obj) { if (obj is Asn1Encodable) { var buf = new StringBuilder(); AsString("", false, ((Asn1Encodable)obj).ToAsn1Object(), buf); return buf.ToString(); } return "unknown object type " + obj.ToString(); } /** * dump out a DER object as a formatted string, in non-verbose mode * * @param obj the Asn1Encodable to be dumped out. * @return the resulting string. */ public static string DumpAsString( Asn1Encodable obj) { return DumpAsString(obj, false); } /** * Dump out the object as a string * * @param obj the Asn1Encodable to be dumped out. * @param verbose if true, dump out the contents of octet and bit strings. * @return the resulting string. */ public static string DumpAsString( Asn1Encodable obj, bool verbose) { var buf = new StringBuilder(); AsString("", verbose, obj.ToAsn1Object(), buf); return buf.ToString(); } private static string dumpBinaryDataAsString(string indent, byte[] bytes) { indent += Tab; var buf = new StringBuilder(NewLine); for (var i = 0; i < bytes.Length; i += SampleSize) { if (bytes.Length - i > SampleSize) { buf.Append(indent); buf.Append(Hex.ToHexString(bytes, i, SampleSize)); buf.Append(Tab); buf.Append(calculateAscString(bytes, i, SampleSize)); buf.Append(NewLine); } else { buf.Append(indent); buf.Append(Hex.ToHexString(bytes, i, bytes.Length - i)); for (var j = bytes.Length - i; j != SampleSize; j++) { buf.Append(" "); } buf.Append(Tab); buf.Append(calculateAscString(bytes, i, bytes.Length - i)); buf.Append(NewLine); } } return buf.ToString(); } private static string calculateAscString( byte[] bytes, int off, int len) { var buf = new StringBuilder(); for (var i = off; i != off + len; i++) { var c = (char)bytes[i]; if (c >= ' ' && c <= '~') { buf.Append(c); } } return buf.ToString(); } } }
#region Using directives #define USE_TRACING using System; using System.Collections.Generic; using System.Globalization; using System.Xml; #endregion // contains AtomId namespace Google.GData.Client { /// <summary>enum to define the GDataBatchOperationType...</summary> public enum GDataBatchOperationType { /// <summary>this is an insert operatoin</summary> insert, /// <summary>this is an update operation</summary> update, /// <summary>this is a delete operation</summary> delete, /// <summary>this is a query operation</summary> query, /// <summary>the default (a no-op)</summary> Default } /// <summary> /// holds the batch status information /// </summary> public class GDataBatchStatus : IExtensionElementFactory { /// <summary>default value for the status code</summary> public const int CodeDefault = -1; private List<GDataBatchError> errorList; /// <summary> /// sets the defaults for code /// </summary> public GDataBatchStatus() { Code = CodeDefault; } /// <summary>returns the status code of the operation</summary> /// <returns> </returns> public int Code { get; set; } /// <summary>accessor method public string Reason</summary> /// <returns> </returns> public string Reason { get; set; } /// <summary>accessor method public string ContentType</summary> /// <returns> </returns> public string ContentType { get; set; } /// <summary>the error list</summary> /// <returns> </returns> public List<GDataBatchError> Errors { get { if (errorList == null) { errorList = new List<GDataBatchError>(); } return errorList; } } #region Persistence overloads /// <summary> /// Persistence method for the GDataBatchStatus object /// </summary> /// <param name="writer">the xmlwriter to write into</param> public void Save(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } writer.WriteStartElement(BaseNameTable.gBatchPrefix, BaseNameTable.XmlElementBatchStatus, BaseNameTable.gBatchPrefix); if (Code != CodeDefault) { writer.WriteAttributeString(BaseNameTable.XmlAttributeBatchStatusCode, Code.ToString(CultureInfo.InvariantCulture)); } if (Utilities.IsPersistable(ContentType)) { writer.WriteAttributeString(BaseNameTable.XmlAttributeBatchContentType, ContentType); } if (Utilities.IsPersistable(Reason)) { writer.WriteAttributeString(BaseNameTable.XmlAttributeBatchReason, Reason); } writer.WriteEndElement(); } #endregion #region IExtensionElementFactory Members /// <summary> /// reads the current positioned reader and creates a batchstatus element /// </summary> /// <param name="reader">XmlReader positioned at the start of the status element</param> /// <param name="parser">The Feedparser to be used</param> /// <returns>GDataBatchStatus</returns> public static GDataBatchStatus ParseBatchStatus(XmlReader reader, AtomFeedParser parser) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } GDataBatchStatus status = null; object localname = reader.LocalName; if (localname.Equals(parser.Nametable.BatchStatus)) { status = new GDataBatchStatus(); if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { localname = reader.LocalName; if (localname.Equals(parser.Nametable.BatchReason)) { status.Reason = Utilities.DecodedValue(reader.Value); } else if (localname.Equals(parser.Nametable.BatchContentType)) { status.ContentType = Utilities.DecodedValue(reader.Value); } else if (localname.Equals(parser.Nametable.BatchStatusCode)) { status.Code = int.Parse(Utilities.DecodedValue(reader.Value), CultureInfo.InvariantCulture); } } } reader.MoveToElement(); // FIX: THIS CODE SEEMS TO MAKE AN INFINITE LOOP WITH NextChildElement() int lvl = -1; // status can have one child element, errors while (Utilities.NextChildElement(reader, ref lvl)) { localname = reader.LocalName; if (localname.Equals(parser.Nametable.BatchErrors)) { GDataBatchError.ParseBatchErrors(reader, parser, status); } } } return status; } /// <summary> /// the xmlname of the element /// </summary> public string XmlName { get { return BaseNameTable.XmlElementBatchStatus; } } /// <summary> /// the xmlnamespace for a batchstatus /// </summary> public string XmlNameSpace { get { return BaseNameTable.gBatchNamespace; } } /// <summary> /// the preferred xmlprefix to use /// </summary> public string XmlPrefix { get { return BaseNameTable.gBatchPrefix; } } /// <summary> /// creates a new batchstatus element /// </summary> /// <param name="node"></param> /// <param name="parser"></param> /// <returns></returns> public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { return ParseBatchStatus(new XmlNodeReader(node), parser); } #endregion } /// <summary> /// represents the Error element in the GDataBatch response /// </summary> public class GDataBatchError : IExtensionElementFactory { /// <summary>accessor method Type</summary> /// <returns> </returns> public string Type { get; set; } /// <summary>accessor method public string Field</summary> /// <returns> </returns> public string Field { get; set; } /// <summary>accessor method public string Reason</summary> /// <returns> </returns> public string Reason { get; set; } #region Persistence overloads /// <summary> /// Persistence method for the GDataBatchError object /// </summary> /// <param name="writer">the xmlwriter to write into</param> public void Save(XmlWriter writer) { } #endregion #region IExtensionElementFactory Members /// <summary> /// parses a list of errors /// </summary> /// <param name="reader">XmlReader positioned at the start of the status element</param> /// <param name="status">the batch status element to add the errors tohe</param> /// <param name="parser">the feedparser to be used</param> public static void ParseBatchErrors(XmlReader reader, AtomFeedParser parser, GDataBatchStatus status) { if (reader == null) { throw new ArgumentNullException("reader"); } object localname = reader.LocalName; if (localname.Equals(parser.Nametable.BatchErrors)) { int lvl = -1; while (Utilities.NextChildElement(reader, ref lvl)) { localname = reader.LocalName; if (localname.Equals(parser.Nametable.BatchError)) { status.Errors.Add(ParseBatchError(reader, parser)); } } } } /// <summary> /// parses a single error element /// </summary> /// <param name="reader">XmlReader positioned at the start of the status element</param> /// <param name="parser">the feedparser to be used</param> /// <returns>GDataBatchError</returns> public static GDataBatchError ParseBatchError(XmlReader reader, AtomFeedParser parser) { if (reader == null) { throw new ArgumentNullException("reader"); } object localname = reader.LocalName; GDataBatchError error = null; if (localname.Equals(parser.Nametable.BatchError)) { error = new GDataBatchError(); if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { localname = reader.LocalName; if (localname.Equals(parser.Nametable.BatchReason)) { error.Reason = Utilities.DecodedValue(reader.Value); } else if (localname.Equals(parser.Nametable.Type)) { error.Type = Utilities.DecodedValue(reader.Value); } else if (localname.Equals(parser.Nametable.BatchField)) { error.Field = Utilities.DecodedValue(reader.Value); } } } } return error; } /// <summary> /// the name to use /// </summary> public string XmlName { get { return BaseNameTable.XmlElementBatchError; } } /// <summary> /// the namespace to use /// </summary> public string XmlNameSpace { get { return BaseNameTable.gBatchNamespace; } } /// <summary> /// the preferred prefix /// </summary> public string XmlPrefix { get { return BaseNameTable.gBatchPrefix; } } /// <summary> /// creates a GDataBatchError element /// </summary> /// <param name="node"></param> /// <param name="parser"></param> /// <returns></returns> public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { return ParseBatchError(new XmlNodeReader(node), parser); } #endregion } /// <summary> /// holds the batch status information /// </summary> public class GDataBatchInterrupt : IExtensionElementFactory { /// <summary>accessor method public string Reason</summary> /// <returns> </returns> public string Reason { get; set; } /// <summary>accessor method public int Successes</summary> /// <returns> </returns> public int Successes { get; set; } /// <summary>accessor method public int Failures</summary> /// <returns> </returns> public int Failures { get; set; } /// <summary>accessor method public int Unprocessed</summary> /// <returns> </returns> public int Unprocessed { get; set; } /// <summary>accessor method public int Parsed</summary> /// <returns> </returns> public int Parsed { get; set; } #region Persistence overloads /// <summary> /// Persistence method for the GDataBatchInterrupt object /// </summary> /// <param name="writer">the xmlwriter to write into</param> public void Save(XmlWriter writer) { } #endregion #region IExtensionElementFactory Members /// <summary> /// parses a batchinterrupt element from a correctly positioned reader /// </summary> /// <param name="reader">XmlReader at the start of the element</param> /// <param name="parser">the feedparser to be used</param> /// <returns>GDataBatchInterrupt</returns> public static GDataBatchInterrupt ParseBatchInterrupt(XmlReader reader, AtomFeedParser parser) { if (reader == null) { throw new ArgumentNullException("reader"); } object localname = reader.LocalName; GDataBatchInterrupt interrupt = null; if (localname.Equals(parser.Nametable.BatchInterrupt)) { interrupt = new GDataBatchInterrupt(); if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { localname = reader.LocalName; if (localname.Equals(parser.Nametable.BatchReason)) { interrupt.Reason = Utilities.DecodedValue(reader.Value); } else if (localname.Equals(parser.Nametable.BatchSuccessCount)) { interrupt.Successes = int.Parse(Utilities.DecodedValue(reader.Value), CultureInfo.InvariantCulture); } else if (localname.Equals(parser.Nametable.BatchFailureCount)) { interrupt.Failures = int.Parse(Utilities.DecodedValue(reader.Value), CultureInfo.InvariantCulture); } else if (localname.Equals(parser.Nametable.BatchParsedCount)) { interrupt.Parsed = int.Parse(Utilities.DecodedValue(reader.Value), CultureInfo.InvariantCulture); } else if (localname.Equals(parser.Nametable.BatchUnprocessed)) { interrupt.Unprocessed = int.Parse(Utilities.DecodedValue(reader.Value), CultureInfo.InvariantCulture); } } } } return interrupt; } /// <summary> /// returns the xmlname to sue /// </summary> public string XmlName { get { return BaseNameTable.XmlElementBatchInterrupt; } } /// <summary> /// returns the xmlnamespace /// </summary> public string XmlNameSpace { get { return BaseNameTable.gBatchNamespace; } } /// <summary> /// the xmlprefix /// </summary> public string XmlPrefix { get { return BaseNameTable.gBatchPrefix; } } /// <summary> /// factory method to create an instance of a batchinterrupt during parsing /// </summary> /// <param name="node">the xmlnode that is going to be parsed</param> /// <param name="parser">the feedparser that is used right now</param> /// <returns></returns> public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { return ParseBatchInterrupt(new XmlNodeReader(node), parser); } #endregion } /// <summary>The GDataFeedBatch object holds batch related information /// for the AtomFeed /// </summary> public class GDataBatchFeedData : IExtensionElementFactory { /// <summary> /// constructor, set's the default for the operation type /// </summary> public GDataBatchFeedData() { Type = GDataBatchOperationType.Default; } /// <summary>accessor method public GDataBatchOperationType Type</summary> /// <returns> </returns> public GDataBatchOperationType Type { get; set; } #region Persistence overloads /// <summary> /// Persistence method for the GDataBatch object /// </summary> /// <param name="writer">the xmlwriter to write into</param> public void Save(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } if (Type != GDataBatchOperationType.Default) { writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace); writer.WriteAttributeString(BaseNameTable.XmlAttributeType, Type.ToString()); writer.WriteEndElement(); } } #endregion #region IExtensionElementFactory Members /// <summary> /// the xmlname to use /// </summary> public string XmlName { get { return BaseNameTable.XmlElementBatchOperation; } } /// <summary> /// the xml namespace to use /// </summary> public string XmlNameSpace { get { return BaseNameTable.gBatchNamespace; } } /// <summary> /// the xmlprefix to use /// </summary> public string XmlPrefix { get { return BaseNameTable.gBatchPrefix; } } /// <summary> /// factory method to create an instance of a batchinterrupt during parsing /// </summary> /// <param name="node">the xmlnode that is going to be parsed</param> /// <param name="parser">the feedparser that is used right now</param> /// <returns></returns> public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { throw new Exception("The method or operation is not implemented."); } #endregion } /// <summary>The GDataEntryBatch object holds batch related information /// for an AtomEntry /// </summary> public class GDataBatchEntryData : IExtensionElementFactory { private GDataBatchStatus status; /// <summary> /// constructor, sets the default for the operation type /// </summary> public GDataBatchEntryData() { Type = GDataBatchOperationType.Default; } /// <summary> /// Constructor for the batch data /// </summary> /// <param name="type">The batch operation to be performed</param> public GDataBatchEntryData(GDataBatchOperationType type) { Type = type; } /// <summary> /// Constructor for batch data /// </summary> /// <param name="id">The batch ID of this entry</param> /// <param name="type">The batch operation to be performed</param> public GDataBatchEntryData(string id, GDataBatchOperationType type) : this(type) { Id = id; } /// <summary>accessor method public GDataBatchOperationType Type</summary> /// <returns> </returns> public GDataBatchOperationType Type { get; set; } /// <summary>accessor method public string Id</summary> /// <returns> </returns> public string Id { get; set; } /// <summary>accessor for the GDataBatchInterrrupt element</summary> /// <returns> </returns> public GDataBatchInterrupt Interrupt { get; set; } /// <summary>accessor method public GDataBatchStatus Status</summary> /// <returns> </returns> public GDataBatchStatus Status { get { if (status == null) { status = new GDataBatchStatus(); } return status; } set { status = value; } } #region Persistence overloads /// <summary> /// Persistence method for the GDataEntryBatch object /// </summary> /// <param name="writer">the xmlwriter to write into</param> public void Save(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } if (Id != null) { writer.WriteElementString(BaseNameTable.XmlElementBatchId, BaseNameTable.gBatchNamespace, Id); } if (Type != GDataBatchOperationType.Default) { writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace); writer.WriteAttributeString(BaseNameTable.XmlAttributeType, Type.ToString()); writer.WriteEndElement(); } if (status != null) { status.Save(writer); } } #endregion #region IExtensionElementFactory Members /// <summary> /// xml local name to use /// </summary> public string XmlName { get { //TODO This doesn't seem correct. return BaseNameTable.XmlElementBatchOperation; } } /// <summary> /// xml namespace to use /// </summary> public string XmlNameSpace { get { return BaseNameTable.gBatchNamespace; } } /// <summary> /// xml prefix to use /// </summary> public string XmlPrefix { get { return BaseNameTable.gBatchPrefix; } } /// <summary> /// creates a new GDataBatchEntryData /// </summary> /// <param name="node"></param> /// <param name="parser"></param> /// <returns></returns> public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { //we really don't know how to create an instance of ourself. throw new Exception("The method or operation is not implemented."); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Orleans.Core; namespace Orleans.Runtime { /// <summary> /// An exception class used by the Orleans runtime for reporting errors. /// </summary> /// <remarks> /// This is also the base class for any more specific exceptions /// raised by the Orleans runtime. /// </remarks> [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1058:TypesShouldNotExtendCertainBaseTypes")] public class OrleansException : Exception { public OrleansException() : base("Unexpected error.") { } public OrleansException(string message) : base(message) { } public OrleansException(string message, Exception innerException) : base(message, innerException) { } #if !NETSTANDARD protected OrleansException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } /// <summary> /// Signifies that a gateway silo is currently in overloaded / load shedding state /// and is unable to currently accept this message being sent. /// </summary> /// <remarks> /// This situation is usaully a transient condition. /// The message is likely to be accepted by this or another gateway if it is retransmitted at a later time. /// </remarks> [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")] public class GatewayTooBusyException : OrleansException { public GatewayTooBusyException() : base("Gateway too busy") { } public GatewayTooBusyException(string message) : base(message) { } public GatewayTooBusyException(string message, Exception innerException) : base(message, innerException) { } #if !NETSTANDARD protected GatewayTooBusyException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } /// <summary> /// Signifies that a silo is in an overloaded state where some /// runtime limit setting is currently being exceeded, /// and so that silo is unable to currently accept this message being sent. /// </summary> /// <remarks> /// This situation is often a transient condition. /// The message is likely to be accepted by this or another silo if it is retransmitted at a later time. /// </remarks> [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")] public class LimitExceededException : OrleansException { public LimitExceededException() : base("Limit exceeded") { } public LimitExceededException(string message) : base(message) { } public LimitExceededException(string message, Exception innerException) : base(message, innerException) { } public LimitExceededException(string limitName, int current, int threshold, object extraInfo) : base(string.Format("Limit exceeded {0} Current={1} Threshold={2} {3}", limitName, current, threshold, extraInfo)) { } #if !NETSTANDARD protected LimitExceededException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } /// <summary> /// Signifies that a silo has detected a deadlock / loop in a call graph. /// </summary> /// <remarks> /// <para> /// Deadlock detection is not enabled by default in Orleans silos, /// because it introduces some extra overhead in call handling. /// </para> /// <para> /// There are some constraints on the types of deadlock that can currently be detected /// by Orleans silos. /// </para> /// </remarks> [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")] public class DeadlockException : OrleansException { internal IEnumerable<Tuple<GrainId, string>> CallChain { get; private set; } public DeadlockException() : base("Deadlock between grain calls") {} public DeadlockException(string message) : base(message) { } public DeadlockException(string message, Exception innerException) : base(message, innerException) { } internal DeadlockException(List<RequestInvocationHistory> callChain) : base(String.Format("Deadlock Exception for grain call chain {0}.", Utils.EnumerableToString(callChain, elem => String.Format("{0}.{1}", elem.GrainId, elem.DebugContext)))) { CallChain = callChain.Select(req => new Tuple<GrainId, string>(req.GrainId, req.DebugContext)).ToList(); } #if !NETSTANDARD protected DeadlockException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info != null) { CallChain = (IEnumerable<Tuple<GrainId, string>>)info.GetValue("CallChain", typeof(IEnumerable<Tuple<GrainId, string>>)); } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info != null) { info.AddValue("CallChain", this.CallChain, typeof(IEnumerable<Tuple<GrainId, string>>)); } base.GetObjectData(info, context); } #endif } /// <summary> /// Signifies that an attempt was made to invoke a grain extension method on a grain where that extension was not installed. /// </summary> [Serializable] public class GrainExtensionNotInstalledException : OrleansException { public GrainExtensionNotInstalledException() : base("GrainExtensionNotInstalledException") { } public GrainExtensionNotInstalledException(string msg) : base(msg) { } public GrainExtensionNotInstalledException(string message, Exception innerException) : base(message, innerException) { } #if !NETSTANDARD protected GrainExtensionNotInstalledException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } /// <summary> /// Signifies that an request was cancelled due to target silo unavailability. /// </summary> [Serializable] public class SiloUnavailableException : OrleansException { public SiloUnavailableException() : base("SiloUnavailableException") { } public SiloUnavailableException(string msg) : base(msg) { } public SiloUnavailableException(string message, Exception innerException) : base(message, innerException) { } #if !NETSTANDARD protected SiloUnavailableException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } /// <summary> /// Signifies that an operation was attempted on an invalid SchedulingContext. /// </summary> [Serializable] internal class InvalidSchedulingContextException : OrleansException { public InvalidSchedulingContextException() : base("InvalidSchedulingContextException") { } public InvalidSchedulingContextException(string msg) : base(msg) { } public InvalidSchedulingContextException(string message, Exception innerException) : base(message, innerException) { } #if !NETSTANDARD protected InvalidSchedulingContextException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } /// <summary> /// Indicates that a client is not longer reachable. /// </summary> [Serializable] public class ClientNotAvailableException : OrleansException { internal ClientNotAvailableException(IGrainIdentity clientId) : base("No activation for client " + clientId) { } internal ClientNotAvailableException(string msg) : base(msg) { } internal ClientNotAvailableException(string message, Exception innerException) : base(message, innerException) { } #if !NETSTANDARD protected ClientNotAvailableException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } }
namespace SimpleGrav { partial class Canvas { /// <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.sidebar = new System.Windows.Forms.Panel(); this.Reset = new System.Windows.Forms.Button(); this.timestep = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.SimMethod = new System.Windows.Forms.ComboBox(); this.IntMethod = new System.Windows.Forms.ComboBox(); this.Start = new System.Windows.Forms.Button(); this.FPSCounter = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.mass = new System.Windows.Forms.TextBox(); this.ObjCounter = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.UpdateInput = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.vel_y = new System.Windows.Forms.TextBox(); this.vel_x = new System.Windows.Forms.TextBox(); this.sidebar.SuspendLayout(); this.SuspendLayout(); // // sidebar // this.sidebar.BackColor = System.Drawing.Color.DarkGray; this.sidebar.Controls.Add(this.Reset); this.sidebar.Controls.Add(this.timestep); this.sidebar.Controls.Add(this.label5); this.sidebar.Controls.Add(this.Start); this.sidebar.Controls.Add(this.SimMethod); this.sidebar.Controls.Add(this.IntMethod); this.sidebar.Controls.Add(this.FPSCounter); this.sidebar.Controls.Add(this.label6); this.sidebar.Controls.Add(this.label4); this.sidebar.Controls.Add(this.ObjCounter); this.sidebar.Controls.Add(this.label3); this.sidebar.Controls.Add(this.UpdateInput); this.sidebar.Controls.Add(this.label2); this.sidebar.Controls.Add(this.label1); this.sidebar.Controls.Add(this.mass); this.sidebar.Controls.Add(this.vel_y); this.sidebar.Controls.Add(this.vel_x); this.sidebar.Dock = System.Windows.Forms.DockStyle.Right; this.sidebar.Location = new System.Drawing.Point(793, 0); this.sidebar.Name = "sidebar"; this.sidebar.Size = new System.Drawing.Size(168, 531); this.sidebar.TabIndex = 2; // // Reset // this.Reset.Location = new System.Drawing.Point(27, 486); this.Reset.Name = "Reset"; this.Reset.Size = new System.Drawing.Size(128, 25); this.Reset.TabIndex = 16; this.Reset.Text = "Reset Simulation"; this.Reset.UseVisualStyleBackColor = true; this.Reset.Click += new System.EventHandler(this.Reset_Click); // // timestep // this.timestep.AutoSize = true; this.timestep.Location = new System.Drawing.Point(70, 48); this.timestep.Name = "timestep"; this.timestep.Size = new System.Drawing.Size(34, 13); this.timestep.TabIndex = 15; this.timestep.Text = "0.001"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(11, 48); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(53, 13); this.label5.TabIndex = 14; this.label5.Text = "Timestep:"; // // SimMethod // this.SimMethod.FormattingEnabled = true; this.SimMethod.Items.AddRange(new object[] { "Brute Force"}); this.SimMethod.Location = new System.Drawing.Point(27, 399); this.SimMethod.Name = "SimMethod"; this.SimMethod.Size = new System.Drawing.Size(127, 21); this.SimMethod.TabIndex = 13; this.SimMethod.Text = "Simulation Method"; // // IntMethod // this.IntMethod.FormattingEnabled = true; this.IntMethod.Items.AddRange(new object[] { "Euler Integration", "Verlet Integration"}); this.IntMethod.Location = new System.Drawing.Point(27, 372); this.IntMethod.Name = "IntMethod"; this.IntMethod.Size = new System.Drawing.Size(127, 21); this.IntMethod.TabIndex = 12; this.IntMethod.Text = "Integration Method"; // // Start // this.Start.Location = new System.Drawing.Point(27, 455); this.Start.Name = "Start"; this.Start.Size = new System.Drawing.Size(128, 25); this.Start.TabIndex = 11; this.Start.Text = "Start Simulation"; this.Start.UseVisualStyleBackColor = true; this.Start.Click += new System.EventHandler(this.Start_Click); // // FPSCounter // this.FPSCounter.AutoSize = true; this.FPSCounter.Location = new System.Drawing.Point(70, 19); this.FPSCounter.Name = "FPSCounter"; this.FPSCounter.Size = new System.Drawing.Size(28, 13); this.FPSCounter.TabIndex = 10; this.FPSCounter.Text = "0.00"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(10, 19); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(30, 13); this.label6.TabIndex = 9; this.label6.Text = "FPS:"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(25, 164); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(32, 13); this.label4.TabIndex = 8; this.label4.Text = "Mass"; // // ObjCounter // this.ObjCounter.AutoSize = true; this.ObjCounter.Location = new System.Drawing.Point(70, 81); this.ObjCounter.Name = "ObjCounter"; this.ObjCounter.Size = new System.Drawing.Size(13, 13); this.ObjCounter.TabIndex = 6; this.ObjCounter.Text = "0"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(11, 81); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(46, 13); this.label3.TabIndex = 5; this.label3.Text = "Objects:"; // // UpdateInput // this.UpdateInput.Location = new System.Drawing.Point(28, 187); this.UpdateInput.Name = "UpdateInput"; this.UpdateInput.Size = new System.Drawing.Size(128, 25); this.UpdateInput.TabIndex = 4; this.UpdateInput.Text = "Change Parameters"; this.UpdateInput.UseVisualStyleBackColor = true; this.UpdateInput.Click += new System.EventHandler(this.UpdateInput_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(35, 136); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(19, 13); this.label2.TabIndex = 3; this.label2.Text = "Vy"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(35, 110); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(19, 13); this.label1.TabIndex = 2; this.label1.Text = "Vx"; // // mass // this.mass.Location = new System.Drawing.Point(56, 161); this.mass.Name = "mass"; this.mass.Size = new System.Drawing.Size(100, 20); this.mass.TabIndex = 7; // // vel_y // this.vel_y.Location = new System.Drawing.Point(57, 133); this.vel_y.Name = "vel_y"; this.vel_y.Size = new System.Drawing.Size(100, 20); this.vel_y.TabIndex = 1; // // vel_x // this.vel_x.Location = new System.Drawing.Point(57, 107); this.vel_x.Name = "vel_x"; this.vel_x.Size = new System.Drawing.Size(100, 20); this.vel_x.TabIndex = 0; // // Canvas // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.Black; this.ClientSize = new System.Drawing.Size(961, 531); this.Controls.Add(this.sidebar); this.DoubleBuffered = true; this.MaximizeBox = false; this.Name = "Canvas"; this.Text = "SimpleGravity"; this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.Canvas_MouseClick); this.Resize += new System.EventHandler(this.Canvas_Resize); this.sidebar.ResumeLayout(false); this.sidebar.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel sidebar; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox vel_y; private System.Windows.Forms.TextBox vel_x; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox mass; private System.Windows.Forms.Label ObjCounter; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button UpdateInput; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox SimMethod; private System.Windows.Forms.ComboBox IntMethod; private System.Windows.Forms.Button Start; private System.Windows.Forms.Label FPSCounter; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label timestep; private System.Windows.Forms.Label label5; private System.Windows.Forms.Button Reset; } }
using System; using System.Collections; using System.Configuration; using System.Data; using System.Text; using ActiveDatabaseSoftware.ActiveQueryBuilder; namespace Samples { public partial class QueryStructure { internal class UnionSubQueryExchangeClass { public string SelectedExpressions; public string DataSources; public string Links; public string Where; } private class ExchangeClass { public string Statistics; public string SubQueries; public string QueryStructure; public UnionSubQueryExchangeClass UnionSubQuery; } private string GetQueryStatistic(QueryStatistics qs) { string stats = ""; stats = "<b>Used Objects (" + qs.UsedDatabaseObjects.Count + "):</b><br/>"; for (int i = 0; i < qs.UsedDatabaseObjects.Count; i++) { stats += "<br />" + qs.UsedDatabaseObjects[i].ObjectName.QualifiedName; } stats += "<br /><br />" + "<b>Used Columns (" + qs.UsedDatabaseObjectFields.Count + "):</b><br />"; for (int i = 0; i < qs.UsedDatabaseObjectFields.Count; i++) { stats += "<br />" + qs.UsedDatabaseObjectFields[i].FullName.QualifiedName; } stats += "<br /><br />" + "<b>Output Expressions (" + qs.OutputColumns.Count + "):</b><br />"; for (int i = 0; i < qs.OutputColumns.Count; i++) { stats += "<br />" + qs.OutputColumns[i].Expression; } return stats; } private string DumpQueryStructureInfo(SubQuery subQuery) { var stringBuilder = new StringBuilder(); DumpUnionGroupInfo(stringBuilder, "", subQuery); return stringBuilder.ToString(); } private void DumpUnionGroupInfo(StringBuilder stringBuilder, string indent, UnionGroup unionGroup) { QueryBase[] children = GetUnionChildren(unionGroup); foreach (QueryBase child in children) { if (stringBuilder.Length > 0) { stringBuilder.AppendLine("<br />"); } if (child is UnionSubQuery) { // UnionSubQuery is a leaf node of query structure. // It represent a single SELECT statement in the tree of unions DumpUnionSubQueryInfo(stringBuilder, indent, (UnionSubQuery)child); } else { // UnionGroup is a tree node. // It contains one or more leafs of other tree nodes. // It represent a root of the subquery of the union tree or a // parentheses in the union tree. unionGroup = (UnionGroup)child; stringBuilder.AppendLine(indent + unionGroup.UnionOperatorFull + "group: ["); DumpUnionGroupInfo(stringBuilder, indent + "&nbsp;&nbsp;&nbsp;&nbsp;", unionGroup); stringBuilder.AppendLine(indent + "]<br />"); } } } private void DumpUnionSubQueryInfo(StringBuilder stringBuilder, string indent, UnionSubQuery unionSubQuery) { string sql = unionSubQuery.GetResultSQL(); stringBuilder.AppendLine(indent + unionSubQuery.UnionOperatorFull + ": " + sql + "<br />"); } private QueryBase[] GetUnionChildren(UnionGroup unionGroup) { ArrayList result = new ArrayList(); for (int i = 0; i < unionGroup.Count; i++) { result.Add(unionGroup[i]); } return (QueryBase[])result.ToArray(typeof(QueryBase)); } public string DumpSelectedExpressionsInfoFromUnionSubQuery(UnionSubQuery unionSubQuery) { var stringBuilder = new StringBuilder(); // get list of CriteriaItems QueryColumnList criteriaList = unionSubQuery.QueryColumnList; // dump all items for (int i = 0; i < criteriaList.Count; i++) { QueryColumnListItem criteriaItem = criteriaList[i]; // only items have .Select property set to True goes to SELECT list if (!criteriaItem.Select) { continue; } // separator if (stringBuilder.Length > 0) { stringBuilder.AppendLine("<br />"); } DumpSelectedExpressionInfo(stringBuilder, criteriaItem); } return stringBuilder.ToString(); } private void DumpSelectedExpressionInfo(StringBuilder stringBuilder, QueryColumnListItem selectedExpression) { // write full sql fragment of selected expression stringBuilder.AppendLine(selectedExpression.ExpressionString + "<br />"); // write alias if (!String.IsNullOrEmpty(selectedExpression.AliasString)) { stringBuilder.AppendLine("&nbsp;&nbsp;alias: " + selectedExpression.AliasString + "<br />"); } // write datasource reference (if any) if (selectedExpression.ExpressionDatasource != null) { stringBuilder.AppendLine("&nbsp;&nbsp;datasource: " + selectedExpression.ExpressionDatasource.GetResultSQL() + "<br />"); } // write metadata information (if any) if (selectedExpression.ExpressionField != null) { MetadataField field = selectedExpression.ExpressionField; stringBuilder.AppendLine("&nbsp;&nbsp;field name: " + field.Name + "<br />"); string s = Enum.GetName(typeof(DbType), field.FieldType); stringBuilder.AppendLine("&nbsp;&nbsp;field type: " + s + "<br />"); } } private void DumpDataSourcesInfo(StringBuilder stringBuilder, ArrayList dataSources) { for (int i = 0; i < dataSources.Count; i++) { if (stringBuilder.Length > 0) { stringBuilder.AppendLine("<br />"); } DumpDataSourceInfo(stringBuilder, (DataSource)dataSources[i]); } } public string DumpDataSourcesInfoFromUnionSubQuery(UnionSubQuery unionSubQuery) { StringBuilder stringBuilder = new StringBuilder(); DumpDataSourcesInfo(stringBuilder, GetDataSourceList(unionSubQuery)); return stringBuilder.ToString(); } private ArrayList GetDataSourceList(UnionSubQuery unionSubQuery) { ArrayList list = new ArrayList(); unionSubQuery.FromClause.GetDatasourceByClass(typeof(DataSource), list); return list; } private void DumpDataSourceInfo(StringBuilder stringBuilder, DataSource dataSource) { // write full sql fragment stringBuilder.AppendLine("<b>" + dataSource.GetResultSQL() + "</b><br />"); // write alias stringBuilder.AppendLine("&nbsp;&nbsp;alias: " + dataSource.Alias + "<br />"); // write referenced MetadataObject (if any) if (dataSource.MetadataObject != null) { stringBuilder.AppendLine("&nbsp;&nbsp;ref: " + dataSource.MetadataObject.Name + "<br />"); } // write subquery (if datasource is actually a derived table) if (dataSource is DataSourceQuery) { stringBuilder.AppendLine("&nbsp;&nbsp;subquery sql: " + ((DataSourceQuery)dataSource).Query.GetResultSQL() + "<br />"); } // write fields string fields = String.Empty; for (int i = 0; i < dataSource.Metadata.Count; i++) { if (fields.Length > 0) { fields += ", "; } fields += dataSource.Metadata[i].Name; } stringBuilder.AppendLine("&nbsp;&nbsp;fields (" + dataSource.Metadata.Count.ToString() + "): " + fields + "<br />"); } private void DumpLinkInfo(StringBuilder stringBuilder, Link link) { // write full sql fragment of link expression stringBuilder.AppendLine(link.LinkExpression.GetSQL(link.SQLContext.SQLBuilderExpression) + "<br />"); // write information about left side of link stringBuilder.AppendLine("&nbsp;&nbsp;left datasource: " + link.LeftDatasource.GetResultSQL() + "<br />"); if (link.LeftType == LinkSideType.Inner) { stringBuilder.AppendLine("&nbsp;&nbsp;left type: Inner" + "<br />"); } else { stringBuilder.AppendLine("&nbsp;&nbsp;left type: Outer" + "<br />"); } // write information about right side of link stringBuilder.AppendLine("&nbsp;&nbsp;right datasource: " + link.RightDatasource.GetResultSQL() + "<br />"); if (link.RightType == LinkSideType.Inner) { stringBuilder.AppendLine("&nbsp;&nbsp;lerightft type: Inner" + "<br />"); } else { stringBuilder.AppendLine("&nbsp;&nbsp;right type: Outer" + "<br />"); } } private void DumpLinksInfo(StringBuilder stringBuilder, ArrayList links) { for (int i = 0; i < links.Count; i++) { if (stringBuilder.Length > 0) { stringBuilder.AppendLine("<br />"); } DumpLinkInfo(stringBuilder, (Link)links[i]); } } private ArrayList GetLinkList(UnionSubQuery unionSubQuery) { ArrayList links = new ArrayList(); unionSubQuery.FromClause.GetLinksRecursive(links); return links; } public string DumpLinksInfoFromUnionSubQuery(UnionSubQuery unionSubQuery) { var stringBuilder = new StringBuilder(); DumpLinksInfo(stringBuilder, GetLinkList(unionSubQuery)); return stringBuilder.ToString(); } public void DumpWhereInfo(StringBuilder stringBuilder, SQLExpressionItem where) { DumpExpression(stringBuilder, "", where); } private void DumpExpression(StringBuilder stringBuilder, string indent, SQLExpressionItem expression) { const string cIndentInc = "&nbsp;&nbsp;&nbsp;&nbsp;"; string newIndent = indent + cIndentInc; if (expression == null) // NULL reference protection { stringBuilder.AppendLine(indent + "--nil--" + "<br />"); } else if (expression is SQLExpressionBrackets) { // Expression is actually the brackets query structure node. // Create the "brackets" tree node and load content of // the brackets as children of the node. stringBuilder.AppendLine(indent + "()" + "<br />"); DumpExpression(stringBuilder, newIndent, ((SQLExpressionBrackets)expression).LExpression); } else if (expression is SQLExpressionOr) { // Expression is actually the "OR" query structure node. // Create the "OR" tree node and load all items of // the "OR" collection as children of the tree node. stringBuilder.AppendLine(indent + "OR" + "<br />"); for (int i = 0; i < ((SQLExpressionOr)expression).Count; i++) { DumpExpression(stringBuilder, newIndent, ((SQLExpressionOr)expression)[i]); } } else if (expression is SQLExpressionAnd) { // Expression is actually the "AND" query structure node. // Create the "AND" tree node and load all items of // the "AND" collection as children of the tree node. stringBuilder.AppendLine(indent + "AND" + "<br />"); for (int i = 0; i < ((SQLExpressionAnd)expression).Count; i++) { DumpExpression(stringBuilder, newIndent, ((SQLExpressionAnd)expression)[i]); } } else if (expression is SQLExpressionNot) { // Expression is actually the "NOT" query structure node. // Create the "NOT" tree node and load content of // the "NOT" operator as children of the tree node. stringBuilder.AppendLine(indent + "NOT" + "<br />"); DumpExpression(stringBuilder, newIndent, ((SQLExpressionNot)expression).LExpression); } else if (expression is SQLExpressionOperatorBinary) { // Expression is actually the "BINARY OPERATOR" query structure node. // Create a tree node containing the operator value and // two leaf nodes with the operator arguments. string s = ((SQLExpressionOperatorBinary)expression).OperatorObj.OperatorName; stringBuilder.AppendLine(indent + s + "<br />"); // left argument of the binary operator DumpExpression(stringBuilder, newIndent, ((SQLExpressionOperatorBinary)expression).LExpression); // right argument of the binary operator DumpExpression(stringBuilder, newIndent, ((SQLExpressionOperatorBinary)expression).RExpression); } else { // other type of AST nodes - out as a text string s = expression.GetSQL(expression.SQLContext.SQLBuilderExpression); stringBuilder.AppendLine(indent + s + "<br />"); } } private string GetWhereInfo(UnionSubQuery unionSubQuery) { StringBuilder stringBuilder = new StringBuilder(); SQLSubQuerySelectExpression unionSubQueryAst = unionSubQuery.ResultQueryAST; try { if (unionSubQueryAst.Where != null) { DumpWhereInfo(stringBuilder, unionSubQueryAst.Where); } } finally { unionSubQueryAst.Dispose(); } return stringBuilder.ToString(); } public string DumpSubQueries(QueryBuilder queryBuilder) { StringBuilder stringBuilder = new StringBuilder(); DumpSubQueriesInfo(stringBuilder, queryBuilder); return stringBuilder.ToString(); } private void DumpSubQueryInfo(StringBuilder stringBuilder, int index, SubQuery subQuery) { string sql = subQuery.GetResultSQL(); stringBuilder.AppendLine(index.ToString() + ": " + sql + "<br />"); } public void DumpSubQueriesInfo(StringBuilder stringBuilder, QueryBuilder queryBuilder) { for (int i = 0; i < queryBuilder.GetSubQueryList().Count; i++) { if (stringBuilder.Length > 0) { stringBuilder.AppendLine("<br />"); } DumpSubQueryInfo(stringBuilder, i, queryBuilder.SubQueries[i]); } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; namespace Orleans.Runtime { internal class StatelessWorkerGrainContext : IGrainContext, IAsyncDisposable, IActivationLifecycleObserver { private readonly GrainAddress _address; private readonly GrainTypeSharedContext _sharedContext; private readonly IGrainContextActivator _innerActivator; private readonly int _maxWorkers; private readonly List<IGrainContext> _workers = new(); private readonly ConcurrentQueue<StatelessWorkerWorkItem> _workItems = new(); private readonly SingleWaiterAutoResetEvent _workSignal = new() { RunContinuationsAsynchronously = false }; /// <summary> /// The <see cref="Task"/> representing the <see cref="RunMessageLoop"/> invocation. /// This is written once but never otherwise accessed. The purpose of retaining this field is for /// debugging, where being able to identify the message loop task corresponding to an activation can /// be useful. /// </summary> #pragma warning disable IDE0052 // Remove unread private members private readonly Task _messageLoopTask; #pragma warning restore IDE0052 // Remove unread private members private int _nextWorker; private GrainReference _grainReference; public StatelessWorkerGrainContext( GrainAddress address, GrainTypeSharedContext sharedContext, IGrainContextActivator innerActivator) { _address = address; _sharedContext = sharedContext; _innerActivator = innerActivator; _maxWorkers = ((StatelessWorkerPlacement)_sharedContext.PlacementStrategy).MaxLocal; _messageLoopTask = Task.Run(RunMessageLoop); _sharedContext.OnCreateActivation(this); } public GrainReference GrainReference => _grainReference ??= _sharedContext.GrainReferenceActivator.CreateReference(GrainId, default); public GrainId GrainId => _address.GrainId; public object GrainInstance => null; public ActivationId ActivationId => _address.ActivationId; public GrainAddress Address => _address; public IServiceProvider ActivationServices => throw new NotImplementedException(); public IGrainLifecycle ObservableLifecycle => throw new NotImplementedException(); public IWorkItemScheduler Scheduler => throw new NotImplementedException(); public PlacementStrategy PlacementStrategy => _sharedContext.PlacementStrategy; public Task Deactivated { get { var completion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); _workItems.Enqueue(new(WorkItemType.DeactivatedTask, new DeactivatedTaskWorkItemState(completion))); return completion.Task; } } public void Activate(Dictionary<string, object> requestContext, CancellationToken? cancellationToken = null) { _workItems.Enqueue(new(WorkItemType.Activate, new ActivateWorkItemState(requestContext, cancellationToken))); _workSignal.Signal(); } public void ReceiveMessage(object message) { _workItems.Enqueue(new(WorkItemType.Message, message)); _workSignal.Signal(); } public void Deactivate(DeactivationReason deactivationReason, CancellationToken? cancellationToken = null) { _workItems.Enqueue(new(WorkItemType.Deactivate, new DeactivateWorkItemState(deactivationReason, cancellationToken))); _workSignal.Signal(); } public async ValueTask DisposeAsync() { try { var completion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); _workItems.Enqueue(new(WorkItemType.DisposeAsync, new DisposeAsyncWorkItemState(completion))); await completion.Task; } finally { _sharedContext.OnDestroyActivation(this); } } public bool Equals([AllowNull] IGrainContext other) => other is not null && ActivationId.Equals(other.ActivationId); public TComponent GetComponent<TComponent>() => throw new NotImplementedException(); public void SetComponent<TComponent>(TComponent value) => throw new NotImplementedException(); public TTarget GetTarget<TTarget>() => throw new NotImplementedException(); private async Task RunMessageLoop() { while (true) { try { while (_workItems.TryDequeue(out var workItem)) { switch (workItem.Type) { case WorkItemType.Message: ReceiveMessageInternal(workItem.State); break; case WorkItemType.Activate: { var state = (ActivateWorkItemState)workItem.State; ActivateInternal(state.RequestContext, state.CancellationToken); break; } case WorkItemType.Deactivate: { var state = (DeactivateWorkItemState)workItem.State; DeactivateInternal(state.DeactivationReason, state.CancellationToken); break; } case WorkItemType.DeactivatedTask: { var state = (DeactivatedTaskWorkItemState)workItem.State; _ = DeactivatedTaskInternal(state.Completion); break; } case WorkItemType.DisposeAsync: { var state = (DisposeAsyncWorkItemState)workItem.State; _ = DisposeAsyncInternal(state.Completion); break; } case WorkItemType.OnDestroyActivation: { var grainContext = (IGrainContext)workItem.State; _workers.Remove(grainContext); break; } default: throw new NotSupportedException($"Work item of type {workItem.Type} is not supported"); } } await _workSignal.WaitAsync(); } catch (Exception exception) { _sharedContext.Logger.LogError(exception, "Error in stateless worker message loop"); } } } private void ReceiveMessageInternal(object message) { try { if (_workers.Count < _maxWorkers) { // Create a new worker var address = GrainAddress.GetAddress(_address.SiloAddress, _address.GrainId, ActivationId.NewId()); var newWorker = _innerActivator.CreateContext(address); // Observe the create/destroy lifecycle of the activation newWorker.SetComponent<IActivationLifecycleObserver>(this); // If this is a new worker and there is a message in scope, try to get the request context and activate the worker var requestContext = (message as Message)?.RequestContextData ?? new Dictionary<string, object>(); var cancellation = new CancellationTokenSource(_sharedContext.InternalRuntime.CollectionOptions.Value.ActivationTimeout); newWorker.Activate(requestContext, cancellation.Token); _workers.Add(newWorker); } var worker = _workers[Math.Abs(_nextWorker++) % _workers.Count]; worker.ReceiveMessage(message); } catch (Exception exception) when (message is Message msg) { _sharedContext.InternalRuntime.MessageCenter.RejectMessage( msg, Message.RejectionTypes.Transient, exception, "Exception while creating grain context"); } } private void ActivateInternal(Dictionary<string, object> requestContext, CancellationToken? cancellationToken) { // No-op } private void DeactivateInternal(DeactivationReason reason, CancellationToken? cancellationToken) { foreach (var worker in _workers) { worker.Deactivate(reason, cancellationToken); } } private async Task DeactivatedTaskInternal(TaskCompletionSource<bool> completion) { try { var tasks = new List<Task>(_workers.Count); foreach (var worker in _workers) { tasks.Add(worker.Deactivated); } await Task.WhenAll(tasks); completion.TrySetResult(true); } catch (Exception exception) { completion.TrySetException(exception); } } private async Task DisposeAsyncInternal(TaskCompletionSource<bool> completion) { try { var tasks = new List<Task>(_workers.Count); foreach (var worker in _workers) { try { if (worker is IAsyncDisposable disposable) { tasks.Add(disposable.DisposeAsync().AsTask()); } else if (worker is IDisposable syncDisposable) { syncDisposable.Dispose(); } } catch (Exception exception) { tasks.Add(Task.FromException(exception)); } } await Task.WhenAll(tasks); completion.TrySetResult(true); } catch (Exception exception) { completion.TrySetException(exception); } } public void OnCreateActivation(IGrainContext grainContext) { } public void OnDestroyActivation(IGrainContext grainContext) { _workItems.Enqueue(new StatelessWorkerWorkItem(WorkItemType.OnDestroyActivation, grainContext)); _workSignal.Signal(); if (_workers.Count == 0) { _sharedContext.InternalRuntime.Catalog.UnregisterMessageTarget(this); } } private struct StatelessWorkerWorkItem { public StatelessWorkerWorkItem(WorkItemType type, object state) { Type = type; State = state; } public WorkItemType Type { get; } public object State { get; } } private enum WorkItemType : byte { Activate = 0, Message = 1, Deactivate = 2, DeactivatedTask = 3, DisposeAsync = 4, OnDestroyActivation = 5, } private record ActivateWorkItemState(Dictionary<string, object> RequestContext, CancellationToken? CancellationToken); private record DeactivateWorkItemState(DeactivationReason DeactivationReason, CancellationToken? CancellationToken); private record DeactivatedTaskWorkItemState(TaskCompletionSource<bool> Completion); private record DisposeAsyncWorkItemState(TaskCompletionSource<bool> Completion); } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.DataFactories.Core; using Microsoft.Azure.Management.DataFactories.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.DataFactories.Core { /// <summary> /// Operations for managing data factories. /// </summary> internal partial class DataFactoryOperations : IServiceOperations<DataFactoryManagementClient>, IDataFactoryOperations { /// <summary> /// Initializes a new instance of the DataFactoryOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DataFactoryOperations(DataFactoryManagementClient client) { this._client = client; } private DataFactoryManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.DataFactories.Core.DataFactoryManagementClient. /// </summary> public DataFactoryManagementClient Client { get { return this._client; } } /// <summary> /// Create or update a data factory. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory operation response. /// </returns> public async Task<DataFactoryCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, DataFactoryCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.DataFactory != null) { if (parameters.DataFactory.Location == null) { throw new ArgumentNullException("parameters.DataFactory.Location"); } if (parameters.DataFactory.Name == null) { throw new ArgumentNullException("parameters.DataFactory.Name"); } if (parameters.DataFactory.Name != null && parameters.DataFactory.Name.Length > 63) { throw new ArgumentOutOfRangeException("parameters.DataFactory.Name"); } if (Regex.IsMatch(parameters.DataFactory.Name, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("parameters.DataFactory.Name"); } } // 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("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", 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/Microsoft.DataFactory/datafactories/"; if (parameters.DataFactory != null && parameters.DataFactory.Name != null) { url = url + Uri.EscapeDataString(parameters.DataFactory.Name); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject dataFactoryCreateOrUpdateParametersValue = new JObject(); requestDoc = dataFactoryCreateOrUpdateParametersValue; if (parameters.DataFactory != null) { if (parameters.DataFactory.Id != null) { dataFactoryCreateOrUpdateParametersValue["id"] = parameters.DataFactory.Id; } dataFactoryCreateOrUpdateParametersValue["name"] = parameters.DataFactory.Name; dataFactoryCreateOrUpdateParametersValue["location"] = parameters.DataFactory.Location; if (parameters.DataFactory.Tags != null) { if (parameters.DataFactory.Tags is ILazyCollection == false || ((ILazyCollection)parameters.DataFactory.Tags).IsInitialized) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.DataFactory.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } dataFactoryCreateOrUpdateParametersValue["tags"] = tagsDictionary; } } if (parameters.DataFactory.Properties != null) { JObject propertiesValue = new JObject(); dataFactoryCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.DataFactory.Properties.ProvisioningState != null) { propertiesValue["provisioningState"] = parameters.DataFactory.Properties.ProvisioningState; } if (parameters.DataFactory.Properties.ErrorMessage != null) { propertiesValue["errorMessage"] = parameters.DataFactory.Properties.ErrorMessage; } if (parameters.DataFactory.Properties.DataFactoryId != null) { propertiesValue["dataFactoryId"] = parameters.DataFactory.Properties.DataFactoryId; } } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataFactoryCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataFactoryCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DataFactory dataFactoryInstance = new DataFactory(); result.DataFactory = dataFactoryInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dataFactoryInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dataFactoryInstance.Name = nameInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dataFactoryInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey2 = ((string)property.Name); string tagsValue2 = ((string)property.Value); dataFactoryInstance.Tags.Add(tagsKey2, tagsValue2); } } JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { DataFactoryProperties propertiesInstance = new DataFactoryProperties(); dataFactoryInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue2["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken errorMessageValue = propertiesValue2["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } JToken dataFactoryIdValue = propertiesValue2["dataFactoryId"]; if (dataFactoryIdValue != null && dataFactoryIdValue.Type != JTokenType.Null) { string dataFactoryIdInstance = ((string)dataFactoryIdValue); propertiesInstance.DataFactoryId = dataFactoryIdInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } result.Location = url; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Create or update a data factory. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory operation response. /// </returns> public async Task<DataFactoryCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, DataFactoryCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { DataFactoryManagementClient client = this.Client; 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("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); DataFactoryCreateOrUpdateResponse response = await client.DataFactories.BeginCreateOrUpdateAsync(resourceGroupName, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); DataFactoryCreateOrUpdateResponse result = await client.DataFactories.GetCreateOrUpdateStatusAsync(response.Location, cancellationToken).ConfigureAwait(false); int delayInSeconds = 5; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.DataFactories.GetCreateOrUpdateStatusAsync(response.Location, cancellationToken).ConfigureAwait(false); delayInSeconds = 5; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Delete a data factory instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string dataFactoryName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } // 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("dataFactoryName", dataFactoryName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a data factory instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get data factory operation response. /// </returns> public async Task<DataFactoryGetResponse> GetAsync(string resourceGroupName, string dataFactoryName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } // 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("dataFactoryName", dataFactoryName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // 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 DataFactoryGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataFactoryGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DataFactory dataFactoryInstance = new DataFactory(); result.DataFactory = dataFactoryInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dataFactoryInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dataFactoryInstance.Name = nameInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dataFactoryInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); dataFactoryInstance.Tags.Add(tagsKey, tagsValue); } } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DataFactoryProperties propertiesInstance = new DataFactoryProperties(); dataFactoryInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken errorMessageValue = propertiesValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } JToken dataFactoryIdValue = propertiesValue["dataFactoryId"]; if (dataFactoryIdValue != null && dataFactoryIdValue.Type != JTokenType.Null) { string dataFactoryIdInstance = ((string)dataFactoryIdValue); propertiesInstance.DataFactoryId = dataFactoryIdInstance; } } } } 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> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory operation response. /// </returns> public async Task<DataFactoryCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetCreateOrUpdateStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); httpRequest.Headers.Add("x-ms-version", "2015-07-01-preview"); // 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 DataFactoryCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataFactoryCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DataFactory dataFactoryInstance = new DataFactory(); result.DataFactory = dataFactoryInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dataFactoryInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dataFactoryInstance.Name = nameInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dataFactoryInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); dataFactoryInstance.Tags.Add(tagsKey, tagsValue); } } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DataFactoryProperties propertiesInstance = new DataFactoryProperties(); dataFactoryInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken errorMessageValue = propertiesValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } JToken dataFactoryIdValue = propertiesValue["dataFactoryId"]; if (dataFactoryIdValue != null && dataFactoryIdValue.Type != JTokenType.Null) { string dataFactoryIdInstance = ((string)dataFactoryIdValue); propertiesInstance.DataFactoryId = dataFactoryIdInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } result.Location = url; if (result.DataFactory != null && result.DataFactory.Properties != null && result.DataFactory.Properties.ProvisioningState == "Failed") { result.Status = OperationStatus.Failed; } if (result.DataFactory != null && result.DataFactory.Properties != null && result.DataFactory.Properties.ProvisioningState == "Succeeded") { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the first page of data factory instances with the link to the /// next page. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factories. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List data factories operation response. /// </returns> public async Task<DataFactoryListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } // 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); 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/Microsoft.DataFactory/datafactories"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // 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 DataFactoryListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataFactoryListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DataFactory dataFactoryInstance = new DataFactory(); result.DataFactories.Add(dataFactoryInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dataFactoryInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dataFactoryInstance.Name = nameInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dataFactoryInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); dataFactoryInstance.Tags.Add(tagsKey, tagsValue); } } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DataFactoryProperties propertiesInstance = new DataFactoryProperties(); dataFactoryInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken errorMessageValue = propertiesValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } JToken dataFactoryIdValue = propertiesValue["dataFactoryId"]; if (dataFactoryIdValue != null && dataFactoryIdValue.Type != JTokenType.Null) { string dataFactoryIdInstance = ((string)dataFactoryIdValue); propertiesInstance.DataFactoryId = dataFactoryIdInstance; } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the next page of data factory instances with the link to the /// next page. /// </summary> /// <param name='nextLink'> /// Required. The url to the next data factories page. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List data factories operation response. /// </returns> public async Task<DataFactoryListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // 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 DataFactoryListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataFactoryListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DataFactory dataFactoryInstance = new DataFactory(); result.DataFactories.Add(dataFactoryInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dataFactoryInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dataFactoryInstance.Name = nameInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dataFactoryInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); dataFactoryInstance.Tags.Add(tagsKey, tagsValue); } } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DataFactoryProperties propertiesInstance = new DataFactoryProperties(); dataFactoryInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken errorMessageValue = propertiesValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } JToken dataFactoryIdValue = propertiesValue["dataFactoryId"]; if (dataFactoryIdValue != null && dataFactoryIdValue.Type != JTokenType.Null) { string dataFactoryIdInstance = ((string)dataFactoryIdValue); propertiesInstance.DataFactoryId = dataFactoryIdInstance; } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// 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. // <spec>http://www.w3.org/TR/xpath#exprlex</spec> //------------------------------------------------------------------------------ using System.Diagnostics; namespace System.Xml.Xsl.XPath { // Extends XPathOperator enumeration internal enum LexKind { Unknown, // Unknown lexeme Or, // Operator 'or' And, // Operator 'and' Eq, // Operator '=' Ne, // Operator '!=' Lt, // Operator '<' Le, // Operator '<=' Gt, // Operator '>' Ge, // Operator '>=' Plus, // Operator '+' Minus, // Operator '-' Multiply, // Operator '*' Divide, // Operator 'div' Modulo, // Operator 'mod' UnaryMinus, // Not used Union, // Operator '|' LastOperator = Union, DotDot, // '..' ColonColon, // '::' SlashSlash, // Operator '//' Number, // Number (numeric literal) Axis, // AxisName Name, // NameTest, NodeType, FunctionName, AxisName, second part of VariableReference String, // Literal (string literal) Eof, // End of the expression FirstStringable = Name, LastNonChar = Eof, LParens = '(', RParens = ')', LBracket = '[', RBracket = ']', Dot = '.', At = '@', Comma = ',', Star = '*', // NameTest Slash = '/', // Operator '/' Dollar = '$', // First part of VariableReference RBrace = '}', // Used for AVTs }; internal sealed class XPathScanner { private string _xpathExpr; private int _curIndex; private char _curChar; private LexKind _kind; private string _name; private string _prefix; private string _stringValue; private bool _canBeFunction; private int _lexStart; private int _prevLexEnd; private LexKind _prevKind; private XPathAxis _axis; private XmlCharType _xmlCharType = XmlCharType.Instance; public XPathScanner(string xpathExpr) : this(xpathExpr, 0) { } public XPathScanner(string xpathExpr, int startFrom) { Debug.Assert(xpathExpr != null); _xpathExpr = xpathExpr; _kind = LexKind.Unknown; SetSourceIndex(startFrom); NextLex(); } public string Source { get { return _xpathExpr; } } public LexKind Kind { get { return _kind; } } public int LexStart { get { return _lexStart; } } public int LexSize { get { return _curIndex - _lexStart; } } public int PrevLexEnd { get { return _prevLexEnd; } } private void SetSourceIndex(int index) { Debug.Assert(0 <= index && index <= _xpathExpr.Length); _curIndex = index - 1; NextChar(); } private void NextChar() { Debug.Assert(-1 <= _curIndex && _curIndex < _xpathExpr.Length); _curIndex++; if (_curIndex < _xpathExpr.Length) { _curChar = _xpathExpr[_curIndex]; } else { Debug.Assert(_curIndex == _xpathExpr.Length); _curChar = '\0'; } } #if XML10_FIFTH_EDITION private char PeekNextChar() { Debug.Assert(-1 <= curIndex && curIndex <= xpathExpr.Length); if (curIndex + 1 < xpathExpr.Length) { return xpathExpr[curIndex + 1]; } else { return '\0'; } } #endif public string Name { get { Debug.Assert(_kind == LexKind.Name); Debug.Assert(_name != null); return _name; } } public string Prefix { get { Debug.Assert(_kind == LexKind.Name); Debug.Assert(_prefix != null); return _prefix; } } public string RawValue { get { if (_kind == LexKind.Eof) { return LexKindToString(_kind); } else { return _xpathExpr.Substring(_lexStart, _curIndex - _lexStart); } } } public string StringValue { get { Debug.Assert(_kind == LexKind.String); Debug.Assert(_stringValue != null); return _stringValue; } } // Returns true if the character following an QName (possibly after intervening // ExprWhitespace) is '('. In this case the token must be recognized as a NodeType // or a FunctionName unless it is an OperatorName. This distinction cannot be done // without knowing the previous lexeme. For example, "or" in "... or (1 != 0)" may // be an OperatorName or a FunctionName. public bool CanBeFunction { get { Debug.Assert(_kind == LexKind.Name); return _canBeFunction; } } public XPathAxis Axis { get { Debug.Assert(_kind == LexKind.Axis); Debug.Assert(_axis != XPathAxis.Unknown); return _axis; } } private void SkipSpace() { while (_xmlCharType.IsWhiteSpace(_curChar)) { NextChar(); } } private static bool IsAsciiDigit(char ch) { return unchecked((uint)(ch - '0')) <= 9; } public void NextLex() { _prevLexEnd = _curIndex; _prevKind = _kind; SkipSpace(); _lexStart = _curIndex; switch (_curChar) { case '\0': _kind = LexKind.Eof; return; case '(': case ')': case '[': case ']': case '@': case ',': case '$': case '}': _kind = (LexKind)_curChar; NextChar(); break; case '.': NextChar(); if (_curChar == '.') { _kind = LexKind.DotDot; NextChar(); } else if (IsAsciiDigit(_curChar)) { SetSourceIndex(_lexStart); goto case '0'; } else { _kind = LexKind.Dot; } break; case ':': NextChar(); if (_curChar == ':') { _kind = LexKind.ColonColon; NextChar(); } else { _kind = LexKind.Unknown; } break; case '*': _kind = LexKind.Star; NextChar(); CheckOperator(true); break; case '/': NextChar(); if (_curChar == '/') { _kind = LexKind.SlashSlash; NextChar(); } else { _kind = LexKind.Slash; } break; case '|': _kind = LexKind.Union; NextChar(); break; case '+': _kind = LexKind.Plus; NextChar(); break; case '-': _kind = LexKind.Minus; NextChar(); break; case '=': _kind = LexKind.Eq; NextChar(); break; case '!': NextChar(); if (_curChar == '=') { _kind = LexKind.Ne; NextChar(); } else { _kind = LexKind.Unknown; } break; case '<': NextChar(); if (_curChar == '=') { _kind = LexKind.Le; NextChar(); } else { _kind = LexKind.Lt; } break; case '>': NextChar(); if (_curChar == '=') { _kind = LexKind.Ge; NextChar(); } else { _kind = LexKind.Gt; } break; case '"': case '\'': _kind = LexKind.String; ScanString(); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': _kind = LexKind.Number; ScanNumber(); break; default: if (_xmlCharType.IsStartNCNameSingleChar(_curChar) #if XML10_FIFTH_EDITION || xmlCharType.IsNCNameHighSurrogateChar(curChar) #endif ) { _kind = LexKind.Name; _name = ScanNCName(); _prefix = string.Empty; _canBeFunction = false; _axis = XPathAxis.Unknown; bool colonColon = false; int saveSourceIndex = _curIndex; // "foo:bar" or "foo:*" -- one lexeme (no spaces allowed) // "foo::" or "foo ::" -- two lexemes, reported as one (AxisName) // "foo:?" or "foo :?" -- lexeme "foo" reported if (_curChar == ':') { NextChar(); if (_curChar == ':') { // "foo::" -> OperatorName, AxisName NextChar(); colonColon = true; SetSourceIndex(saveSourceIndex); } else { // "foo:bar", "foo:*" or "foo:?" if (_curChar == '*') { NextChar(); _prefix = _name; _name = "*"; } else if (_xmlCharType.IsStartNCNameSingleChar(_curChar) #if XML10_FIFTH_EDITION || xmlCharType.IsNCNameHighSurrogateChar(curChar) #endif ) { _prefix = _name; _name = ScanNCName(); // Look ahead for '(' to determine whether QName can be a FunctionName saveSourceIndex = _curIndex; SkipSpace(); _canBeFunction = (_curChar == '('); SetSourceIndex(saveSourceIndex); } else { // "foo:?" -> OperatorName, NameTest // Return "foo" and leave ":" to be reported later as an unknown lexeme SetSourceIndex(saveSourceIndex); } } } else { SkipSpace(); if (_curChar == ':') { // "foo ::" or "foo :?" NextChar(); if (_curChar == ':') { NextChar(); colonColon = true; } SetSourceIndex(saveSourceIndex); } else { _canBeFunction = (_curChar == '('); } } if (!CheckOperator(false) && colonColon) { _axis = CheckAxis(); } } else { _kind = LexKind.Unknown; NextChar(); } break; } } private bool CheckOperator(bool star) { LexKind opKind; if (star) { opKind = LexKind.Multiply; } else { if (_prefix.Length != 0 || _name.Length > 3) return false; switch (_name) { case "or": opKind = LexKind.Or; break; case "and": opKind = LexKind.And; break; case "div": opKind = LexKind.Divide; break; case "mod": opKind = LexKind.Modulo; break; default: return false; } } // If there is a preceding token and the preceding token is not one of '@', '::', '(', '[', ',' or an Operator, // then a '*' must be recognized as a MultiplyOperator and an NCName must be recognized as an OperatorName. if (_prevKind <= LexKind.LastOperator) return false; switch (_prevKind) { case LexKind.Slash: case LexKind.SlashSlash: case LexKind.At: case LexKind.ColonColon: case LexKind.LParens: case LexKind.LBracket: case LexKind.Comma: case LexKind.Dollar: return false; } _kind = opKind; return true; } private XPathAxis CheckAxis() { _kind = LexKind.Axis; switch (_name) { case "ancestor": return XPathAxis.Ancestor; case "ancestor-or-self": return XPathAxis.AncestorOrSelf; case "attribute": return XPathAxis.Attribute; case "child": return XPathAxis.Child; case "descendant": return XPathAxis.Descendant; case "descendant-or-self": return XPathAxis.DescendantOrSelf; case "following": return XPathAxis.Following; case "following-sibling": return XPathAxis.FollowingSibling; case "namespace": return XPathAxis.Namespace; case "parent": return XPathAxis.Parent; case "preceding": return XPathAxis.Preceding; case "preceding-sibling": return XPathAxis.PrecedingSibling; case "self": return XPathAxis.Self; default: _kind = LexKind.Name; return XPathAxis.Unknown; } } private void ScanNumber() { Debug.Assert(IsAsciiDigit(_curChar) || _curChar == '.'); while (IsAsciiDigit(_curChar)) { NextChar(); } if (_curChar == '.') { NextChar(); while (IsAsciiDigit(_curChar)) { NextChar(); } } if ((_curChar & (~0x20)) == 'E') { NextChar(); if (_curChar == '+' || _curChar == '-') { NextChar(); } while (IsAsciiDigit(_curChar)) { NextChar(); } throw CreateException(SR.XPath_ScientificNotation); } } private void ScanString() { int startIdx = _curIndex + 1; int endIdx = _xpathExpr.IndexOf(_curChar, startIdx); if (endIdx < 0) { SetSourceIndex(_xpathExpr.Length); throw CreateException(SR.XPath_UnclosedString); } _stringValue = _xpathExpr.Substring(startIdx, endIdx - startIdx); SetSourceIndex(endIdx + 1); } private string ScanNCName() { Debug.Assert(_xmlCharType.IsStartNCNameSingleChar(_curChar) #if XML10_FIFTH_EDITION || xmlCharType.IsNCNameHighSurrogateChar(curChar) #endif ); int start = _curIndex; for (;;) { if (_xmlCharType.IsNCNameSingleChar(_curChar)) { NextChar(); } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(PeekNextChar(), curChar)) { NextChar(); NextChar(); } #endif else { break; } } return _xpathExpr.Substring(start, _curIndex - start); } public void PassToken(LexKind t) { CheckToken(t); NextLex(); } public void CheckToken(LexKind t) { Debug.Assert(LexKind.FirstStringable <= t); if (_kind != t) { if (t == LexKind.Eof) { throw CreateException(SR.XPath_EofExpected, RawValue); } else { throw CreateException(SR.XPath_TokenExpected, LexKindToString(t), RawValue); } } } // May be called for the following tokens: Name, String, Eof, Comma, LParens, RParens, LBracket, RBracket, RBrace private string LexKindToString(LexKind t) { Debug.Assert(LexKind.FirstStringable <= t); if (LexKind.LastNonChar < t) { Debug.Assert("()[].@,*/$}".IndexOf((char)t) >= 0); return char.ToString((char)t); } switch (t) { case LexKind.Name: return "<name>"; case LexKind.String: return "<string literal>"; case LexKind.Eof: return "<eof>"; default: Debug.Fail("Unexpected LexKind: " + t.ToString()); return string.Empty; } } public XPathCompileException CreateException(string resId, params string[] args) { return new XPathCompileException(_xpathExpr, _lexStart, _curIndex, resId, args); } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using HutongGames.PlayMaker; using MSCLoader; using UnityEngine; //Standard unity MonoBehaviour class using UnityEngine.Rendering; using Random = UnityEngine.Random; namespace MSCDirtMod { public class ModBehaviour : MonoBehaviour { public class SaveData { public float bodyDirtCutoff; public float windowWipeAmount; public float wheelDirtCutoff; } private static AssetBundle m_bundle; private Transform m_wiperPivot; private float m_oldWiperAngle; private float m_windowWipeAmount = 0; private float m_bodyDirtCutoff = 1; private GameObject m_satsuma; private CarDynamics m_carDynamics; private float m_rainAmount; private float m_wiperOnAmount; private AudioSource m_rainAudioSource; private GameObject m_rightFist, m_leftFist; private BoxCollider m_cleanCollider; private AudioSource m_smackAudioSource; private FsmFloat m_playerDirtiness, m_playerStress; private readonly List<Material> m_wheelMaterials = new List<Material>(); private readonly List<Material> m_opaqueMaterials = new List<Material>(); private readonly List<Material> m_transparentMaterials = new List<Material>(); private readonly Dictionary<string, Transform> m_bodyParts = new Dictionary<string, Transform>(); private readonly Dictionary<string, Transform> m_wheels = new Dictionary<string, Transform>(); private readonly Dictionary<string, Transform> m_rims = new Dictionary<string, Transform>(); private readonly Dictionary<string, Transform> m_windowParts = new Dictionary<string, Transform>(); private Texture2D m_genericDirtTexture; private Texture2D m_bodyDirtTexture; private Texture2D m_windowDirtTexture; private Shader m_bodyDirtShader; private Shader m_windowDirtShader; private Material m_noDrawMaterial; private Texture2D m_windowDirtWiperHoleTexture; private AudioSource m_spongeAudioSource; private AudioSource m_spongeOffAudioSource; private GameObject m_spongePrefab; private readonly List<AudioClip> m_easterAudioClips = new List<AudioClip>(); private AudioSource m_easterAudioSource; private Texture2D m_tireDirtTextureNew2; private Texture2D m_tireDirtTextureRally; private Texture2D m_tireDirtTextureRallye; private Texture2D m_tireDirtTextureStandard; private Texture2D m_tireDirtTextureSlicks; private Texture2D m_rimsDirtTexture; private float m_wheelDirtCutoff = 1; private FsmBool m_handLeft; private FsmBool m_handRight; private bool m_halt = false; private bool m_isSetup; private static ModBehaviour m_instance; public static ModBehaviour Instance { get { return m_instance; } } private void Start() { m_instance = this; StartCoroutine(SetupMod()); Load(); GameHook.InjectStateHook(GameObject.Find("ITEMS"), "Save game", Save); } private void Save() { var data = new SaveData { bodyDirtCutoff = m_bodyDirtCutoff, windowWipeAmount = m_windowWipeAmount, wheelDirtCutoff = m_wheelDirtCutoff }; SaveUtil.SerializeWriteFile(data, SaveFilePath); } private void Load() { if (File.Exists(SaveFilePath)) { var data = SaveUtil.DeserializeReadFile<SaveData>(SaveFilePath); m_bodyDirtCutoff = data.bodyDirtCutoff; m_windowWipeAmount = data.windowWipeAmount; m_wheelDirtCutoff = data.wheelDirtCutoff; } } private IEnumerator SetupMod() { while (GameObject.Find("PLAYER") == null || GameObject.Find("PLAYER/Pivot/Camera/FPSCamera/FPSCamera/AudioRain") == null) { yield return null; } ModConsole.Print("Dirt mod loading assetbundle..."); var path = MSCDirtMod.assetPath; if (SystemInfo.graphicsDeviceVersion.StartsWith("OpenGL") && Application.platform == RuntimePlatform.WindowsPlayer) path = Path.Combine(path, "bundle-linux"); // apparently fixes opengl else if (Application.platform == RuntimePlatform.WindowsPlayer) path = Path.Combine(path, "bundle-windows"); else if (Application.platform == RuntimePlatform.OSXPlayer) path = Path.Combine(path, "bundle-osx"); else if (Application.platform == RuntimePlatform.LinuxPlayer) path = Path.Combine(path, "bundle-linux"); if (!File.Exists(path)) { ModConsole.Error("Couldn't find asset bundle from path " + path); yield break; } m_bundle = AssetBundle.CreateFromMemoryImmediate(File.ReadAllBytes(path)); LoadAssets(); ModConsole.Print("Dirt mod doing final setup..."); m_rainAudioSource = GameObject.Find("PLAYER/Pivot/Camera/FPSCamera/FPSCamera/AudioRain").GetComponent<AudioSource>(); m_satsuma = PlayMakerGlobals.Instance.Variables.GetFsmGameObject("TheCar").Value; m_carDynamics = m_satsuma.GetComponentInChildren<CarDynamics>(); m_wiperPivot = m_satsuma.transform.FindChild("Wipers/WiperLeftPivot"); ModConsole.Print("Setting up buckets..."); SetupBuckets(); ModConsole.Print("Setting up audio..."); SetupAudio(); ModConsole.Print("Dirt Mod Setup!"); m_isSetup = true; } private void LoadAssets() { // only load one set of textures m_bodyDirtTexture = m_bundle.LoadAsset<Texture2D>("BodyDirt"); m_genericDirtTexture = m_bundle.LoadAsset<Texture2D>("GenericDirt"); m_windowDirtTexture = m_bundle.LoadAsset<Texture2D>("WindowDirt"); m_windowDirtWiperHoleTexture = m_bundle.LoadAsset<Texture2D>("WindowWiperHole"); // load shaders m_bodyDirtShader = m_bundle.LoadAsset<Shader>("BodyDirtShader"); m_windowDirtShader = m_bundle.LoadAsset<Shader>("WindowDirtShader"); m_noDrawMaterial = new Material(m_bundle.LoadAsset<Shader>("NoDraw")); m_spongePrefab = m_bundle.LoadAssetWithSubAssets<GameObject>("SpongePrefab")[0]; m_easterAudioClips.Add(m_bundle.LoadAsset<AudioClip>("easter_1")); m_easterAudioClips.Add(m_bundle.LoadAsset<AudioClip>("easter_2")); m_easterAudioClips.Add(m_bundle.LoadAsset<AudioClip>("easter_3")); m_easterAudioClips.Add(m_bundle.LoadAsset<AudioClip>("easter_4")); m_easterAudioClips.Add(m_bundle.LoadAsset<AudioClip>("easter_5")); m_easterAudioClips.Add(m_bundle.LoadAsset<AudioClip>("easter_6")); m_tireDirtTextureNew2 = m_bundle.LoadAsset<Texture2D>("TireDirtNew2"); m_tireDirtTextureRally = m_bundle.LoadAsset<Texture2D>("TireDirtRally"); m_tireDirtTextureRallye = m_bundle.LoadAsset<Texture2D>("TireDirtRallye"); m_tireDirtTextureStandard = m_bundle.LoadAsset<Texture2D>("TireDirtStandard"); m_tireDirtTextureSlicks = m_bundle.LoadAsset<Texture2D>("TireDirtSlicks"); m_rimsDirtTexture = m_bundle.LoadAsset<Texture2D>("RimsDirt"); } private void Update() { try { if (m_isSetup && !m_halt) { DebugKeys(); UseSponge(); SetupBody(); SetupWindows(); SetupWheels(); SetupMisc(); UpdateMaterialValues(); } } catch (Exception e) { ModConsole.Error(e.ToString()); m_halt = true; } } private void OnDestroy() { m_bundle.Unload(true); } private void DebugKeys() { if (MSCDirtMod.keyLessDirt.IsPressed()) { m_bodyDirtCutoff += Time.deltaTime * 0.1f; m_windowWipeAmount += Time.deltaTime * 0.1f; m_wheelDirtCutoff += Time.deltaTime * 0.1f; } else if (MSCDirtMod.keyMoreDirt.IsPressed()) { m_bodyDirtCutoff -= Time.deltaTime * 0.1f; m_windowWipeAmount -= Time.deltaTime * 0.1f; m_wheelDirtCutoff -= Time.deltaTime * 0.1f; } } private void UseSponge() { // block hand usage if (m_handRight.Value == false && m_rightFist.activeSelf) m_handRight.Value = true; if (m_handLeft.Value == false && m_leftFist.activeSelf) m_handLeft.Value = true; if (Input.GetMouseButtonDown(0) && m_rightFist.activeSelf) { m_rightFist.transform.FindChild("Pivot").GetComponent<Animation>().Play(); CleanCar(); } if (Input.GetMouseButtonDown(1) && m_leftFist.activeSelf) { m_leftFist.transform.FindChild("Pivot").GetComponent<Animation>().Play(); CleanCar(); } } private void CleanCar() { // enable our collider m_cleanCollider.gameObject.SetActive(true); var cam = Camera.main; var hits = Physics.RaycastAll(cam.transform.position, cam.transform.forward, 2f); if (hits.Any(raycastHit => raycastHit.collider == m_cleanCollider)) { m_smackAudioSource.pitch = Random.Range(0.9f, 1.1f); m_smackAudioSource.Play(); m_bodyDirtCutoff += 0.05f; m_windowWipeAmount += 0.05f; m_wheelDirtCutoff += 0.05f; m_playerDirtiness.Value += 5; m_playerStress.Value -= 2; } // disable our collider m_cleanCollider.gameObject.SetActive(false); } private Transform DupeWindow(Transform glass) { var dupeGlass = Instantiate(glass.gameObject).transform; dupeGlass.SetParent(glass.parent); dupeGlass.localPosition = glass.localPosition; dupeGlass.localScale = glass.localScale; dupeGlass.localRotation = glass.localRotation; return dupeGlass; } private void SetupMisc() { SwapMiscPartMaterial("Body/pivot_fender_right/fender right(Clone)/pivot_flares_fr/fender flare fr(Clone)", m_genericDirtTexture); SwapMiscPartMaterial("Body/pivot_fender_left/fender left(Clone)/pivot_flares_fl/fender flare fl(Clone)", m_genericDirtTexture); SwapMiscPartMaterial("Body/pivot_flares_rr/fender flare rr(Clone)", m_genericDirtTexture); SwapMiscPartMaterial("Body/pivot_flares_rl/fender flare rl(Clone)", m_genericDirtTexture); SwapMiscPartMaterial("Body/pivot_grille/grille(Clone)", m_genericDirtTexture); SwapMiscPartMaterial("Body/pivot_hood/fiberglass hood(Clone)", m_genericDirtTexture); SwapMiscPartMaterial("Body/pivot_bumper_front/bumper front(Clone)", m_genericDirtTexture); SwapMiscPartMaterial("Body/pivot_bumper_rear/bumper rear(Clone)", m_genericDirtTexture); SwapMiscPartMaterial("Body/pivot_spoiler_front/fender flare spoiler(Clone)", m_genericDirtTexture); SwapMiscPartMaterial("Body/pivot_bootlid/bootlid(Clone)/pivot_spoiler/rear spoiler(Clone)", m_genericDirtTexture); SwapMiscPartMaterial("Body/pivot_bootlid/bootlid(Clone)/bootlid_emblem", m_genericDirtTexture); SwapMiscPartMaterial("Body/pivot_bootlid/bootlid(Clone)/RegPlateRear", m_genericDirtTexture); SwapMiscPartMaterial("Body/pivot_bootlid/bootlid(Clone)/RegPlateRear", m_genericDirtTexture); } private void SwapMiscPartMaterial(string miscpart, Texture2D texture) { var part = m_satsuma.transform.FindChild(miscpart); if (part != null) { if (m_windowParts.ContainsKey(miscpart) && m_windowParts[miscpart] == part) return; if (!m_windowParts.ContainsKey(miscpart)) m_windowParts.Add(miscpart, part); m_windowParts[miscpart] = part; var mr = part.GetComponent<MeshRenderer>(); mr.material = SwapOpaqueShader(mr.material, texture); m_opaqueMaterials.Add(mr.material); } } private void SetupWindows() { RemoveBrokenWindshield(); SwapWindowPartMaterial("Body/Windshield/mesh", true); SwapWindowPartMaterial("Body/rear_windows/standard", false); SwapWindowPartMaterial("Body/rear_windows/black windows(xxxxx)", false); SwapWindowPartMaterial("Body/pivot_door_right/door right(Clone)/windows_pivot/coll/glass", true); SwapWindowPartMaterial("Body/pivot_door_left/door left(Clone)/windows_pivot/coll/glass", true); } private void RemoveBrokenWindshield() { const string part = "Body/Windshield/mesh"; if (m_windowParts.ContainsKey(part)) { m_windowParts[part].parent.FindChild("DupeDirt").gameObject.SetActive(m_windowParts[part].gameObject.activeSelf); } } private void SwapWindowPartMaterial(string windowpart, bool flipMaterials) { var part = m_satsuma.transform.FindChild(windowpart); if (part != null) { if (m_windowParts.ContainsKey(windowpart) && m_windowParts[windowpart] == part) return; if (!m_windowParts.ContainsKey(windowpart)) m_windowParts.Add(windowpart, part); m_windowParts[windowpart] = part; // already swapped glass if (part.parent.FindChild("DupeDirt") == null) { var dupe = DupeWindow(part); dupe.name = "DupeDirt"; // turn window shadow receive off so they don't compete part.GetComponent<MeshRenderer>().receiveShadows = false; //dupe.localScale = new Vector3(1.005f,1.005f,1.005f); var mr = dupe.GetComponent<MeshRenderer>(); var dirtInside = SwapWindowMaterialShaderDirt(mr.materials[0], flipMaterials ? -1 : 1); var dirtOutside = SwapWindowMaterialShaderDirt(mr.materials[0], flipMaterials ? 1 : -1); mr.shadowCastingMode = ShadowCastingMode.On; mr.receiveShadows = true; mr.materials = new[] {dirtInside, dirtOutside}; m_transparentMaterials.Add(dirtInside); m_transparentMaterials.Add(dirtOutside); } } } private void SetupBody() { SwapBodyPartMaterial("Body/car body(xxxxx)"); SwapBodyPartMaterial("Body/pivot_hood/hood(Clone)"); SwapBodyPartMaterial("Body/pivot_door_left/door left(Clone)"); SwapBodyPartMaterial("Body/pivot_door_right/door right(Clone)"); SwapBodyPartMaterial("Body/pivot_fender_left/fender left(Clone)"); SwapBodyPartMaterial("Body/pivot_fender_right/fender right(Clone)"); SwapBodyPartMaterial("Body/pivot_bootlid/bootlid(Clone)"); } private void SwapBodyPartMaterial(string bodypart) { var part = m_satsuma.transform.FindChild(bodypart); if (part != null) { if (m_bodyParts.ContainsKey(bodypart) && m_bodyParts[bodypart] == part) return; if (!m_bodyParts.ContainsKey(bodypart)) m_bodyParts.Add(bodypart, part); m_bodyParts[bodypart] = part; //ModConsole.Print("Swapped body " + bodypart); var mr = part.GetComponent<MeshRenderer>(); mr.shadowCastingMode = ShadowCastingMode.On; mr.material = SwapOpaqueShader(mr.material, m_bodyDirtTexture); m_opaqueMaterials.Add(mr.material); } } private void SetupWheels() { SwapWheelMaterial("wheelFL/TireFL/OFFSET/pivot_wheel_standard"); SwapWheelMaterial("wheelFR/TireFR/OFFSET/pivot_wheel_standard"); SwapWheelMaterial("wheelRL/TireRL/pivot_wheel_standard"); SwapWheelMaterial("wheelRR/TireRR/pivot_wheel_standard"); } private void SwapWheelMaterial(string pivotPart) { var pivot = m_satsuma.transform.FindChild(pivotPart); if (pivot == null) return; var rim = pivot.transform.Cast<Transform>().FirstOrDefault(x => x.name.Contains("wheel")); if (rim == null) return; var wheel = rim.transform.Cast<Transform>().FirstOrDefault(x => x.name.Contains("Tire")); if (wheel == null) return; SwapTireMaterial(pivotPart + "/" + wheel.name, wheel); SwapRimMaterial(pivotPart + "/" + rim.name, rim); } private void SwapRimMaterial(string rim, Transform part) { if (m_rims.ContainsKey(rim) && m_rims[rim] == part) return; if (!m_rims.ContainsKey(rim)) m_rims.Add(rim, part); m_rims[rim] = part; var texture = m_rimsDirtTexture; //ModConsole.Print("Swapped rim " + rim); var mr = part.GetComponent<MeshRenderer>(); // use the body shader for wheels too mr.material = SwapOpaqueShader(mr.material, texture); m_wheelMaterials.Add(mr.material); } private void SwapTireMaterial(string tire, Transform part) { if (m_wheels.ContainsKey(tire) && m_wheels[tire] == part) return; if (!m_wheels.ContainsKey(tire)) m_wheels.Add(tire, part); m_wheels[tire] = part; var texture = m_tireDirtTextureNew2; if (tire.Contains("Standard")) texture = m_tireDirtTextureStandard; else if (tire.Contains("Slicks")) texture = m_tireDirtTextureSlicks; else if (tire.Contains("Gobra")) texture = m_tireDirtTextureRallye; else if (tire.Contains("Rally")) texture = m_tireDirtTextureRally; //ModConsole.Print("Swapped tire " + tire); var mr = part.GetComponent<MeshRenderer>(); // use the body shader for wheels too mr.material = SwapOpaqueShader(mr.material, texture); m_wheelMaterials.Add(mr.material); } private void SetupAudio() { var fpsCamera = GameObject.Find("FPSCamera"); var go = new GameObject("SmackSound"); m_smackAudioSource = go.AddComponent<AudioSource>(); m_smackAudioSource.playOnAwake = false; m_smackAudioSource.clip = m_bundle.LoadAsset<AudioClip>("WetSmack"); m_smackAudioSource.transform.SetParent(fpsCamera.transform); m_spongeAudioSource = go.AddComponent<AudioSource>(); m_spongeAudioSource.playOnAwake = false; m_spongeAudioSource.clip = m_bundle.LoadAsset<AudioClip>("Sponge"); m_spongeAudioSource.transform.SetParent(fpsCamera.transform); m_spongeOffAudioSource = go.AddComponent<AudioSource>(); m_spongeOffAudioSource.playOnAwake = false; m_spongeOffAudioSource.clip = m_bundle.LoadAsset<AudioClip>("SpongeOff"); m_spongeOffAudioSource.transform.SetParent(fpsCamera.transform); m_easterAudioSource = go.AddComponent<AudioSource>(); m_easterAudioSource.playOnAwake = false; m_easterAudioSource.clip = null; m_easterAudioSource.transform.SetParent(fpsCamera.transform); } private void SetupBuckets() { var bucket = Instantiate(m_bundle.LoadAssetWithSubAssets<GameObject>("BucketPrefab")[0]).AddComponent<BucketBehaviour>(); bucket.Setup("home"); bucket = Instantiate(m_bundle.LoadAssetWithSubAssets<GameObject>("BucketPrefab")[0]).AddComponent<BucketBehaviour>(); bucket.Setup("teimo"); // setup satsuma trigger var go = new GameObject("CleaningTrigger"); go.transform.SetParent(m_satsuma.transform, false); go.transform.localPosition = Vector3.zero; go.transform.localRotation = Quaternion.identity; //go.transform.localScale = new Vector3(1.9f, 1.7f, 3.7f); var collider = go.AddComponent<BoxCollider>(); collider.isTrigger = true; collider.size = new Vector3(1.9f, 1.7f, 3.7f); m_cleanCollider = collider; // disable our collider m_cleanCollider.gameObject.SetActive(false); m_playerDirtiness = PlayMakerGlobals.Instance.Variables.FindFsmFloat("PlayerDirtiness"); m_playerStress = PlayMakerGlobals.Instance.Variables.FindFsmFloat("PlayerStress"); m_handLeft = PlayMakerGlobals.Instance.Variables.FindFsmBool("PlayerHandLeft"); m_handRight = PlayMakerGlobals.Instance.Variables.FindFsmBool("PlayerHandRight"); // setup hands var fpsCamera = GameObject.Find("FPSCamera"); m_rightFist = Instantiate(fpsCamera.transform.FindChild("Fist")).gameObject; m_rightFist.transform.SetParent(fpsCamera.transform, false); m_rightFist.SetActive(false); m_rightFist.transform.localPosition += new Vector3(0, 0, 0.2f); var sponge = Instantiate(m_spongePrefab); sponge.transform.SetParent(m_rightFist.transform.FindChild("Pivot/hand/Armature/Bone/Bone_001/Bone_006").transform, false); sponge.transform.localPosition = Vector3.zero; sponge.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f); sponge.transform.FindChild("Sponge").GetComponent<MeshRenderer>().sortingLayerID = m_rightFist.transform.FindChild("Pivot/hand/hand_rigged").GetComponent<SkinnedMeshRenderer>().sortingLayerID; m_leftFist = Instantiate(m_rightFist); m_leftFist.transform.SetParent(fpsCamera.transform, false); m_leftFist.SetActive(false); m_leftFist.transform.localScale = new Vector3( -m_leftFist.transform.localScale.x, m_leftFist.transform.localScale.y, m_leftFist.transform.localScale.z); m_leftFist.transform.localPosition += new Vector3(-0.1f, 0, 0f); } private void PlayTakeSponge() { m_spongeAudioSource.pitch = Random.Range(0.9f, 1.1f); m_spongeAudioSource.Play(); } private void PlayDropSponge() { m_spongeOffAudioSource.pitch = Random.Range(0.9f, 1.1f); m_spongeOffAudioSource.Play(); } public void BucketUse(BucketBehaviour trigger, bool hasSponge) { try { if (hasSponge) { if (!m_handRight.Value) { m_handRight.Value = true; m_rightFist.SetActive(true); trigger.SetSponge(false); PlayTakeSponge(); } else if (!m_handLeft.Value) { m_handLeft.Value = true; m_leftFist.SetActive(true); trigger.SetSponge(false); PlayTakeSponge(); } if (m_rightFist.activeSelf && m_leftFist.activeSelf) StartCoroutine(UltraClean()); } else { if (m_leftFist.activeSelf) { m_handLeft.Value = false; m_leftFist.SetActive(false); trigger.SetSponge(true); PlayDropSponge(); } else { m_handRight.Value = false; m_rightFist.SetActive(false); trigger.SetSponge(true); PlayDropSponge(); } } } catch (Exception e) { ModConsole.Print(e.ToString()); throw; } } private IEnumerator UltraClean() { var i = Random.Range(0, m_easterAudioClips.Count - 1); m_easterAudioSource.clip = m_easterAudioClips[i]; m_easterAudioSource.Play(); var str = ""; switch (i) { case 0: str = "God help me! Double goat!"; break; case 1: str = "No, perkele, two pieces!"; break; case 2: str = "Yup, gets moving!"; break; case 3: str = "Perkele, now the dirt will go!"; break; case 4: str = "Yes! Doubles!"; break; case 5: str = "With two hands! God help me!"; break; } var tm = GameObject.Find("GUI/Indicators/Subtitles").GetComponent<TextMesh>(); while (m_easterAudioSource.isPlaying) { tm.text = str; yield return new WaitForSeconds(1f); } tm.text = ""; } private void UpdateMaterialValues() { // remove null materials (old parts that were destroyed) m_transparentMaterials.RemoveAll(x => x == null); m_opaqueMaterials.RemoveAll(x => x == null); m_wheelMaterials.RemoveAll(x => x == null); // wipers are moving if (!Mathf.Approximately(m_wiperPivot.localRotation.eulerAngles.z, m_oldWiperAngle)) { m_oldWiperAngle = m_wiperPivot.localRotation.eulerAngles.z; m_windowWipeAmount += Time.deltaTime * 0.15f; m_wiperOnAmount += Time.deltaTime * 5f; } else { m_wiperOnAmount -= Time.deltaTime * 0.2f * m_rainAmount; } // clean car when it rains if (m_rainAudioSource.isPlaying) { m_wheelDirtCutoff += Time.deltaTime * 0.01f; m_bodyDirtCutoff += Time.deltaTime * 0.01f; m_windowWipeAmount += Time.deltaTime * 0.01f; m_rainAmount += Time.deltaTime * 0.1f; } else { m_rainAmount -= Time.deltaTime * 0.1f; } // dirty car when it moves, based on surface var wheel = m_satsuma.GetComponentInChildren<Wheel>(); if (wheel != null) { var minDirt = 0f; var minWheelDirt = 0f; var amount = 0f; switch (wheel.surfaceType) { case CarDynamics.SurfaceType.sand: amount = 0.0002f; minDirt = 0.4f; minWheelDirt = 0.6f; break; case CarDynamics.SurfaceType.grass: amount = 0.0006f; minDirt = 0; minWheelDirt = 0; break; case CarDynamics.SurfaceType.offroad: amount = 0.0002f; minDirt = 0.4f; minWheelDirt = 0.6f; break; case CarDynamics.SurfaceType.track: amount = 0.0001f; minDirt = 0.8f; minWheelDirt = 0.8f; break; case CarDynamics.SurfaceType.oil: amount = 0.0001f; minDirt = 0.1f; minWheelDirt = 0f; break; } amount *= m_bodyDirtCutoff + 0.1f; // diminishing returns to dirt (accumulate at 110% at no dirt, 10% at full dirt) var v = Time.deltaTime * m_carDynamics.velo * amount; if (m_bodyDirtCutoff > minDirt) m_bodyDirtCutoff -= v; if (m_windowWipeAmount > minDirt) m_windowWipeAmount -= v * 50f; // clean wheels (based off of surface) if (m_wheelDirtCutoff > minWheelDirt) m_wheelDirtCutoff -= v * 100f; else m_wheelDirtCutoff += v * 100f; // tires dirty real fast } m_bodyDirtCutoff = Mathf.Clamp01(m_bodyDirtCutoff); m_windowWipeAmount = Mathf.Clamp(m_windowWipeAmount, 0, 0.8f); m_wiperOnAmount = Mathf.Clamp01(m_wiperOnAmount); m_rainAmount = Mathf.Clamp01(m_rainAmount); SetTransparentDirtMaterialFloat("_Cutoff", m_bodyDirtCutoff + 0.2f); SetTransparentDirtMaterialFloat("_WipeAmount", m_windowWipeAmount); SetOpaqueDirtMaterialFloat("_Cutoff", m_bodyDirtCutoff); SetWheelMaterialFloat("_Cutoff", m_wheelDirtCutoff); } private void SetOpaqueDirtMaterialFloat(string key, float value) { foreach (var mat in m_opaqueMaterials) { mat.SetFloat(key, value); } } private void SetTransparentDirtMaterialFloat(string key, float value) { foreach (var mat in m_transparentMaterials) { mat.SetFloat(key, value); } } private void SetWheelMaterialFloat(string key, float value) { foreach (var mat in m_wheelMaterials) { mat.SetFloat(key, value); } } private Material SwapOpaqueShader(Material material, Texture2D texture) { var newMat = new Material(m_bodyDirtShader); newMat.CopyPropertiesFromMaterial(material); newMat.SetTexture("_DirtTex", texture); return newMat; } private Material SwapTransparentShader(Material material, Texture2D texture, int offset) { var newMat = new Material(m_windowDirtShader); newMat.CopyPropertiesFromMaterial(material); newMat.SetTexture("_MainTex", texture); newMat.SetInt("_Offset", offset); return newMat; } private Material SwapWindowMaterialShaderDirt(Material material, int offset) { var newMat = new Material(m_windowDirtShader); newMat.CopyPropertiesFromMaterial(material); newMat.SetTexture("_MainTex", m_windowDirtTexture); newMat.SetTexture("_WiperHole", m_windowDirtWiperHoleTexture); newMat.SetInt("_Offset", offset); return newMat; } public string SaveFilePath { get { return Path.Combine(Application.persistentDataPath, "dirt_dirt.xml"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class SwitchTests { [Theory] [ClassData(typeof(CompilationTypes))] public void IntSwitch1(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(int)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant(1)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant(2)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant(1))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<int, string> f = Expression.Lambda<Func<int, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void NullableIntSwitch1(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(int?)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant((int?)1, typeof(int?))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant((int?)2, typeof(int?))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant((int?)1, typeof(int?)))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<int?, string> f = Expression.Lambda<Func<int?, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("two", f(2)); Assert.Equal("default", f(null)); Assert.Equal("default", f(3)); } [Theory, ClassData(typeof(CompilationTypes))] public void SwitchToGotos(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(int)); ParameterExpression p1 = Expression.Parameter(typeof(string)); LabelTarget end = Expression.Label(); LabelTarget lala = Expression.Label(); LabelTarget hello = Expression.Label(); BlockExpression block =Expression.Block( new [] { p1 }, Expression.Switch( p, Expression.Block( Expression.Assign(p1, Expression.Constant("default")), Expression.Goto(end) ), Expression.SwitchCase(Expression.Goto(hello), Expression.Constant(1)), Expression.SwitchCase(Expression.Block( Expression.Assign(p1, Expression.Constant("two")), Expression.Goto(end) ), Expression.Constant(2)), Expression.SwitchCase(Expression.Goto(lala), Expression.Constant(4)) ), Expression.Label(hello), Expression.Assign(p1, Expression.Constant("hello")), Expression.Goto(end), Expression.Label(lala), Expression.Assign(p1, Expression.Constant("lala")), Expression.Label(end), p1 ); Func<int, string> f = Expression.Lambda<Func<int, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); Assert.Equal("lala", f(4)); } [Theory, ClassData(typeof(CompilationTypes))] public void SwitchToGotosOutOfTry(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(char)); ParameterExpression p1 = Expression.Parameter(typeof(string)); LabelTarget end = Expression.Label(); LabelTarget lala = Expression.Label(); LabelTarget hello = Expression.Label(); BlockExpression block = Expression.Block( new[] { p1 }, Expression.TryFinally( Expression.Switch( p, Expression.Block( Expression.Assign(p1, Expression.Constant("default")), Expression.Goto(end) ), Expression.SwitchCase(Expression.Goto(hello), Expression.Constant('a')), Expression.SwitchCase(Expression.Block( Expression.Assign(p1, Expression.Constant("two")), Expression.Goto(end) ), Expression.Constant('b')), Expression.SwitchCase(Expression.Goto(lala), Expression.Constant('d')) ), Expression.Empty() ), Expression.Label(hello), Expression.Assign(p1, Expression.Constant("hello")), Expression.Goto(end), Expression.Label(lala), Expression.Assign(p1, Expression.Constant("lala")), Expression.Label(end), p1 ); Func<char, string> f = Expression.Lambda<Func<char, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f('a')); Assert.Equal("two", f('b')); Assert.Equal("default", f('c')); Assert.Equal("lala", f('d')); } [Theory] [ClassData(typeof(CompilationTypes))] public void NullableIntSwitch2(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(int?)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant((int?)1, typeof(int?))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant((int?)2, typeof(int?))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("null")), Expression.Constant((int?)null, typeof(int?))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant((int?)1, typeof(int?)))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<int?, string> f = Expression.Lambda<Func<int?, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("two", f(2)); Assert.Equal("null", f(null)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void IntSwitch2(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(byte)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant((byte)1)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant((byte)2)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant((byte)1))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<byte, string> f = Expression.Lambda<Func<byte, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void IntSwitch3(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(uint)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant((uint)1)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant((uint)2)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant((uint)1)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("wow")), Expression.Constant(uint.MaxValue))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<uint, string> f = Expression.Lambda<Func<uint, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("wow", f(uint.MaxValue)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void LongSwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(long)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant(1L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant(2L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant(1L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("wow")), Expression.Constant(long.MaxValue))); BlockExpression block = Expression.Block(new [] { p1 }, s, p1); Func<long, string> f = Expression.Lambda<Func<long, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("wow", f(long.MaxValue)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void ULongSwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(ulong)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant(1UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant(2UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant(1UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("wow")), Expression.Constant(ulong.MaxValue))); BlockExpression block = Expression.Block(new [] { p1 }, s, p1); Func<ulong, string> f = Expression.Lambda<Func<ulong, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("wow", f(ulong.MaxValue)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void SparseULongSwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(ulong)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant(1UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant(2UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("three")), Expression.Constant(203212UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("four")), Expression.Constant(10212UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("five")), Expression.Constant(5021029121UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("six")), Expression.Constant(690219291UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant(1UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("wow")), Expression.Constant(ulong.MaxValue))); BlockExpression block = Expression.Block(new[] { p1 }, s, p1); Func<ulong, string> f = Expression.Lambda<Func<ulong, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("three", f(203212UL)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void SparseLongSwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(long)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant(1L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant(2L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("three")), Expression.Constant(203212L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("four")), Expression.Constant(10212L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("five")), Expression.Constant(5021029121L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("six")), Expression.Constant(690219291L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant(1L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("wow")), Expression.Constant(long.MaxValue))); BlockExpression block = Expression.Block(new[] { p1 }, s, p1); Func<long, string> f = Expression.Lambda<Func<long, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("three", f(203212L)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StringSwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Constant("default"), Expression.SwitchCase(Expression.Constant("hello"), Expression.Constant("hi")), Expression.SwitchCase(Expression.Constant("lala"), Expression.Constant("bye"))); Func<string, string> f = Expression.Lambda<Func<string, string>>(s, p).Compile(useInterpreter); Assert.Equal("hello", f("hi")); Assert.Equal("lala", f("bye")); Assert.Equal("default", f("hi2")); Assert.Equal("default", f(null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StringSwitchTailCall(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Constant("default"), Expression.SwitchCase(Expression.Constant("hello"), Expression.Constant("hi")), Expression.SwitchCase(Expression.Constant("lala"), Expression.Constant("bye"))); Func<string, string> f = Expression.Lambda<Func<string, string>>(s, true, p).Compile(useInterpreter); Assert.Equal("hello", f("hi")); Assert.Equal("lala", f("bye")); Assert.Equal("default", f("hi2")); Assert.Equal("default", f(null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StringSwitchTailCallButNotLast(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Constant("default"), Expression.SwitchCase(Expression.Constant("hello"), Expression.Constant("hi")), Expression.SwitchCase(Expression.Constant("lala"), Expression.Constant("bye"))); BlockExpression block = Expression.Block(s, Expression.Constant("Not from the switch")); Func<string, string> f = Expression.Lambda<Func<string, string>>(block, true, p).Compile(useInterpreter); Assert.Equal("Not from the switch", f("hi")); Assert.Equal("Not from the switch", f("bye")); Assert.Equal("Not from the switch", f("hi2")); Assert.Equal("Not from the switch", f(null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StringSwitch1(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(string)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant("hi")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("null")), Expression.Constant(null, typeof(string))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant("bye"))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<string, string> f = Expression.Lambda<Func<string, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f("hi")); Assert.Equal("lala", f("bye")); Assert.Equal("default", f("hi2")); Assert.Equal("null", f(null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StringSwitchNotConstant(bool useInterpreter) { Expression<Func<string>> expr1 = () => new string('a', 5); Expression<Func<string>> expr2 = () => new string('q', 5); ParameterExpression p = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Constant("default"), Expression.SwitchCase(Expression.Invoke(expr1), Expression.Invoke(expr2)), Expression.SwitchCase(Expression.Constant("lala"), Expression.Constant("bye"))); Func<string, string> f = Expression.Lambda<Func<string, string>>(s, p).Compile(useInterpreter); Assert.Equal("aaaaa", f("qqqqq")); Assert.Equal("lala", f("bye")); Assert.Equal("default", f("hi2")); Assert.Equal("default", f(null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void ObjectSwitch1(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(object)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant("hi")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("null")), Expression.Constant(null, typeof(string))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant("bye")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lalala")), Expression.Constant("hi"))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<object, string> f = Expression.Lambda<Func<object, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f("hi")); Assert.Equal("lala", f("bye")); Assert.Equal("default", f("hi2")); Assert.Equal("default", f("HI")); Assert.Equal("null", f(null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void DefaultOnlySwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(int)); SwitchExpression s = Expression.Switch(p, Expression.Constant(42)); Func<int, int> fInt32Int32 = Expression.Lambda<Func<int, int>>(s, p).Compile(useInterpreter); Assert.Equal(42, fInt32Int32(0)); Assert.Equal(42, fInt32Int32(1)); Assert.Equal(42, fInt32Int32(-1)); s = Expression.Switch(typeof(object), p, Expression.Constant("A test string"), null); Func<int, object> fInt32Object = Expression.Lambda<Func<int, object>>(s, p).Compile(useInterpreter); Assert.Equal("A test string", fInt32Object(0)); Assert.Equal("A test string", fInt32Object(1)); Assert.Equal("A test string", fInt32Object(-1)); p = Expression.Parameter(typeof(string)); s = Expression.Switch(p, Expression.Constant("foo")); Func<string, string> fStringString = Expression.Lambda<Func<string, string>>(s, p).Compile(useInterpreter); Assert.Equal("foo", fStringString("bar")); Assert.Equal("foo", fStringString(null)); Assert.Equal("foo", fStringString("foo")); } [Theory] [ClassData(typeof(CompilationTypes))] public void NoDefaultOrCasesSwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(int)); SwitchExpression s = Expression.Switch(p); Action<int> f = Expression.Lambda<Action<int>>(s, p).Compile(useInterpreter); f(0); Assert.Equal(s.Type, typeof(void)); } [Fact] public void TypedNoDefaultOrCasesSwitch() { ParameterExpression p = Expression.Parameter(typeof(int)); // A SwitchExpression with neither a defaultBody nor any cases can not be any type except void. AssertExtensions.Throws<ArgumentException>("defaultBody", () => Expression.Switch(typeof(int), p, null, null)); } private delegate int RefSettingDelegate(ref bool changed); private delegate void JustRefSettingDelegate(ref bool changed); public static int QuestionMeaning(ref bool changed) { changed = true; return 42; } [Theory] [ClassData(typeof(CompilationTypes))] public void DefaultOnlySwitchWithSideEffect(bool useInterpreter) { bool changed = false; ParameterExpression pOut = Expression.Parameter(typeof(bool).MakeByRefType(), "changed"); MethodCallExpression switchValue = Expression.Call(typeof(SwitchTests).GetMethod(nameof(QuestionMeaning)), pOut); SwitchExpression s = Expression.Switch(switchValue, Expression.Constant(42)); RefSettingDelegate fInt32Int32 = Expression.Lambda<RefSettingDelegate>(s, pOut).Compile(useInterpreter); Assert.False(changed); Assert.Equal(42, fInt32Int32(ref changed)); Assert.True(changed); changed = false; Assert.Equal(42, fInt32Int32(ref changed)); Assert.True(changed); } [Theory] [ClassData(typeof(CompilationTypes))] public void NoDefaultOrCasesSwitchWithSideEffect(bool useInterpreter) { bool changed = false; ParameterExpression pOut = Expression.Parameter(typeof(bool).MakeByRefType(), "changed"); MethodCallExpression switchValue = Expression.Call(typeof(SwitchTests).GetMethod(nameof(QuestionMeaning)), pOut); SwitchExpression s = Expression.Switch(switchValue, (Expression)null); JustRefSettingDelegate f = Expression.Lambda<JustRefSettingDelegate>(s, pOut).Compile(useInterpreter); Assert.False(changed); f(ref changed); Assert.True(changed); } public class TestComparers { public static bool CaseInsensitiveStringCompare(string s1, string s2) { return StringComparer.OrdinalIgnoreCase.Equals(s1, s2); } } [Theory] [ClassData(typeof(CompilationTypes))] public void SwitchWithComparison(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(string)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), typeof(TestComparers).GetMethod(nameof(TestComparers.CaseInsensitiveStringCompare)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant("hi")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("null")), Expression.Constant(null, typeof(string))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant("bye")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lalala")), Expression.Constant("hi"))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<string, string> f = Expression.Lambda<Func<string, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f("hi")); Assert.Equal("lala", f("bYe")); Assert.Equal("default", f("hi2")); Assert.Equal("hello", f("HI")); Assert.Equal("null", f(null)); } [Fact] public void NullSwitchValue() { AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(null)); AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(null, Expression.Empty())); AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(null, Expression.Empty(), default(MethodInfo))); AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(null, Expression.Empty(), default(MethodInfo), Enumerable.Empty<SwitchCase>())); AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(typeof(int), null, Expression.Constant(1), default(MethodInfo))); AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(typeof(int), null, Expression.Constant(1), default(MethodInfo), Enumerable.Empty<SwitchCase>())); } [Fact] public void VoidSwitchValue() { AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(Expression.Empty())); AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(Expression.Empty(), Expression.Empty())); AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(Expression.Empty(), Expression.Empty(), default(MethodInfo))); AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(Expression.Empty(), Expression.Empty(), default(MethodInfo), Enumerable.Empty<SwitchCase>())); AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(typeof(int), Expression.Empty(), Expression.Constant(1), default(MethodInfo))); AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(typeof(int), Expression.Empty(), Expression.Constant(1), default(MethodInfo), Enumerable.Empty<SwitchCase>())); } public static IEnumerable<object[]> ComparisonsWithInvalidParmeterCounts() { Func<bool> nullary = () => true; yield return new object[] { nullary.GetMethodInfo() }; Func<int, bool> unary = x => x % 2 == 0; yield return new object[] { unary.GetMethodInfo() }; Func<int, int, int, bool> ternary = (x, y, z) => (x == y) == (y == z); yield return new object[] { ternary.GetMethodInfo() }; Func<int, int, int, int, bool> quaternary = (a, b, c, d) => (a == b) == (c == d); yield return new object[] { quaternary.GetMethodInfo() }; } [Theory, MemberData(nameof(ComparisonsWithInvalidParmeterCounts))] public void InvalidComparisonMethodParameterCount(MethodInfo comparison) { AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparison)); AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparison, Enumerable.Empty<SwitchCase>())); AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparison)); AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparison, Enumerable.Empty<SwitchCase>())); } [Fact] public void ComparisonLeftParameterIncorrect() { Func<string, int, bool> isLength = (x, y) => (x?.Length).GetValueOrDefault() == y; MethodInfo comparer = isLength.GetMethodInfo(); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Enumerable.Empty<SwitchCase>())); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Enumerable.Empty<SwitchCase>())); } [Fact] public void ComparisonRightParameterIncorrect() { Func<int, string, bool> isLength = (x, y) => (y?.Length).GetValueOrDefault() == x; MethodInfo comparer = isLength.GetMethodInfo(); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)))); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Enumerable.Repeat(Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)), 1))); AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)))); AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Enumerable.Repeat(Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)), 1))); } private class GenClass<T> { public static bool WithinTwo(int x, int y) => Math.Abs(x - y) < 2; } [Theory, ClassData(typeof(CompilationTypes))] public void OpenGenericMethodDeclarer(bool useInterpreter) { Expression switchVal = Expression.Constant(30); Expression defaultExp = Expression.Constant(0); SwitchCase switchCase = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(2)); MethodInfo method = typeof(GenClass<>).GetMethod(nameof(GenClass<int>.WithinTwo), BindingFlags.Static | BindingFlags.Public); AssertExtensions.Throws<ArgumentException>( "comparison", () => Expression.Switch(switchVal, defaultExp, method, switchCase)); } static bool WithinTen(int x, int y) => Math.Abs(x - y) < 10; [Theory, ClassData(typeof(CompilationTypes))] public void LiftedCall(bool useInterpreter) { Func<int> f = Expression.Lambda<Func<int>>( Expression.Switch( Expression.Constant(30, typeof(int?)), Expression.Constant(0), typeof(SwitchTests).GetMethod(nameof(WithinTen), BindingFlags.Static | BindingFlags.NonPublic), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(2, typeof(int?))), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(9, typeof(int?)), Expression.Constant(28, typeof(int?))), Expression.SwitchCase(Expression.Constant(3), Expression.Constant(49, typeof(int?))) ) ).Compile(useInterpreter); Assert.Equal(2, f()); } [Fact] public void LeftLiftedCall() { AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch( Expression.Constant(30, typeof(int?)), Expression.Constant(0), typeof(SwitchTests).GetMethod(nameof(WithinTen), BindingFlags.Static | BindingFlags.NonPublic), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(2)) ) ); } [Fact] public void CaseTypeMisMatch() { AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch( Expression.Constant(30), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant("Foo")) ) ); AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch( Expression.Constant(30), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant("Foo")) ) ); } static int NonBooleanMethod(int x, int y) => x + y; [Fact] public void NonBooleanComparer() { MethodInfo comparer = typeof(SwitchTests).GetMethod(nameof(NonBooleanMethod), BindingFlags.Static | BindingFlags.NonPublic); AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)))); AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Enumerable.Repeat(Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)), 1))); AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)))); AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Enumerable.Repeat(Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)), 1))); } [Fact] public void MismatchingCasesAndType() { AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(Expression.Constant(2), Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant(0)), Expression.SwitchCase(Expression.Constant(3), Expression.Constant(9)))); } [Fact] public void MismatchingCasesAndExpclitType() { AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), null, null, Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant(0)))); } [Fact] public void MismatchingDefaultAndExpclitType() { AssertExtensions.Throws<ArgumentException>("defaultBody", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant("Foo"), null)); } [Theory, ClassData(typeof(CompilationTypes))] public void MismatchingAllowedIfExplicitlyVoidIntgralValueType(bool useInterpreter) { Expression.Lambda<Action>( Expression.Switch( typeof(void), Expression.Constant(0), Expression.Constant(1), null, Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant(2)), Expression.SwitchCase(Expression.Constant(DateTime.MinValue), Expression.Constant(3)) ) ).Compile(useInterpreter)(); } [Theory, ClassData(typeof(CompilationTypes))] public void MismatchingAllowedIfExplicitlyVoidStringValueType(bool useInterpreter) { Expression.Lambda<Action>( Expression.Switch( typeof(void), Expression.Constant("Foo"), Expression.Constant(1), null, Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant("Bar")), Expression.SwitchCase(Expression.Constant(DateTime.MinValue), Expression.Constant("Foo")) ) ).Compile(useInterpreter)(); } [Theory, ClassData(typeof(CompilationTypes))] public void MismatchingAllowedIfExplicitlyVoidDateTimeValueType(bool useInterpreter) { Expression.Lambda<Action>( Expression.Switch( typeof(void), Expression.Constant(DateTime.MinValue), Expression.Constant(1), null, Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant(DateTime.MinValue)), Expression.SwitchCase(Expression.Constant(DateTime.MinValue), Expression.Constant(DateTime.MaxValue)) ) ).Compile(useInterpreter)(); } [Fact] public void SwitchCaseUpdateSameToSame() { Expression[] tests = {Expression.Constant(0), Expression.Constant(2)}; SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), tests); Assert.Same(sc, sc.Update(tests, sc.Body)); Assert.Same(sc, sc.Update(sc.TestValues, sc.Body)); } [Fact] public void SwitchCaseUpdateNullTestsToSame() { SwitchCase sc = Expression.SwitchCase(Expression.Constant(0), Expression.Constant(1)); AssertExtensions.Throws<ArgumentException>("testValues", () => sc.Update(null, sc.Body)); AssertExtensions.Throws<ArgumentNullException>("body", () => sc.Update(sc.TestValues, null)); } [Fact] public void SwitchCaseDifferentBodyToDifferent() { SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant(2)); Assert.NotSame(sc, sc.Update(sc.TestValues, Expression.Constant(1))); } [Fact] public void SwitchCaseDifferentTestsToDifferent() { SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant(2)); Assert.NotSame(sc, sc.Update(new[] { Expression.Constant(0), Expression.Constant(2) }, sc.Body)); } [Fact] public void SwitchCaseUpdateDoesntRepeatEnumeration() { SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant(2)); Assert.NotSame(sc, sc.Update(new RunOnceEnumerable<Expression>(new[] { Expression.Constant(0), Expression.Constant(2) }), sc.Body)); } [Fact] public void SwitchUpdateSameToSame() { SwitchCase[] cases = { Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) }; SwitchExpression sw = Expression.Switch( Expression.Constant(0), Expression.Constant(0), cases ); Assert.Same(sw, sw.Update(sw.SwitchValue, cases.Skip(0), sw.DefaultBody)); Assert.Same(sw, sw.Update(sw.SwitchValue, cases, sw.DefaultBody)); Assert.Same(sw, NoOpVisitor.Instance.Visit(sw)); } [Fact] public void SwitchUpdateDifferentDefaultToDifferent() { SwitchExpression sw = Expression.Switch( Expression.Constant(0), Expression.Constant(0), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) ); Assert.NotSame(sw, sw.Update(sw.SwitchValue, sw.Cases, Expression.Constant(0))); } [Fact] public void SwitchUpdateDifferentValueToDifferent() { SwitchExpression sw = Expression.Switch( Expression.Constant(0), Expression.Constant(0), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) ); Assert.NotSame(sw, sw.Update(Expression.Constant(0), sw.Cases, sw.DefaultBody)); } [Fact] public void SwitchUpdateDifferentCasesToDifferent() { SwitchExpression sw = Expression.Switch( Expression.Constant(0), Expression.Constant(0), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) ); SwitchCase[] newCases = new[] { Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) }; Assert.NotSame(sw, sw.Update(sw.SwitchValue, newCases, sw.DefaultBody)); } [Fact] public void SwitchUpdateDoesntRepeatEnumeration() { SwitchExpression sw = Expression.Switch( Expression.Constant(0), Expression.Constant(0), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) ); IEnumerable<SwitchCase> newCases = new RunOnceEnumerable<SwitchCase>( new SwitchCase[] { Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) }); Assert.NotSame(sw, sw.Update(sw.SwitchValue, newCases, sw.DefaultBody)); } [Fact] public void SingleTestCaseToString() { SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0)); Assert.Equal("case (0): ...", sc.ToString()); } [Fact] public void MultipleTestCaseToString() { SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant("A")); Assert.Equal("case (0, \"A\"): ...", sc.ToString()); } [Theory, ClassData(typeof(CompilationTypes))] public void SwitchOnString(bool useInterpreter) { var values = new string[] { "foobar", "foo", "bar", "baz", "qux", "quux", "corge", "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud" }; for (var i = 1; i <= values.Length; i++) { SwitchCase[] cases = values.Take(i).Select((s, j) => Expression.SwitchCase(Expression.Constant(j), Expression.Constant(values[j]))).ToArray(); ParameterExpression value = Expression.Parameter(typeof(string)); Expression<Func<string, int>> e = Expression.Lambda<Func<string, int>>(Expression.Switch(value, Expression.Constant(-1), cases), value); Func<string, int> f = e.Compile(useInterpreter); int k = 0; foreach (var str in values.Take(i)) { Assert.Equal(k, f(str)); k++; } foreach (var str in values.Skip(i).Concat(new[] { default(string), "whatever", "FOO" })) { Assert.Equal(-1, f(str)); k++; } } } [Theory, ClassData(typeof(CompilationTypes))] public void SwitchOnStringEqualsMethod(bool useInterpreter) { var values = new string[] { "foobar", "foo", "bar", "baz", "qux", "quux", "corge", "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud", null }; for (var i = 1; i <= values.Length; i++) { SwitchCase[] cases = values.Take(i).Select((s, j) => Expression.SwitchCase(Expression.Constant(j), Expression.Constant(values[j], typeof(string)))).ToArray(); ParameterExpression value = Expression.Parameter(typeof(string)); Expression<Func<string, int>> e = Expression.Lambda<Func<string, int>>(Expression.Switch(value, Expression.Constant(-1), typeof(string).GetMethod("Equals", new[] { typeof(string), typeof(string) }), cases), value); Func<string, int> f = e.Compile(useInterpreter); int k = 0; foreach (var str in values.Take(i)) { Assert.Equal(k, f(str)); k++; } foreach (var str in values.Skip(i).Concat(new[] { "whatever", "FOO" })) { Assert.Equal(-1, f(str)); k++; } } } [Fact] public void ToStringTest() { SwitchExpression e1 = Expression.Switch(Expression.Parameter(typeof(int), "x"), Expression.SwitchCase(Expression.Empty(), Expression.Constant(1))); Assert.Equal("switch (x) { ... }", e1.ToString()); SwitchCase e2 = Expression.SwitchCase(Expression.Parameter(typeof(int), "x"), Expression.Constant(1)); Assert.Equal("case (1): ...", e2.ToString()); SwitchCase e3 = Expression.SwitchCase(Expression.Parameter(typeof(int), "x"), Expression.Constant(1), Expression.Constant(2)); Assert.Equal("case (1, 2): ...", e3.ToString()); } private delegate void TwoOutAction(int input, ref int x, ref int y); [Theory, ClassData(typeof(CompilationTypes))] public void JumpBetweenCases(bool useIntepreter) { LabelTarget label = Expression.Label(); ParameterExpression xParam = Expression.Parameter(typeof(int).MakeByRefType()); ParameterExpression yParam = Expression.Parameter(typeof(int).MakeByRefType()); ParameterExpression inpParam = Expression.Parameter(typeof(int)); Expression<TwoOutAction> lambda = Expression.Lambda<TwoOutAction>( Expression.Switch( inpParam, Expression.Empty(), Expression.SwitchCase( Expression.Block(Expression.Assign(xParam, Expression.Constant(1)), Expression.Goto(label), Expression.Empty()), Expression.Constant(0)), Expression.SwitchCase( Expression.Block(Expression.Label(label), Expression.Assign(yParam, Expression.Constant(2)), Expression.Empty()), Expression.Constant(1))), inpParam, xParam, yParam); TwoOutAction act = lambda.Compile(useIntepreter); int x = 0; int y = 0; act(2, ref x, ref y); Assert.Equal(0, x); Assert.Equal(0, y); act(1, ref x, ref y); Assert.Equal(0, x); Assert.Equal(2, y); y = 0; act(0, ref x, ref y); Assert.Equal(1, x); Assert.Equal(2, y); } } }
namespace KabMan.Client { partial class Blech { /// <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(); this.barManager1 = new DevExpress.XtraBars.BarManager(this.components); this.bar1 = new DevExpress.XtraBars.Bar(); this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem2 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem3 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem4 = new DevExpress.XtraBars.BarButtonItem(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.gridControl1 = new DevExpress.XtraGrid.GridControl(); this.gridView1 = new DevExpress.XtraGrid.Views.Grid.GridView(); this.ServerId = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn3 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn5 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn2 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn(); this.Room = new DevExpress.XtraGrid.Columns.GridColumn(); this.OPSys = new DevExpress.XtraGrid.Columns.GridColumn(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); this.SuspendLayout(); // // barManager1 // this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.bar1}); this.barManager1.DockControls.Add(this.barDockControlTop); this.barManager1.DockControls.Add(this.barDockControlBottom); this.barManager1.DockControls.Add(this.barDockControlLeft); this.barManager1.DockControls.Add(this.barDockControlRight); this.barManager1.Form = this; this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.barButtonItem1, this.barButtonItem2, this.barButtonItem3, this.barButtonItem4}); this.barManager1.MaxItemId = 4; // // bar1 // this.bar1.Appearance.BackColor = System.Drawing.Color.WhiteSmoke; this.bar1.Appearance.BackColor2 = System.Drawing.Color.WhiteSmoke; this.bar1.Appearance.BorderColor = System.Drawing.Color.Gainsboro; this.bar1.Appearance.Options.UseBackColor = true; this.bar1.Appearance.Options.UseBorderColor = true; this.bar1.BarName = "Tools"; this.bar1.DockCol = 0; this.bar1.DockRow = 0; this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem1), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem2), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem3), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem4)}); this.bar1.OptionsBar.AllowQuickCustomization = false; this.bar1.OptionsBar.DrawDragBorder = false; this.bar1.OptionsBar.UseWholeRow = true; this.bar1.Text = "Tools"; // // barButtonItem1 // this.barButtonItem1.Caption = "Add"; this.barButtonItem1.Glyph = global::KabMan.Client.Properties.Resources.neu; this.barButtonItem1.Id = 0; this.barButtonItem1.Name = "barButtonItem1"; this.barButtonItem1.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItem1_ItemClick); // // barButtonItem2 // this.barButtonItem2.Caption = "Detail"; this.barButtonItem2.Glyph = global::KabMan.Client.Properties.Resources.detail; this.barButtonItem2.Id = 1; this.barButtonItem2.Name = "barButtonItem2"; this.barButtonItem2.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItem2_ItemClick); // // barButtonItem3 // this.barButtonItem3.Caption = "Delete"; this.barButtonItem3.Glyph = global::KabMan.Client.Properties.Resources.loeschen; this.barButtonItem3.Id = 2; this.barButtonItem3.Name = "barButtonItem3"; this.barButtonItem3.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItem3_ItemClick); // // barButtonItem4 // this.barButtonItem4.Caption = "Close"; this.barButtonItem4.Glyph = global::KabMan.Client.Properties.Resources.exit; this.barButtonItem4.Id = 3; this.barButtonItem4.Name = "barButtonItem4"; this.barButtonItem4.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItem4_ItemClick); // // layoutControl1 // this.layoutControl1.Controls.Add(this.gridControl1); this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.layoutControl1.Location = new System.Drawing.Point(0, 26); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; this.layoutControl1.Size = new System.Drawing.Size(408, 301); this.layoutControl1.TabIndex = 4; this.layoutControl1.Text = "layoutControl1"; // // gridControl1 // this.gridControl1.EmbeddedNavigator.Name = ""; this.gridControl1.Location = new System.Drawing.Point(7, 7); this.gridControl1.MainView = this.gridView1; this.gridControl1.Name = "gridControl1"; this.gridControl1.Size = new System.Drawing.Size(395, 288); this.gridControl1.TabIndex = 8; this.gridControl1.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.gridView1}); this.gridControl1.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.gridControl1_MouseDoubleClick); // // gridView1 // this.gridView1.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray; this.gridView1.Appearance.ColumnFilterButton.Options.UseBackColor = true; this.gridView1.Appearance.ColumnFilterButton.Options.UseBorderColor = true; this.gridView1.Appearance.ColumnFilterButton.Options.UseForeColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.gridView1.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true; this.gridView1.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.gridView1.Appearance.Empty.Options.UseBackColor = true; this.gridView1.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.gridView1.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite; this.gridView1.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.EvenRow.Options.UseBackColor = true; this.gridView1.Appearance.EvenRow.Options.UseForeColor = true; this.gridView1.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225))))); this.gridView1.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.FilterCloseButton.Options.UseBackColor = true; this.gridView1.Appearance.FilterCloseButton.Options.UseBorderColor = true; this.gridView1.Appearance.FilterCloseButton.Options.UseForeColor = true; this.gridView1.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135))))); this.gridView1.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.FilterPanel.Options.UseBackColor = true; this.gridView1.Appearance.FilterPanel.Options.UseForeColor = true; this.gridView1.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58))))); this.gridView1.Appearance.FixedLine.Options.UseBackColor = true; this.gridView1.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225))))); this.gridView1.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FocusedCell.Options.UseBackColor = true; this.gridView1.Appearance.FocusedCell.Options.UseForeColor = true; this.gridView1.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy; this.gridView1.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178))))); this.gridView1.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.FocusedRow.Options.UseBackColor = true; this.gridView1.Appearance.FocusedRow.Options.UseForeColor = true; this.gridView1.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FooterPanel.Options.UseBackColor = true; this.gridView1.Appearance.FooterPanel.Options.UseBorderColor = true; this.gridView1.Appearance.FooterPanel.Options.UseForeColor = true; this.gridView1.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.GroupButton.Options.UseBackColor = true; this.gridView1.Appearance.GroupButton.Options.UseBorderColor = true; this.gridView1.Appearance.GroupButton.Options.UseForeColor = true; this.gridView1.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.gridView1.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.gridView1.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.GroupFooter.Options.UseBackColor = true; this.gridView1.Appearance.GroupFooter.Options.UseBorderColor = true; this.gridView1.Appearance.GroupFooter.Options.UseForeColor = true; this.gridView1.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165))))); this.gridView1.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White; this.gridView1.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.gridView1.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.GroupPanel.Options.UseBackColor = true; this.gridView1.Appearance.GroupPanel.Options.UseFont = true; this.gridView1.Appearance.GroupPanel.Options.UseForeColor = true; this.gridView1.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray; this.gridView1.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupRow.Options.UseBackColor = true; this.gridView1.Appearance.GroupRow.Options.UseForeColor = true; this.gridView1.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.gridView1.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.HeaderPanel.Options.UseBackColor = true; this.gridView1.Appearance.HeaderPanel.Options.UseBorderColor = true; this.gridView1.Appearance.HeaderPanel.Options.UseFont = true; this.gridView1.Appearance.HeaderPanel.Options.UseForeColor = true; this.gridView1.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray; this.gridView1.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.HideSelectionRow.Options.UseBackColor = true; this.gridView1.Appearance.HideSelectionRow.Options.UseForeColor = true; this.gridView1.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HorzLine.Options.UseBackColor = true; this.gridView1.Appearance.OddRow.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.OddRow.BackColor2 = System.Drawing.Color.White; this.gridView1.Appearance.OddRow.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal; this.gridView1.Appearance.OddRow.Options.UseBackColor = true; this.gridView1.Appearance.OddRow.Options.UseForeColor = true; this.gridView1.Appearance.Preview.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.Preview.ForeColor = System.Drawing.Color.Navy; this.gridView1.Appearance.Preview.Options.UseBackColor = true; this.gridView1.Appearance.Preview.Options.UseForeColor = true; this.gridView1.Appearance.Row.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.Row.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.Row.Options.UseBackColor = true; this.gridView1.Appearance.Row.Options.UseForeColor = true; this.gridView1.Appearance.RowSeparator.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.gridView1.Appearance.RowSeparator.Options.UseBackColor = true; this.gridView1.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138))))); this.gridView1.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.SelectedRow.Options.UseBackColor = true; this.gridView1.Appearance.SelectedRow.Options.UseForeColor = true; this.gridView1.Appearance.VertLine.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.VertLine.Options.UseBackColor = true; this.gridView1.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.ServerId, this.gridColumn3, this.gridColumn5, this.gridColumn2, this.gridColumn1, this.Room, this.OPSys}); this.gridView1.GridControl = this.gridControl1; this.gridView1.Name = "gridView1"; this.gridView1.OptionsBehavior.AllowIncrementalSearch = true; this.gridView1.OptionsBehavior.Editable = false; this.gridView1.OptionsCustomization.AllowFilter = false; this.gridView1.OptionsMenu.EnableColumnMenu = false; this.gridView1.OptionsMenu.EnableFooterMenu = false; this.gridView1.OptionsMenu.EnableGroupPanelMenu = false; this.gridView1.OptionsView.EnableAppearanceEvenRow = true; this.gridView1.OptionsView.EnableAppearanceOddRow = true; this.gridView1.OptionsView.ShowAutoFilterRow = true; this.gridView1.OptionsView.ShowGroupPanel = false; this.gridView1.OptionsView.ShowIndicator = false; // // ServerId // this.ServerId.Caption = "Id"; this.ServerId.FieldName = "Id"; this.ServerId.Name = "ServerId"; // // gridColumn3 // this.gridColumn3.Caption = "Blech Name"; this.gridColumn3.FieldName = "Name"; this.gridColumn3.Name = "gridColumn3"; this.gridColumn3.Visible = true; this.gridColumn3.VisibleIndex = 0; // // gridColumn5 // this.gridColumn5.Caption = "Object Name"; this.gridColumn5.FieldName = "ObjectName"; this.gridColumn5.Name = "gridColumn5"; this.gridColumn5.Visible = true; this.gridColumn5.VisibleIndex = 1; // // gridColumn2 // this.gridColumn2.Caption = "Blech Type"; this.gridColumn2.FieldName = "BlechType"; this.gridColumn2.Name = "gridColumn2"; this.gridColumn2.Visible = true; this.gridColumn2.VisibleIndex = 2; // // gridColumn1 // this.gridColumn1.Caption = "Location"; this.gridColumn1.FieldName = "Location"; this.gridColumn1.Name = "gridColumn1"; this.gridColumn1.Visible = true; this.gridColumn1.VisibleIndex = 3; // // Room // this.Room.Caption = "Data Center"; this.Room.FieldName = "Room"; this.Room.Name = "Room"; this.Room.Visible = true; this.Room.VisibleIndex = 4; this.Room.Width = 108; // // OPSys // this.OPSys.Caption = "Visible"; this.OPSys.FieldName = "Visible"; this.OPSys.Name = "OPSys"; this.OPSys.Visible = true; this.OPSys.VisibleIndex = 5; this.OPSys.Width = 84; // // layoutControlGroup1 // this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1"; this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem1}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "layoutControlGroup1"; this.layoutControlGroup1.Size = new System.Drawing.Size(408, 301); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.Text = "layoutControlGroup1"; this.layoutControlGroup1.TextVisible = false; // // layoutControlItem1 // this.layoutControlItem1.Control = this.gridControl1; this.layoutControlItem1.CustomizationFormText = "layoutControlItem1"; this.layoutControlItem1.Location = new System.Drawing.Point(0, 0); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(406, 299); this.layoutControlItem1.Text = "layoutControlItem1"; this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem1.TextToControlDistance = 0; this.layoutControlItem1.TextVisible = false; // // Blech // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(408, 327); this.Controls.Add(this.layoutControl1); this.Controls.Add(this.barDockControlLeft); this.Controls.Add(this.barDockControlRight); this.Controls.Add(this.barDockControlBottom); this.Controls.Add(this.barDockControlTop); this.Name = "Blech"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Blech"; this.Load += new System.EventHandler(this.Blech_Load); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraBars.BarManager barManager1; private DevExpress.XtraBars.Bar bar1; private DevExpress.XtraBars.BarButtonItem barButtonItem1; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraBars.BarButtonItem barButtonItem2; private DevExpress.XtraBars.BarButtonItem barButtonItem3; private DevExpress.XtraBars.BarButtonItem barButtonItem4; private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraGrid.GridControl gridControl1; private DevExpress.XtraGrid.Views.Grid.GridView gridView1; private DevExpress.XtraGrid.Columns.GridColumn ServerId; private DevExpress.XtraGrid.Columns.GridColumn gridColumn1; private DevExpress.XtraGrid.Columns.GridColumn Room; private DevExpress.XtraGrid.Columns.GridColumn gridColumn2; private DevExpress.XtraGrid.Columns.GridColumn gridColumn3; private DevExpress.XtraGrid.Columns.GridColumn OPSys; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; private DevExpress.XtraGrid.Columns.GridColumn gridColumn5; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; namespace Google.ProtocolBuffers.Serialization { /// <summary> /// JSon Tokenizer used by JsonFormatReader /// </summary> internal abstract class JsonCursor { public enum JsType { String, Number, Object, Array, True, False, Null } #region Buffering implementations private class JsonStreamCursor : JsonCursor { private readonly byte[] _buffer; private int _bufferPos; private readonly Stream _input; public JsonStreamCursor(Stream input) { _input = input; _next = _input.ReadByte(); } public JsonStreamCursor(byte[] input) { _input = null; _buffer = input; _next = _buffer[_bufferPos]; } protected override int Peek() { if (_input != null) { return _next; } else if (_bufferPos < _buffer.Length) { return _buffer[_bufferPos]; } else { return -1; } } protected override int Read() { if (_input != null) { int result = _next; _next = _input.ReadByte(); return result; } else if (_bufferPos < _buffer.Length) { return _buffer[_bufferPos++]; } else { return -1; } } } private class JsonTextCursor : JsonCursor { private readonly char[] _buffer; private int _bufferPos; private readonly TextReader _input; public JsonTextCursor(char[] input) { _input = null; _buffer = input; _bufferPos = 0; _next = Peek(); } public JsonTextCursor(TextReader input) { _input = input; _next = Peek(); } protected override int Peek() { if (_input != null) { return _input.Peek(); } else if (_bufferPos < _buffer.Length) { return _buffer[_bufferPos]; } else { return -1; } } protected override int Read() { if (_input != null) { return _input.Read(); } else if (_bufferPos < _buffer.Length) { return _buffer[_bufferPos++]; } else { return -1; } } } #endregion protected int _next; private int _lineNo, _linePos; public static JsonCursor CreateInstance(byte[] input) { return new JsonStreamCursor(input); } public static JsonCursor CreateInstance(Stream input) { return new JsonStreamCursor(input); } public static JsonCursor CreateInstance(string input) { return new JsonTextCursor(input.ToCharArray()); } public static JsonCursor CreateInstance(TextReader input) { return new JsonTextCursor(input); } protected JsonCursor() { _lineNo = 1; _linePos = 0; } /// <summary>Returns the next character without actually 'reading' it</summary> protected abstract int Peek(); /// <summary>Reads the next character in the input</summary> protected abstract int Read(); public Char NextChar { get { SkipWhitespace(); return (char) _next; } } #region Assert(...) [DebuggerNonUserCode] private string CharDisplay(int ch) { return ch == -1 ? "EOF" : (ch > 32 && ch < 127) ? String.Format("'{0}'", (char) ch) : String.Format("'\\u{0:x4}'", ch); } [DebuggerNonUserCode] private void Assert(bool cond, char expected) { if (!cond) { throw new FormatException( String.Format(FrameworkPortability.InvariantCulture, "({0}:{1}) error: Unexpected token {2}, expected: {3}.", _lineNo, _linePos, CharDisplay(_next), CharDisplay(expected) )); } } [DebuggerNonUserCode] public void Assert(bool cond, string message) { if (!cond) { throw new FormatException( String.Format(FrameworkPortability.InvariantCulture, "({0},{1}) error: {2}", _lineNo, _linePos, message)); } } [DebuggerNonUserCode] public void Assert(bool cond, string format, params object[] args) { if (!cond) { if (args != null && args.Length > 0) { format = String.Format(format, args); } throw new FormatException( String.Format(FrameworkPortability.InvariantCulture, "({0},{1}) error: {2}", _lineNo, _linePos, format)); } } #endregion private char ReadChar() { int ch = Read(); Assert(ch != -1, "Unexpected end of file."); if (ch == '\n') { _lineNo++; _linePos = 0; } else if (ch != '\r') { _linePos++; } _next = Peek(); return (char) ch; } public void Consume(char ch) { Assert(TryConsume(ch), ch); } public bool TryConsume(char ch) { SkipWhitespace(); if (_next == ch) { ReadChar(); return true; } return false; } public void Consume(string sequence) { SkipWhitespace(); foreach (char ch in sequence) { Assert(ch == ReadChar(), "Expected token '{0}'.", sequence); } } public void SkipWhitespace() { int chnext = _next; while (chnext != -1) { if (!Char.IsWhiteSpace((char) chnext)) { break; } ReadChar(); chnext = _next; } } public string ReadString() { SkipWhitespace(); Consume('"'); List<Char> sb = new List<char>(100); while (_next != '"') { if (_next == '\\') { Consume('\\'); //skip the escape char ch = ReadChar(); switch (ch) { case 'b': sb.Add('\b'); break; case 'f': sb.Add('\f'); break; case 'n': sb.Add('\n'); break; case 'r': sb.Add('\r'); break; case 't': sb.Add('\t'); break; case 'u': { string hex = new string(new char[] {ReadChar(), ReadChar(), ReadChar(), ReadChar()}); int result; Assert( FrameworkPortability.TryParseInt32(hex, NumberStyles.AllowHexSpecifier, FrameworkPortability.InvariantCulture, out result), "Expected a 4-character hex specifier."); sb.Add((char) result); break; } default: sb.Add(ch); break; } } else { Assert(_next != '\n' && _next != '\r' && _next != '\f' && _next != -1, '"'); sb.Add(ReadChar()); } } Consume('"'); return new String(sb.ToArray()); } public string ReadNumber() { SkipWhitespace(); List<Char> sb = new List<char>(24); if (_next == '-') { sb.Add(ReadChar()); } Assert(_next >= '0' && _next <= '9', "Expected a numeric type."); while ((_next >= '0' && _next <= '9') || _next == '.') { sb.Add(ReadChar()); } if (_next == 'e' || _next == 'E') { sb.Add(ReadChar()); if (_next == '-' || _next == '+') { sb.Add(ReadChar()); } Assert(_next >= '0' && _next <= '9', "Expected a numeric type."); while (_next >= '0' && _next <= '9') { sb.Add(ReadChar()); } } return new String(sb.ToArray()); } public JsType ReadVariant(out object value) { SkipWhitespace(); switch (_next) { case 'n': Consume("null"); value = null; return JsType.Null; case 't': Consume("true"); value = true; return JsType.True; case 'f': Consume("false"); value = false; return JsType.False; case '"': value = ReadString(); return JsType.String; case '{': { Consume('{'); while (NextChar != '}') { ReadString(); Consume(':'); object tmp; ReadVariant(out tmp); if (!TryConsume(',')) { break; } } Consume('}'); value = null; return JsType.Object; } case '[': { Consume('['); List<object> values = new List<object>(); while (NextChar != ']') { object tmp; ReadVariant(out tmp); values.Add(tmp); if (!TryConsume(',')) { break; } } Consume(']'); value = values.ToArray(); return JsType.Array; } default: if ((_next >= '0' && _next <= '9') || _next == '-') { value = ReadNumber(); return JsType.Number; } Assert(false, "Expected a value."); throw new FormatException(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime.GrainDirectory { internal class AdaptiveDirectoryCacheMaintainer<TValue> : AsynchAgent { private static readonly TimeSpan SLEEP_TIME_BETWEEN_REFRESHES = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromMinutes(1); // this should be something like minTTL/4 private readonly AdaptiveGrainDirectoryCache<TValue> cache; private readonly LocalGrainDirectory router; private long lastNumAccesses; // for stats private long lastNumHits; // for stats internal AdaptiveDirectoryCacheMaintainer(ILocalGrainDirectory router, IGrainDirectoryCache<TValue> cache) { this.router = (LocalGrainDirectory)router; this.cache = (AdaptiveGrainDirectoryCache<TValue>) cache; lastNumAccesses = 0; lastNumHits = 0; OnFault = FaultBehavior.RestartOnFault; } protected override void Run() { while (router.Running) { // Run through all cache entries and do the following: // 1. If the entry is not expired, skip it // 2. If the entry is expired and was not accessed in the last time interval -- throw it away // 3. If the entry is expired and was accessed in the last time interval, put into "fetch-batch-requests" list // At the end of the process, fetch batch requests for entries that need to be refreshed // Upon receiving refreshing answers, if the entry was not changed, double its expiration timer. // If it was changed, update the cache and reset the expiration timer. // this dictionary holds a map between a silo address and the list of grains that need to be refreshed var fetchInBatchList = new Dictionary<SiloAddress, List<GrainId>>(); // get the list of cached grains // for debug only int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0; // run through all cache entries var enumerator = cache.GetStoredEntries(); while (enumerator.MoveNext()) { var pair = enumerator.Current; GrainId grain = pair.Key; var entry = pair.Value; SiloAddress owner = router.CalculateTargetSilo(grain); if (owner == null) // Null means there's no other silo and we're shutting down, so skip this entry { continue; } if (owner.Equals(router.MyAddress)) { // we found our owned entry in the cache -- it is not supposed to happen unless there were // changes in the membership Log.Warn(ErrorCode.Runtime_Error_100185, "Grain {0} owned by {1} was found in the cache of {1}", grain, owner, owner); cache.Remove(grain); cnt1++; // for debug } else { if (entry == null) { // 0. If the entry was deleted in parallel, presumably due to cleanup after silo death cache.Remove(grain); // for debug cnt3++; } else if (!entry.IsExpired()) { // 1. If the entry is not expired, skip it cnt2++; // for debug } else if (entry.NumAccesses == 0) { // 2. If the entry is expired and was not acccessed in the last time interval -- throw it away cache.Remove(grain); // for debug cnt3++; } else { // 3. If the entry is expired and was accessed in the last time interval, put into "fetch-batch-requests" list if (!fetchInBatchList.ContainsKey(owner)) { fetchInBatchList[owner] = new List<GrainId>(); } fetchInBatchList[owner].Add(grain); // And reset the entry's access count for next time entry.NumAccesses = 0; cnt4++; // for debug } } } if (Log.IsVerbose2) Log.Verbose2("Silo {0} self-owned (and removed) {1}, kept {2}, removed {3} and tries to refresh {4} grains", router.MyAddress, cnt1, cnt2, cnt3, cnt4); // send batch requests SendBatchCacheRefreshRequests(fetchInBatchList); ProduceStats(); // recheck every X seconds (Consider making it a configurable parameter) Thread.Sleep(SLEEP_TIME_BETWEEN_REFRESHES); } } private void SendBatchCacheRefreshRequests(Dictionary<SiloAddress, List<GrainId>> refreshRequests) { foreach (SiloAddress silo in refreshRequests.Keys) { List<Tuple<GrainId, int>> cachedGrainAndETagList = BuildGrainAndETagList(refreshRequests[silo]); SiloAddress capture = silo; router.CacheValidationsSent.Increment(); // Send all of the items in one large request var validator = InsideRuntimeClient.Current.InternalGrainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryCacheValidatorId, capture); router.Scheduler.QueueTask(async () => { var response = await validator.LookUpMany(cachedGrainAndETagList); ProcessCacheRefreshResponse(capture, response); }, router.CacheValidator.SchedulingContext).Ignore(); if (Log.IsVerbose2) Log.Verbose2("Silo {0} is sending request to silo {1} with {2} entries", router.MyAddress, silo, cachedGrainAndETagList.Count); } } private void ProcessCacheRefreshResponse( SiloAddress silo, IReadOnlyCollection<Tuple<GrainId, int, List<ActivationAddress>>> refreshResponse) { if (Log.IsVerbose2) Log.Verbose2("Silo {0} received ProcessCacheRefreshResponse. #Response entries {1}.", router.MyAddress, refreshResponse.Count); int cnt1 = 0, cnt2 = 0, cnt3 = 0; //TODO: this is unsafe in case TValue changes in the future as it assumes List<Tuple<SiloAddress, ActivationId>> var cacheRef = cache as AdaptiveGrainDirectoryCache<List<Tuple<SiloAddress, ActivationId>>>; // pass through returned results and update the cache if needed foreach (Tuple<GrainId, int, List<ActivationAddress>> tuple in refreshResponse) { if (tuple.Item3 != null) { // the server returned an updated entry var list = tuple.Item3.Select(a => Tuple.Create(a.Silo, a.Activation)).ToList(); cacheRef.AddOrUpdate(tuple.Item1, list, tuple.Item2); cnt1++; } else if (tuple.Item2 == -1) { // The server indicates that it does not own the grain anymore. // It could be that by now, the cache has been already updated and contains an entry received from another server (i.e., current owner for the grain). // For simplicity, we do not care about this corner case and simply remove the cache entry. cache.Remove(tuple.Item1); cnt2++; } else { // The server returned only a (not -1) generation number, indicating that we hold the most // updated copy of the grain's activations list. // Validate that the generation number in the request and the response are equal // Contract.Assert(tuple.Item2 == refreshRequest.Find(o => o.Item1 == tuple.Item1).Item2); // refresh the entry in the cache cache.MarkAsFresh(tuple.Item1); cnt3++; } } if (Log.IsVerbose2) Log.Verbose2("Silo {0} processed refresh response from {1} with {2} updated, {3} removed, {4} unchanged grains", router.MyAddress, silo, cnt1, cnt2, cnt3); } /// <summary> /// Gets the list of grains (all owned by the same silo) and produces a new list /// of tuples, where each tuple holds the grain and its generation counter currently stored in the cache /// </summary> /// <param name="grains">List of grains owned by the same silo</param> /// <returns>List of grains in input along with their generation counters stored in the cache </returns> private List<Tuple<GrainId, int>> BuildGrainAndETagList(IEnumerable<GrainId> grains) { var grainAndETagList = new List<Tuple<GrainId, int>>(); foreach (GrainId grain in grains) { // NOTE: should this be done with TryGet? Won't Get invoke the LRU getter function? AdaptiveGrainDirectoryCache<TValue>.GrainDirectoryCacheEntry entry = cache.Get(grain); if (entry != null) { grainAndETagList.Add(new Tuple<GrainId, int>(grain, entry.ETag)); } else { // this may happen only if the LRU cache is full and decided to drop this grain // while we try to refresh it Log.Warn(ErrorCode.Runtime_Error_100199, "Grain {0} disappeared from the cache during maintainance", grain); } } return grainAndETagList; } private void ProduceStats() { // We do not want to synchronize the access on numAccess and numHits in cache to avoid performance issues. // Thus we take the current reading of these fields and calculate the stats. We might miss an access or two, // but it should not be matter. long curNumAccesses = cache.NumAccesses; long curNumHits = cache.NumHits; long numAccesses = curNumAccesses - lastNumAccesses; long numHits = curNumHits - lastNumHits; if (Log.IsVerbose2) Log.Verbose2("#accesses: {0}, hit-ratio: {1}%", numAccesses, (numHits / Math.Max(numAccesses, 0.00001)) * 100); lastNumAccesses = curNumAccesses; lastNumHits = curNumHits; } } }
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 MaxMelcher.ShareCamp.ProviderHostedAppWeb { 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 } }
#region License /* * HttpConnection.cs * * This code is derived from HttpConnection.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2016 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <[email protected]> */ #endregion #region Contributors /* * Contributors: * - Liryna <[email protected]> * - Rohan Singh <[email protected]> */ #endregion using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Text; using System.Threading; namespace WebSocketSharp.Net { internal sealed class HttpConnection { #region Private Fields private byte[] _buffer; private const int _bufferLength = 8192; private HttpListenerContext _context; private bool _contextRegistered; private StringBuilder _currentLine; private InputState _inputState; private RequestStream _inputStream; private HttpListener _lastListener; private LineState _lineState; private EndPointListener _listener; private EndPoint _localEndPoint; private ResponseStream _outputStream; private int _position; private EndPoint _remoteEndPoint; private MemoryStream _requestBuffer; private int _reuses; private bool _secure; private Socket _socket; private Stream _stream; private object _sync; private int _timeout; private Dictionary<int, bool> _timeoutCanceled; private Timer _timer; #endregion #region Internal Constructors internal HttpConnection (Socket socket, EndPointListener listener) { _socket = socket; _listener = listener; var netStream = new NetworkStream (socket, false); if (listener.IsSecure) { var sslConf = listener.SslConfiguration; var sslStream = new SslStream ( netStream, false, sslConf.ClientCertificateValidationCallback ); sslStream.AuthenticateAsServer ( sslConf.ServerCertificate, sslConf.ClientCertificateRequired, sslConf.EnabledSslProtocols, sslConf.CheckCertificateRevocation ); _secure = true; _stream = sslStream; } else { _stream = netStream; } _localEndPoint = socket.LocalEndPoint; _remoteEndPoint = socket.RemoteEndPoint; _sync = new object (); _timeout = 90000; // 90k ms for first request, 15k ms from then on. _timeoutCanceled = new Dictionary<int, bool> (); _timer = new Timer (onTimeout, this, Timeout.Infinite, Timeout.Infinite); init (); } #endregion #region Public Properties public bool IsClosed { get { return _socket == null; } } public bool IsLocal { get { return ((IPEndPoint) _remoteEndPoint).Address.IsLocal (); } } public bool IsSecure { get { return _secure; } } public IPEndPoint LocalEndPoint { get { return (IPEndPoint) _localEndPoint; } } public IPEndPoint RemoteEndPoint { get { return (IPEndPoint) _remoteEndPoint; } } public int Reuses { get { return _reuses; } } public Stream Stream { get { return _stream; } } #endregion #region Private Methods private void close () { lock (_sync) { if (_socket == null) return; disposeTimer (); disposeRequestBuffer (); disposeStream (); closeSocket (); } unregisterContext (); removeConnection (); } private void closeSocket () { try { _socket.Shutdown (SocketShutdown.Both); } catch { } _socket.Close (); _socket = null; } private void disposeRequestBuffer () { if (_requestBuffer == null) return; _requestBuffer.Dispose (); _requestBuffer = null; } private void disposeStream () { if (_stream == null) return; _inputStream = null; _outputStream = null; _stream.Dispose (); _stream = null; } private void disposeTimer () { if (_timer == null) return; try { _timer.Change (Timeout.Infinite, Timeout.Infinite); } catch { } _timer.Dispose (); _timer = null; } private void init () { _context = new HttpListenerContext (this); _inputState = InputState.RequestLine; _inputStream = null; _lineState = LineState.None; _outputStream = null; _position = 0; _requestBuffer = new MemoryStream (); } private static void onRead (IAsyncResult asyncResult) { var conn = (HttpConnection) asyncResult.AsyncState; if (conn._socket == null) return; lock (conn._sync) { if (conn._socket == null) return; var nread = -1; var len = 0; try { var current = conn._reuses; if (!conn._timeoutCanceled[current]) { conn._timer.Change (Timeout.Infinite, Timeout.Infinite); conn._timeoutCanceled[current] = true; } nread = conn._stream.EndRead (asyncResult); conn._requestBuffer.Write (conn._buffer, 0, nread); len = (int) conn._requestBuffer.Length; } catch (Exception ex) { if (conn._requestBuffer != null && conn._requestBuffer.Length > 0) { conn.SendError (ex.Message, 400); return; } conn.close (); return; } if (nread <= 0) { conn.close (); return; } if (conn.processInput (conn._requestBuffer.GetBuffer (), len)) { if (!conn._context.HasError) conn._context.Request.FinishInitialization (); if (conn._context.HasError) { conn.SendError (); return; } HttpListener lsnr; if (!conn._listener.TrySearchHttpListener (conn._context.Request.Url, out lsnr)) { conn.SendError (null, 404); return; } if (conn._lastListener != lsnr) { conn.removeConnection (); if (!lsnr.AddConnection (conn)) { conn.close (); return; } conn._lastListener = lsnr; } conn._context.Listener = lsnr; if (!conn._context.Authenticate ()) return; if (conn._context.Register ()) conn._contextRegistered = true; return; } conn._stream.BeginRead (conn._buffer, 0, _bufferLength, onRead, conn); } } private static void onTimeout (object state) { var conn = (HttpConnection) state; var current = conn._reuses; if (conn._socket == null) return; lock (conn._sync) { if (conn._socket == null) return; if (conn._timeoutCanceled[current]) return; conn.SendError (null, 408); } } // true -> Done processing. // false -> Need more input. private bool processInput (byte[] data, int length) { if (_currentLine == null) _currentLine = new StringBuilder (64); var nread = 0; try { string line; while ((line = readLineFrom (data, _position, length, out nread)) != null) { _position += nread; if (line.Length == 0) { if (_inputState == InputState.RequestLine) continue; if (_position > 32768) _context.ErrorMessage = "Headers too long"; _currentLine = null; return true; } if (_inputState == InputState.RequestLine) { _context.Request.SetRequestLine (line); _inputState = InputState.Headers; } else { _context.Request.AddHeader (line); } if (_context.HasError) return true; } } catch (Exception ex) { _context.ErrorMessage = ex.Message; return true; } _position += nread; if (_position >= 32768) { _context.ErrorMessage = "Headers too long"; return true; } return false; } private string readLineFrom (byte[] buffer, int offset, int length, out int read) { read = 0; for (var i = offset; i < length && _lineState != LineState.Lf; i++) { read++; var b = buffer[i]; if (b == 13) _lineState = LineState.Cr; else if (b == 10) _lineState = LineState.Lf; else _currentLine.Append ((char) b); } if (_lineState != LineState.Lf) return null; var line = _currentLine.ToString (); _currentLine.Length = 0; _lineState = LineState.None; return line; } private void removeConnection () { if (_lastListener != null) _lastListener.RemoveConnection (this); else _listener.RemoveConnection (this); } private void unregisterContext () { if (!_contextRegistered) return; _context.Unregister (); _contextRegistered = false; } #endregion #region Internal Methods internal void Close (bool force) { if (_socket == null) return; lock (_sync) { if (_socket == null) return; if (force) { if (_outputStream != null) _outputStream.Close (true); close (); return; } GetResponseStream ().Close (false); if (_context.Response.CloseConnection) { close (); return; } if (!_context.Request.FlushInput ()) { close (); return; } disposeRequestBuffer (); unregisterContext (); init (); _reuses++; BeginReadRequest (); } } #endregion #region Public Methods public void BeginReadRequest () { if (_buffer == null) _buffer = new byte[_bufferLength]; if (_reuses == 1) _timeout = 15000; try { _timeoutCanceled.Add (_reuses, false); _timer.Change (_timeout, Timeout.Infinite); _stream.BeginRead (_buffer, 0, _bufferLength, onRead, this); } catch { close (); } } public void Close () { Close (false); } public RequestStream GetRequestStream (long contentLength, bool chunked) { lock (_sync) { if (_socket == null) return null; if (_inputStream != null) return _inputStream; var buff = _requestBuffer.GetBuffer (); var len = (int) _requestBuffer.Length; var cnt = len - _position; disposeRequestBuffer (); _inputStream = chunked ? new ChunkedRequestStream ( _stream, buff, _position, cnt, _context ) : new RequestStream ( _stream, buff, _position, cnt, contentLength ); return _inputStream; } } public ResponseStream GetResponseStream () { // TODO: Can we get this stream before reading the input? lock (_sync) { if (_socket == null) return null; if (_outputStream != null) return _outputStream; var lsnr = _context.Listener; var ignore = lsnr != null ? lsnr.IgnoreWriteExceptions : true; _outputStream = new ResponseStream (_stream, _context.Response, ignore); return _outputStream; } } public void SendError () { SendError (_context.ErrorMessage, _context.ErrorStatus); } public void SendError (string message, int status) { if (_socket == null) return; lock (_sync) { if (_socket == null) return; try { var res = _context.Response; res.StatusCode = status; res.ContentType = "text/html"; var content = new StringBuilder (64); content.AppendFormat ("<html><body><h1>{0} {1}", status, res.StatusDescription); if (message != null && message.Length > 0) content.AppendFormat (" ({0})</h1></body></html>", message); else content.Append ("</h1></body></html>"); var enc = Encoding.UTF8; var entity = enc.GetBytes (content.ToString ()); res.ContentEncoding = enc; res.ContentLength64 = entity.LongLength; res.Close (entity, true); } catch { Close (true); } } } #endregion } }
/* * MindTouch DekiWiki - a commercial grade open source wiki * Copyright (C) 2006 MindTouch, Inc. * www.mindtouch.com [email protected] * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * 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. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Text; using MindTouch.Dream; namespace MindTouch.Deki { [DreamService("MindTouch DekiWiki - DekiBizCard", "Copyright (c) 2006 MindTouch, Inc.", "http://doc.opengarden.org/Deki_API/Reference/Widgets/DekiBizCard")] public class DekiBizCard : DekiWikiServiceBase { // --- Constants --- private const string template_given_name = " <span class=\"given-name\">${given_name}</span>"; private const string template_additional_name = " &nbsp;<span class=\"additional-name\">${additional_name}</span>&nbsp;"; private const string template_family_name = " <span class=\"family-name\">${family_name}</span>"; private const string template_photo = " <div class=\"photo_frame\">${download_1}<span class=\"bg\">&nbsp;</span><img class=\"photo\" alt=\"photo\" src=\"${photo_url}\" />${download_2}</div>"; private const string template_download_1 = "<a href=\"/dream/wiki-data/content?${page_q}=${page_id}&amp;id=${id}&amp;dream.out.saveas=${save_as}.vcf&amp;dream.out.type=text/x-vcard&amp;dream.out.format=versit&amp;dream.out.select=//vcard\">"; private const string template_download_2 = "<center><span class=\"vc\">vCard</span></center></a>"; private const string template_title = " <div class=\"title\">${title}</div>"; private const string template_org = " <div class=\"org\">${org}</div>"; private const string template_email = " <a class=\"email\" href=\"mailto:${email}\">${email}</a>"; private const string template_street_address = " <div class=\"street-address\">${street_address}</div>"; private const string template_extended_address = " <div class=\"extended-address\">${extended_address}</div>"; private const string template_city = " <span class=\"locality\">${city}</span>"; private const string template_region = " <span class=\"region\">${region}</span>"; private const string template_postal_code = " <span class=\"postal-code\">${postal_code}</span>"; private const string template_country_name = " <div class=\"country-name\">${country}</div>"; private const string template_tel = " <div class=\"tel\"><span class=\"value\">${value}</span>&nbsp;<span class=\"type\">${type}</span></div>"; private const string template_aim = " <a class=\"url\" href=\"aim:goim?screenname=${aim}\">AIM</a>\n"; private const string template_yim = " <a class=\"url\" href=\"ymsgr:sendIM?${yim}\">YIM</a>\n"; // --- Members --- private string addressBookHtmlTemplate = null; private string formHtml = null; // --- Functions --- private static string NormalizeSpace(string str) { if (str == null) str = ""; str = str.Trim(); while (true) { string tmp = str.Replace(" ", " "); if (tmp.Length == str.Length) break; str = tmp; } return str; } private static XDoc EnsureElement(XDoc doc, string parentKey, string key, string def) { XDoc parent = doc[parentKey]; if (parent.IsEmpty) { doc.Start(parentKey); if (key == null) doc.Value(def); doc.End(); parent = doc[parentKey]; } if (key == null) return parent; XDoc child = parent[key]; if (child.IsEmpty) { if (def == null) { child = null; } else { parent.Start(key); parent.Value(def); parent.End(); child = parent[key]; } } else if (def == null && child.Contents == "") { child.Remove(); child = null; } return child; } private static void EnsureAttribute(XDoc doc, string attr, string def) { if (doc["@" + attr].IsEmpty) doc.Attr(attr, def); } private static string EncodeVersit(string str) { return str; // issues with outlook: str.Replace("\\\\", "\\").Replace(",", "\\,").Replace(";", "\\;").Replace("\n", "\\n"); } private static string DecodeVersit(string str) { return str; // issues with outlook: str.Replace("\\,", ",").Replace("\\;", ";").Replace("\\n", "\n").Replace("\\\\", "\\"); } private static string RenderCard(XDoc vcard, string page_title, string pageid, string id) { // 0:Family Name, 1:Given Name, 2:Additional Names, 3:Honorific Prefixes, and 4:Honorific Suffixes IList<string> vcard_n = new List<string>(vcard["vcard/n"].Contents.Split(';')); while (vcard_n.Count < 3) vcard_n.Add(string.Empty); string givenname = DecodeVersit(NormalizeSpace(vcard_n[1])); string additionalname = DecodeVersit(NormalizeSpace(vcard_n[2])); string familyname = DecodeVersit(NormalizeSpace(vcard_n[0])); string url = DecodeVersit(vcard["vcard/url"].Contents); string aim = DecodeVersit(vcard["vcard/aim"].Contents); string yim = DecodeVersit(vcard["vcard/yim"].Contents); string title = DecodeVersit(vcard["vcard/title"].Contents); string vorg = DecodeVersit(vcard["vcard/org"].Contents); string email = DecodeVersit(vcard["vcard/email"].Contents); IList<string> vcard_adr = new List<string>(vcard["vcard/adr"].Contents.Split(';')); while (vcard_adr.Count < 7) vcard_adr.Add(string.Empty); string extended = DecodeVersit(vcard_adr[1]); string street = DecodeVersit(vcard_adr[2]); string city = DecodeVersit(vcard_adr[3]); string region = DecodeVersit(vcard_adr[4]); string postal = DecodeVersit(vcard_adr[5]); string country = DecodeVersit(vcard_adr[6]); string voice = DecodeVersit(vcard["vcard/tel[@type='voice']"].Contents); string home = DecodeVersit(vcard["vcard/tel[@type='home']"].Contents); string work = DecodeVersit(vcard["vcard/tel[@type='work']"].Contents); string fax = DecodeVersit(vcard["vcard/tel[@type='fax']"].Contents); string cell = DecodeVersit(vcard["vcard/tel[@type='cell']"].Contents); string photo = DecodeVersit(vcard["vcard/photo"].Contents); bool implied_fn_opt = (additionalname == "") && (familyname.IndexOf(" ") == -1); string fn, fullname; if (implied_fn_opt) { fn = givenname + " " + familyname; fullname = fn; } else { fn = template_given_name.Replace("${given_name}", givenname) + "\n"; if (additionalname != "") { fn += template_additional_name.Replace("${additional_name}", additionalname) + "\n"; } fn += template_family_name.Replace("${family_name}", familyname) + "\n"; fullname = givenname; if (additionalname != "") fullname += " " + additionalname; fullname += " " + familyname; } fn = NormalizeSpace(fn); fullname = NormalizeSpace(fullname); string resultstr = "<div class=\"vcard\""; if (id != "") resultstr += string.Format(" widgetid=\"{0}\"", id); resultstr += ">\n"; if (photo.StartsWith("mos://localhost/")) photo = photo.Substring("mos://localhost".Length); if (photo == "") photo = "/editor/widgets/generichead.png"; string download_1 = ((page_title != "" || pageid != "") && id != "") ? template_download_1 .Replace("${page_q}", pageid != "" ? "pageid" : "title") .Replace("${page_id}", pageid != "" ? pageid : System.Web.HttpUtility.UrlEncode(page_title)) .Replace("${id}", id) .Replace("${save_as}", System.Web.HttpUtility.UrlEncode(NormalizeSpace(fullname.Replace(".", " "))) ) : ""; string download_2 = ((page_title != "" || pageid != "") && id != "") ? template_download_2 : ""; resultstr += template_photo.Replace("${photo_url}", photo).Replace("${download_1}", download_1).Replace("${download_2}", download_2) + "\n"; if (url.StartsWith("http://")) { // make sure the url at least looks like a url before we load it resultstr += " <a class=\"url fn\""; if (!implied_fn_opt) resultstr += " n"; resultstr += "\" href=\"" + url + "\">" + fn + "</a>\n"; } else { resultstr += " <div class=\"" + (implied_fn_opt ? "fn" : "fn n") + "\">"; resultstr += (implied_fn_opt ? "" : "\n ") + fn + "</div>\n"; } if (title != "") resultstr += template_title.Replace("${title}", title) + "\n"; if (vorg != "") resultstr += template_org.Replace("${org}", vorg) + "\n"; if (street != "" || extended != "" || city != "" || region != "" || postal != "" || country != "") { resultstr += " <div class=\"adr\">\n"; if (street != "") resultstr += template_street_address.Replace("${street_address}", street) + "\n"; if (extended != "") resultstr += template_extended_address.Replace("${extended_address}", extended) + "\n"; string csz = ""; if (city != "") csz += template_city.Replace("${city}", city); if (region != "") { if (csz != "") csz += ", \n"; csz += template_region.Replace("${region}", region); } if (postal != "") { if (csz != "") csz += "&nbsp;\n"; csz += template_postal_code.Replace("${postal_code}", postal); } if (country != "") { if (csz != "") csz += "\n"; csz += template_country_name.Replace("${country}", country) + "\n"; } else if (csz != "") csz += "\n"; resultstr += csz + " </div>\n"; } if (voice != "") resultstr += template_tel.Replace("${value}", voice).Replace("${type}", "voice") + "\n"; if (home != "") resultstr += template_tel.Replace("${value}", home).Replace("${type}", "home") + "\n"; if (work != "") resultstr += template_tel.Replace("${value}", work).Replace("${type}", "work") + "\n"; if (fax != "") resultstr += template_tel.Replace("${value}", fax).Replace("${type}", "fax") + "\n"; if (cell != "") resultstr += template_tel.Replace("${value}", cell).Replace("${type}", "cell") + "\n"; if (email != "") resultstr += template_email.Replace("${email}", email) + "\n"; if (aim != "") resultstr += template_aim.Replace("${aim}", aim) + "\n"; if (yim != "") resultstr += template_yim.Replace("${yim}", yim) + "\n"; resultstr += "</div>"; return resultstr; } #region -- Handlers public override string AuthenticationRealm { get { return "DekiWiki"; } } [DreamFeature("addressbook", "/", "GET", "", "http://doc.opengarden.org/Deki_API/Reference/Widgets/DekiBizCard")] public DreamMessage GetAddressBookHandler(DreamContext context, DreamMessage message) { user user = Authenticate(context, message, DekiUserLevel.User); page page = Authorize(context, user, DekiAccessLevel.Read, "pageid"); string title = page.PrefixedName; if (this.addressBookHtmlTemplate == null) this.addressBookHtmlTemplate = Plug.New(Env.RootUri).At("mount", "deki-widgets").At("addressbook.html").Get().Text; string addressBookHtml = WidgetService.ReplaceVariables(addressBookHtmlTemplate, new MyDictionary("%%TITLE%%", title)); return DreamMessage.Ok(MimeType.HTML, addressBookHtml); } [DreamFeature("normalize", "/", "POST", "", "http://doc.opengarden.org/Deki_API/Reference/Widgets/DekiBizCard")] public DreamMessage PostNormalizeHandler(DreamContext context, DreamMessage message) { XDoc vcard = message.Document; EnsureElement(vcard, "style", null, "standard"); EnsureElement(vcard, "vcard", "prodid", "-//mindtouch.com//DekiWiki 1.0//EN"); EnsureElement(vcard, "vcard", "version", "3.0"); EnsureElement(vcard, "vcard", "source", "(source of hCard)"); XDoc nDoc = EnsureElement(vcard, "vcard", "n", ";;;;"); EnsureAttribute(nDoc, "charset", "utf-8"); List<string> vcard_n = new List<string>(nDoc.Contents.Split(';')); if (vcard_n.Count < 5) { while (vcard_n.Count < 5) vcard_n.Add(string.Empty); nDoc.ReplaceValue(string.Join(";", vcard_n.ToArray())); } string givenname = DecodeVersit(NormalizeSpace(vcard_n[1])); string additionalname = DecodeVersit(NormalizeSpace(vcard_n[2])); string familyname = DecodeVersit(NormalizeSpace(vcard_n[0])); string fn; if ((additionalname == "") && (familyname.IndexOf(" ") == -1)) { fn = givenname + " " + familyname; } else { fn = givenname; if (additionalname != "") fn += " " + additionalname; fn += " " + familyname; } fn = NormalizeSpace(fn); XDoc fnDoc = EnsureElement(vcard, "vcard", "fn", fn); EnsureAttribute(fnDoc, "charset", "utf-8"); if (fnDoc.Contents != EncodeVersit(fn)) fnDoc.ReplaceValue(EncodeVersit(fn)); string name = EncodeVersit(fn + "'s hCard"); XDoc nameDoc = EnsureElement(vcard, "vcard", "name", name); if (nameDoc.Contents != name) nameDoc.ReplaceValue(name); XDoc adrDoc = EnsureElement(vcard, "vcard", "adr", ";;;;;;"); EnsureAttribute(adrDoc, "charset", "utf-8"); List<string> vcard_adr = new List<string>(adrDoc.Contents.Split(';')); if (vcard_adr.Count < 7) { while (vcard_adr.Count < 7) vcard_adr.Add(string.Empty); adrDoc.ReplaceValue(string.Join(";", vcard_adr.ToArray())); } EnsureElement(vcard, "vcard", "email", null); XDoc orgDoc = EnsureElement(vcard, "vcard", "org", null); if (orgDoc != null) EnsureAttribute(orgDoc, "charset", "utf-8"); XDoc titleDoc = EnsureElement(vcard, "vcard", "title", null); if (titleDoc != null) EnsureAttribute(titleDoc, "charset", "utf-8"); XDoc photoDoc = EnsureElement(vcard, "vcard", "photo", null); if (photoDoc != null) { EnsureAttribute(photoDoc, "value", "uri"); if (photoDoc.Contents.StartsWith("/")) photoDoc.ReplaceValue("mos://localhost" + photoDoc.Contents); } foreach (XDoc tel in vcard["vcard/tel"]) { if (tel["@type"].Contents == "") tel.Remove(); } return DreamMessage.Ok(vcard); } /* <vcard> <prodid>-//mindtouch.com//DekiWiki 1.0//EN</prodid> <source>mos://localhost/User:JohnS/</source> <version>3.0</version> <name>John C. Smith's hCard</name> <fn charset="utf-8">John C. Smith</fn> <n charset="utf-8">Smith;John;C;;</n> <org charset="utf-8">MyCorp, Inc.</org> <title charset="utf-8">My Fancy Title</title> <adr charset="utf-8">;;12345 MyStreet Ave.;MyCity;MN;55101;USA</adr> <email>[email protected]</email> <tel type="work">(000) 000-0000</tel> <tel type="fax">(000) 000-0000</tel> <tel type="cell">(000) 000-0000</tel> <photo value="uri">mos://localhost/File:User:JohnS/Photo.png</photo> </vcard> */ [DreamFeature("render", "/", "POST", "", "http://doc.opengarden.org/Deki_API/Reference/Widgets/DekiBizCard")] public DreamMessage PostRenderHandler(DreamContext context, DreamMessage message) { string pageid = context.Uri.GetParam("pageid", ""); string title = context.Uri.GetParam("title", ""); if (context.Uri.GetParam("mode", "card") == "card") { XDoc vcard = message.Document; string id = context.Uri.GetParam("id", ""); string resultstr = RenderCard(vcard, title, pageid, id); return DreamMessage.Ok(MimeType.HTML, resultstr); } else { XDoc widgets = message.Document; string resultstr = "<div>"; foreach (XDoc widget in widgets["//widget"]) { resultstr += RenderCard(widget["dekibizcard"], title, pageid, widget["@id"].Contents); } resultstr += "</div>"; return DreamMessage.Ok(XDoc.FromXml(resultstr)); } } [DreamFeature("edit", "/", "POST", "", "http://doc.opengarden.org/Deki_API/Reference/Widgets/DekiBizCard")] public void PostEditHandler(DreamContext context) { context.Redirect(Plug.New( Env.RootUri.At("widget", "load", "dekibizcard") .With("mode", "edit") .With("id", context.Uri.GetParam("id", "-1")) )); } [DreamFeature("form", "/", "GET", "", "http://doc.opengarden.org/Deki_API/Reference/Widgets/DekiBizCard")] public DreamMessage PostFormHandler(DreamContext context, DreamMessage message) { if (this.formHtml == null) { string formTemplate = Plug.New(Env.RootUri).At("mount", "deki-widgets").At("widget-editor-form.html").Get().Text; string form = Plug.New(Env.RootUri).At("mount", "deki-widgets").At("dekibizcard-form.html").Get().Text; this.formHtml = WidgetService.ReplaceVariables(formTemplate, new MyDictionary( "%%TITLE%%", "BizCard Editor", "%%HEAD%%", "<script type=\"text/javascript\" src=\"/editor/widgets/dekibizcard.js\"></script>\n<style type=\"text/css\" src=\"/editor/widgets/bizcard.css\" ></style>", "%%FORM%%", form )); } return DreamMessage.Ok(MimeType.HTML, this.formHtml); } System.Xml.Xsl.XslTransform _xslTransform; System.Xml.Xsl.XslTransform xslTransform { get { if (_xslTransform == null) { Plug widgetStorage = Plug.New(Env.RootUri).At("mount", "deki-widgets"); _xslTransform = new System.Xml.Xsl.XslTransform(); _xslTransform.Load(widgetStorage.At("xhtml2vcard.xsl").Get().Document.AsXmlNode.ParentNode); } return _xslTransform; } } XDoc GetVCard(XDoc input) { try { using (System.IO.MemoryStream outStream = new System.IO.MemoryStream()) { System.IO.TextWriter writer = new System.IO.StreamWriter(outStream, Encoding.UTF8); xslTransform.Transform(input.AsXmlNode.ParentNode, null, writer); string vcard = Encoding.UTF8.GetString(outStream.ToArray()).Trim(); if (vcard == "") return XDoc.Empty; return XDoc.FromVersit(vcard, "dekibizcard"); } } catch { return XDoc.Empty; } } [DreamFeature("hcardtoedit", "/", "POST", "", "http://doc.opengarden.org/Deki_API/Reference/Widgets/DekiBizCard")] public DreamMessage PosthCardToEditHandler(DreamContext context, DreamMessage message) { XDoc vcard = GetVCard(message.Document); if (vcard.IsEmpty) { return DreamMessage.Ok(vcard); } Plug widgetToEdit = Plug.New(Env.RootUri.At("wiki-data", "dekibizcard", "edit")); return DreamMessage.Ok(widgetToEdit.Post(vcard).Document); } [DreamFeature("hcardtoxspan", "/", "POST", "", "http://doc.opengarden.org/Deki_API/Reference/Widgets/DekiBizCard")] public DreamMessage PosthCardToXSpanHandler(DreamContext context, DreamMessage message) { XDoc vcard = message.Document; if (vcard.IsEmpty) { return DreamMessage.Ok(vcard); } return DreamMessage.Ok(XDoc.FromXml(vcard.ToXSpan())); } #endregion } }
using System; using System.IO; using Kafka.Client.Api; using Kafka.Client.IO; using KafkaClient.Tests.TestHelpers; using Xunit; using Xunit.Should; namespace KafkaClient.Tests.Api { public class MessageTests { private readonly byte[] _testMessage1 = new byte[] { 0x0F, 0x66, 0xBB, 0xB7, // CRC 0x00, // MagicByte 0x00, // Attributes 0xFF, 0xFF, 0xFF, 0xFF, // Key, length = -1 0x00, 0x00, 0x00, 0x03, // Value, length 0x48, 0x69, 0x21, // Value "Hi!" }; [Fact] public void When_valid_message_Then_all_properties_are_correct() { var bytes = _testMessage1; var buffer = new RandomAccessReadBuffer(bytes); var message = new global::Kafka.Client.Api.Message(buffer); message.HasKey.ShouldBeFalse(); message.Key.ShouldNotHaveValue(); message.KeySize.ShouldBe(-1); message.ValueSize.ShouldBe(3); message.Value.ShouldHaveValue(); var arraySegment = message.Value.Value; arraySegment.Array[arraySegment.Offset].ShouldBe((byte)'H'); arraySegment.Array[arraySegment.Offset + 1].ShouldBe((byte)'i'); arraySegment.Array[arraySegment.Offset + 2].ShouldBe((byte)'!'); message.Magic.ShouldBe((byte)0); message.Attributes.ShouldBe((byte)0); message.Checksum.ShouldBe(0x0f66bbb7u); message.IsValid.ShouldBeTrue(); message.ComputeChecksum().ShouldBe(0x0f66bbb7u); } [Fact] public void When_invalid_crc_Then_message_is_invalid() { var bytes = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, // CRC 0x00, // MagicByte 0x00, // Attributes 0xFF, 0xFF, 0xFF, 0xFF, // Key, length = -1 0x00, 0x00, 0x00, 0x03, // Value, length 0x48, 0x69, 0x21, // Value "Hi!" }; var buffer = new RandomAccessReadBuffer(bytes); var message = new global::Kafka.Client.Api.Message(buffer); message.IsValid.ShouldBeFalse(); } [Fact] public void When_creating_message_with_No_key_and_A_Message_Then_all_properties_are_correctly_set() { var key = (string)null; var msg = new byte[] { 0x48, 0x69, 0x21 }; //Hi! var message = new Message(key, msg); message.HasKey.ShouldBeFalse(); message.KeySize.ShouldBe(-1); message.Key.ShouldBeNull(); message.ValueSize.ShouldBe(3); message.Value.ShouldHaveValue(); var arraySegment = message.Value.Value; arraySegment.ShouldBeString("Hi!"); message.Magic.ShouldBe((byte)0); message.Attributes.ShouldBe((byte)0); message.Checksum.ShouldBe(0x0f66bbb7u); message.IsValid.ShouldBeTrue(); message.ComputeChecksum().ShouldBe(0x0f66bbb7u); ((IKafkaRequestPart)message).GetSize().ShouldBe(17); var buffer = new byte[17]; var writer = new KafkaBinaryWriter(new MemoryStream(buffer)); ((IKafkaRequestPart)message).WriteTo(writer); buffer.ShouldOnlyContainInOrder(_testMessage1); } [Fact] public void When_creating_message_with_A_key_and_A_Message_Then_all_properties_are_correctly_set() { var key = new byte[] { 0x4B }; //K var msg = new byte[] { 0x48, 0x69, 0x21 }; //Hi! var message = new Message(key, msg); message.HasKey.ShouldBeTrue(); message.KeySize.ShouldBe(1); message.Key.ShouldHaveValue(); message.Key.Value.ShouldBeString("K"); message.ValueSize.ShouldBe(3); message.Value.ShouldHaveValue(); message.Value.Value.ShouldBeString("Hi!"); message.Magic.ShouldBe((byte)0); message.Attributes.ShouldBe((byte)0); message.Checksum.ShouldBe(0x265D0019u); message.IsValid.ShouldBeTrue(); message.ComputeChecksum().ShouldBe(0x265D0019u); ((IKafkaRequestPart)message).GetSize().ShouldBe(18); var buffer = new byte[18]; var writer = new KafkaBinaryWriter(new MemoryStream(buffer)); ((IKafkaRequestPart)message).WriteTo(writer); var expectedBytes = new byte[] { 0x26, 0x5D, 0x00, 0x19, // CRC 0x00, // MagicByte 0x00, // Attributes 0x00, 0x00, 0x00, 0x01, // Key, length = -1 0x4B, // Key "K" 0x00, 0x00, 0x00, 0x03, // Value, length 0x48, 0x69, 0x21, // Value "Hi!" }; buffer.ShouldOnlyContainInOrder(expectedBytes); } [Fact] public void When_creating_message_with_A_key_and_No_Message_Then_all_properties_are_correctly_set() { var key = new byte[] { 0x4B }; //K var msg = (byte[])null; var message = new Message(key, msg); message.HasKey.ShouldBeTrue(); message.KeySize.ShouldBe(1); message.Key.ShouldHaveValue(); message.Key.Value.ShouldBeString("K"); message.ValueSize.ShouldBe(-1); message.Value.ShouldBeNull(); message.Magic.ShouldBe((byte)0); message.Attributes.ShouldBe((byte)0); message.Checksum.ShouldBe(0x51432BF2u); message.IsValid.ShouldBeTrue(); message.ComputeChecksum().ShouldBe(0x51432BF2u); ((IKafkaRequestPart)message).GetSize().ShouldBe(15); var buffer = new byte[15]; var writer = new KafkaBinaryWriter(new MemoryStream(buffer)); ((IKafkaRequestPart)message).WriteTo(writer); var expectedBytes = new byte[] { 0x51, 0x43, 0x2B, 0xF2, // CRC 0x00, // MagicByte 0x00, // Attributes 0x00, 0x00, 0x00, 0x01, // Key, length 0x4B, // Key "K" 0xFF, 0xFF, 0xFF, 0xFF, // Value, length = -1 }; buffer.ShouldOnlyContainInOrder(expectedBytes); } [Fact] public void When_creating_message_with_No_key_and_No_Message_Then_all_properties_are_correctly_set() { var key = (byte[])null; var msg = (byte[])null; var message = new Message(key, msg); message.HasKey.ShouldBeFalse(); message.KeySize.ShouldBe(-1); message.Key.ShouldBeNull(); message.ValueSize.ShouldBe(-1); message.Value.ShouldBeNull(); message.Magic.ShouldBe((byte)0); message.Attributes.ShouldBe((byte)0); message.Checksum.ShouldBe(0xA7EC6803u); message.IsValid.ShouldBeTrue(); message.ComputeChecksum().ShouldBe(0xA7EC6803u); ((IKafkaRequestPart)message).GetSize().ShouldBe(14); var buffer = new byte[14]; var writer = new KafkaBinaryWriter(new MemoryStream(buffer)); ((IKafkaRequestPart)message).WriteTo(writer); var expectedBytes = new byte[] { 0xA7, 0xEC, 0x68, 0x03, // CRC 0x00, // MagicByte 0x00, // Attributes 0xFF, 0xFF, 0xFF, 0xFF, // Key, length = -1 0xFF, 0xFF, 0xFF, 0xFF, // Value, length = -1 }; buffer.ShouldOnlyContainInOrder(expectedBytes); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Security; namespace System.DirectoryServices.Interop { #pragma warning disable BCL0015 // CoreFxPort [StructLayout(LayoutKind.Explicit)] internal struct Variant { [FieldOffset(0)] public ushort varType; [FieldOffset(2)] public ushort reserved1; [FieldOffset(4)] public ushort reserved2; [FieldOffset(6)] public ushort reserved3; [FieldOffset(8)] public short boolvalue; [FieldOffset(8)] public IntPtr ptr1; [FieldOffset(12)] public IntPtr ptr2; } [SuppressUnmanagedCodeSecurity] internal class UnsafeNativeMethods { [DllImport(ExternDll.Activeds, ExactSpelling = true, EntryPoint = "ADsOpenObject", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] private static extern int IntADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject); public static int ADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject) { try { return IntADsOpenObject(path, userName, password, flags, ref iid, out ppObject); } catch (EntryPointNotFoundException) { throw new InvalidOperationException(SR.DSAdsiNotInstalled); } } [ComImport, Guid("FD8256D0-FD15-11CE-ABC4-02608C9E7553")] public interface IAds { string Name { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurity] get; } string Class { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurity] get; } string GUID { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurity] get; } string ADsPath { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurity] get; } string Parent { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurity] get; } string Schema { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurity] get; } [SuppressUnmanagedCodeSecurity] void GetInfo(); [SuppressUnmanagedCodeSecurity] void SetInfo(); object Get([In, MarshalAs(UnmanagedType.BStr)] string bstrName); [SuppressUnmanagedCodeSecurity] void Put([In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In] object vProp); [SuppressUnmanagedCodeSecurity] [PreserveSig] int GetEx([In, MarshalAs(UnmanagedType.BStr)] string bstrName, [Out] out object value); [SuppressUnmanagedCodeSecurity] void PutEx( [In, MarshalAs(UnmanagedType.U4)] int lnControlCode, [In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In] object vProp); [SuppressUnmanagedCodeSecurity] void GetInfoEx([In] object vProperties, [In, MarshalAs(UnmanagedType.U4)] int lnReserved); } [ComImport, Guid("001677D0-FD16-11CE-ABC4-02608C9E7553")] public interface IAdsContainer { int Count { [return: MarshalAs(UnmanagedType.U4)] [SuppressUnmanagedCodeSecurity] get; } object _NewEnum { [return: MarshalAs(UnmanagedType.Interface)] [SuppressUnmanagedCodeSecurity] get; } object Filter { get; set; } object Hints { get; set; } [return: MarshalAs(UnmanagedType.Interface)] [SuppressUnmanagedCodeSecurity] object GetObject( [In, MarshalAs(UnmanagedType.BStr)] string className, [In, MarshalAs(UnmanagedType.BStr)] string relativeName); [return: MarshalAs(UnmanagedType.Interface)] [SuppressUnmanagedCodeSecurity] object Create( [In, MarshalAs(UnmanagedType.BStr)] string className, [In, MarshalAs(UnmanagedType.BStr)] string relativeName); [SuppressUnmanagedCodeSecurity] void Delete( [In, MarshalAs(UnmanagedType.BStr)] string className, [In, MarshalAs(UnmanagedType.BStr)] string relativeName); [return: MarshalAs(UnmanagedType.Interface)] [SuppressUnmanagedCodeSecurity] object CopyHere( [In, MarshalAs(UnmanagedType.BStr)] string sourceName, [In, MarshalAs(UnmanagedType.BStr)] string newName); [return: MarshalAs(UnmanagedType.Interface)] [SuppressUnmanagedCodeSecurity] object MoveHere( [In, MarshalAs(UnmanagedType.BStr)] string sourceName, [In, MarshalAs(UnmanagedType.BStr)] string newName); } [ComImport, Guid("B2BD0902-8878-11D1-8C21-00C04FD8D503")] public interface IAdsDeleteOps { [SuppressUnmanagedCodeSecurity] void DeleteObject(int flags); } /// <summary> /// PropertyValue as a co-class that implements the IAdsPropertyValue interface. /// </summary> [ComImport, Guid("7b9e38b0-a97c-11d0-8534-00c04fd8d503")] public class PropertyValue { } [ComImport, Guid("9068270B-0939-11D1-8BE1-00C04FD8D503")] public interface IADsLargeInteger { int HighPart { get; set; } int LowPart { get; set; } } [ComImport, Guid("79FA9AD0-A97C-11D0-8534-00C04FD8D503")] public interface IAdsPropertyValue { [SuppressUnmanagedCodeSecurity] void Clear(); int ADsType { [SuppressUnmanagedCodeSecurity] get; [SuppressUnmanagedCodeSecurity] set; } string DNString { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurity] get; [param: MarshalAs(UnmanagedType.BStr)] set; } string CaseExactString { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurity] get; [param: MarshalAs(UnmanagedType.BStr)] set; } string CaseIgnoreString { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurity] get; [param: MarshalAs(UnmanagedType.BStr)] set; } string PrintableString { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurity] get; [param: MarshalAs(UnmanagedType.BStr)] set; } string NumericString { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurity] get; [param: MarshalAs(UnmanagedType.BStr)] set; } bool Boolean { get; set; } int Integer { get; set; } object OctetString { [SuppressUnmanagedCodeSecurity] get; [SuppressUnmanagedCodeSecurity] set; } object SecurityDescriptor { [SuppressUnmanagedCodeSecurity] get; set; } object LargeInteger { [SuppressUnmanagedCodeSecurity] get; set; } object UTCTime { [SuppressUnmanagedCodeSecurity] get; set; } } /// <summary> /// PropertyEntry as a co-class that implements the IAdsPropertyEntry interface. /// </summary> [ComImport, Guid("72D3EDC2-A4C4-11D0-8533-00C04FD8D503")] public class PropertyEntry { } [ComImport, Guid("05792C8E-941F-11D0-8529-00C04FD8D503")] public interface IAdsPropertyEntry { [SuppressUnmanagedCodeSecurity] void Clear(); string Name { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurity] get; [param: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurity] set; } int ADsType { [SuppressUnmanagedCodeSecurity] get; [SuppressUnmanagedCodeSecurity] set; } int ControlCode { [SuppressUnmanagedCodeSecurity] get; [SuppressUnmanagedCodeSecurity] set; } object Values { get; set; } } [ComImport, Guid("C6F602B6-8F69-11D0-8528-00C04FD8D503")] public interface IAdsPropertyList { int PropertyCount { [return: MarshalAs(UnmanagedType.U4)] [SuppressUnmanagedCodeSecurity] get; } [return: MarshalAs(UnmanagedType.I4)] [SuppressUnmanagedCodeSecurity] [PreserveSig] int Next([Out] out object nextProp); void Skip([In] int cElements); [SuppressUnmanagedCodeSecurity] void Reset(); object Item([In] object varIndex); object GetPropertyItem([In, MarshalAs(UnmanagedType.BStr)] string bstrName, int ADsType); [SuppressUnmanagedCodeSecurity] void PutPropertyItem([In] object varData); void ResetPropertyItem([In] object varEntry); void PurgePropertyList(); } [ComImport, Guid("109BA8EC-92F0-11D0-A790-00C04FD8D5A8"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public interface IDirectorySearch { [SuppressUnmanagedCodeSecurity] void SetSearchPreference([In] IntPtr /*ads_searchpref_info * */pSearchPrefs, int dwNumPrefs); [SuppressUnmanagedCodeSecurity] void ExecuteSearch( [In, MarshalAs(UnmanagedType.LPWStr)] string pszSearchFilter, [In, MarshalAs(UnmanagedType.LPArray)] string[] pAttributeNames, [In] int dwNumberAttributes, [Out] out IntPtr hSearchResult); [SuppressUnmanagedCodeSecurity] void AbandonSearch([In] IntPtr hSearchResult); [return: MarshalAs(UnmanagedType.U4)] [SuppressUnmanagedCodeSecurity] [PreserveSig] int GetFirstRow([In] IntPtr hSearchResult); [return: MarshalAs(UnmanagedType.U4)] [SuppressUnmanagedCodeSecurity] [PreserveSig] int GetNextRow([In] IntPtr hSearchResult); [return: MarshalAs(UnmanagedType.U4)] [SuppressUnmanagedCodeSecurity] [PreserveSig] int GetPreviousRow([In] IntPtr hSearchResult); [return: MarshalAs(UnmanagedType.U4)] [SuppressUnmanagedCodeSecurity] [PreserveSig] int GetNextColumnName( [In] IntPtr hSearchResult, [Out] IntPtr ppszColumnName); [SuppressUnmanagedCodeSecurity] void GetColumn( [In] IntPtr hSearchResult, [In] IntPtr /* char * */ szColumnName, [In] IntPtr pSearchColumn); [SuppressUnmanagedCodeSecurity] void FreeColumn([In] IntPtr pSearchColumn); [SuppressUnmanagedCodeSecurity] void CloseSearchHandle([In] IntPtr hSearchResult); } [ComImport, Guid("46F14FDA-232B-11D1-A808-00C04FD8D5A8")] public interface IAdsObjectOptions { object GetOption(int flag); [SuppressUnmanagedCodeSecurity] void SetOption(int flag, [In] object varValue); } /// <summary> /// For boolean type, the default marshaller does not work, so need to have specific marshaller. For other types, use the /// default marshaller which is more efficient. There is no such interface on the type library this is the same as IAdsObjectOptions /// with a different signature. /// </summary> [ComImport, Guid("46F14FDA-232B-11D1-A808-00C04FD8D5A8")] public interface IAdsObjectOptions2 { [SuppressUnmanagedCodeSecurity] [PreserveSig] int GetOption(int flag, [Out] out object value); [SuppressUnmanagedCodeSecurity] void SetOption(int option, Variant value); } // IDirecorySearch return codes internal const int S_ADS_NOMORE_ROWS = 0x00005012; internal const int INVALID_FILTER = unchecked((int)0x8007203E); internal const int SIZE_LIMIT_EXCEEDED = unchecked((int)0x80072023); } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Text; using Epi.Analysis; using Epi.Collections; using Epi.Core.AnalysisInterpreter; using Epi.Data; using Epi.Windows.Dialogs; using Epi.Windows.Analysis; using Epi; namespace Epi.Windows.Analysis.Dialogs { public partial class BuildKeyDialog : CommandDesignDialog { #region Private Members string relatedTable = string.Empty; private object selectedDataSource = null; string callingDialog = string.Empty; List<string> relatedFields = new List<string>(); List<string> currentFields = new List<string>(); List<string> relatedFields2 = new List<string>(); List<string> currentFields2 = new List<string>(); bool LoadIsFinished = false; /// <summary> /// key variable /// </summary> public string key = string.Empty; #endregion #region Public Properties /// <summary> /// List of related table column names. /// </summary> public string RelatedTable { get { return relatedTable; } set { relatedTable = value; } } /// <summary> /// selectedDataSource from calling dialog. Used to get the column names for the related table. /// </summary> public object SelectedDataSource { get { return selectedDataSource; } set { selectedDataSource = value; } } /// <summary> /// CallingDialog from the dialog that called this dialog. Used to determine if BuildKeyDialog was called by the /// MERGE or RELATE command dialogs so the appropriate instructions can be dispalyed. /// </summary> public string CallingDialog { get { return callingDialog; } set { callingDialog = value; } } /// <summary> /// KEY statement /// </summary> public string Key { get { return key; } set { key = value; } } #endregion #region Constructors /// <summary> /// Default constructor - NOT TO BE USED FOR INSTANTIATION /// </summary> [Obsolete("Use of default constructor not allowed", true)] public BuildKeyDialog() { InitializeComponent(); } /// <summary> /// Constructor for BuildKey dialog /// </summary> public BuildKeyDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm) : base(frm) { InitializeComponent(); Construct(); } private void Construct() { if (!this.DesignMode) { this.btnOK.Click += new System.EventHandler(this.btnOK_Click); } } #endregion #region Event Handlers private void ClickHandler(object sender, System.EventArgs e) { ToolStripButton btn = (ToolStripButton)sender; txtKeyComponent.Text += StringLiterals.SPACE; if ((string)btn.Tag == null) { txtKeyComponent.Text += btn.Text; } else { txtKeyComponent.Text += (string)btn.Tag; } txtKeyComponent.Text += StringLiterals.SPACE; } private void btnClear_Click(object sender, EventArgs e) { txtKeyComponent.Text = string.Empty; currentFields.Clear(); relatedFields.Clear(); currentFields2.Clear(); relatedFields2.Clear(); } /// <summary> /// Opens a process to show the related help topic /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> protected override void btnHelp_Click(object sender, System.EventArgs e) { System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/classic-analysis/managedata.html"); } private void BuildKeyDialog_Load(object sender, EventArgs e) { if (SelectedDataSource != null) { if (SelectedDataSource is IDbDriver) { IDbDriver db = SelectedDataSource as IDbDriver; //--EI-114 // relatedFields = db.GetTableColumnNames(RelatedTable); if (RelatedTable.Contains(StringLiterals.SPACE)) { string pstr = "Select TOP 2 * from [" + RelatedTable + "]"; DataTable relfields = DBReadExecute.GetDataTable(db, pstr); foreach (DataColumn dc in relfields.Columns) { relatedFields.Add(dc.ColumnName); } } else { relatedFields = db.GetTableColumnNames(RelatedTable); } //--- } else if (SelectedDataSource is Project) { Project project = SelectedDataSource as Project; if (project.Views.Exists(relatedTable)) { foreach (Epi.Fields.IField field in project.Views[RelatedTable].Fields) { if (!(field is Epi.Fields.LabelField) & !(field is Epi.Fields.CommandButtonField) & !(field is Epi.Fields.PhoneNumberField) & !(field is Epi.Fields.MultilineTextField) & !(field is Epi.Fields.GroupField) & !(field is Epi.Fields.CheckBoxField) & !(field is Epi.Fields.ImageField) & !(field is Epi.Fields.OptionField) & !(field is Epi.Fields.GridField) & !(field is Epi.Fields.MirrorField)) relatedFields.Add(field.Name); } } else { relatedFields = project.GetTableColumnNames(RelatedTable); } } currentFields = GetCurrentFields(); } relatedFields.Sort(); currentFields.Sort(); lbxRelatedTableFields.DataSource = relatedFields; lbxCurrentTableFields.DataSource = currentFields; lbxCurrentTableFields.SelectedIndex = -1; lbxRelatedTableFields.SelectedIndex = -1; if (CallingDialog == "RELATE") { lblBuildKeyInstructions.Text = SharedStrings.BUILDKEY_RELATE_INSTRUCTIONS; } else { lblBuildKeyInstructions.Text = SharedStrings.BUILDKEY_MERGE_INSTRUCTIONS; } this.LoadIsFinished = true; } /// <summary> /// Returns a list of field names that can be selected from the parent table and be used in a Relate command. /// Care is take to remove fields from Project Views that do not contain data like MirrorFields, GroupFields, etc. /// /// </summary> private List<String> GetCurrentFields() { List<String> fieldNames = new List<string>(); int numberOfBaseTableFields = 5; // {FirstSaveLogonName}, {FirstSaveTime}, {LastSaveLogonName}, {LastSaveTime}, {FKEY} if (this.EpiInterpreter.Context.DataSet != null) { View currentView = null; if (this.EpiInterpreter.Context.CurrentProject != null) { currentView = this.EpiInterpreter.Context.CurrentProject.GetViewByName(this.EpiInterpreter.Context.CurrentRead.Identifier); bool isPreRelateCommand = this.EpiInterpreter.Context.DataSet.Tables["Output"].Columns.Count == currentView.TableColumnNames.Count + numberOfBaseTableFields; if (isPreRelateCommand && this.EpiInterpreter.Context.CurrentProject.IsView(this.EpiInterpreter.Context.CurrentRead.Identifier)) { foreach (DataColumn column in this.EpiInterpreter.Context.DataSet.Tables["Output"].Columns) { if ((currentView.Fields.Exists(column.ColumnName) && !(currentView.Fields[column.ColumnName] is Epi.Fields.LabelField)) & (currentView.Fields.Exists(column.ColumnName) && !(currentView.Fields[column.ColumnName] is Epi.Fields.CommandButtonField)) & (currentView.Fields.Exists(column.ColumnName) && !(currentView.Fields[column.ColumnName] is Epi.Fields.PhoneNumberField)) & (currentView.Fields.Exists(column.ColumnName) && !(currentView.Fields[column.ColumnName] is Epi.Fields.MultilineTextField)) & (currentView.Fields.Exists(column.ColumnName) && !(currentView.Fields[column.ColumnName] is Epi.Fields.GroupField)) & (currentView.Fields.Exists(column.ColumnName) && !(currentView.Fields[column.ColumnName] is Epi.Fields.CheckBoxField)) & (currentView.Fields.Exists(column.ColumnName) && !(currentView.Fields[column.ColumnName] is Epi.Fields.ImageField)) & (currentView.Fields.Exists(column.ColumnName) && !(currentView.Fields[column.ColumnName] is Epi.Fields.OptionField)) & (currentView.Fields.Exists(column.ColumnName) && !(currentView.Fields[column.ColumnName] is Epi.Fields.GridField)) & (currentView.Fields.Exists(column.ColumnName) && !(currentView.Fields[column.ColumnName] is Epi.Fields.MirrorField)) ) { fieldNames.Add(column.ColumnName); } } } else { foreach (DataColumn column in this.EpiInterpreter.Context.DataSet.Tables["Output"].Columns) { fieldNames.Add(column.ColumnName); } } } else { foreach (DataColumn column in this.EpiInterpreter.Context.DataSet.Tables["Output"].Columns) { fieldNames.Add(column.ColumnName); } } } return fieldNames; } //private void selectedTable_CheckedChanged(object sender, EventArgs e) //{ // if (rdbRelatedTable.Checked) // { // if (!string.IsNullOrEmpty(txtKeyComponent.Text)) // { // lbxCurrentTableFields.Items.Add(txtKeyComponent.Text); // } // } // else // { // if (!string.IsNullOrEmpty(txtKeyComponent.Text)) // { // lbxRelatedTableFields.Items.Add(txtKeyComponent.Text); // } // } // txtKeyComponent.Text = string.Empty; // cmbAvailableVariables.SelectedIndex = -1; //} //private void cmbAvailableVariables_SelectedIndexChanged(object sender, EventArgs e) //{ // if (cmbAvailableVariables.SelectedIndex != -1) // { // string strSelectedVar = cmbAvailableVariables.SelectedItem.ToString(); // txtKeyComponent.Text += FieldNameNeedsBrackets(strSelectedVar) ? Util.InsertInSquareBrackets(strSelectedVar) : strSelectedVar; // cmbAvailableVariables.SelectedIndex = -1; // } //} //private void cmbAvailableVariables2_SelectedIndexChanged(object sender, EventArgs e) //{ // if (cmbAvailableVariables.SelectedIndex != -1) // { // string strSelectedVar = cmbAvailableVariables2.SelectedItem.ToString(); // txtKeyComponent.Text += FieldNameNeedsBrackets(strSelectedVar) ? Util.InsertInSquareBrackets(strSelectedVar) : strSelectedVar; // cmbAvailableVariables2.SelectedIndex = -1; // } //} /// <summary> /// Override of OK click event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void btnOK_Click(object sender, EventArgs e) { if (currentFields2.Count == relatedFields2.Count) { StringBuilder builtKey = new StringBuilder(); for (int i = 0; i < currentFields2.Count; i++) { if (i > 0) { builtKey.Append(StringLiterals.SPACE); builtKey.Append("AND"); builtKey.Append(StringLiterals.SPACE); } builtKey.Append(currentFields2[i]); builtKey.Append(StringLiterals.SPACE); builtKey.Append(StringLiterals.COLON); builtKey.Append(StringLiterals.COLON); builtKey.Append(StringLiterals.SPACE); builtKey.Append(relatedFields2[i]); } this.Key = builtKey.ToString(); this.DialogResult = DialogResult.OK; this.Hide(); } else { MsgBox.ShowError(SharedStrings.ERROR_RELATE_KEYS); } } #endregion private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { //ListBox btn = (ListBox)sender; //txtKeyComponent.Text += StringLiterals.SPACE; //switch(btn.Text) //{ // case "\"Yes\"": // txtKeyComponent.Text += "(+)"; // break; // case "\"No\"": // txtKeyComponent.Text += "(-)"; // break; // case "\"Missing\"": // txtKeyComponent.Text += "(.)"; // break; // default: // txtKeyComponent.Text += btn.Text; // break; //} //txtKeyComponent.Text += StringLiterals.SPACE; } private void lbxRelatedTableFields_SelectedIndexChanged(object sender, EventArgs e) { if (this.LoadIsFinished && lbxCurrentTableFields.SelectedIndex != -1 && lbxRelatedTableFields.SelectedIndex != -1 ) { string strSelectedVar = lbxCurrentTableFields.SelectedItem.ToString(); AddLabel.Text = FieldNameNeedsBrackets(strSelectedVar) ? Util.InsertInSquareBrackets(strSelectedVar) : strSelectedVar; AddLabel.Text += StringLiterals.SPACE; AddLabel.Text += " = "; AddLabel.Text += StringLiterals.SPACE; strSelectedVar = lbxRelatedTableFields.SelectedItem.ToString(); AddLabel.Text += FieldNameNeedsBrackets(strSelectedVar) ? Util.InsertInSquareBrackets(strSelectedVar) : strSelectedVar; } else { AddLabel.Text = ""; } } private void lbxCurrentTableFields_SelectedIndexChanged(object sender, EventArgs e) { if (this.LoadIsFinished && lbxCurrentTableFields.SelectedIndex != -1 && lbxRelatedTableFields.SelectedIndex != -1) { string strSelectedVar = lbxCurrentTableFields.SelectedItem.ToString(); AddLabel.Text = FieldNameNeedsBrackets(strSelectedVar) ? Util.InsertInSquareBrackets(strSelectedVar) : strSelectedVar; AddLabel.Text += StringLiterals.SPACE; AddLabel.Text += " = "; AddLabel.Text += StringLiterals.SPACE; strSelectedVar = lbxRelatedTableFields.SelectedItem.ToString(); AddLabel.Text += FieldNameNeedsBrackets(strSelectedVar) ? Util.InsertInSquareBrackets(strSelectedVar) : strSelectedVar; } else { AddLabel.Text = ""; } } private void BackCommandButton_Click(object sender, EventArgs e) { //txtKeyComponent.SelectionStart = txtKeyComponent.Text.Length; if(txtKeyComponent.Text.Length > 0) { txtKeyComponent.Text = txtKeyComponent.Text.Remove(txtKeyComponent.Text.Length - 1); } } private void EraseWordCommandButton_Click(object sender, EventArgs e) { if (txtKeyComponent.Text.Length > 0 && txtKeyComponent.Text.LastIndexOf(" ") > 0) { txtKeyComponent.Text = txtKeyComponent.Text.Remove(txtKeyComponent.Text.LastIndexOf(" ")); } } private void AddCommandButton_Click(object sender, EventArgs e) { if (lbxCurrentTableFields.SelectedIndex != -1 && lbxRelatedTableFields.SelectedIndex != -1 ) { string strSelectedVar = lbxCurrentTableFields.SelectedItem.ToString(); currentFields2.Add(FieldNameNeedsBrackets(strSelectedVar) ? Util.InsertInSquareBrackets(strSelectedVar) : strSelectedVar); txtKeyComponent.AppendText(FieldNameNeedsBrackets(strSelectedVar) ? Util.InsertInSquareBrackets(strSelectedVar) : strSelectedVar); lbxCurrentTableFields.SelectedIndex = -1; txtKeyComponent.AppendText(StringLiterals.SPACE); txtKeyComponent.AppendText(" = "); /* switch (this.listBox1.Text) { case "\"Yes\"": txtKeyComponent.Text += "(+)"; break; case "\"No\"": txtKeyComponent.Text += "(-)"; break; case "\"Missing\"": txtKeyComponent.Text += "(.)"; break; default: txtKeyComponent.Text += this.listBox1.Text; break; }*/ txtKeyComponent.AppendText(StringLiterals.SPACE); strSelectedVar = lbxRelatedTableFields.SelectedItem.ToString(); relatedFields2.Add(FieldNameNeedsBrackets(strSelectedVar) ? Util.InsertInSquareBrackets(strSelectedVar) : strSelectedVar); txtKeyComponent.AppendText(FieldNameNeedsBrackets(strSelectedVar) ? Util.InsertInSquareBrackets(strSelectedVar) : strSelectedVar); lbxRelatedTableFields.SelectedIndex = -1; txtKeyComponent.AppendText("\n"); AddLabel.Text = ""; } } #region Private Methods #endregion } }
using Microsoft.Azure.Commands.Compute.Common; using Microsoft.Azure.Common.Authentication.Models; using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC; using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC.Publish; using Microsoft.WindowsAzure.Storage.Auth; using System; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Extension.DSC { /// <summary> /// Uploads a Desired State Configuration script to Azure blob storage, which /// later can be applied to Azure Virtual Machines using the /// Set-AzureVMDscExtension cmdlet. /// </summary> [Cmdlet( VerbsData.Publish, ProfileNouns.VirtualMachineDscConfiguration, SupportsShouldProcess = true, DefaultParameterSetName = UploadArchiveParameterSetName), OutputType( typeof(String))] public class PublishAzureVMDscConfigurationCommand : DscExtensionPublishCmdletCommonBase { private const string CreateArchiveParameterSetName = "CreateArchive"; private const string UploadArchiveParameterSetName = "UploadArchive"; [Parameter( Mandatory = true, Position = 2, ParameterSetName = UploadArchiveParameterSetName, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the resource group that contains the storage account.")] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } /// <summary> /// Path to a file containing one or more configurations; the file can be a /// PowerShell script (*.ps1) or MOF interface (*.mof). /// </summary> [Parameter( Mandatory = true, Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a file containing one or more configurations")] [ValidateNotNullOrEmpty] public string ConfigurationPath { get; set; } /// <summary> /// Name of the Azure Storage Container the configuration is uploaded to. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, Position = 4, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "Name of the Azure Storage Container the configuration is uploaded to")] [ValidateNotNullOrEmpty] public string ContainerName { get; set; } /// <summary> /// The Azure Storage Account name used to upload the configuration script to the container specified by ContainerName. /// </summary> [Parameter( Mandatory = true, Position = 3, ValueFromPipelineByPropertyName = true, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "The Azure Storage Account name used to upload the configuration script to the container " + "specified by ContainerName ")] [ValidateNotNullOrEmpty] public String StorageAccountName { get; set; } /// <summary> /// Path to a local ZIP file to write the configuration archive to. /// When using this parameter, Publish-AzureVMDscConfiguration creates a /// local ZIP archive instead of uploading it to blob storage.. /// </summary> [Alias("ConfigurationArchivePath")] [Parameter( Position = 2, ValueFromPipelineByPropertyName = true, ParameterSetName = CreateArchiveParameterSetName, HelpMessage = "Path to a local ZIP file to write the configuration archive to.")] [ValidateNotNullOrEmpty] public string OutputArchivePath { get; set; } /// <summary> /// Suffix for the storage end point, e.g. core.windows.net /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "Suffix for the storage end point, e.g. core.windows.net")] [ValidateNotNullOrEmpty] public string StorageEndpointSuffix { get; set; } /// <summary> /// By default Publish-AzureVMDscConfiguration will not overwrite any existing blobs. /// Use -Force to overwrite them. /// </summary> [Parameter(HelpMessage = "By default Publish-AzureVMDscConfiguration will not overwrite any existing blobs")] public SwitchParameter Force { get; set; } /// <summary> /// Excludes DSC resource dependencies from the configuration archive /// </summary> [Parameter(HelpMessage = "Excludes DSC resource dependencies from the configuration archive")] public SwitchParameter SkipDependencyDetection { get; set; } /// <summary> ///Path to a .psd1 file that specifies the data for the Configuration. This /// file must contain a hashtable with the items described in /// http://technet.microsoft.com/en-us/library/dn249925.aspx. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration. This is added to the configuration " + "archive and then passed to the configuration function. It gets overwritten by the configuration data path " + "provided through the Set-AzureVMDscExtension cmdlet")] [ValidateNotNullOrEmpty] public string ConfigurationDataPath { get; set; } /// <summary> /// Path to a file or a directory to include in the configuration archive /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a file or a directory to include in the configuration archive. It gets downloaded to the " + "VM along with the configuration")] [ValidateNotNullOrEmpty] public String[] AdditionalPath { get; set; } //Private Variables /// <summary> /// Credentials used to access Azure Storage /// </summary> private StorageCredentials _storageCredentials; protected override void ProcessRecord() { base.ProcessRecord(); try { ValidatePsVersion(); //validate cmdlet params ConfigurationPath = GetUnresolvedProviderPathFromPSPath(ConfigurationPath); ValidateConfigurationPath(ConfigurationPath, ParameterSetName); if (ConfigurationDataPath != null) { ConfigurationDataPath = GetUnresolvedProviderPathFromPSPath(ConfigurationDataPath); ValidateConfigurationDataPath(ConfigurationDataPath); } if (AdditionalPath != null && AdditionalPath.Length > 0) { for (var count = 0; count < AdditionalPath.Length; count++) { AdditionalPath[count] = GetUnresolvedProviderPathFromPSPath(AdditionalPath[count]); } } switch (ParameterSetName) { case CreateArchiveParameterSetName: OutputArchivePath = GetUnresolvedProviderPathFromPSPath(OutputArchivePath); break; case UploadArchiveParameterSetName: _storageCredentials = this.GetStorageCredentials(ResourceGroupName,StorageAccountName); if (ContainerName == null) { ContainerName = DscExtensionCmdletConstants.DefaultContainerName; } if (StorageEndpointSuffix == null) { StorageEndpointSuffix = DefaultProfile.Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix); } break; } PublishConfiguration( ConfigurationPath, ConfigurationDataPath, AdditionalPath, OutputArchivePath, StorageEndpointSuffix, ContainerName, ParameterSetName, Force.IsPresent, SkipDependencyDetection.IsPresent, _storageCredentials); } finally { DeleteTemporaryFiles(); } } } }
using System; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using TestExtensions; using UnitTests.GrainInterfaces; using UnitTests.Grains; using Xunit; using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils; namespace DefaultCluster.Tests { using Microsoft.Extensions.DependencyInjection; public class GrainReferenceCastTests : HostedTestClusterEnsureDefaultStarted { private readonly IInternalGrainFactory internalGrainFactory; public GrainReferenceCastTests(DefaultClusterFixture fixture) : base(fixture) { var client = this.HostedCluster.Client; this.internalGrainFactory = client.ServiceProvider.GetRequiredService<IInternalGrainFactory>(); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public void CastGrainRefCastFromMyType() { GrainReference grain = (GrainReference)this.GrainFactory.GetGrain<ISimpleGrain>(random.Next(), SimpleGrain.SimpleGrainNamePrefix); GrainReference cast = (GrainReference)grain.AsReference<ISimpleGrain>(); Assert.IsAssignableFrom(grain.GetType(), cast); Assert.IsAssignableFrom<ISimpleGrain>(cast); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public void CastGrainRefCastFromMyTypePolymorphic() { // MultifacetTestGrain implements IMultifacetReader // MultifacetTestGrain implements IMultifacetWriter IAddressable grain = this.GrainFactory.GetGrain<IMultifacetTestGrain>(0); Assert.IsAssignableFrom<IMultifacetWriter>(grain); Assert.IsAssignableFrom<IMultifacetReader>(grain); IAddressable cast = grain.AsReference<IMultifacetReader>(); Assert.IsAssignableFrom(grain.GetType(), cast); Assert.IsAssignableFrom<IMultifacetWriter>(cast); Assert.IsAssignableFrom<IMultifacetReader>(grain); IAddressable cast2 = grain.AsReference<IMultifacetWriter>(); Assert.IsAssignableFrom(grain.GetType(), cast2); Assert.IsAssignableFrom<IMultifacetReader>(cast2); Assert.IsAssignableFrom<IMultifacetWriter>(grain); } // Test case currently fails intermittently [Fact, TestCategory("BVT"), TestCategory("Cast")] public void CastMultifacetRWReference() { // MultifacetTestGrain implements IMultifacetReader // MultifacetTestGrain implements IMultifacetWriter int newValue = 3; IMultifacetWriter writer = this.GrainFactory.GetGrain<IMultifacetWriter>(1); // No Wait in this test case IMultifacetReader reader = writer.AsReference<IMultifacetReader>(); // --> Test case intermittently fails here // Error: System.InvalidCastException: Grain reference MultifacetGrain.MultifacetWriterFactory+MultifacetWriterReference service interface mismatch: expected interface id=[1947430462] received interface name=[MultifacetGrain.IMultifacetWriter] id=[62435819] in grainRef=[GrainReference:*std/b198f19f] writer.SetValue(newValue).Wait(); Task<int> readAsync = reader.GetValue(); readAsync.Wait(); int result = readAsync.Result; Assert.Equal(newValue, result); } // Test case currently fails [Fact, TestCategory("BVT"), TestCategory("Cast")] public void CastMultifacetRWReferenceWaitForResolve() { // MultifacetTestGrain implements IMultifacetReader // MultifacetTestGrain implements IMultifacetWriter //Interface Id values for debug: // IMultifacetWriter = 62435819 // IMultifacetReader = 1947430462 // IMultifacetTestGrain = 222717230 (also compatable with 1947430462 or 62435819) int newValue = 4; IMultifacetWriter writer = this.GrainFactory.GetGrain<IMultifacetWriter>(2); IMultifacetReader reader = writer.AsReference<IMultifacetReader>(); // --> Test case fails here // Error: System.InvalidCastException: Grain reference MultifacetGrain.MultifacetWriterFactory+MultifacetWriterReference service interface mismatch: expected interface id=[1947430462] received interface name=[MultifacetGrain.IMultifacetWriter] id=[62435819] in grainRef=[GrainReference:*std/8408c2bc] writer.SetValue(newValue).Wait(); int result = reader.GetValue().Result; Assert.Equal(newValue, result); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public void ConfirmServiceInterfacesListContents() { // GeneratorTestDerivedDerivedGrainReference extends GeneratorTestDerivedGrain2Reference // GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference Type t1 = typeof(IGeneratorTestDerivedDerivedGrain); Type t2 = typeof(IGeneratorTestDerivedGrain2); Type t3 = typeof(IGeneratorTestGrain); var interfaces = GrainInterfaceUtils.GetRemoteInterfaces(typeof(IGeneratorTestDerivedDerivedGrain)); Assert.NotNull(interfaces); Assert.Equal(3, interfaces.Count); Assert.Contains(t1, interfaces); Assert.Contains(t2, interfaces); Assert.Contains(t3, interfaces); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public void CastCheckExpectedCompatIds2() { // GeneratorTestDerivedDerivedGrainReference extends GeneratorTestDerivedGrain2Reference // GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference Type t1 = typeof(IGeneratorTestDerivedDerivedGrain); Type t2 = typeof(IGeneratorTestDerivedGrain2); Type t3 = typeof(IGeneratorTestGrain); int id1 = GrainInterfaceUtils.GetGrainInterfaceId(t1); int id2 = GrainInterfaceUtils.GetGrainInterfaceId(t2); int id3 = GrainInterfaceUtils.GetGrainInterfaceId(t3); Assert.Equal(-692645356, id1); Assert.Equal(-342583538, id2); Assert.Equal(-712890543, id3); GrainReference grain = (GrainReference) this.GrainFactory.GetGrain<IGeneratorTestDerivedDerivedGrain>(GetRandomGrainId()); Assert.NotNull(grain); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public void CastFailInternalCastFromBadType() { var grain = this.GrainFactory.GetGrain<ISimpleGrain>( random.Next(), SimpleGrain.SimpleGrainNamePrefix); // Attempting to cast a grain to a non-grain type should fail. Assert.Throws<ArgumentException>(() => this.internalGrainFactory.Cast(grain, typeof(bool))); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public void CastInternalCastFromMyType() { GrainReference grain = (GrainReference)this.GrainFactory.GetGrain<ISimpleGrain>(random.Next(), SimpleGrain.SimpleGrainNamePrefix); // This cast should be a no-op, since the interface matches the initial reference's exactly. IAddressable cast = grain.Cast<ISimpleGrain>(); Assert.Same(grain, cast); Assert.IsAssignableFrom<ISimpleGrain>(cast); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public void CastInternalCastUpFromChild() { // GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference GrainReference grain = (GrainReference)this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId()); // This cast should be a no-op, since the interface is implemented by the initial reference's interface. IAddressable cast = grain.Cast<IGeneratorTestGrain>(); Assert.Same(grain, cast); Assert.IsAssignableFrom<IGeneratorTestGrain>(cast); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public void CastGrainRefUpCastFromChild() { // GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference GrainReference grain = (GrainReference) this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId()); GrainReference cast = (GrainReference) grain.AsReference<IGeneratorTestGrain>(); Assert.IsAssignableFrom<IGeneratorTestDerivedGrain1>(cast); Assert.IsAssignableFrom<IGeneratorTestGrain>(cast); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public async Task FailSideCastAfterResolve() { // GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference // GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference IGeneratorTestDerivedGrain1 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId()); Assert.True(grain.StringIsNullOrEmpty().Result); // Fails the next line as grain reference is already resolved IGeneratorTestDerivedGrain2 cast = grain.AsReference<IGeneratorTestDerivedGrain2>(); await Assert.ThrowsAsync<InvalidCastException>(() => cast.StringConcat("a", "b", "c")); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public async Task FailOperationAfterSideCast() { // GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference // GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference IGeneratorTestDerivedGrain1 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId()); // Cast works optimistically when the grain reference is not already resolved IGeneratorTestDerivedGrain2 cast = grain.AsReference<IGeneratorTestDerivedGrain2>(); // Operation fails when grain reference is completely resolved await Assert.ThrowsAsync<InvalidCastException>(() => cast.StringConcat("a", "b", "c")); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public void FailSideCastAfterContinueWith() { Assert.Throws<InvalidCastException>(() => { // GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference // GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference try { IGeneratorTestDerivedGrain1 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId()); IGeneratorTestDerivedGrain2 cast = null; Task<bool> av = grain.StringIsNullOrEmpty(); Task<bool> av2 = av.ContinueWith((Task<bool> t) => Assert.True(t.Result)).ContinueWith((_AppDomain) => { cast = grain.AsReference<IGeneratorTestDerivedGrain2>(); }).ContinueWith((_) => cast.StringConcat("a", "b", "c")).ContinueWith((_) => cast.StringIsNullOrEmpty().Result); Assert.False(av2.Result); } catch (AggregateException ae) { Exception ex = ae.InnerException; while (ex is AggregateException) ex = ex.InnerException; throw ex; } Assert.True(false, "Exception should have been raised"); }); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public void CastGrainRefUpCastFromGrandchild() { // GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference GrainReference cast; GrainReference grain = (GrainReference)this.GrainFactory.GetGrain<IGeneratorTestDerivedDerivedGrain>(GetRandomGrainId()); // Parent cast = (GrainReference) grain.AsReference<IGeneratorTestDerivedGrain2>(); Assert.IsAssignableFrom<IGeneratorTestDerivedDerivedGrain>(cast); Assert.IsAssignableFrom<IGeneratorTestDerivedGrain2>(cast); Assert.IsAssignableFrom<IGeneratorTestGrain>(cast); // Cross-cast outside the inheritance hierarchy should not work Assert.False(cast is IGeneratorTestDerivedGrain1); // Grandparent cast = (GrainReference) grain.AsReference<IGeneratorTestGrain>(); Assert.IsAssignableFrom<IGeneratorTestDerivedDerivedGrain>(cast); Assert.IsAssignableFrom<IGeneratorTestGrain>(cast); // Cross-cast outside the inheritance hierarchy should not work Assert.False(cast is IGeneratorTestDerivedGrain1); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public void CastGrainRefUpCastFromDerivedDerivedChild() { // GeneratorTestDerivedDerivedGrainReference extends GeneratorTestDerivedGrain2Reference // GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference GrainReference grain = (GrainReference) this.GrainFactory.GetGrain<IGeneratorTestDerivedDerivedGrain>(GetRandomGrainId()); GrainReference cast = (GrainReference) grain.AsReference<IGeneratorTestDerivedGrain2>(); Assert.IsAssignableFrom<IGeneratorTestDerivedDerivedGrain>(cast); Assert.IsAssignableFrom<IGeneratorTestDerivedGrain2>(cast); Assert.IsAssignableFrom<IGeneratorTestGrain>(cast); Assert.False(cast is IGeneratorTestDerivedGrain1); } [Fact, TestCategory("BVT"), TestCategory("Cast")] public void CastAsyncGrainRefCastFromSelf() { IAddressable grain = this.GrainFactory.GetGrain<ISimpleGrain>(random.Next(), SimpleGrain.SimpleGrainNamePrefix); ; ISimpleGrain cast = grain.AsReference<ISimpleGrain>(); Task<int> successfulCallPromise = cast.GetA(); successfulCallPromise.Wait(); Assert.Equal(TaskStatus.RanToCompletion, successfulCallPromise.Status); } // todo: implement white box access #if TODO [Fact] public void CastAsyncGrainRefUpCastFromChild() { // GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference //GrainReference grain = GeneratorTestDerivedGrain1Reference.GetGrain(GetRandomGrainId()); var lookupPromise = GrainReference.CreateGrain( "", "GeneratorTestGrain.GeneratorTestDerivedGrain1" ); GrainReference grain = new GrainReference(lookupPromise); GrainReference cast = (GrainReference) GeneratorTestGrainFactory.Cast(grain); Assert.NotNull(cast); //Assert.Same(typeof(IGeneratorTestGrain), cast.GetType()); if (!cast.IsResolved) { cast.Wait(100); // Resolve the grain reference } Assert.True(cast.IsResolved); Assert.True(grain.IsResolved); } [Fact] public void CastAsyncGrainRefUpCastFromGrandchild() { // GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference //GrainReference grain = GeneratorTestDerivedDerivedGrainReference.GetGrain(GetRandomGrainId()); var lookupPromise = GrainReference.CreateGrain( "", "GeneratorTestGrain.GeneratorTestDerivedDerivedGrain" ); GrainReference grain = new GrainReference(lookupPromise); GrainReference cast = (GrainReference) GeneratorTestGrainFactory.Cast(grain); Assert.NotNull(cast); //Assert.Same(typeof(IGeneratorTestGrain), cast.GetType()); if (!cast.IsResolved) { cast.Wait(100); // Resolve the grain reference } Assert.True(cast.IsResolved); Assert.True(grain.IsResolved); } [Fact] [ExpectedExceptionAttribute(typeof(InvalidCastException))] public void CastAsyncGrainRefFailSideCastToPeer() { // GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference //GrainReference grain = GeneratorTestDerivedGrain1Reference.GetGrain(GetRandomGrainId()); var lookupPromise = GrainReference.CreateGrain( "", "GeneratorTestGrain.GeneratorTestDerivedGrain1" ); GrainReference grain = new GrainReference(lookupPromise); GrainReference cast = (GrainReference) GeneratorTestDerivedGrain2Factory.Cast(grain); if (!cast.IsResolved) { cast.Wait(100); // Resolve the grain reference } Assert.True(false, "Exception should have been raised"); } [Fact] [ExpectedExceptionAttribute(typeof(InvalidCastException))] public void CastAsyncGrainRefFailDownCastToChild() { // GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference //GrainReference grain = GeneratorTestGrainReference.GetGrain(GetRandomGrainId()); var lookupPromise = GrainReference.CreateGrain( "", "GeneratorTestGrain.GeneratorTestGrain"); GrainReference grain = new GrainReference(lookupPromise); GrainReference cast = (GrainReference) GeneratorTestDerivedGrain1Factory.Cast(grain); if (!cast.IsResolved) { cast.Wait(100); // Resolve the grain reference } Assert.True(false, "Exception should have been raised"); } [Fact] [ExpectedExceptionAttribute(typeof(InvalidCastException))] public void CastAsyncGrainRefFailDownCastToGrandchild() { // GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference //GrainReference grain = GeneratorTestGrainReference.GetGrain(GetRandomGrainId()); var lookupPromise = GrainReference.CreateGrain( "", "GeneratorTestGrain.GeneratorTestGrain"); GrainReference grain = new GrainReference(lookupPromise); GrainReference cast = (GrainReference) GeneratorTestDerivedDerivedGrainFactory.Cast(grain); if (!cast.IsResolved) { cast.Wait(100); // Resolve the grain reference } Assert.True(false, "Exception should have been raised"); } #endif [Fact, TestCategory("BVT"), TestCategory("Cast")] public void CastCallMethodInheritedFromBaseClass() { // GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference // GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference Task<bool> isNullStr; IGeneratorTestDerivedGrain1 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId()); isNullStr = grain.StringIsNullOrEmpty(); Assert.True(isNullStr.Result, "Value should be null initially"); isNullStr = grain.StringSet("a").ContinueWith((_) => grain.StringIsNullOrEmpty()).Unwrap(); Assert.False(isNullStr.Result, "Value should not be null after SetString(a)"); isNullStr = grain.StringSet(null).ContinueWith((_) => grain.StringIsNullOrEmpty()).Unwrap(); Assert.True(isNullStr.Result, "Value should be null after SetString(null)"); IGeneratorTestGrain cast = grain.AsReference<IGeneratorTestGrain>(); isNullStr = cast.StringSet("b").ContinueWith((_) => grain.StringIsNullOrEmpty()).Unwrap(); Assert.False(isNullStr.Result, "Value should not be null after cast.SetString(b)"); } } }
using System; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Runtime.InteropServices; using System.Collections; using System.ComponentModel; using MS.Win32; // PRESHARP: In order to avoid generating warnings about unkown message numbers and unknown pragmas. #pragma warning disable 1634, 1691 namespace MS.Internal.AutomationProxies { static internal class ClickablePoint { /// <summary> /// Static Constructor. Retrieve and keeps the hwnd for "Program" /// The Windows Rectangle for "Program" is the union for the real /// Estate for all the monitors. /// </summary> static ClickablePoint() { _hwndProgman = Misc.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Progman", null); if (_hwndProgman == IntPtr.Zero) { _hwndProgman = _hwndDesktop; } } //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// Return a clickable point in a Rectangle for a given window /// /// The algorithm uses the Windows Z order. /// To be visible, a rectangle must be enclosed in the hwnd of its parents /// and must but at least partially on top of the all of siblings as predecessors. /// In the windows ordered scheme, the first sibling comes on top followed by the /// next, etc. For a given hwnd, it is sufficent then to look for all the /// predecessor siblings. /// /// The scheme below is using recursion. This is make slightly harder to read /// But makes it a bit more efficent. /// </summary> /// <param name="hwnd">Window Handle</param> /// <param name="alIn">Input list of Rectangles to check GetPoint against</param> /// <param name="alOut">Output list of Rectangles after the exclusion test</param> /// <param name="pt">Clickable Point</param> /// <returns>True if there is a clickable in ro</returns> static internal bool GetPoint(IntPtr hwnd, ArrayList alIn, ArrayList alOut, ref NativeMethods.Win32Point pt) { IntPtr hwndStart = hwnd; IntPtr hwndCurrent = hwnd; // Do the window on top exclusion // Only one level deep is necessary as grand children are clipped to their parent (our children) for (hwnd = Misc.GetWindow(hwnd, NativeMethods.GW_CHILD); hwnd != IntPtr.Zero; hwnd = Misc.GetWindow(hwnd, NativeMethods.GW_HWNDNEXT)) { // For siblings, the element bounding rectangle must not be covered by the // bounding rect of its siblings if (!ClickableInRect(hwnd, ref pt, true, alIn, alOut)) { return false; } } // Check for Parent and Sibling hwnd = hwndStart; while (true) { hwnd = Misc.GetWindow(hwnd, NativeMethods.GW_HWNDPREV); if (hwnd == IntPtr.Zero) { // Very top of the Windows hierarchy we're done if (hwndCurrent == _hwndDesktop) { break; } // The desktop is the parent we should stop here if (Misc.IsBitSet(Misc.GetWindowStyle(hwndCurrent), NativeMethods.WS_POPUP)) { hwnd = _hwndDesktop; } else { // We finished with all the hwnd siblings so get to the parent hwnd = Misc.GetParent(hwndCurrent); } if (hwnd == IntPtr.Zero) { // final clipping against the desktop hwnd = _hwndDesktop; } // For parent, the element bounding rectangle must be within it's parent bounding rect // The desktop contains the bounding rectangle only for the main monintor, the // The Progman window contains the area for the union of all the monitors // Substitute the Desktop with the Progman hwnd for clipping calculation IntPtr hwndClip = hwnd == _hwndDesktop ? _hwndProgman : hwnd; if (!ClickableInRect(hwndClip, ref pt, false, alIn, alOut)) { return false; } // Current Parent hwndCurrent = hwnd; continue; } // For siblings, the element bounding rectangle must not be covered by the // bounding rect of its siblings if (!ClickableInRect(hwnd, ref pt, true, alIn, alOut)) { return false; } } return true; } /// <summary> /// Go through the list of all element chidren and exclude them from the list of /// visible/clickable rectangles. /// The element children may be listed in any order. A check on all of them must /// be performed. There is no easy way out. /// </summary> /// <param name="fragment"></param> /// <param name="alIn"></param> /// <param name="alOut"></param> internal static void ExcludeChildren(ProxyFragment fragment, ArrayList alIn, ArrayList alOut) { // First go through all the children to exclude whatever is on top for (ProxySimple simple = fragment.GetFirstChild(); simple != null; simple = fragment.GetNextSibling(simple)) { // The exclusion for hwnd children is done by the GetPoint routine if (simple is ProxyHwnd) { continue; } // Copy the output bits alIn.Clear(); alIn.AddRange(alOut); NativeMethods.Win32Rect rc = new NativeMethods.Win32Rect(simple.BoundingRectangle); CPRect rcp = new CPRect(ref rc, false); ClickablePoint.SplitRect(alIn, ref rcp, alOut, true); // recurse on the children if (simple is ProxyFragment) { ExcludeChildren((ProxyFragment)simple, alIn, alOut); } } } #endregion // ------------------------------------------------------ // // Internal Fields // // ------------------------------------------------------ #region Internal Fields /// <summary> /// Rectangle is inclusive exclusive /// </summary> internal struct CPRect { internal bool _fNotCovered; internal int _left; internal int _top; internal int _right; internal int _bottom; internal CPRect(int left, int top, int right, int bottom, bool fRiAsInsideRect) { _left = left; _top = top; _right = right; _bottom = bottom; _fNotCovered = fRiAsInsideRect; } // ref to make it a pointer internal CPRect(ref NativeMethods.Win32Rect rc, bool fRiAsInsideRect) { _left = rc.left; _top = rc.top; _right = rc.right; _bottom = rc.bottom; _fNotCovered = fRiAsInsideRect; } // return true if the 2 rectangle intersects internal bool Intersect(ref CPRect ri) { return !(_top >= ri._bottom || ri._top >= _bottom || _left >= ri._right || ri._left >= _right); } // return true if ri completely covers this internal bool Overlap(ref CPRect ri) { return (ri._left <= _left && ri._right >= _right && ri._top <= _top && ri._bottom >= _bottom); } } #endregion // ------------------------------------------------------ // // Private Methods // // ------------------------------------------------------ #region Private Methods private static bool ClickableInRect(IntPtr hwnd, ref NativeMethods.Win32Point pt, bool fRiAsInsideRect, ArrayList alIn, ArrayList alOut) { if (!SafeNativeMethods.IsWindowVisible(hwnd)) { return fRiAsInsideRect; } // Get the window rect. If this window has a width and it is effectivly invisible NativeMethods.Win32Rect rc = new NativeMethods.Win32Rect(); if (!Misc.GetWindowRect(hwnd, ref rc)) { return fRiAsInsideRect; } if ((rc.right - rc.left) <= 0 || (rc.bottom - rc.top) <= 0) { return fRiAsInsideRect; } // Try for transparency... if (fRiAsInsideRect) { int x = (rc.right + rc.left) / 2; int y = (rc.top + rc.bottom) / 2; try { int lr = Misc.ProxySendMessageInt(hwnd, NativeMethods.WM_NCHITTEST, IntPtr.Zero, NativeMethods.Util.MAKELPARAM(x, y)); if (lr == NativeMethods.HTTRANSPARENT) { return true; } } // PRESHARP: Warning - Catch statements should not have empty bodies #pragma warning disable 6502 catch (TimeoutException) { // Ignore this timeout error. Avalon HwndWrappers have a problem with this WM_NCHITTEST call sometimes. } #pragma warning restore 6502 } // Copy the output bits alIn.Clear(); alIn.AddRange(alOut); CPRect rcp = new CPRect(ref rc, false); ClickablePoint.SplitRect(alIn, ref rcp, alOut, fRiAsInsideRect); if (!GetClickablePoint(alOut, out pt.x, out pt.y)) { return false; } return true; } /// <summary> /// Split a rectangle into a maximum of 3 rectangble. /// ro is the outside rectangle and ri is the inside rectangle /// ro might is split vertically in a a maximim of 3 rectangles sharing the same /// right and left margin /// </summary> /// <param name="ro">Outside Rectangle</param> /// <param name="ri">Inside Rectangle</param> /// <param name="left">Left Margin for the resulting rectangles</param> /// <param name="right">Right Margin for the resulting rectangles</param> /// <param name="alRect">Array of resulting rectangles</param> /// <param name="fRiAsInsideRect">Covered flag</param> static private void SplitVertical(ref CPRect ro, ref CPRect ri, int left, int right, ArrayList alRect, bool fRiAsInsideRect) { // bottom clip if (ri._bottom > ro._bottom) { ri._bottom = ro._bottom; } int top = ro._top; int bottom = ri._top; if (bottom > top) { alRect.Add(new CPRect(left, top, right, bottom, ro._fNotCovered)); top = bottom; } bottom = ri._bottom; if (bottom > top) { alRect.Add(new CPRect(left, top, right, bottom, ro._fNotCovered & fRiAsInsideRect)); top = bottom; } bottom = ro._bottom; if (bottom > top) { alRect.Add(new CPRect(left, top, right, bottom, ro._fNotCovered)); } } /// <summary> /// Slip a rectangle into a maximum of 5 pieces. /// ro is the out rectangle and ri is the exclusion rectangle. /// The number of resulting rectangles varies based on the position of ri relative to ro /// Each resulting reactangles are flaged as covered or not. /// The ro covered flag is or'ed to allow for recursive calls /// /// +-----------------+ /// | : 2 : | /// | : : | /// | ###### | /// | ###3## | /// | 1 ###### 5 | /// | ###### | /// | : : | /// | : 4 : | /// | : : | /// +-----------------+ /// </summary> /// <param name="ro">Outside Rectangle</param> /// <param name="ri">Inside Rectangle</param> /// <param name="alRect">Collection of resulting rectangles</param> /// <param name="fRiAsInsideRect"></param> static private void SplitRect(ref CPRect ro, CPRect ri, ArrayList alRect, bool fRiAsInsideRect) { // If ri is fully outside easy way out. if (!ro._fNotCovered || !ro.Intersect(ref ri)) { ro._fNotCovered &= fRiAsInsideRect; alRect.Add(ro); return; } if (ro.Overlap(ref ri)) { ro._fNotCovered &= !fRiAsInsideRect; alRect.Add(ro); return; } // right clip if (ri._right > ro._right) { ri._right = ro._right; } // bottom clip if (ri._bottom > ro._bottom) { ri._bottom = ro._bottom; } int left = ro._left; int right = ri._left; if (right > left) { alRect.Add(new CPRect(left, ro._top, right, ro._bottom, ro._fNotCovered & fRiAsInsideRect)); left = right; } right = ri._right; if (right > left) { SplitVertical(ref ro, ref ri, left, right, alRect, !fRiAsInsideRect); left = right; } right = ro._right; if (right > left) { alRect.Add(new CPRect(left, ro._top, right, ro._bottom, ro._fNotCovered & fRiAsInsideRect)); } } /// <summary> /// Takes as input a set of rectangles to perform a rectangular decomposition /// based on the ri. It creates a new set of rectangles each of them being /// marked as covered or not. /// /// </summary> /// <param name="alIn">List of input rectangle</param> /// <param name="ri">Overlapping Rectangle</param> /// <param name="alOut">New sets of reactangle</param> /// <param name="fRiAsInsideRect">Input Rectangle is rectangle covering alIn Rects or everything /// outside of ri must be marked as covered</param> static private void SplitRect(ArrayList alIn, ref CPRect ri, ArrayList alOut, bool fRiAsInsideRect) { alOut.Clear(); for (int i = 0, c = alIn.Count; i < c; i++) { CPRect ro = (CPRect)alIn[i]; SplitRect(ref ro, ri, alOut, fRiAsInsideRect); } } /// <summary> /// Find a clickable point in a list of rectangle. /// Goes through the list of rectangle, stops on the first rectangle that is not covered /// and returns the mid point /// </summary> /// <param name="al">list of ractangle</param> /// <param name="x">X coordinate for a clickable point</param> /// <param name="y">Y coordinate for a clickable point</param> /// <returns>Clickable point found</returns> static private bool GetClickablePoint(ArrayList al, out int x, out int y) { for (int i = 0, c = al.Count; i < c; i++) { CPRect r = (CPRect)al[i]; if (r._fNotCovered == true && (r._right - r._left) * (r._bottom - r._top) > 0) { // Skip if the rectangle is empty if (r._right > r._left && r._bottom > r._top) { // mid point rounded to the left x = ((r._right - 1) + r._left) / 2; y = ((r._bottom - 1) + r._top) / 2; return true; } } } x = y = 0; return false; } #endregion #region Private fields // Top level Desktop window private static IntPtr _hwndDesktop = UnsafeNativeMethods.GetDesktopWindow(); /// The WindowsRect for "Program" is the union for the real /// estate for all the monitors. Instead of doing clipping against the root of the hwnd /// tree that is the desktop. The last clipping should be done against the Progman hwnd. private static IntPtr _hwndProgman; #endregion Private fields } }
/* * 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.CodeAnalysis; using System.IO; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Binary.Structure; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Binary reader implementation. /// </summary> internal class BinaryReader : IBinaryReader, IBinaryRawReader { /** Marshaller. */ private readonly Marshaller _marsh; /** Parent builder. */ private readonly BinaryObjectBuilder _builder; /** Handles. */ private BinaryReaderHandleDictionary _hnds; /** Current position. */ private int _curPos; /** Current raw flag. */ private bool _curRaw; /** Detach flag. */ private bool _detach; /** Binary read mode. */ private BinaryMode _mode; /** Current type structure tracker. */ private BinaryStructureTracker _curStruct; /** Current schema. */ private int[] _curSchema; /** Current schema with positions. */ private Dictionary<int, int> _curSchemaMap; /** Current header. */ private BinaryObjectHeader _curHdr; /// <summary> /// Constructor. /// </summary> /// <param name="marsh">Marshaller.</param> /// <param name="stream">Input stream.</param> /// <param name="mode">The mode.</param> /// <param name="builder">Builder.</param> public BinaryReader (Marshaller marsh, IBinaryStream stream, BinaryMode mode, BinaryObjectBuilder builder) { _marsh = marsh; _mode = mode; _builder = builder; Stream = stream; } /// <summary> /// Gets the marshaller. /// </summary> public Marshaller Marshaller { get { return _marsh; } } /** <inheritdoc /> */ public IBinaryRawReader GetRawReader() { MarkRaw(); return this; } /** <inheritdoc /> */ public bool ReadBoolean(string fieldName) { return ReadField(fieldName, r => r.ReadBoolean(), BinaryUtils.TypeBool); } /** <inheritdoc /> */ public bool ReadBoolean() { return Stream.ReadBool(); } /** <inheritdoc /> */ public bool[] ReadBooleanArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadBooleanArray, BinaryUtils.TypeArrayBool); } /** <inheritdoc /> */ public bool[] ReadBooleanArray() { return Read(BinaryUtils.ReadBooleanArray, BinaryUtils.TypeArrayBool); } /** <inheritdoc /> */ public byte ReadByte(string fieldName) { return ReadField(fieldName, ReadByte, BinaryUtils.TypeByte); } /** <inheritdoc /> */ public byte ReadByte() { return Stream.ReadByte(); } /** <inheritdoc /> */ public byte[] ReadByteArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadByteArray, BinaryUtils.TypeArrayByte); } /** <inheritdoc /> */ public byte[] ReadByteArray() { return Read(BinaryUtils.ReadByteArray, BinaryUtils.TypeArrayByte); } /** <inheritdoc /> */ public short ReadShort(string fieldName) { return ReadField(fieldName, ReadShort, BinaryUtils.TypeShort); } /** <inheritdoc /> */ public short ReadShort() { return Stream.ReadShort(); } /** <inheritdoc /> */ public short[] ReadShortArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadShortArray, BinaryUtils.TypeArrayShort); } /** <inheritdoc /> */ public short[] ReadShortArray() { return Read(BinaryUtils.ReadShortArray, BinaryUtils.TypeArrayShort); } /** <inheritdoc /> */ public char ReadChar(string fieldName) { return ReadField(fieldName, ReadChar, BinaryUtils.TypeChar); } /** <inheritdoc /> */ public char ReadChar() { return Stream.ReadChar(); } /** <inheritdoc /> */ public char[] ReadCharArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadCharArray, BinaryUtils.TypeArrayChar); } /** <inheritdoc /> */ public char[] ReadCharArray() { return Read(BinaryUtils.ReadCharArray, BinaryUtils.TypeArrayChar); } /** <inheritdoc /> */ public int ReadInt(string fieldName) { return ReadField(fieldName, ReadInt, BinaryUtils.TypeInt); } /** <inheritdoc /> */ public int ReadInt() { return Stream.ReadInt(); } /** <inheritdoc /> */ public int[] ReadIntArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadIntArray, BinaryUtils.TypeArrayInt); } /** <inheritdoc /> */ public int[] ReadIntArray() { return Read(BinaryUtils.ReadIntArray, BinaryUtils.TypeArrayInt); } /** <inheritdoc /> */ public long ReadLong(string fieldName) { return ReadField(fieldName, ReadLong, BinaryUtils.TypeLong); } /** <inheritdoc /> */ public long ReadLong() { return Stream.ReadLong(); } /** <inheritdoc /> */ public long[] ReadLongArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadLongArray, BinaryUtils.TypeArrayLong); } /** <inheritdoc /> */ public long[] ReadLongArray() { return Read(BinaryUtils.ReadLongArray, BinaryUtils.TypeArrayLong); } /** <inheritdoc /> */ public float ReadFloat(string fieldName) { return ReadField(fieldName, ReadFloat, BinaryUtils.TypeFloat); } /** <inheritdoc /> */ public float ReadFloat() { return Stream.ReadFloat(); } /** <inheritdoc /> */ public float[] ReadFloatArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadFloatArray, BinaryUtils.TypeArrayFloat); } /** <inheritdoc /> */ public float[] ReadFloatArray() { return Read(BinaryUtils.ReadFloatArray, BinaryUtils.TypeArrayFloat); } /** <inheritdoc /> */ public double ReadDouble(string fieldName) { return ReadField(fieldName, ReadDouble, BinaryUtils.TypeDouble); } /** <inheritdoc /> */ public double ReadDouble() { return Stream.ReadDouble(); } /** <inheritdoc /> */ public double[] ReadDoubleArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadDoubleArray, BinaryUtils.TypeArrayDouble); } /** <inheritdoc /> */ public double[] ReadDoubleArray() { return Read(BinaryUtils.ReadDoubleArray, BinaryUtils.TypeArrayDouble); } /** <inheritdoc /> */ public decimal? ReadDecimal(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadDecimal, BinaryUtils.TypeDecimal); } /** <inheritdoc /> */ public decimal? ReadDecimal() { return Read(BinaryUtils.ReadDecimal, BinaryUtils.TypeDecimal); } /** <inheritdoc /> */ public decimal?[] ReadDecimalArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadDecimalArray, BinaryUtils.TypeArrayDecimal); } /** <inheritdoc /> */ public decimal?[] ReadDecimalArray() { return Read(BinaryUtils.ReadDecimalArray, BinaryUtils.TypeArrayDecimal); } /** <inheritdoc /> */ public DateTime? ReadTimestamp(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadTimestamp, BinaryUtils.TypeTimestamp); } /** <inheritdoc /> */ public DateTime? ReadTimestamp() { return Read(BinaryUtils.ReadTimestamp, BinaryUtils.TypeTimestamp); } /** <inheritdoc /> */ public DateTime?[] ReadTimestampArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadTimestampArray, BinaryUtils.TypeArrayTimestamp); } /** <inheritdoc /> */ public DateTime?[] ReadTimestampArray() { return Read(BinaryUtils.ReadTimestampArray, BinaryUtils.TypeArrayTimestamp); } /** <inheritdoc /> */ public string ReadString(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadString, BinaryUtils.TypeString); } /** <inheritdoc /> */ public string ReadString() { return Read(BinaryUtils.ReadString, BinaryUtils.TypeString); } /** <inheritdoc /> */ public string[] ReadStringArray(string fieldName) { return ReadField(fieldName, r => BinaryUtils.ReadArray<string>(r, false), BinaryUtils.TypeArrayString); } /** <inheritdoc /> */ public string[] ReadStringArray() { return Read(r => BinaryUtils.ReadArray<string>(r, false), BinaryUtils.TypeArrayString); } /** <inheritdoc /> */ public Guid? ReadGuid(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadGuid, BinaryUtils.TypeGuid); } /** <inheritdoc /> */ public Guid? ReadGuid() { return Read(BinaryUtils.ReadGuid, BinaryUtils.TypeGuid); } /** <inheritdoc /> */ public Guid?[] ReadGuidArray(string fieldName) { return ReadField(fieldName, r => BinaryUtils.ReadArray<Guid?>(r, false), BinaryUtils.TypeArrayGuid); } /** <inheritdoc /> */ public Guid?[] ReadGuidArray() { return Read(r => BinaryUtils.ReadArray<Guid?>(r, false), BinaryUtils.TypeArrayGuid); } /** <inheritdoc /> */ public T ReadEnum<T>(string fieldName) { return SeekField(fieldName) ? ReadEnum<T>() : default(T); } /** <inheritdoc /> */ public T ReadEnum<T>() { var hdr = ReadByte(); switch (hdr) { case BinaryUtils.HdrNull: return default(T); case BinaryUtils.TypeEnum: // Never read enums in binary mode when reading a field (we do not support half-binary objects) return ReadEnum0<T>(this, false); case BinaryUtils.HdrFull: // Unregistered enum written as serializable Stream.Seek(-1, SeekOrigin.Current); return ReadObject<T>(); default: throw new BinaryObjectException( string.Format("Invalid header on enum deserialization. Expected: {0} or {1} but was: {2}", BinaryUtils.TypeEnum, BinaryUtils.HdrFull, hdr)); } } /** <inheritdoc /> */ public T[] ReadEnumArray<T>(string fieldName) { return ReadField(fieldName, r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArrayEnum); } /** <inheritdoc /> */ public T[] ReadEnumArray<T>() { return Read(r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArrayEnum); } /** <inheritdoc /> */ public T ReadObject<T>(string fieldName) { if (_curRaw) throw new BinaryObjectException("Cannot read named fields after raw data is read."); if (SeekField(fieldName)) return Deserialize<T>(); return default(T); } /** <inheritdoc /> */ public T ReadObject<T>() { return Deserialize<T>(); } /** <inheritdoc /> */ public T[] ReadArray<T>(string fieldName) { return ReadField(fieldName, r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArray); } /** <inheritdoc /> */ public T[] ReadArray<T>() { return Read(r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArray); } /** <inheritdoc /> */ public ICollection ReadCollection(string fieldName) { return ReadCollection(fieldName, null, null); } /** <inheritdoc /> */ public ICollection ReadCollection() { return ReadCollection(null, null); } /** <inheritdoc /> */ public ICollection ReadCollection(string fieldName, Func<int, ICollection> factory, Action<ICollection, object> adder) { return ReadField(fieldName, r => BinaryUtils.ReadCollection(r, factory, adder), BinaryUtils.TypeCollection); } /** <inheritdoc /> */ public ICollection ReadCollection(Func<int, ICollection> factory, Action<ICollection, object> adder) { return Read(r => BinaryUtils.ReadCollection(r, factory, adder), BinaryUtils.TypeCollection); } /** <inheritdoc /> */ public IDictionary ReadDictionary(string fieldName) { return ReadDictionary(fieldName, null); } /** <inheritdoc /> */ public IDictionary ReadDictionary() { return ReadDictionary((Func<int, IDictionary>) null); } /** <inheritdoc /> */ public IDictionary ReadDictionary(string fieldName, Func<int, IDictionary> factory) { return ReadField(fieldName, r => BinaryUtils.ReadDictionary(r, factory), BinaryUtils.TypeDictionary); } /** <inheritdoc /> */ public IDictionary ReadDictionary(Func<int, IDictionary> factory) { return Read(r => BinaryUtils.ReadDictionary(r, factory), BinaryUtils.TypeDictionary); } /// <summary> /// Enable detach mode for the next object read. /// </summary> public BinaryReader DetachNext() { _detach = true; return this; } /// <summary> /// Deserialize object. /// </summary> /// <returns>Deserialized object.</returns> public T Deserialize<T>() { T res; // ReSharper disable once CompareNonConstrainedGenericWithNull if (!TryDeserialize(out res) && default(T) != null) throw new BinaryObjectException(string.Format("Invalid data on deserialization. " + "Expected: '{0}' But was: null", typeof (T))); return res; } /// <summary> /// Deserialize object. /// </summary> /// <returns>Deserialized object.</returns> public bool TryDeserialize<T>(out T res) { int pos = Stream.Position; byte hdr = Stream.ReadByte(); var doDetach = _detach; // save detach flag into a var and reset so it does not go deeper _detach = false; switch (hdr) { case BinaryUtils.HdrNull: res = default(T); return false; case BinaryUtils.HdrHnd: res = ReadHandleObject<T>(pos); return true; case BinaryUtils.HdrFull: res = ReadFullObject<T>(pos); return true; case BinaryUtils.TypeBinary: res = ReadBinaryObject<T>(doDetach); return true; case BinaryUtils.TypeEnum: res = ReadEnum0<T>(this, _mode != BinaryMode.Deserialize); return true; } if (BinarySystemHandlers.TryReadSystemType(hdr, this, out res)) return true; throw new BinaryObjectException("Invalid header on deserialization [pos=" + pos + ", hdr=" + hdr + ']'); } /// <summary> /// Reads the binary object. /// </summary> private T ReadBinaryObject<T>(bool doDetach) { var len = Stream.ReadInt(); var binaryBytesPos = Stream.Position; if (_mode != BinaryMode.Deserialize) return TypeCaster<T>.Cast(ReadAsBinary(binaryBytesPos, len, doDetach)); Stream.Seek(len, SeekOrigin.Current); var offset = Stream.ReadInt(); var retPos = Stream.Position; Stream.Seek(binaryBytesPos + offset, SeekOrigin.Begin); _mode = BinaryMode.KeepBinary; try { return Deserialize<T>(); } finally { _mode = BinaryMode.Deserialize; Stream.Seek(retPos, SeekOrigin.Begin); } } /// <summary> /// Reads the binary object in binary form. /// </summary> private BinaryObject ReadAsBinary(int binaryBytesPos, int dataLen, bool doDetach) { try { Stream.Seek(dataLen + binaryBytesPos, SeekOrigin.Begin); var offs = Stream.ReadInt(); // offset inside data var pos = binaryBytesPos + offs; var hdr = BinaryObjectHeader.Read(Stream, pos); if (!doDetach) return new BinaryObject(_marsh, Stream.GetArray(), pos, hdr); Stream.Seek(pos, SeekOrigin.Begin); return new BinaryObject(_marsh, Stream.ReadByteArray(hdr.Length), 0, hdr); } finally { Stream.Seek(binaryBytesPos + dataLen + 4, SeekOrigin.Begin); } } /// <summary> /// Reads the full object. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "hashCode")] private T ReadFullObject<T>(int pos) { var hdr = BinaryObjectHeader.Read(Stream, pos); // Validate protocol version. BinaryUtils.ValidateProtocolVersion(hdr.Version); try { // Already read this object? object hndObj; if (_hnds != null && _hnds.TryGetValue(pos, out hndObj)) return (T) hndObj; if (hdr.IsUserType && _mode == BinaryMode.ForceBinary) { BinaryObject portObj; if (_detach) { Stream.Seek(pos, SeekOrigin.Begin); portObj = new BinaryObject(_marsh, Stream.ReadByteArray(hdr.Length), 0, hdr); } else portObj = new BinaryObject(_marsh, Stream.GetArray(), pos, hdr); T obj = _builder == null ? TypeCaster<T>.Cast(portObj) : TypeCaster<T>.Cast(_builder.Child(portObj)); AddHandle(pos, obj); return obj; } else { // Find descriptor. var desc = _marsh.GetDescriptor(hdr.IsUserType, hdr.TypeId); // Instantiate object. if (desc.Type == null) { if (desc is BinarySurrogateTypeDescriptor) throw new BinaryObjectException("Unknown type ID: " + hdr.TypeId); throw new BinaryObjectException("No matching type found for object [typeId=" + desc.TypeId + ", typeName=" + desc.TypeName + ']'); } // Preserve old frame. var oldHdr = _curHdr; int oldPos = _curPos; var oldStruct = _curStruct; bool oldRaw = _curRaw; var oldSchema = _curSchema; var oldSchemaMap = _curSchemaMap; // Set new frame. _curHdr = hdr; _curPos = pos; SetCurSchema(desc); _curStruct = new BinaryStructureTracker(desc, desc.ReaderTypeStructure); _curRaw = false; // Read object. Stream.Seek(pos + BinaryObjectHeader.Size, SeekOrigin.Begin); var obj = desc.Serializer.ReadBinary<T>(this, desc.Type, pos); _curStruct.UpdateReaderStructure(); // Restore old frame. _curHdr = oldHdr; _curPos = oldPos; _curStruct = oldStruct; _curRaw = oldRaw; _curSchema = oldSchema; _curSchemaMap = oldSchemaMap; return obj; } } finally { // Advance stream pointer. Stream.Seek(pos + hdr.Length, SeekOrigin.Begin); } } /// <summary> /// Sets the current schema. /// </summary> private void SetCurSchema(IBinaryTypeDescriptor desc) { if (_curHdr.HasSchema) { _curSchema = desc.Schema.Get(_curHdr.SchemaId); if (_curSchema == null) { _curSchema = ReadSchema(); desc.Schema.Add(_curHdr.SchemaId, _curSchema); } } } /// <summary> /// Reads the schema. /// </summary> private int[] ReadSchema() { if (_curHdr.IsCompactFooter) { // Get schema from Java var schema = Marshaller.Ignite.ClusterGroup.GetSchema(_curHdr.TypeId, _curHdr.SchemaId); if (schema == null) throw new BinaryObjectException("Cannot find schema for object with compact footer [" + "typeId=" + _curHdr.TypeId + ", schemaId=" + _curHdr.SchemaId + ']'); return schema; } Stream.Seek(_curPos + _curHdr.SchemaOffset, SeekOrigin.Begin); var count = _curHdr.SchemaFieldCount; var offsetSize = _curHdr.SchemaFieldOffsetSize; var res = new int[count]; for (int i = 0; i < count; i++) { res[i] = Stream.ReadInt(); Stream.Seek(offsetSize, SeekOrigin.Current); } return res; } /// <summary> /// Reads the handle object. /// </summary> private T ReadHandleObject<T>(int pos) { // Get handle position. int hndPos = pos - Stream.ReadInt(); int retPos = Stream.Position; try { object hndObj; if (_builder == null || !_builder.TryGetCachedField(hndPos, out hndObj)) { if (_hnds == null || !_hnds.TryGetValue(hndPos, out hndObj)) { // No such handler, i.e. we trying to deserialize inner object before deserializing outer. Stream.Seek(hndPos, SeekOrigin.Begin); hndObj = Deserialize<T>(); } // Notify builder that we deserialized object on other location. if (_builder != null) _builder.CacheField(hndPos, hndObj); } return (T) hndObj; } finally { // Position stream to correct place. Stream.Seek(retPos, SeekOrigin.Begin); } } /// <summary> /// Adds a handle to the dictionary. /// </summary> /// <param name="pos">Position.</param> /// <param name="obj">Object.</param> internal void AddHandle(int pos, object obj) { if (_hnds == null) _hnds = new BinaryReaderHandleDictionary(pos, obj); else _hnds.Add(pos, obj); } /// <summary> /// Underlying stream. /// </summary> public IBinaryStream Stream { get; private set; } /// <summary> /// Mark current output as raw. /// </summary> private void MarkRaw() { if (!_curRaw) { _curRaw = true; Stream.Seek(_curPos + _curHdr.GetRawOffset(Stream, _curPos), SeekOrigin.Begin); } } /// <summary> /// Seeks the field by name. /// </summary> private bool SeekField(string fieldName) { if (_curRaw) throw new BinaryObjectException("Cannot read named fields after raw data is read."); if (!_curHdr.HasSchema) return false; var actionId = _curStruct.CurStructAction; var fieldId = _curStruct.GetFieldId(fieldName); if (_curSchema == null || actionId >= _curSchema.Length || fieldId != _curSchema[actionId]) { _curSchemaMap = _curSchemaMap ?? BinaryObjectSchemaSerializer.ReadSchema(Stream, _curPos, _curHdr, () => _curSchema).ToDictionary(); _curSchema = null; // read order is different, ignore schema for future reads int pos; if (!_curSchemaMap.TryGetValue(fieldId, out pos)) return false; Stream.Seek(pos + _curPos, SeekOrigin.Begin); } return true; } /// <summary> /// Seeks specified field and invokes provided func. /// </summary> private T ReadField<T>(string fieldName, Func<IBinaryStream, T> readFunc, byte expHdr) { return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T); } /// <summary> /// Seeks specified field and invokes provided func. /// </summary> private T ReadField<T>(string fieldName, Func<BinaryReader, T> readFunc, byte expHdr) { return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T); } /// <summary> /// Seeks specified field and invokes provided func. /// </summary> private T ReadField<T>(string fieldName, Func<T> readFunc, byte expHdr) { return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T); } /// <summary> /// Reads header and invokes specified func if the header is not null. /// </summary> private T Read<T>(Func<BinaryReader, T> readFunc, byte expHdr) { return Read(() => readFunc(this), expHdr); } /// <summary> /// Reads header and invokes specified func if the header is not null. /// </summary> private T Read<T>(Func<IBinaryStream, T> readFunc, byte expHdr) { return Read(() => readFunc(Stream), expHdr); } /// <summary> /// Reads header and invokes specified func if the header is not null. /// </summary> private T Read<T>(Func<T> readFunc, byte expHdr) { var hdr = ReadByte(); if (hdr == BinaryUtils.HdrNull) return default(T); if (hdr == BinaryUtils.HdrHnd) return ReadHandleObject<T>(Stream.Position - 1); if (expHdr != hdr) throw new BinaryObjectException(string.Format("Invalid header on deserialization. " + "Expected: {0} but was: {1}", expHdr, hdr)); return readFunc(); } /// <summary> /// Reads the enum. /// </summary> private static T ReadEnum0<T>(BinaryReader reader, bool keepBinary) { var enumType = reader.ReadInt(); var enumValue = reader.ReadInt(); if (!keepBinary) return BinaryUtils.GetEnumValue<T>(enumValue, enumType, reader.Marshaller); return TypeCaster<T>.Cast(new BinaryEnum(enumType, enumValue, reader.Marshaller)); } } }
// *********************************************************************** // Copyright (c) 2014 Charlie Poole // // 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. // *********************************************************************** #if !SILVERLIGHT && !PORTABLE #region Using Directives using System; using System.IO; using NUnit.TestUtilities; #endregion namespace NUnit.Framework.Assertions { [TestFixture] public class DirectoryAssertTests { private TestDirectory _goodDir1; private TestDirectory _goodDir2; private const string BAD_DIRECTORY = @"\I\hope\this\is\garbage"; [SetUp] public void SetUp() { _goodDir1 = new TestDirectory(); _goodDir2 = new TestDirectory(); Assume.That(_goodDir1.Directory, Is.Not.EqualTo(_goodDir2.Directory), "The two good directories are the same"); Assume.That(BAD_DIRECTORY, Does.Not.Exist, BAD_DIRECTORY + " exists"); } [TearDown] public void TearDown() { if (_goodDir1 != null) _goodDir1.Dispose(); if (_goodDir2 != null) _goodDir2.Dispose(); } #region AreEqual #region Success Tests [Test] public void AreEqualPassesWithDirectoryInfos() { var expected = new DirectoryInfo(_goodDir1.ToString()); var actual = new DirectoryInfo(_goodDir1.ToString()); DirectoryAssert.AreEqual(expected, actual); DirectoryAssert.AreEqual(expected, actual); } #endregion #region Failure Tests [Test] public void AreEqualFailsWithDirectoryInfos() { var expected = _goodDir1.Directory; var actual = _goodDir2.Directory; var expectedMessage = string.Format(" Expected: <{0}>{2} But was: <{1}>{2}", expected.FullName, actual.FullName, Environment.NewLine); var ex = Assert.Throws<AssertionException>(() => DirectoryAssert.AreEqual(expected, actual)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #endregion #region AreNotEqual #region Success Tests [Test] public void AreNotEqualPassesIfExpectedIsNull() { DirectoryAssert.AreNotEqual(_goodDir1.Directory, null); } [Test] public void AreNotEqualPassesIfActualIsNull() { DirectoryAssert.AreNotEqual(null, _goodDir1.Directory); } [Test] public void AreNotEqualPassesWithDirectoryInfos() { var expected = _goodDir1.Directory; var actual = _goodDir2.Directory; DirectoryAssert.AreNotEqual(expected, actual); } #endregion #region Failure Tests [Test] public void AreNotEqualFailsWithDirectoryInfos() { var expected = new DirectoryInfo(_goodDir1.ToString()); var actual = new DirectoryInfo(_goodDir1.ToString()); var expectedMessage = string.Format( " Expected: not equal to <{0}>{2} But was: <{1}>{2}", expected.FullName, actual.FullName, Environment.NewLine ); var ex = Assert.Throws<AssertionException>(() => DirectoryAssert.AreNotEqual(expected, actual)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #endregion #region Exists [Test] public void ExistsPassesWhenDirectoryInfoExists() { DirectoryAssert.Exists(_goodDir1.Directory); } [Test] public void ExistsPassesWhenStringExists() { DirectoryAssert.Exists(_goodDir1.ToString()); } [Test] public void ExistsFailsWhenDirectoryInfoDoesNotExist() { var ex = Assert.Throws<AssertionException>(() => DirectoryAssert.Exists(new DirectoryInfo(BAD_DIRECTORY))); Assert.That(ex.Message, Does.StartWith(" Expected: directory exists")); } [Test] public void ExistsFailsWhenStringDoesNotExist() { var ex = Assert.Throws<AssertionException>(() => DirectoryAssert.Exists(BAD_DIRECTORY)); Assert.That(ex.Message, Does.StartWith(" Expected: directory exists")); } [Test] public void ExistsFailsWhenDirectoryInfoIsNull() { var ex = Assert.Throws<ArgumentNullException>(() => DirectoryAssert.Exists((DirectoryInfo)null)); Assert.That(ex.Message, Does.StartWith("The actual value must be a non-null string or DirectoryInfo")); } [Test] public void ExistsFailsWhenStringIsNull() { var ex = Assert.Throws<ArgumentNullException>(() => DirectoryAssert.Exists((string)null)); Assert.That(ex.Message, Does.StartWith("The actual value must be a non-null string or DirectoryInfo")); } [Test] public void ExistsFailsWhenStringIsEmpty() { var ex = Assert.Throws<ArgumentException>(() => DirectoryAssert.Exists(string.Empty)); Assert.That(ex.Message, Does.StartWith("The actual value cannot be an empty string")); } #endregion #region DoesNotExist [Test] public void DoesNotExistFailsWhenDirectoryInfoExists() { var ex = Assert.Throws<AssertionException>(() => DirectoryAssert.DoesNotExist(_goodDir1.Directory)); Assert.That(ex.Message, Does.StartWith(" Expected: not directory exists")); } [Test] public void DoesNotExistFailsWhenStringExists() { var ex = Assert.Throws<AssertionException>(() => DirectoryAssert.DoesNotExist(_goodDir1.ToString())); Assert.That(ex.Message, Does.StartWith(" Expected: not directory exists")); } [Test] public void DoesNotExistPassesWhenDirectoryInfoDoesNotExist() { DirectoryAssert.DoesNotExist(new DirectoryInfo(BAD_DIRECTORY)); } [Test] public void DoesNotExistPassesWhenStringDoesNotExist() { DirectoryAssert.DoesNotExist(BAD_DIRECTORY); } [Test] public void DoesNotExistFailsWhenDirectoryInfoIsNull() { var ex = Assert.Throws<ArgumentNullException>(() => DirectoryAssert.DoesNotExist((DirectoryInfo)null)); Assert.That(ex.Message, Does.StartWith("The actual value must be a non-null string or DirectoryInfo")); } [Test] public void DoesNotExistFailsWhenStringIsNull() { var ex = Assert.Throws<ArgumentNullException>(() => DirectoryAssert.DoesNotExist((string)null)); Assert.That(ex.Message, Does.StartWith("The actual value must be a non-null string or DirectoryInfo")); } [Test] public void DoesNotExistFailsWhenStringIsEmpty() { var ex = Assert.Throws<ArgumentException>(() => DirectoryAssert.DoesNotExist(string.Empty)); Assert.That(ex.Message, Does.StartWith("The actual value cannot be an empty string")); } [Test] public void EqualsFailsWhenUsed() { var ex = Assert.Throws<InvalidOperationException>(() => DirectoryAssert.Equals(string.Empty, string.Empty)); Assert.That(ex.Message, Does.StartWith("DirectoryAssert.Equals should not be used for Assertions")); } [Test] public void ReferenceEqualsFailsWhenUsed() { var ex = Assert.Throws<InvalidOperationException>(() => DirectoryAssert.ReferenceEquals(string.Empty, string.Empty)); Assert.That(ex.Message, Does.StartWith("DirectoryAssert.ReferenceEquals should not be used for Assertions")); } #endregion } } #endif
using Microsoft.AspNet.Http; 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.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.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; //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 AspNet5.Mvc6.StarterWeb { 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(HttpRequest 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.Query[paramName])) { return request.Query[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 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 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 false; // 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 } }
/****************************************************************************** * $Id$ * * Project: GDAL/OGR ArcGIS Datasource * Purpose: Workspace Factory Implementation for ArcGIS * Author: Ragi Yaser Burhum, [email protected] * ****************************************************************************** * Copyright (c) 2012, Ragi Yaser Burhum * * 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 System.Runtime.InteropServices; using Microsoft.Win32; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.ADF; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geodatabase; using System.Windows.Forms; using OSGeo.OGR; namespace GDAL.OGRPlugin { [Guid("36eb2528-077b-4d83-a73e-2d83e284c000")] [ClassInterface(ClassInterfaceType.None)] [ProgId("OGRPlugin.OGRWorkspaceFactory")] [ComVisible(true)] public sealed class OGRWorkspaceFactory : IPlugInWorkspaceFactoryHelper { #region "Component Category Registration" [ComRegisterFunction()] public static void RegisterFunction(String regKey) { PlugInWorkspaceFactoryHelpers.Register(regKey); } [ComUnregisterFunction()] public static void UnregisterFunction(String regKey) { PlugInWorkspaceFactoryHelpers.Unregister(regKey); } #endregion #region class constructor public OGRWorkspaceFactory() { System.Environment.SetEnvironmentVariable("GDAL_DATA", System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\gdal-data"); } #endregion #region IPlugInWorkspaceFactoryHelper Members public string get_DatasetDescription(esriDatasetType DatasetType) { switch (DatasetType) { case esriDatasetType.esriDTTable: return "OGR Table"; case esriDatasetType.esriDTFeatureClass: return "OGR Feature Class"; case esriDatasetType.esriDTFeatureDataset: return "OGR Feature Dataset"; default: return null; } } public string get_WorkspaceDescription(bool plural) { return "OGR Workspace"; } public bool CanSupportSQL { get { return true; } } public string DataSourceName { /* * This is how the prog id will be found by the PluginWorkspaceHelper * it will expect a string in the form of * * ProgID = esriGeoDatabase.<DataSourceName>WorkspaceFactory * * so in our case it will be: * * ProgID = esriGeoDatabase.OGRPluginWorkspaceFactory * * see: * http://help.arcgis.com/en/sdk/10.0/arcobjects_net/conceptualhelp/index.html#/Adding_a_plug_in_data_source_programmatically/000100000305000000/ */ get { return "OGRPlugin"; } } public bool ContainsWorkspace(string parentDirectory, IFileNames fileNames) { // TODO: Look into openshared to see if we can optimize it if (this.IsWorkspace(parentDirectory)) return true; else if (fileNames == null) return false; //isWorkspace is false and no filenames // isWorkspace is false, but at least we can try other files if (!System.IO.Directory.Exists(parentDirectory)) return false; string sFileName; while ((sFileName = fileNames.Next()) != null) { if (fileNames.IsDirectory()) continue; if (this.IsWorkspace(parentDirectory + "\\" + sFileName)) return true; } return false; } public UID WorkspaceFactoryTypeID { get { UID wkspFTypeID = new UIDClass(); wkspFTypeID.Value = "{6381befb-b2bc-4715-a836-8995112333de}"; //proxy return wkspFTypeID; } } public bool IsWorkspace(string wksString) { OSGeo.OGR.DataSource ds = null; try { ds = OSGeo.OGR.Ogr.OpenShared(wksString, 0); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } if (ds != null) return true; else return false; } public esriWorkspaceType WorkspaceType { //TODO: WorkspaceType in OGR can be remote - test later what happens when we change this get { return esriWorkspaceType.esriFileSystemWorkspace; } } public IPlugInWorkspaceHelper OpenWorkspace(string wksString) { OSGeo.OGR.DataSource ds = OSGeo.OGR.Ogr.OpenShared(wksString, 0); if (ds != null) { OGRWorkspace openWksp = new OGRWorkspace(ds, wksString); return (IPlugInWorkspaceHelper)openWksp; } return null; } public string GetWorkspaceString(string parentDirectory, IFileNames fileNames) { if (fileNames == null) { //could be a database connection if (this.IsWorkspace(parentDirectory)) return parentDirectory; return null; } // GetWorkspaceString - claim and remove file names from list. What a silly design! string sFileName; bool fileFound = false; while ((sFileName = fileNames.Next()) != null) { if (this.IsWorkspace(sFileName)) { fileFound = true; fileNames.Remove(); } } if (fileFound) return parentDirectory; else return null; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using UIKit; using PageUIStatusBarAnimation = Xamarin.Forms.PlatformConfiguration.iOSSpecific.UIStatusBarAnimation; using Xamarin.Forms.PlatformConfiguration.iOSSpecific; namespace Xamarin.Forms.Platform.iOS { public class PageRenderer : UIViewController, IVisualElementRenderer, IEffectControlProvider { bool _appeared; bool _disposed; EventTracker _events; VisualElementPackager _packager; VisualElementTracker _tracker; IPageController PageController => Element as IPageController; public PageRenderer() { } void IEffectControlProvider.RegisterEffect(Effect effect) { VisualElementRenderer<VisualElement>.RegisterEffect(effect, View); } public VisualElement Element { get; private set; } public event EventHandler<VisualElementChangedEventArgs> ElementChanged; public SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint) { return NativeView.GetSizeRequest(widthConstraint, heightConstraint); } public UIView NativeView { get { return _disposed ? null : View; } } public void SetElement(VisualElement element) { VisualElement oldElement = Element; Element = element; UpdateTitle(); OnElementChanged(new VisualElementChangedEventArgs(oldElement, element)); if (Element != null && !string.IsNullOrEmpty(Element.AutomationId)) SetAutomationId(Element.AutomationId); if (element != null) element.SendViewInitialized(NativeView); EffectUtilities.RegisterEffectControlProvider(this, oldElement, element); } public void SetElementSize(Size size) { Element.Layout(new Rectangle(Element.X, Element.Y, size.Width, size.Height)); } public UIViewController ViewController => _disposed ? null : this; public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); if (_appeared || _disposed) return; _appeared = true; PageController.SendAppearing(); UpdateStatusBarPrefersHidden(); } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); if (!_appeared || _disposed) return; _appeared = false; PageController.SendDisappearing(); } public override void ViewDidLoad() { base.ViewDidLoad(); var uiTapGestureRecognizer = new UITapGestureRecognizer(a => View.EndEditing(true)); uiTapGestureRecognizer.ShouldRecognizeSimultaneously = (recognizer, gestureRecognizer) => true; uiTapGestureRecognizer.ShouldReceiveTouch = OnShouldReceiveTouch; uiTapGestureRecognizer.DelaysTouchesBegan = uiTapGestureRecognizer.DelaysTouchesEnded = uiTapGestureRecognizer.CancelsTouchesInView = false; View.AddGestureRecognizer(uiTapGestureRecognizer); UpdateBackground(); _packager = new VisualElementPackager(this); _packager.Load(); Element.PropertyChanged += OnHandlePropertyChanged; _tracker = new VisualElementTracker(this); _events = new EventTracker(this); _events.LoadEvents(View); Element.SendViewInitialized(View); } public override void ViewWillDisappear(bool animated) { base.ViewWillDisappear(animated); View.Window?.EndEditing(true); } protected override void Dispose(bool disposing) { if (disposing && !_disposed) { Element.PropertyChanged -= OnHandlePropertyChanged; Platform.SetRenderer(Element, null); if (_appeared) PageController.SendDisappearing(); _appeared = false; if (_events != null) { _events.Dispose(); _events = null; } if (_packager != null) { _packager.Dispose(); _packager = null; } if (_tracker != null) { _tracker.Dispose(); _tracker = null; } Element = null; _disposed = true; } base.Dispose(disposing); } protected virtual void OnElementChanged(VisualElementChangedEventArgs e) { ElementChanged?.Invoke(this, e); } protected virtual void SetAutomationId(string id) { if (NativeView != null) NativeView.AccessibilityIdentifier = id; } void OnHandlePropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName) UpdateBackground(); else if (e.PropertyName == Page.BackgroundImageProperty.PropertyName) UpdateBackground(); else if (e.PropertyName == Page.TitleProperty.PropertyName) UpdateTitle(); else if (e.PropertyName == PlatformConfiguration.iOSSpecific.Page.PrefersStatusBarHiddenProperty.PropertyName) UpdateStatusBarPrefersHidden(); } public override UIKit.UIStatusBarAnimation PreferredStatusBarUpdateAnimation { get { var animation = ((Page)Element).OnThisPlatform().PreferredStatusBarUpdateAnimation(); switch (animation) { case (PageUIStatusBarAnimation.Fade): return UIKit.UIStatusBarAnimation.Fade; case (PageUIStatusBarAnimation.Slide): return UIKit.UIStatusBarAnimation.Slide; case (PageUIStatusBarAnimation.None): default: return UIKit.UIStatusBarAnimation.None; } } } void UpdateStatusBarPrefersHidden() { var animation = ((Page)Element).OnThisPlatform().PreferredStatusBarUpdateAnimation(); if (animation == PageUIStatusBarAnimation.Fade || animation == PageUIStatusBarAnimation.Slide) UIView.Animate(0.25, () => SetNeedsStatusBarAppearanceUpdate()); else SetNeedsStatusBarAppearanceUpdate(); View.SetNeedsLayout(); } bool OnShouldReceiveTouch(UIGestureRecognizer recognizer, UITouch touch) { foreach (UIView v in ViewAndSuperviewsOfView(touch.View)) { if (v is UITableView || v is UITableViewCell || v.CanBecomeFirstResponder) return false; } return true; } public override bool PrefersStatusBarHidden() { var mode = ((Page)Element).OnThisPlatform().PrefersStatusBarHidden(); switch (mode) { case (StatusBarHiddenMode.True): return true; case (StatusBarHiddenMode.False): return false; case (StatusBarHiddenMode.Default): default: { if (Device.info.CurrentOrientation.IsLandscape()) return true; else return false; } } } void UpdateBackground() { string bgImage = ((Page)Element).BackgroundImage; if (!string.IsNullOrEmpty(bgImage)) { View.BackgroundColor = UIColor.FromPatternImage(UIImage.FromBundle(bgImage)); return; } Color bgColor = Element.BackgroundColor; if (bgColor.IsDefault) View.BackgroundColor = UIColor.White; else View.BackgroundColor = bgColor.ToUIColor(); } void UpdateTitle() { if (!string.IsNullOrWhiteSpace(((Page)Element).Title)) Title = ((Page)Element).Title; } IEnumerable<UIView> ViewAndSuperviewsOfView(UIView view) { while (view != null) { yield return view; view = view.Superview; } } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ #region license /* DirectShowLib - Provide access to DirectShow interfaces via .NET Copyright (C) 2006 http://sourceforge.net/projects/directshownet/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #endregion using System; using System.Drawing; using System.Runtime.InteropServices; namespace DirectShowLib.Dvd { #region Declarations #if ALLOW_UNTESTED_INTERFACES /// <summary> /// From DVD_ATR /// </summary> [StructLayout(LayoutKind.Sequential)] public struct DvdAtr { public int ulCAT; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.I1, SizeConst=768)] public byte[] registers; } /// <summary> /// From typedef BYTE /// </summary> [StructLayout(LayoutKind.Sequential)] public struct DvdVideoATR { [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.I1, SizeConst=2)] public byte[] attributes; } /// <summary> /// From typedef BYTE /// </summary> [StructLayout(LayoutKind.Sequential)] public struct DvdAudioATR { [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.I1, SizeConst=8)] public byte[] attributes; } /// <summary> /// From typedef BYTE /// </summary> [StructLayout(LayoutKind.Sequential)] public struct DvdSubpictureATR { [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.I1, SizeConst=6)] public byte[] attributes; } /// <summary> /// From DVD_PLAYBACK_LOCATION /// </summary> [StructLayout(LayoutKind.Sequential)] public struct DvdPlaybackLocation { public int TitleNum; public int ChapterNum; public int TimeCode; } #endif /// <summary> /// From DVD_DOMAIN /// </summary> public enum DvdDomain { FirstPlay = 1, VideoManagerMenu, VideoTitleSetMenu, Title, Stop } /// <summary> /// From DVD_MENU_ID /// </summary> public enum DvdMenuId { Title = 2, Root = 3, Subpicture = 4, Audio = 5, Angle = 6, Chapter = 7 } /// <summary> /// From DVD_DISC_SIDE /// </summary> public enum DvdDiscSide { SideA = 1, SideB = 2 } /// <summary> /// From DVD_PREFERRED_DISPLAY_MODE /// </summary> public enum DvdPreferredDisplayMode { DisplayContentDefault = 0, Display16x9 = 1, Display4x3PanScanPreferred = 2, Display4x3LetterBoxPreferred = 3 } /// <summary> /// From DVD_FRAMERATE /// </summary> public enum DvdFrameRate { FPS25 = 1, FPS30NonDrop = 3 } /// <summary> /// From DVD_TIMECODE_FLAGS /// </summary> [Flags] public enum DvdTimeCodeFlags { None = 0, FPS25 = 0x00000001, FPS30 = 0x00000002, DropFrame = 0x00000004, Interpolated = 0x00000008, } /// <summary> /// From VALID_UOP_FLAG /// </summary> [Flags] public enum ValidUOPFlag { None = 0, PlayTitleOrAtTime = 0x00000001, PlayChapter = 0x00000002, PlayTitle = 0x00000004, Stop = 0x00000008, ReturnFromSubMenu = 0x00000010, PlayChapterOrAtTime = 0x00000020, PlayPrevOrReplay_Chapter = 0x00000040, PlayNextChapter = 0x00000080, PlayForwards = 0x00000100, PlayBackwards = 0x00000200, ShowMenuTitle = 0x00000400, ShowMenuRoot = 0x00000800, ShowMenuSubPic = 0x00001000, ShowMenuAudio = 0x00002000, ShowMenuAngle = 0x00004000, ShowMenuChapter = 0x00008000, Resume = 0x00010000, SelectOrActivateButton = 0x00020000, StillOff = 0x00040000, PauseOn = 0x00080000, SelectAudioStream = 0x00100000, SelectSubPicStream = 0x00200000, SelectAngle = 0x00400000, SelectKaraokeAudioPresentationMode = 0x00800000, SelectVideoModePreference = 0x01000000 } /// <summary> /// From DVD_CMD_FLAGS /// </summary> [Flags] public enum DvdCmdFlags { None = 0x00000000, Flush = 0x00000001, SendEvents = 0x00000002, Block = 0x00000004, StartWhenRendered = 0x00000008, EndAfterRendered = 0x00000010, } /// <summary> /// From DVD_OPTION_FLAG /// </summary> public enum DvdOptionFlag { ResetOnStop = 1, NotifyParentalLevelChange = 2, HMSFTimeCodeEvents = 3, AudioDuringFFwdRew = 4 } /// <summary> /// From DVD_RELATIVE_BUTTON /// </summary> public enum DvdRelativeButton { Upper = 1, Lower = 2, Left = 3, Right = 4 } /// <summary> /// From DVD_PARENTAL_LEVEL /// </summary> [Flags] public enum DvdParentalLevel { None = 0, Level8 = 0x8000, Level7 = 0x4000, Level6 = 0x2000, Level5 = 0x1000, Level4 = 0x0800, Level3 = 0x0400, Level2 = 0x0200, Level1 = 0x0100 } /// <summary> /// From DVD_AUDIO_LANG_EXT /// </summary> public enum DvdAudioLangExt { NotSpecified = 0, Captions = 1, VisuallyImpaired = 2, DirectorComments1 = 3, DirectorComments2 = 4, } /// <summary> /// From DVD_SUBPICTURE_LANG_EXT /// </summary> public enum DvdSubPictureLangExt { NotSpecified = 0, CaptionNormal = 1, CaptionBig = 2, CaptionChildren = 3, CCNormal = 5, CCBig = 6, CCChildren = 7, Forced = 9, DirectorCommentsNormal = 13, DirectorCommentsBig = 14, DirectorCommentsChildren = 15, } /// <summary> /// From DVD_AUDIO_APPMODE /// </summary> public enum DvdAudioAppMode { None = 0, Karaoke = 1, Surround = 2, Other = 3, } /// <summary> /// From DVD_AUDIO_FORMAT /// </summary> public enum DvdAudioFormat { AC3 = 0, MPEG1 = 1, MPEG1_DRC = 2, MPEG2 = 3, MPEG2_DRC = 4, LPCM = 5, DTS = 6, SDDS = 7, Other = 8 } /// <summary> /// From DVD_KARAOKE_DOWNMIX /// </summary> [Flags] public enum DvdKaraokeDownMix { None = 0, Mix_0to0 = 0x0001, Mix_1to0 = 0x0002, Mix_2to0 = 0x0004, Mix_3to0 = 0x0008, Mix_4to0 = 0x0010, Mix_Lto0 = 0x0020, Mix_Rto0 = 0x0040, Mix_0to1 = 0x0100, Mix_1to1 = 0x0200, Mix_2to1 = 0x0400, Mix_3to1 = 0x0800, Mix_4to1 = 0x1000, Mix_Lto1 = 0x2000, Mix_Rto1 = 0x4000, } /// <summary> /// From DVD_KARAOKE_CONTENTS /// </summary> [Flags] public enum DvdKaraokeContents : short { None = 0, GuideVocal1 = 0x0001, GuideVocal2 = 0x0002, GuideMelody1 = 0x0004, GuideMelody2 = 0x0008, GuideMelodyA = 0x0010, GuideMelodyB = 0x0020, SoundEffectA = 0x0040, SoundEffectB = 0x0080 } /// <summary> /// From DVD_KARAOKE_ASSIGNMENT /// </summary> public enum DvdKaraokeAssignment { reserved0 = 0, reserved1 = 1, LR = 2, LRM = 3, LR1 = 4, LRM1 = 5, LR12 = 6, LRM12 = 7 } /// <summary> /// From DVD_VIDEO_COMPRESSION /// </summary> public enum DvdVideoCompression { Other = 0, Mpeg1 = 1, Mpeg2 = 2 } /// <summary> /// From DVD_SUBPICTURE_TYPE /// </summary> public enum DvdSubPictureType { NotSpecified = 0, Language = 1, Other = 2, } /// <summary> /// From DVD_SUBPICTURE_CODING /// </summary> public enum DvdSubPictureCoding { RunLength = 0, Extended = 1, Other = 2, } /// <summary> /// From DVD_TITLE_APPMODE /// </summary> public enum DvdTitleAppMode { NotSpecified = 0, Karaoke = 1, Other = 3, } /// <summary> /// From DVD_TextStringType /// </summary> public enum DvdTextStringType { DVD_Struct_Volume = 0x01, DVD_Struct_Title = 0x02, DVD_Struct_ParentalID = 0x03, DVD_Struct_PartOfTitle = 0x04, DVD_Struct_Cell = 0x05, DVD_Stream_Audio = 0x10, DVD_Stream_Subpicture = 0x11, DVD_Stream_Angle = 0x12, DVD_Channel_Audio = 0x20, DVD_General_Name = 0x30, DVD_General_Comments = 0x31, DVD_Title_Series = 0x38, DVD_Title_Movie = 0x39, DVD_Title_Video = 0x3a, DVD_Title_Album = 0x3b, DVD_Title_Song = 0x3c, DVD_Title_Other = 0x3f, DVD_Title_Sub_Series = 0x40, DVD_Title_Sub_Movie = 0x41, DVD_Title_Sub_Video = 0x42, DVD_Title_Sub_Album = 0x43, DVD_Title_Sub_Song = 0x44, DVD_Title_Sub_Other = 0x47, DVD_Title_Orig_Series = 0x48, DVD_Title_Orig_Movie = 0x49, DVD_Title_Orig_Video = 0x4a, DVD_Title_Orig_Album = 0x4b, DVD_Title_Orig_Song = 0x4c, DVD_Title_Orig_Other = 0x4f, DVD_Other_Scene = 0x50, DVD_Other_Cut = 0x51, DVD_Other_Take = 0x52, } /// <summary> /// From DVD_TextCharSet /// </summary> public enum DvdTextCharSet { CharSet_Unicode = 0, CharSet_ISO646 = 1, CharSet_JIS_Roman_Kanji = 2, CharSet_ISO8859_1 = 3, CharSet_ShiftJIS_Kanji_Roman_Katakana = 4 } /// <summary> /// From DVD_AUDIO_CAPS_* defines /// </summary> [Flags] public enum DvdAudioCaps { None = 0, AC3 = 0x00000001, MPEG2 = 0x00000002, LPCM = 0x00000004, DTS = 0x00000008, SDDS = 0x00000010, } /// <summary> /// From AM_DVD_GRAPH_FLAGS /// </summary> [Flags] public enum AMDvdGraphFlags { None = 0, HWDecPrefer = 0x01, HWDecOnly = 0x02, SWDecPrefer = 0x04, SWDecOnly = 0x08, NoVPE = 0x100, VMR9Only = 0x800 } /// <summary> /// From AM_DVD_STREAM_FLAGS /// </summary> [Flags] public enum AMDvdStreamFlags { None = 0x00, Video = 0x01, Audio = 0x02, SubPic = 0x04 } [Flags] public enum AMOverlayNotifyFlags { None = 0, VisibleChange = 0x00000001, SourceChange = 0x00000002, DestChange = 0x00000004 } /// <summary> /// From GPRMARRAY /// </summary> [StructLayout(LayoutKind.Sequential)] public struct GPRMArray { [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.I2, SizeConst=16)] public short[] registers; } /// <summary> /// From SPRMARRAY /// </summary> [StructLayout(LayoutKind.Sequential)] public struct SPRMArray { [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.I2, SizeConst=24)] public short[] registers; } /// <summary> /// From DVD_HMSF_TIMECODE /// </summary> [StructLayout(LayoutKind.Sequential, Pack=1)] public class DvdHMSFTimeCode { public byte bHours; public byte bMinutes; public byte bSeconds; public byte bFrames; } /// <summary> /// From DVD_PLAYBACK_LOCATION2 /// </summary> [StructLayout(LayoutKind.Sequential, Pack=1)] public struct DvdPlaybackLocation2 { public int TitleNum; public int ChapterNum; public DvdHMSFTimeCode TimeCode; public int TimeCodeFlags; } /// <summary> /// From DVD_AudioAttributes /// </summary> [StructLayout(LayoutKind.Sequential)] public struct DvdAudioAttributes { public DvdAudioAppMode AppMode; public byte AppModeData; public DvdAudioFormat AudioFormat; public int Language; public DvdAudioLangExt LanguageExtension; [MarshalAs(UnmanagedType.Bool)] public bool fHasMultichannelInfo; public int dwFrequency; public byte bQuantization; public byte bNumberOfChannels; public int dwReserved1; public int dwReserved2; } /// <summary> /// From DVD_MUA_MixingInfo /// </summary> [StructLayout(LayoutKind.Sequential)] public struct DvdMUAMixingInfo { [MarshalAs(UnmanagedType.Bool)] public bool fMixTo0; [MarshalAs(UnmanagedType.Bool)] public bool fMixTo1; [MarshalAs(UnmanagedType.Bool)] public bool fMix0InPhase; [MarshalAs(UnmanagedType.Bool)] public bool fMix1InPhase; public int dwSpeakerPosition; } /// <summary> /// From DVD_MUA_Coeff /// </summary> [StructLayout(LayoutKind.Sequential)] public struct DvdMUACoeff { public double log2_alpha; public double log2_beta; } /// <summary> /// From DVD_MultichannelAudioAttributes /// </summary> [StructLayout(LayoutKind.Sequential)] public struct DvdMultichannelAudioAttributes { [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.Struct, SizeConst=8)] public DvdMUAMixingInfo[] Info; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.Struct, SizeConst=8)] public DvdMUACoeff[] Coeff; } /// <summary> /// From DVD_KaraokeAttributes /// </summary> [StructLayout(LayoutKind.Sequential, Pack=1, Size=32)] public class DvdKaraokeAttributes { public byte bVersion; public bool fMasterOfCeremoniesInGuideVocal1; public bool fDuet; public DvdKaraokeAssignment ChannelAssignment; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.I2, SizeConst=8)] public DvdKaraokeContents[] wChannelContents; } /// <summary> /// From DVD_VideoAttributes /// </summary> [StructLayout(LayoutKind.Sequential)] public struct DvdVideoAttributes { [MarshalAs(UnmanagedType.Bool)] public bool panscanPermitted; [MarshalAs(UnmanagedType.Bool)] public bool letterboxPermitted; public int aspectX; public int aspectY; public int frameRate; public int frameHeight; public DvdVideoCompression compression; [MarshalAs(UnmanagedType.Bool)] public bool line21Field1InGOP; [MarshalAs(UnmanagedType.Bool)] public bool line21Field2InGOP; public int sourceResolutionX; public int sourceResolutionY; [MarshalAs(UnmanagedType.Bool)] public bool isSourceLetterboxed; [MarshalAs(UnmanagedType.Bool)] public bool isFilmMode; } /// <summary> /// From DVD_SubpictureAttributes /// </summary> [StructLayout(LayoutKind.Sequential)] public struct DvdSubpictureAttributes { public DvdSubPictureType Type; public DvdSubPictureCoding CodingMode; public int Language; public DvdSubPictureLangExt LanguageExtension; } /// <summary> /// From DVD_TitleAttributes /// </summary> [StructLayout(LayoutKind.Sequential)] public class DvdTitleAttributes { public DvdTitleAppMode AppMode; public DvdVideoAttributes VideoAttributes; public int ulNumberOfAudioStreams; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.Struct, SizeConst=8)] public DvdAudioAttributes[] AudioAttributes; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.Struct, SizeConst=8)] public DvdMultichannelAudioAttributes[] MultichannelAudioAttributes; public int ulNumberOfSubpictureStreams; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.Struct, SizeConst=32)] public DvdSubpictureAttributes[] SubpictureAttributes; } /// <summary> /// From DVD_MenuAttributes /// </summary> [StructLayout(LayoutKind.Sequential)] public struct DvdMenuAttributes { [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.Bool, SizeConst=8)] public bool[] fCompatibleRegion; public DvdVideoAttributes VideoAttributes; [MarshalAs(UnmanagedType.Bool)] public bool fAudioPresent; public DvdAudioAttributes AudioAttributes; [MarshalAs(UnmanagedType.Bool)] public bool fSubpicturePresent; public DvdSubpictureAttributes SubpictureAttributes; } /// <summary> /// From DVD_DECODER_CAPS /// </summary> [StructLayout(LayoutKind.Sequential)] public struct DvdDecoderCaps { public int dwSize; public DvdAudioCaps dwAudioCaps; public double dFwdMaxRateVideo; public double dFwdMaxRateAudio; public double dFwdMaxRateSP; public double dBwdMaxRateVideo; public double dBwdMaxRateAudio; public double dBwdMaxRateSP; public int dwRes1; public int dwRes2; public int dwRes3; public int dwRes4; } /// <summary> /// From AM_DVD_RENDERSTATUS /// </summary> [StructLayout(LayoutKind.Sequential)] public struct AMDvdRenderStatus { public int hrVPEStatus; [MarshalAs(UnmanagedType.Bool)] public bool bDvdVolInvalid; [MarshalAs(UnmanagedType.Bool)] public bool bDvdVolUnknown; [MarshalAs(UnmanagedType.Bool)] public bool bNoLine21In; [MarshalAs(UnmanagedType.Bool)] public bool bNoLine21Out; public int iNumStreams; public int iNumStreamsFailed; public AMDvdStreamFlags dwFailedStreamsFlag; } #endregion #region Interfaces #if ALLOW_UNTESTED_INTERFACES [ComImport, Guid("A70EFE61-E2A3-11d0-A9BE-00AA0061BE93"), Obsolete("The IDvdControl interface is deprecated. Use IDvdControl2 instead.", false), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDvdControl { [PreserveSig] int TitlePlay([In] int ulTitle); [PreserveSig] int ChapterPlay( [In] int ulTitle, [In] int ulChapter ); [PreserveSig] int TimePlay( [In] int ulTitle, [In] int bcdTime ); [PreserveSig] int StopForResume(); [PreserveSig] int GoUp(); [PreserveSig] int TimeSearch([In] int bcdTime); [PreserveSig] int ChapterSearch([In] int ulChapter); [PreserveSig] int PrevPGSearch(); [PreserveSig] int TopPGSearch(); [PreserveSig] int NextPGSearch(); [PreserveSig] int ForwardScan([In] double dwSpeed); [PreserveSig] int BackwardScan([In] double dwSpeed); [PreserveSig] int MenuCall([In] DvdMenuId MenuID); [PreserveSig] int Resume(); [PreserveSig] int UpperButtonSelect(); [PreserveSig] int LowerButtonSelect(); [PreserveSig] int LeftButtonSelect(); [PreserveSig] int RightButtonSelect(); [PreserveSig] int ButtonActivate(); [PreserveSig] int ButtonSelectAndActivate([In] int ulButton); [PreserveSig] int StillOff(); [PreserveSig] int PauseOn(); [PreserveSig] int PauseOff(); [PreserveSig] int MenuLanguageSelect([In] int Language); [PreserveSig] int AudioStreamChange([In] int ulAudio); [PreserveSig] int SubpictureStreamChange( [In] int ulSubPicture, [In, MarshalAs(UnmanagedType.Bool)] bool bDisplay ); [PreserveSig] int AngleChange([In] int ulAngle); [PreserveSig] int ParentalLevelSelect([In] int ulParentalLevel); [PreserveSig] int ParentalCountrySelect([In] short wCountry); [PreserveSig] int KaraokeAudioPresentationModeChange([In] int ulMode); [PreserveSig] int VideoModePreferrence([In] int ulPreferredDisplayMode); [PreserveSig] int SetRoot([In, MarshalAs(UnmanagedType.LPWStr)] string pszPath); [PreserveSig] int MouseActivate([In] Point point); [PreserveSig] int MouseSelect([In] Point point); [PreserveSig] int ChapterPlayAutoStop( [In] int ulTitle, [In] int ulChapter, [In] int ulChaptersToPlay ); } [ComImport, Guid("A70EFE60-E2A3-11d0-A9BE-00AA0061BE93"), Obsolete("The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.", false), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDvdInfo { [PreserveSig] int GetCurrentDomain([Out] out DvdDomain pDomain); [PreserveSig] int GetCurrentLocation([Out] out DvdPlaybackLocation pLocation); [PreserveSig] int GetTotalTitleTime([Out] out int pulTotalTime); [PreserveSig] int GetCurrentButton( [Out] out int pulButtonsAvailable, [Out] out int pulCurrentButton ); [PreserveSig] int GetCurrentAngle( [Out] out int pulAnglesAvailable, [Out] out int pulCurrentAngle ); [PreserveSig] int GetCurrentAudio( [Out] out int pulStreamsAvailable, [Out] out int pulCurrentStream ); [PreserveSig] int GetCurrentSubpicture( [Out] out int pulStreamsAvailable, [Out] out int pulCurrentStream, [Out, MarshalAs(UnmanagedType.Bool)] out bool pIsDisabled ); [PreserveSig] int GetCurrentUOPS([Out] out int pUOP); [PreserveSig] int GetAllSPRMs([Out] out SPRMArray pRegisterArray); [PreserveSig] int GetAllGPRMs([Out] out GPRMArray pRegisterArray); [PreserveSig] int GetAudioLanguage( [In] int ulStream, [Out] out int pLanguage ); [PreserveSig] int GetSubpictureLanguage( [In] int ulStream, [Out] out int pLanguage ); [PreserveSig] int GetTitleAttributes( [In] int ulTitle, [Out] out DvdAtr pATR ); [PreserveSig] int GetVMGAttributes([Out] out DvdAtr pATR); [PreserveSig] int GetCurrentVideoAttributes([Out] out DvdVideoATR pATR); [PreserveSig] int GetCurrentAudioAttributes([Out] out DvdAudioATR pATR); [PreserveSig] int GetCurrentSubpictureAttributes([Out] out DvdSubpictureATR pATR); [PreserveSig] int GetCurrentVolumeInfo( [Out] out int pulNumOfVol, [Out] out int pulThisVolNum, [Out] DvdDiscSide pSide, [Out] out int pulNumOfTitles ); [PreserveSig] int GetDVDTextInfo( [Out] out IntPtr pTextManager, // BYTE * [In] int ulBufSize, [Out] out int pulActualSize ); [PreserveSig] int GetPlayerParentalLevel( [Out] out int pulParentalLevel, [Out] out int pulCountryCode ); [PreserveSig] int GetNumberOfChapters( [In] int ulTitle, [Out] out int pulNumberOfChapters ); [PreserveSig] int GetTitleParentalLevels( [In] int ulTitle, [Out] out int pulParentalLevels ); [PreserveSig] int GetRoot( [Out] out IntPtr pRoot, // LPSTR [In] int ulBufSize, [Out] out int pulActualSize ); } [ComImport, Guid("153ACC21-D83B-11d1-82BF-00A0C9696C8F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDDrawExclModeVideo { [PreserveSig] int SetDDrawObject([In, MarshalAs(UnmanagedType.IUnknown)] object pDDrawObject); [PreserveSig] int GetDDrawObject( [Out, MarshalAs(UnmanagedType.IUnknown)] out object ppDDrawObject, [Out, MarshalAs(UnmanagedType.Bool)] out bool pbUsingExternal ); [PreserveSig] int SetDDrawSurface([In, MarshalAs(UnmanagedType.IUnknown)] object pDDrawSurface); [PreserveSig] int GetDDrawSurface( [Out, MarshalAs(UnmanagedType.IUnknown)] out object ppDDrawSurface, [Out, MarshalAs(UnmanagedType.Bool)] out bool pbUsingExternal ); [PreserveSig] int SetDrawParameters( [In] Rectangle prcSource, [In] Rectangle prcTarget ); [PreserveSig] int GetNativeVideoProps( [Out] out int pdwVideoWidth, [Out] out int pdwVideoHeight, [Out] out int pdwPictAspectRatioX, [Out] out int pdwPictAspectRatioY ); [PreserveSig] int SetCallbackInterface( [In, MarshalAs(UnmanagedType.IUnknown)] object pCallback, [In] int dwFlags ); } [ComImport, Guid("913c24a0-20ab-11d2-9038-00a0c9697298"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDDrawExclModeVideoCallback { [PreserveSig] int OnUpdateOverlay( [In, MarshalAs(UnmanagedType.Bool)] bool bBefore, [In] AMOverlayNotifyFlags dwFlags, [In, MarshalAs(UnmanagedType.Bool)] bool bOldVisible, [In] Rectangle prcOldSrc, [In] Rectangle prcOldDest, [In, MarshalAs(UnmanagedType.Bool)] bool bNewVisible, [In] Rectangle prcNewSrc, [In] Rectangle prcNewDest ); [PreserveSig] int OnUpdateColorKey( [In] ColorKey pKey, [In] int dwColor ); [PreserveSig] int OnUpdateSize( [In] int dwWidth, [In] int dwHeight, [In] int dwARWidth, [In] int dwARHeight ); } #endif [ComImport, Guid("FCC152B6-F372-11d0-8E00-00C04FD7C08B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDvdGraphBuilder { [PreserveSig] int GetFiltergraph([Out] out IGraphBuilder ppGB); [PreserveSig] int GetDvdInterface( [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppvIF ); [PreserveSig] int RenderDvdVideoVolume( [In, MarshalAs(UnmanagedType.LPWStr)] string lpcwszPathName, [In] AMDvdGraphFlags dwFlags, [Out] out AMDvdRenderStatus pStatus ); } [ComImport, Guid("33BC7430-EEC0-11D2-8201-00A0C9D74842"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDvdControl2 { [PreserveSig] int PlayTitle( [In] int ulTitle, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int PlayChapterInTitle( [In] int ulTitle, [In] int ulChapter, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int PlayAtTimeInTitle( [In] int ulTitle, [In] DvdHMSFTimeCode pStartTime, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int Stop(); [PreserveSig] int ReturnFromSubmenu( [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int PlayAtTime( [In] DvdHMSFTimeCode pTime, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int PlayChapter( [In] int ulChapter, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int PlayPrevChapter( [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int ReplayChapter( [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int PlayNextChapter( [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int PlayForwards( [In] double dSpeed, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int PlayBackwards( [In] double dSpeed, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int ShowMenu( [In] DvdMenuId MenuID, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int Resume( [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int SelectRelativeButton(DvdRelativeButton buttonDir); [PreserveSig] int ActivateButton(); [PreserveSig] int SelectButton([In] int ulButton); [PreserveSig] int SelectAndActivateButton([In] int ulButton); [PreserveSig] int StillOff(); [PreserveSig] int Pause([In, MarshalAs(UnmanagedType.Bool)] bool bState); [PreserveSig] int SelectAudioStream( [In] int ulAudio, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int SelectSubpictureStream( [In] int ulSubPicture, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int SetSubpictureState( [In, MarshalAs(UnmanagedType.Bool)] bool bState, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int SelectAngle( [In] int ulAngle, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int SelectParentalLevel([In] int ulParentalLevel); [PreserveSig] int SelectParentalCountry([In, MarshalAs(UnmanagedType.LPArray)] byte[] bCountry); [PreserveSig] int SelectKaraokeAudioPresentationMode([In] DvdKaraokeDownMix ulMode); [PreserveSig] int SelectVideoModePreference([In] DvdPreferredDisplayMode ulPreferredDisplayMode); [PreserveSig] int SetDVDDirectory([In, MarshalAs(UnmanagedType.LPWStr)] string pszwPath); [PreserveSig] int ActivateAtPosition([In] Point point); [PreserveSig] int SelectAtPosition([In] Point point); [PreserveSig] int PlayChaptersAutoStop( [In] int ulTitle, [In] int ulChapter, [In] int ulChaptersToPlay, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int AcceptParentalLevelChange([In, MarshalAs(UnmanagedType.Bool)] bool bAccept); [PreserveSig] int SetOption( [In] DvdOptionFlag flag, [In, MarshalAs(UnmanagedType.Bool)] bool fState ); [PreserveSig] int SetState( [In] IDvdState pState, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int PlayPeriodInTitleAutoStop( [In] int ulTitle, [In, MarshalAs(UnmanagedType.LPStruct)] DvdHMSFTimeCode pStartTime, [In, MarshalAs(UnmanagedType.LPStruct)] DvdHMSFTimeCode pEndTime, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int SetGPRM( [In] int ulIndex, [In] short wValue, [In] DvdCmdFlags dwFlags, [Out] out IDvdCmd ppCmd ); [PreserveSig] int SelectDefaultMenuLanguage([In] int Language); [PreserveSig] int SelectDefaultAudioLanguage( [In] int Language, [In] DvdAudioLangExt audioExtension ); [PreserveSig] int SelectDefaultSubpictureLanguage( [In] int Language, [In] DvdSubPictureLangExt subpictureExtension ); } [ComImport, Guid("34151510-EEC0-11D2-8201-00A0C9D74842"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDvdInfo2 { [PreserveSig] int GetCurrentDomain([Out] out DvdDomain pDomain); [PreserveSig] int GetCurrentLocation([Out] out DvdPlaybackLocation2 pLocation); [PreserveSig] int GetTotalTitleTime( [Out] DvdHMSFTimeCode pTotalTime, [Out] out DvdTimeCodeFlags ulTimeCodeFlags ); [PreserveSig] int GetCurrentButton( [Out] out int pulButtonsAvailable, [Out] out int pulCurrentButton ); [PreserveSig] int GetCurrentAngle( [Out] out int pulAnglesAvailable, [Out] out int pulCurrentAngle ); [PreserveSig] int GetCurrentAudio( [Out] out int pulStreamsAvailable, [Out] out int pulCurrentStream ); [PreserveSig] int GetCurrentSubpicture( [Out] out int pulStreamsAvailable, [Out] out int pulCurrentStream, [Out, MarshalAs(UnmanagedType.Bool)] out bool pbIsDisabled ); [PreserveSig] int GetCurrentUOPS([Out] out ValidUOPFlag pulUOPs); [PreserveSig] int GetAllSPRMs([Out] out SPRMArray pRegisterArray); [PreserveSig] int GetAllGPRMs([Out] out GPRMArray pRegisterArray); [PreserveSig] int GetAudioLanguage( [In] int ulStream, [Out] out int pLanguage ); [PreserveSig] int GetSubpictureLanguage( [In] int ulStream, [Out] out int pLanguage ); [PreserveSig] int GetTitleAttributes( [In] int ulTitle, [Out] out DvdMenuAttributes pMenu, [In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(DTAMarshaler))] DvdTitleAttributes pTitle ); [PreserveSig] int GetVMGAttributes([Out] out DvdMenuAttributes pATR); [PreserveSig] int GetCurrentVideoAttributes([Out] out DvdVideoAttributes pATR); [PreserveSig] int GetAudioAttributes( [In] int ulStream, [Out] out DvdAudioAttributes pATR ); [PreserveSig] int GetKaraokeAttributes( [In] int ulStream, [In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(DKAMarshaler))] DvdKaraokeAttributes pAttributes ); [PreserveSig] int GetSubpictureAttributes( [In] int ulStream, [Out] out DvdSubpictureAttributes pATR ); [PreserveSig] int GetDVDVolumeInfo( [Out] out int pulNumOfVolumes, [Out] out int pulVolume, [Out] out DvdDiscSide pSide, [Out] out int pulNumOfTitles ); [PreserveSig] int GetDVDTextNumberOfLanguages([Out] out int pulNumOfLangs); [PreserveSig] int GetDVDTextLanguageInfo( [In] int ulLangIndex, [Out] out int pulNumOfStrings, [Out] out int pLangCode, [Out] out DvdTextCharSet pbCharacterSet ); [PreserveSig] int GetDVDTextStringAsNative( [In] int ulLangIndex, [In] int ulStringIndex, [MarshalAs(UnmanagedType.LPStr)]System.Text.StringBuilder pbBuffer, [In] int ulMaxBufferSize, [Out] out int pulActualSize, [Out] out DvdTextStringType pType ); [PreserveSig] int GetDVDTextStringAsUnicode( [In] int ulLangIndex, [In] int ulStringIndex, System.Text.StringBuilder pchwBuffer, [In] int ulMaxBufferSize, [Out] out int pulActualSize, [Out] out DvdTextStringType pType ); [PreserveSig] int GetPlayerParentalLevel( [Out] out int pulParentalLevel, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst=2)] byte[] pbCountryCode ); [PreserveSig] int GetNumberOfChapters( [In] int ulTitle, [Out] out int pulNumOfChapters ); [PreserveSig] int GetTitleParentalLevels( [In] int ulTitle, [Out] out DvdParentalLevel pulParentalLevels ); [PreserveSig] int GetDVDDirectory( System.Text.StringBuilder pszwPath, [In] int ulMaxSize, [Out] out int pulActualSize ); [PreserveSig] int IsAudioStreamEnabled( [In] int ulStreamNum, [Out, MarshalAs(UnmanagedType.Bool)] out bool pbEnabled ); [PreserveSig] int GetDiscID( [In, MarshalAs(UnmanagedType.LPWStr)] string pszwPath, [Out] out long pullDiscID ); [PreserveSig] int GetState([Out] out IDvdState pStateData); [PreserveSig] int GetMenuLanguages( [MarshalAs(UnmanagedType.LPArray)] int [] pLanguages, [In] int ulMaxLanguages, [Out] out int pulActualLanguages ); [PreserveSig] int GetButtonAtPosition( [In] Point point, [Out] out int pulButtonIndex ); [PreserveSig] int GetCmdFromEvent( [In] int lParam1, [Out] out IDvdCmd pCmdObj ); [PreserveSig] int GetDefaultMenuLanguage([Out] out int pLanguage); [PreserveSig] int GetDefaultAudioLanguage( [Out] out int pLanguage, [Out] out DvdAudioLangExt pAudioExtension ); [PreserveSig] int GetDefaultSubpictureLanguage( [Out] out int pLanguage, [Out] out DvdSubPictureLangExt pSubpictureExtension ); [PreserveSig] int GetDecoderCaps(ref DvdDecoderCaps pCaps); [PreserveSig] int GetButtonRect( [In] int ulButton, [Out] DsRect pRect ); [PreserveSig] int IsSubpictureStreamEnabled( [In] int ulStreamNum, [Out, MarshalAs(UnmanagedType.Bool)] out bool pbEnabled ); } [ComImport, Guid("5a4a97e4-94ee-4a55-9751-74b5643aa27d"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDvdCmd { [PreserveSig] int WaitForStart(); [PreserveSig] int WaitForEnd(); } [ComImport, Guid("86303d6d-1c4a-4087-ab42-f711167048ef"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDvdState { [PreserveSig] int GetDiscID([Out] out long pullUniqueID); [PreserveSig] int GetParentalLevel([Out] out int pulParentalLevel); } #endregion }
// Copyright 2021 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using Foundation; using System; using System.Drawing; using UIKit; namespace ArcGISRuntime.Samples.AddGraphicsRenderer { [Register("AddGraphicsRenderer")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Add graphics with renderer", category: "GraphicsOverlay", description: "A renderer allows you to change the style of all graphics in a graphics overlay by referencing a single symbol style. A renderer will only affect graphics that do not specify their own symbol style.", instructions: "Pan and zoom on the map to view graphics for points, lines, and polygons (including polygons with curve segments) which are stylized using renderers.", tags: new[] { "arc", "bezier", "curve", "display", "graphics", "marker", "overlay", "renderer", "segment", "symbol", "true curve", "Featured" })] public class AddGraphicsRenderer : UIViewController { // Hold references to UI controls. private MapView _myMapView; public AddGraphicsRenderer() { Title = "Add graphics with renderer"; } public override void ViewDidLoad() { base.ViewDidLoad(); Initialize(); } private void Initialize() { // Create a map for the map view. _myMapView.Map = new Map(BasemapStyle.ArcGISTopographic); // Add graphics overlays to the map view. _myMapView.GraphicsOverlays.AddRange(new[] { MakePointGraphicsOverlay(), MakeLineGraphicsOverlay(), MakeSquareGraphicsOverlay(), MakeCurvedGraphicsOverlay(), }); } private GraphicsOverlay MakePointGraphicsOverlay() { // Create a simple marker symbol. SimpleMarkerSymbol pointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Diamond, Color.Green, 10); // Create a graphics overlay for the points. GraphicsOverlay pointGraphicsOverlay = new GraphicsOverlay(); // Create and assign a simple renderer to the graphics overlay. pointGraphicsOverlay.Renderer = new SimpleRenderer(pointSymbol); // Create a graphic with the map point geometry. MapPoint pointGeometry = new MapPoint(x: 40e5, y: 40e5, SpatialReferences.WebMercator); Graphic pointGraphic = new Graphic(pointGeometry); // Add the graphic to the overlay. pointGraphicsOverlay.Graphics.Add(pointGraphic); return pointGraphicsOverlay; } private GraphicsOverlay MakeLineGraphicsOverlay() { // Create a simple line symbol. SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Blue, 5); // Create a graphics overlay for the polylines. GraphicsOverlay lineGraphicsOverlay = new GraphicsOverlay(); // Create and assign a simple renderer to the graphics overlay. lineGraphicsOverlay.Renderer = new SimpleRenderer(lineSymbol); // Create a line graphic with new Polyline geometry. PolylineBuilder lineBuilder = new PolylineBuilder(SpatialReferences.WebMercator); lineBuilder.AddPoint(x: -10e5, y: 40e5); lineBuilder.AddPoint(x: 20e5, y: 50e5); Graphic lineGraphic = new Graphic(lineBuilder.ToGeometry()); // Add the graphic to the overlay. lineGraphicsOverlay.Graphics.Add(lineGraphic); return lineGraphicsOverlay; } private GraphicsOverlay MakeSquareGraphicsOverlay() { // Create a simple fill symbol. SimpleFillSymbol squareSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Yellow, null); // Create a graphics overlay for the square polygons. GraphicsOverlay squareGraphicsOverlay = new GraphicsOverlay(); // Create and assign a simple renderer to the graphics overlay. squareGraphicsOverlay.Renderer = new SimpleRenderer(squareSymbol); // Create a polygon graphic with `new Polygon` geometry. PolygonBuilder polygonBuilder = new PolygonBuilder(SpatialReferences.WebMercator); polygonBuilder.AddPoint(x: -20e5, y: 20e5); polygonBuilder.AddPoint(x: 20e5, y: 20e5); polygonBuilder.AddPoint(x: 20e5, y: -20e5); polygonBuilder.AddPoint(x: -20e5, y: -20e5); Graphic polygonGraphic = new Graphic(polygonBuilder.ToGeometry()); // Add the graphic to the overlay. squareGraphicsOverlay.Graphics.Add(polygonGraphic); return squareGraphicsOverlay; } private GraphicsOverlay MakeCurvedGraphicsOverlay() { // Create a simple fill symbol with outline. SimpleLineSymbol curvedLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Black, 1); SimpleFillSymbol curvedFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Red, curvedLineSymbol); // Create a graphics overlay for the polygons with curve segments. GraphicsOverlay curvedGraphicsOverlay = new GraphicsOverlay(); // Create and assign a simple renderer to the graphics overlay. curvedGraphicsOverlay.Renderer = new SimpleRenderer(curvedFillSymbol); // Create a heart-shaped graphic. MapPoint origin = new MapPoint(x: 40e5, y: 5e5, SpatialReferences.WebMercator); Geometry heartGeometry = MakeHeartGeometry(origin, 10e5); Graphic heartGraphic = new Graphic(heartGeometry); curvedGraphicsOverlay.Graphics.Add(heartGraphic); return curvedGraphicsOverlay; } private Geometry MakeHeartGeometry(MapPoint center, double sideLength) { if (sideLength <= 0) return null; SpatialReference spatialReference = center.SpatialReference; // The x and y coordinates to simplify the calculation. double minX = center.X - 0.5 * sideLength; double minY = center.Y - 0.5 * sideLength; // The radius of the arcs. double arcRadius = sideLength * 0.25; // Bottom left curve. MapPoint leftCurveStart = new MapPoint(center.X, minY, spatialReference); MapPoint leftCurveEnd = new MapPoint(minX, minY + 0.75 * sideLength, spatialReference); MapPoint leftControlMapPoint1 = new MapPoint(center.X, minY + 0.25 * sideLength, spatialReference); MapPoint leftControlMapPoint2 = new MapPoint(minX, center.Y, spatialReference: spatialReference); CubicBezierSegment leftCurve = new CubicBezierSegment(leftCurveStart, leftControlMapPoint1, leftControlMapPoint2, leftCurveEnd, spatialReference); // Top left arc. MapPoint leftArcCenter = new MapPoint(minX + 0.25 * sideLength, minY + 0.75 * sideLength, spatialReference); EllipticArcSegment leftArc = EllipticArcSegment.CreateCircularEllipticArc(leftArcCenter, arcRadius, Math.PI, centralAngle: -Math.PI, spatialReference); // Top right arc. MapPoint rightArcCenter = new MapPoint(minX + 0.75 * sideLength, minY + 0.75 * sideLength, spatialReference); EllipticArcSegment rightArc = EllipticArcSegment.CreateCircularEllipticArc(rightArcCenter, arcRadius, Math.PI, centralAngle: -Math.PI, spatialReference); // Bottom right curve. MapPoint rightCurveStart = new MapPoint(minX + sideLength, minY + 0.75 * sideLength, spatialReference); MapPoint rightCurveEnd = leftCurveStart; MapPoint rightControlMapPoint1 = new MapPoint(minX + sideLength, center.Y, spatialReference); MapPoint rightControlMapPoint2 = leftControlMapPoint1; CubicBezierSegment rightCurve = new CubicBezierSegment(rightCurveStart, rightControlMapPoint1, rightControlMapPoint2, rightCurveEnd, spatialReference); // Create the heart polygon. Part newPart = new Part(new Segment[] { leftCurve, leftArc, rightArc, rightCurve }, spatialReference); PolygonBuilder builder = new PolygonBuilder(spatialReference); builder.AddPart(newPart); return builder.ToGeometry(); } public override void LoadView() { // Create the views. View = new UIView() { BackgroundColor = ApplicationTheme.BackgroundColor }; _myMapView = new MapView(); _myMapView.TranslatesAutoresizingMaskIntoConstraints = false; // Add the views. View.AddSubviews(_myMapView); // Lay out the views. NSLayoutConstraint.ActivateConstraints(new[] { _myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor), _myMapView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor), _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor) }); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Xml; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.Shared; using Xunit; namespace Microsoft.Build.UnitTests.OM.Definition { /// <summary> /// Tests for ProjectProperty /// </summary> public class ProjectProperty_Tests { /// <summary> /// Project getter /// </summary> [Fact] public void ProjectGetter() { Project project = new Project(); ProjectProperty property = project.SetProperty("p", "v"); Assert.True(Object.ReferenceEquals(project, property.Project)); } /// <summary> /// Property with nothing to expand /// </summary> [Fact] public void NoExpansion() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <PropertyGroup> <p>v1</p> </PropertyGroup> </Project> "; ProjectProperty property = GetFirstProperty(content); Assert.NotNull(property.Xml); Assert.Equal("p", property.Name); Assert.Equal("v1", property.EvaluatedValue); Assert.Equal("v1", property.UnevaluatedValue); } /// <summary> /// Embedded property /// </summary> [Fact] public void ExpandProperty() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <PropertyGroup> <o>v1</o> <p>$(o)</p> </PropertyGroup> </Project> "; ProjectProperty property = GetFirstProperty(content); Assert.NotNull(property.Xml); Assert.Equal("p", property.Name); Assert.Equal("v1", property.EvaluatedValue); Assert.Equal("$(o)", property.UnevaluatedValue); } /// <summary> /// Set the value of a property /// </summary> [Fact] public void SetValue() { Project project = new Project(); ProjectProperty property = project.SetProperty("p", "v1"); project.ReevaluateIfNecessary(); property.UnevaluatedValue = "v2"; Assert.Equal("v2", property.EvaluatedValue); Assert.Equal("v2", property.UnevaluatedValue); Assert.True(project.IsDirty); } /// <summary> /// Set the value of a property /// </summary> [Fact] public void SetValue_Escaped() { Project project = new Project(); ProjectProperty property = project.SetProperty("p", "v1"); project.ReevaluateIfNecessary(); property.UnevaluatedValue = "v%282%29"; Assert.Equal("v(2)", property.EvaluatedValue); Assert.Equal("v%282%29", property.UnevaluatedValue); Assert.True(project.IsDirty); } /// <summary> /// Set the value of a property to the same value. /// This should not dirty the project. /// </summary> [Fact] public void SetValueSameValue() { Project project = new Project(); ProjectProperty property = project.SetProperty("p", "v1"); project.ReevaluateIfNecessary(); property.UnevaluatedValue = "v1"; Assert.False(project.IsDirty); } /// <summary> /// Attempt to set the value of a built-in property /// </summary> [Fact] public void InvalidSetValueBuiltInProperty() { Assert.Throws<InvalidOperationException>(() => { Project project = new Project(); ProjectProperty property = project.GetProperty("MSBuildProjectDirectory"); property.UnevaluatedValue = "v"; } ); } /// <summary> /// Set the value of a property originating in the environment. /// Should work even though there is no XML behind it. /// Also, should persist. /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] public void SetValueEnvironmentProperty() { Project project = new Project(); string varName = NativeMethodsShared.IsWindows ? "username" : "USER"; ProjectProperty property = project.GetProperty(varName); property.UnevaluatedValue = "v"; Assert.Equal("v", property.EvaluatedValue); Assert.Equal("v", property.UnevaluatedValue); project.ReevaluateIfNecessary(); property = project.GetProperty(varName); Assert.Equal("v", property.UnevaluatedValue); } /// <summary> /// Test IsEnvironmentVariable /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] public void IsEnvironmentVariable() { Project project = new Project(); string varName = NativeMethodsShared.IsWindows ? "username" : "USER"; Assert.True(project.GetProperty(varName).IsEnvironmentProperty); Assert.False(project.GetProperty(varName).IsGlobalProperty); Assert.False(project.GetProperty(varName).IsReservedProperty); Assert.False(project.GetProperty(varName).IsImported); } /// <summary> /// Test IsGlobalProperty /// </summary> [Fact] public void IsGlobalProperty() { Dictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); globalProperties["g"] = String.Empty; Project project = new Project(globalProperties, null, ProjectCollection.GlobalProjectCollection); Assert.False(project.GetProperty("g").IsEnvironmentProperty); Assert.True(project.GetProperty("g").IsGlobalProperty); Assert.False(project.GetProperty("g").IsReservedProperty); Assert.False(project.GetProperty("g").IsImported); } /// <summary> /// Test IsReservedProperty /// </summary> [Fact] public void IsReservedProperty() { Project project = new Project(); project.FullPath = @"c:\x"; project.ReevaluateIfNecessary(); Assert.False(project.GetProperty("MSBuildProjectFile").IsEnvironmentProperty); Assert.False(project.GetProperty("MSBuildProjectFile").IsGlobalProperty); Assert.True(project.GetProperty("MSBuildProjectFile").IsReservedProperty); Assert.False(project.GetProperty("MSBuildProjectFile").IsImported); } /// <summary> /// Verify properties are expanded in new property values /// </summary> [Fact] public void SetPropertyWithPropertyExpression() { Project project = new Project(); project.SetProperty("p0", "v0"); ProjectProperty property = project.SetProperty("p1", "v1"); property.UnevaluatedValue = "$(p0)"; Assert.Equal("v0", project.GetPropertyValue("p1")); Assert.Equal("v0", property.EvaluatedValue); Assert.Equal("$(p0)", property.UnevaluatedValue); } /// <summary> /// Verify item expressions are not expanded in new property values. /// NOTE: They aren't expanded to "blank". It just seems like that, because /// when you output them, item expansion happens after property expansion, and /// they may evaluate to blank then. (Unless items do exist at that point.) /// </summary> [Fact] public void SetPropertyWithItemAndMetadataExpression() { Project project = new Project(); project.SetProperty("p0", "v0"); ProjectProperty property = project.SetProperty("p1", "v1"); property.UnevaluatedValue = "@(i)-%(m)"; Assert.Equal("@(i)-%(m)", project.GetPropertyValue("p1")); Assert.Equal("@(i)-%(m)", property.EvaluatedValue); Assert.Equal("@(i)-%(m)", property.UnevaluatedValue); } /// <summary> /// Attempt to set value on imported property should fail /// </summary> [Fact] public void SetPropertyImported() { Assert.Throws<InvalidOperationException>(() => { string file = null; try { file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); Project import = new Project(); import.SetProperty("p", "v0"); import.Save(file); ProjectRootElement xml = ProjectRootElement.Create(); xml.AddImport(file); Project project = new Project(xml); ProjectProperty property = project.GetProperty("p"); property.UnevaluatedValue = "v1"; } finally { File.Delete(file); } } ); } /// <summary> /// Get the property named "p" in the project provided /// </summary> private static ProjectProperty GetFirstProperty(string content) { ProjectRootElement projectXml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Project project = new Project(projectXml); ProjectProperty property = project.GetProperty("p"); return property; } } }
// 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 GetAndWithElementInt641() { var test = new VectorGetAndWithElement__GetAndWithElementInt641(); // 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__GetAndWithElementInt641 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 1, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Int64[] values = new Int64[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt64(); } Vector256<Int64> value = Vector256.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { Int64 result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Int64.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Int64 insertedValue = TestLibrary.Generator.GetInt64(); try { Vector256<Int64> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Int64.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 1, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Int64[] values = new Int64[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt64(); } Vector256<Int64> value = Vector256.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector256) .GetMethod(nameof(Vector256.GetElement)) .MakeGenericMethod(typeof(Int64)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Int64)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Int64.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Int64 insertedValue = TestLibrary.Generator.GetInt64(); try { object result2 = typeof(Vector256) .GetMethod(nameof(Vector256.WithElement)) .MakeGenericMethod(typeof(Int64)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector256<Int64>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Int64.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(1 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(1 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(1 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(1 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Int64 result, Int64[] values, [CallerMemberName] string method = "") { if (result != values[1]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector256<Int64.GetElement(1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector256<Int64> result, Int64[] values, Int64 insertedValue, [CallerMemberName] string method = "") { Int64[] resultElements = new Int64[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Int64[] result, Int64[] values, Int64 insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 1) && (result[i] != values[i])) { succeeded = false; break; } } if (result[1] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Int64.WithElement(1): {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; } } } }
// ----------------------------------------------------------- // // This file was generated, please do not modify. // // ----------------------------------------------------------- namespace EmptyKeys.UserInterface.Generated { using System; using System.CodeDom.Compiler; using System.Collections.ObjectModel; using EmptyKeys.UserInterface; using EmptyKeys.UserInterface.Data; using EmptyKeys.UserInterface.Controls; using EmptyKeys.UserInterface.Controls.Primitives; using EmptyKeys.UserInterface.Input; using EmptyKeys.UserInterface.Media; using EmptyKeys.UserInterface.Media.Animation; using EmptyKeys.UserInterface.Media.Imaging; using EmptyKeys.UserInterface.Shapes; using EmptyKeys.UserInterface.Renderers; using EmptyKeys.UserInterface.Themes; [GeneratedCodeAttribute("Empty Keys UI Generator", "1.10.0.0")] public partial class ProfilerWindow : UserControl { private StackPanel e_37; private ToggleButton e_38; private ToggleButton e_39; private ToggleButton e_40; private ItemsControl pgLevelsListBox; private ItemsControl trLevelsListBox; private ItemsControl psLevelsListBox; public ProfilerWindow() { Style style = UserControlStyle.CreateUserControlStyle(); style.TargetType = this.GetType(); this.Style = style; this.InitializeComponent(); } private void InitializeComponent() { InitializeElementResources(this); // e_37 element this.e_37 = new StackPanel(); this.Content = this.e_37; this.e_37.Name = "e_37"; this.e_37.Background = new SolidColorBrush(new ColorW(0, 0, 0, 0)); // e_38 element this.e_38 = new ToggleButton(); this.e_37.Children.Add(this.e_38); this.e_38.Name = "e_38"; this.e_38.Content = "Performance Graph"; Binding binding_e_38_Command = new Binding("PerformanceGraphButtonClick"); this.e_38.SetBinding(ToggleButton.CommandProperty, binding_e_38_Command); Binding binding_e_38_IsChecked = new Binding("PerformanceGraphActive"); this.e_38.SetBinding(ToggleButton.IsCheckedProperty, binding_e_38_IsChecked); // e_39 element this.e_39 = new ToggleButton(); this.e_37.Children.Add(this.e_39); this.e_39.Name = "e_39"; this.e_39.Content = "Time Ruler"; Binding binding_e_39_Command = new Binding("TimeRulerGraphButtonClick"); this.e_39.SetBinding(ToggleButton.CommandProperty, binding_e_39_Command); Binding binding_e_39_IsChecked = new Binding("TimeRulerActive"); this.e_39.SetBinding(ToggleButton.IsCheckedProperty, binding_e_39_IsChecked); // e_40 element this.e_40 = new ToggleButton(); this.e_37.Children.Add(this.e_40); this.e_40.Name = "e_40"; this.e_40.Content = "Summary Log"; Binding binding_e_40_Command = new Binding("SummaryLogButtonClick"); this.e_40.SetBinding(ToggleButton.CommandProperty, binding_e_40_Command); Binding binding_e_40_IsChecked = new Binding("SummaryLogActive"); this.e_40.SetBinding(ToggleButton.IsCheckedProperty, binding_e_40_IsChecked); // pgLevelsListBox element this.pgLevelsListBox = new ItemsControl(); this.e_37.Children.Add(this.pgLevelsListBox); this.pgLevelsListBox.Name = "pgLevelsListBox"; this.pgLevelsListBox.Background = new SolidColorBrush(new ColorW(255, 255, 255, 0)); this.pgLevelsListBox.BorderThickness = new Thickness(0F, 0F, 0F, 0F); Func<UIElement, UIElement> pgLevelsListBox_dtFunc = pgLevelsListBox_dtMethod; this.pgLevelsListBox.ItemTemplate = new DataTemplate(pgLevelsListBox_dtFunc); Binding binding_pgLevelsListBox_Visibility = new Binding("PerformanceGraphVisibility"); this.pgLevelsListBox.SetBinding(ItemsControl.VisibilityProperty, binding_pgLevelsListBox_Visibility); Binding binding_pgLevelsListBox_ItemsSource = new Binding("PgLevels"); this.pgLevelsListBox.SetBinding(ItemsControl.ItemsSourceProperty, binding_pgLevelsListBox_ItemsSource); // trLevelsListBox element this.trLevelsListBox = new ItemsControl(); this.e_37.Children.Add(this.trLevelsListBox); this.trLevelsListBox.Name = "trLevelsListBox"; this.trLevelsListBox.Background = new SolidColorBrush(new ColorW(255, 255, 255, 0)); this.trLevelsListBox.BorderThickness = new Thickness(0F, 0F, 0F, 0F); Func<UIElement, UIElement> trLevelsListBox_dtFunc = trLevelsListBox_dtMethod; this.trLevelsListBox.ItemTemplate = new DataTemplate(trLevelsListBox_dtFunc); Binding binding_trLevelsListBox_Visibility = new Binding("TimeRulerVisibility"); this.trLevelsListBox.SetBinding(ItemsControl.VisibilityProperty, binding_trLevelsListBox_Visibility); Binding binding_trLevelsListBox_ItemsSource = new Binding("TrLevels"); this.trLevelsListBox.SetBinding(ItemsControl.ItemsSourceProperty, binding_trLevelsListBox_ItemsSource); // psLevelsListBox element this.psLevelsListBox = new ItemsControl(); this.e_37.Children.Add(this.psLevelsListBox); this.psLevelsListBox.Name = "psLevelsListBox"; this.psLevelsListBox.Background = new SolidColorBrush(new ColorW(255, 255, 255, 0)); this.psLevelsListBox.BorderThickness = new Thickness(0F, 0F, 0F, 0F); Func<UIElement, UIElement> psLevelsListBox_dtFunc = psLevelsListBox_dtMethod; this.psLevelsListBox.ItemTemplate = new DataTemplate(psLevelsListBox_dtFunc); Binding binding_psLevelsListBox_Visibility = new Binding("SummaryLogVisibility"); this.psLevelsListBox.SetBinding(ItemsControl.VisibilityProperty, binding_psLevelsListBox_Visibility); Binding binding_psLevelsListBox_ItemsSource = new Binding("PsLevels"); this.psLevelsListBox.SetBinding(ItemsControl.ItemsSourceProperty, binding_psLevelsListBox_ItemsSource); FontManager.Instance.AddFont("Segoe UI", 12F, FontStyle.Regular, "Segoe_UI_9_Regular"); } private static void InitializeElementResources(UIElement elem) { elem.Resources.MergedDictionaries.Add(CommonStyle.Instance); // Resource - [levelTemplate] DataTemplate Func<UIElement, UIElement> r_0_dtFunc = r_0_dtMethod; elem.Resources.Add("levelTemplate", new DataTemplate(r_0_dtFunc)); } private static UIElement r_0_dtMethod(UIElement parent) { // e_34 element DockPanel e_34 = new DockPanel(); e_34.Parent = parent; e_34.Name = "e_34"; // e_35 element CheckBox e_35 = new CheckBox(); e_34.Children.Add(e_35); e_35.Name = "e_35"; e_35.Margin = new Thickness(0F, 0F, 5F, 0F); DockPanel.SetDock(e_35, Dock.Left); Binding binding_e_35_IsChecked = new Binding("Enabled"); e_35.SetBinding(CheckBox.IsCheckedProperty, binding_e_35_IsChecked); // e_36 element TextBlock e_36 = new TextBlock(); e_34.Children.Add(e_36); e_36.Name = "e_36"; e_36.Padding = new Thickness(0F, 3F, 0F, 0F); Binding binding_e_36_Text = new Binding("Name"); e_36.SetBinding(TextBlock.TextProperty, binding_e_36_Text); return e_34; } private static UIElement pgLevelsListBox_dtMethod(UIElement parent) { // e_41 element DockPanel e_41 = new DockPanel(); e_41.Parent = parent; e_41.Name = "e_41"; // e_42 element CheckBox e_42 = new CheckBox(); e_41.Children.Add(e_42); e_42.Name = "e_42"; e_42.Margin = new Thickness(0F, 0F, 5F, 0F); DockPanel.SetDock(e_42, Dock.Left); Binding binding_e_42_IsChecked = new Binding("Enabled"); e_42.SetBinding(CheckBox.IsCheckedProperty, binding_e_42_IsChecked); // e_43 element TextBlock e_43 = new TextBlock(); e_41.Children.Add(e_43); e_43.Name = "e_43"; e_43.Padding = new Thickness(0F, 3F, 0F, 0F); Binding binding_e_43_Text = new Binding("Name"); e_43.SetBinding(TextBlock.TextProperty, binding_e_43_Text); return e_41; } private static UIElement trLevelsListBox_dtMethod(UIElement parent) { // e_44 element DockPanel e_44 = new DockPanel(); e_44.Parent = parent; e_44.Name = "e_44"; // e_45 element CheckBox e_45 = new CheckBox(); e_44.Children.Add(e_45); e_45.Name = "e_45"; e_45.Margin = new Thickness(0F, 0F, 5F, 0F); DockPanel.SetDock(e_45, Dock.Left); Binding binding_e_45_IsChecked = new Binding("Enabled"); e_45.SetBinding(CheckBox.IsCheckedProperty, binding_e_45_IsChecked); // e_46 element TextBlock e_46 = new TextBlock(); e_44.Children.Add(e_46); e_46.Name = "e_46"; e_46.Padding = new Thickness(0F, 3F, 0F, 0F); Binding binding_e_46_Text = new Binding("Name"); e_46.SetBinding(TextBlock.TextProperty, binding_e_46_Text); return e_44; } private static UIElement psLevelsListBox_dtMethod(UIElement parent) { // e_47 element DockPanel e_47 = new DockPanel(); e_47.Parent = parent; e_47.Name = "e_47"; // e_48 element CheckBox e_48 = new CheckBox(); e_47.Children.Add(e_48); e_48.Name = "e_48"; e_48.Margin = new Thickness(0F, 0F, 5F, 0F); DockPanel.SetDock(e_48, Dock.Left); Binding binding_e_48_IsChecked = new Binding("Enabled"); e_48.SetBinding(CheckBox.IsCheckedProperty, binding_e_48_IsChecked); // e_49 element TextBlock e_49 = new TextBlock(); e_47.Children.Add(e_49); e_49.Name = "e_49"; e_49.Padding = new Thickness(0F, 3F, 0F, 0F); Binding binding_e_49_Text = new Binding("Name"); e_49.SetBinding(TextBlock.TextProperty, binding_e_49_Text); return e_47; } } }
namespace SIM.Tool.Windows { public static class MainWindowData { private static TabDefinition HomeTab { get; } = new TabDefinition { Name = "Home", Groups = new[] { new GroupDefinition { Name = "Refresh", Buttons = new[] { new ButtonDefinition { Label = "Refresh sites", Image = "/Images/$lg/refresh.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.RefreshButton("sites"), Buttons = new[] { new ButtonDefinition { Label = "Refresh sites", Image = "/Images/$sm/refresh.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.RefreshButton("sites") }, new ButtonDefinition { Label = "Refresh installer", Image = "/Images/$sm/refresh.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.RefreshButton("installer") }, new ButtonDefinition { Label = "Refresh caches", Image = "/Images/$sm/refresh.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.RefreshButton("caches") }, new ButtonDefinition(), new ButtonDefinition { Label = "Refresh all", Image = "/Images/$sm/refresh.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.RefreshButton("all") }, } }, } }, new GroupDefinition { Name = "Install", Buttons = new[] { new ButtonDefinition { Label = "Install Instance", Image = "/Images/$lg/add_domain.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.InstallInstanceButton() }, new ButtonDefinition { Label = "Import Solution", Image = "/Images/$lg/upload.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ImportInstanceButton() }, } }, new GroupDefinition { Name = "Tools", Buttons = new[] { new ButtonDefinition { Label = "Get Sitecore", Image = "/Images/$lg/cloud_download.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.Download8Button() }, new ButtonDefinition { Label = "Bundled Tools", Image = "/Images/$lg/toolbox.png, SIM.Tool.Windows", Buttons = new[] { new ButtonDefinition { Label = "Command Line", Image = "/Images/$sm/console.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.CommandLineButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "SIM Logs", Image = "/Images/$sm/folder_document2.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFolderButton(@"%APPDATA%\Sitecore\Sitecore Instance Manager\Logs") }, new ButtonDefinition { Label = "SIM Data Folder", Image = "/Images/$sm/folder_window.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFolderButton(@"%APPDATA%\Sitecore\Sitecore Instance Manager") }, new ButtonDefinition(), new ButtonDefinition { Label = "Create Support Patch", Image = "/Images/$sm/vs.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.CreateSupportPatchButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Download Sitecore 8.x", Image = "/Images/$sm/cloud_download.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.Download8Button() }, new ButtonDefinition(), new ButtonDefinition { Label = "Hosts Editor", Image = "/Images/$sm/modem_earth.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenHostsButton() }, new ButtonDefinition { Label = "MS SQL Manager", Image = "/Images/$sm/data.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.DatabaseManagerButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Update Licenses", Image = "/Images/$lg/scroll_refresh.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.UpdateLicenseButton() }, new ButtonDefinition { Label = "Multiple Deletion", Image = "/Images/$lg/delete.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.MultipleDeletionButton(), Width = "55" }, new ButtonDefinition(), new ButtonDefinition { Label = "Log Analyzer", Image = "/Images/$lg/zoom_vertical.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenLogsButton() }, new ButtonDefinition { Label = "SSPG", Image = "/Images/$lg/package_edit.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenSSPGButton() }, new ButtonDefinition { Label = "Config Builder", Image = "/Images/$sm/wrench.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ConfigBuilderButton() }, new ButtonDefinition { Label = "Install MongoDB", Image = "/Images/$lg/scroll_refresh.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.InstallMongoDbButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Generate NuGet packages", Image = "/Images/$sm/new_package.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.GenerateNuGetPackagesButton() }, new ButtonDefinition { Label = "Generate NuGet packages for selected instance", Image = "/Images/$sm/new_package.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.GenerateNuGetPackagesButton("instance") }, } }, } }, new GroupDefinition { Name = "App", Buttons = new[] { new ButtonDefinition { Label = "Settings", Image = "/Images/$lg/wrench.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.SettingsButton() }, } }, } }; private static TabDefinition OpenTab { get; } = new TabDefinition { Name = "Open", Groups = new[] { new GroupDefinition { Name = "Page", Buttons = new[] { new ButtonDefinition { Label = "Sitecore Client", Image = "/Images/$lg/Sitecore.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/sitecore"), Buttons = new[] { new ButtonDefinition { Label = "Front-end Site", Image = "/Images/$sm/earth2.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Sitecore Login", Image = "/Images/$sm/log_out.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/sitecore/login") }, new ButtonDefinition(), new ButtonDefinition { Label = "Sitecore Desktop", Image = "/Images/$sm/Windows Table.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/sitecore/shell") }, new ButtonDefinition(), new ButtonDefinition { Label = "Content Editor", Image = "/Images/$sm/Pencil.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/sitecore/shell/applications/content%20editor") }, new ButtonDefinition { Label = "Page Editor", Image = "/Images/$sm/Paint.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/?sc_mode=edit") }, new ButtonDefinition { Label = "Launch Pad", Image = "/Images/$sm/startpage.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/sitecore/client/Applications/Launch%20Pad") }, new ButtonDefinition(), new ButtonDefinition { Label = "Google Chrome", Image = "/Images/$lg/chrome.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/sitecore:chrome") }, new ButtonDefinition { Label = "Google Chrome (Incognito)", Image = "/Images/$lg/chrome.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/sitecore:chrome:/incognito") }, new ButtonDefinition { Label = "Mozilla Firefox", Image = "/Images/$lg/firefox.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/sitecore:firefox") }, new ButtonDefinition { Label = "Mozilla Firefox (Private)", Image = "/Images/$lg/firefox.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/sitecore:firefox:-private-window") }, new ButtonDefinition { Label = "Internet Explorer", Image = "/Images/$lg/ie.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/sitecore:iexplore") }, new ButtonDefinition { Label = "Internet Explorer (Private)", Image = "/Images/$lg/ie.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/sitecore:iexplore:-private") }, new ButtonDefinition { Label = "Apple Safari", Image = "/Images/$lg/safari.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/sitecore:safari") }, new ButtonDefinition(), new ButtonDefinition { Label = "Sitecore Admin", Image = "/Images/$lg/toolbox.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenToolboxButton() }, } }, new ButtonDefinition { Label = "Log in admin", Image = "/Images/$lg/log_in.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore/"), Buttons = new[] { new ButtonDefinition { Label = "Sitecore Desktop", Image = "/Images/$sm/Windows Table.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore/shell") }, new ButtonDefinition(), new ButtonDefinition { Label = "Content Editor", Image = "/Images/$sm/Pencil.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore/shell/applications/content%20editor") }, new ButtonDefinition { Label = "Page Editor", Image = "/Images/$sm/Paint.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/?sc_mode=edit") }, new ButtonDefinition { Label = "Launch Pad", Image = "/Images/$sm/startpage.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore/client/Applications/Launch%20Pad") }, new ButtonDefinition(), new ButtonDefinition { Label = "Google Chrome", Image = "/Images/$lg/chrome.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore:chrome") }, new ButtonDefinition { Label = "Google Chrome (Incognito)", Image = "/Images/$lg/chrome.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore:chrome:/incognito") }, new ButtonDefinition { Label = "Mozilla Firefox", Image = "/Images/$lg/firefox.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore:firefox") }, new ButtonDefinition { Label = "Mozilla Firefox (Private)", Image = "/Images/$lg/firefox.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore:firefox:-private-window") }, new ButtonDefinition { Label = "Internet Explorer", Image = "/Images/$lg/ie.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore:iexplore") }, new ButtonDefinition { Label = "Internet Explorer (Private)", Image = "/Images/$lg/ie.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore:iexplore:-private") }, new ButtonDefinition { Label = "Apple Safari", Image = "/Images/$lg/safari.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore:safari") }, new ButtonDefinition(), new ButtonDefinition { Label = "Sitecore Admin", Image = "/Images/$lg/toolbox.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenToolboxButton("bypass") }, new ButtonDefinition(), new ButtonDefinition { Label = "Copy URL", Image = "/Images/$lg/astrologer.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("$(clipboard)") }, } }, } }, new GroupDefinition { Name = "File System", Buttons = new[] { new ButtonDefinition { Label = "Website Folder", Image = "/Images/$lg/folder_open.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFolderButton("$(website)"), Buttons = new[] { new ButtonDefinition { Label = "Root Folder", Image = "/Images/$sm/folder_network.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFolderButton("$(root)") }, new ButtonDefinition(), new ButtonDefinition { Label = "Website Folder", Image = "/Images/$sm/folder_open.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFolderButton("$(website)") }, new ButtonDefinition { Label = "Data Folder", Image = "/Images/$sm/folders.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFolderButton("$(data)") }, new ButtonDefinition { Label = "Databases Folder", Image = "/Images/$sm/folders.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFolderButton("$(root)/Databases") }, new ButtonDefinition(), new ButtonDefinition { Label = "App_Config Folder", Image = "/Images/$sm/folder_open.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFolderButton("$(website)/App_Config") }, new ButtonDefinition { Label = "Include Folder", Image = "/Images/$sm/folder_open.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFolderButton("$(website)/App_Config/Include") }, new ButtonDefinition { Label = "zzz Folder", Image = "/Images/$sm/folder_open.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFolderButton("$(website)/App_Config/Include/zzz") }, } }, new ButtonDefinition { Label = "Config Files", Image = "/Images/$lg/copy.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenWebConfigButton(), Buttons = new[] { new ButtonDefinition { Label = "web.config", Image = "/Images/$sm/document_text.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenWebConfigButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Global.asax", Image = "/Images/$sm/document_text.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFileButton("/Global.asax") }, new ButtonDefinition(), new ButtonDefinition { Label = "ConnectionStrings.config", Image = "/Images/$sm/data_copy.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFileButton("/App_Config/ConnectionStrings.config") }, new ButtonDefinition { Label = "Sitecore.config", Image = "/Images/$sm/data_copy.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFileButton("/App_Config/Sitecore.config") }, new ButtonDefinition(), new ButtonDefinition { Label = "Showconfig.xml", Image = "/Images/$sm/document_gear.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ConfigBuilderButton("/showconfig") }, new ButtonDefinition { Label = "Showconfig.xml (normalized)", Image = "/Images/$sm/document_gear.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ConfigBuilderButton("/showconfig /normalized") }, new ButtonDefinition { Label = "web.config.result.xml", Image = "/Images/$sm/document_gear.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ConfigBuilderButton("/webconfigresult") }, new ButtonDefinition { Label = "web.config.result.xml (normalized)", Image = "/Images/$sm/document_gear.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ConfigBuilderButton("/webconfigresult /normalized") }, } }, new ButtonDefinition { Label = "Log Files", Image = "/Images/$lg/history2.png, SIM.Tool.Windows", Buttons = new[] { new ButtonDefinition { Label = "Current Log file", Image = "/Images/$sm/console.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenCurrentLogButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Current 'log' Log file", Image = "/Images/$sm/console.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenCurrentLogButton("log") }, new ButtonDefinition(), new ButtonDefinition { Label = "Current 'Crawling.log' Log file", Image = "/Images/$sm/console.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenCurrentLogButton("Crawling.log") }, new ButtonDefinition { Label = "Current 'Search.log' Log file", Image = "/Images/$sm/console.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenCurrentLogButton("Search.log") }, new ButtonDefinition { Label = "Current 'Publishing.log' Log file", Image = "/Images/$sm/console.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenCurrentLogButton("Publishing.log") }, new ButtonDefinition { Label = "Current 'Client.log' Log file", Image = "/Images/$sm/console.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenCurrentLogButton("Client.log") }, new ButtonDefinition(), new ButtonDefinition { Label = "Current 'EXM.log' Log file", Image = "/Images/$sm/console.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenCurrentLogButton("Exm.log") }, new ButtonDefinition(), new ButtonDefinition { Label = "Entire Log files", Image = "/Images/$lg/zoom_vertical.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenLogsButton() }, } }, } }, new GroupDefinition { Name = "Apps", Buttons = new[] { new ButtonDefinition { Label = "Visual Studio", Image = "/Images/$lg/vs.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenVisualStudioButton(), Buttons = new[] { new ButtonDefinition { Label = "Visual Studio", Image = "/Images/$sm/vs.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenVisualStudioButton() }, new ButtonDefinition { Label = "Create Support Patch", Image = "/Images/$sm/console.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.CreateSupportPatchButton() }, } }, } }, } }; private static TabDefinition EditTab { get; } = new TabDefinition { Name = "Edit", Groups = new[] { new GroupDefinition { Name = "Install", Buttons = new[] { new ButtonDefinition { Label = "Install Packages", Image = "/Images/$lg/install.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.InstallModulesButton() }, } }, new GroupDefinition { Name = "Manage", Buttons = new[] { new ButtonDefinition { Label = "App State", Image = "/Images/$lg/gearwheels.png, SIM.Tool.Windows", Buttons = new[] { new ButtonDefinition { Label = "Start", Image = "/Images/$sm/media_play.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ControlAppPoolButton("start") }, new ButtonDefinition { Label = "Stop", Image = "/Images/$sm/media_stop.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ControlAppPoolButton("stop") }, new ButtonDefinition(), new ButtonDefinition { Label = "Recycle", Image = "/Images/$sm/garbage.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ControlAppPoolButton("recycle") }, new ButtonDefinition { Label = "Kill process", Image = "/Images/$sm/cpu.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ControlAppPoolButton("kill") }, new ButtonDefinition(), new ButtonDefinition { Label = "Change mode", Image = "/Images/$sm/cpu.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ControlAppPoolButton("mode") }, } }, new ButtonDefinition { Label = "Delete", Image = "/Images/$lg/uninstall.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.DeleteInstanceButton(), Buttons = new[] { new ButtonDefinition { Label = "Delete", Image = "/Images/$sm/uninstall.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.DeleteInstanceButton() }, new ButtonDefinition { Label = "Reinstall", Image = "/Images/$sm/redo.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ReinstallInstanceButton() }, } }, new ButtonDefinition { Label = "Extra Actions", Image = "/Images/$lg/atom2.png, SIM.Tool.Windows", Buttons = new[] { new ButtonDefinition { Label = "Publish (Incremental)", Image = "/Images/$sm/publish.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.PublishButton("incremental") }, new ButtonDefinition { Label = "Publish (Smart)", Image = "/Images/$sm/publish.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.PublishButton("smart") }, new ButtonDefinition { Label = "Publish (Republish)", Image = "/Images/$sm/publish.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.PublishButton("republish") }, new ButtonDefinition(), new ButtonDefinition { Label = "Cleanup logs and temp folder", Image = "/Images/$sm/uninstall.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.CleanupInstanceButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Attach Reporting database", Image = "/Images/$sm/data.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.AttachReportingDatabaseButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Attach Reporting.Secondary database", Image = "/Images/$sm/data.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.AttachReportingSecondaryDatabaseButton() }, new ButtonDefinition { Label = "Copy marketing definition tables", Image = "/Images/$sm/data.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.CopyMarketingDefinitionTablesButton() }, new ButtonDefinition { Label = "Replace Reporting database with Reporting.Secondary", Image = "/Images/$sm/data.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ReplaceReportingDatabaseWithSecondaryButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Clear Event Queues of All Databases", Image = "/Images/$sm/data.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ClearEventQueueButton() }, new ButtonDefinition { Label = "Clear Event Queues of Core Database", Image = "/Images/$sm/data.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ClearEventQueueButton("core") }, new ButtonDefinition { Label = "Clear Event Queues of Master Database", Image = "/Images/$sm/data.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ClearEventQueueButton("master") }, new ButtonDefinition { Label = "Clear Event Queues of Web Database", Image = "/Images/$sm/data.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ClearEventQueueButton("web") }, new ButtonDefinition(), new ButtonDefinition { Label = "Recycle All But This", Image = "/Images/$sm/data.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.RecycleAllButThisButton() }, new ButtonDefinition { Label = "Kill All w3wp But This", Image = "/Images/$sm/data.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.KillAllButThisButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Attach debugger to process", Image = "/Images/$lg/wrench.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.AttachDebuggerButton() }, new ButtonDefinition { Label = "Collect Memory Dump with MGAD", Image = "/Images/$lg/wrench.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.CollectMemoryDumpButton() }, new ButtonDefinition { Label = "Trace method call with MAT", Image = "/Images/$lg/wrench.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ManagedArgsTracerButton() }, } }, } }, new GroupDefinition { Name = "Backup", Buttons = new[] { new ButtonDefinition { Label = "Backup", Image = "/Images/$lg/floppy_disks.png, SIM.Tool.Windows", Buttons = new[] { new ButtonDefinition { Label = "Backup", Image = "/Images/$sm/box_into.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BackupInstanceButton() }, new ButtonDefinition { Label = "Export", Image = "/Images/$lg/download.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ExportInstanceButton() }, } }, new ButtonDefinition { Label = "Restore", Image = "/Images/$lg/box_out.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.RestoreInstanceButton() }, } }, } }; internal static ButtonDefinition[] MenuItems { get; } = { new ButtonDefinition { Label = "Browse Sitecore Website", Image = "/Images/$sm/earth2.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton() }, new ButtonDefinition { Label = "Browse Sitecore Client", Image = "/Images/$sm/Sitecore.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BrowseButton("/sitecore") }, new ButtonDefinition { Label = "Log in admin", Image = "/Images/$sm/log_in.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore"), Buttons = new [] { new ButtonDefinition { Label = "Google Chrome", Image = "/Images/$lg/chrome.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore:chrome") }, new ButtonDefinition { Label = "Mozilla Firefox", Image = "/Images/$lg/firefox.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore:firefox") }, new ButtonDefinition { Label = "Internet Explorer", Image = "/Images/$lg/ie.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore:iexplore") }, new ButtonDefinition { Label = "Apple Safari", Image = "/Images/$lg/safari.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("/sitecore:safari") }, new ButtonDefinition(), new ButtonDefinition { Label = "Sitecore Admin", Image = "/Images/$lg/toolbox.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenToolboxButton("bypass") }, new ButtonDefinition(), new ButtonDefinition { Label = "Copy URL", Image = "/Images/$lg/astrologer.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.LoginAdminButton("$(clipboard)") }, }}, new ButtonDefinition { Label = "Sitecore Admin", Image = "/Images/$lg/toolbox.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenToolboxButton() }, new ButtonDefinition { Label = "Open Folder", Image = "/Images/$sm/folder_open.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenFolderButton("$(website)") }, new ButtonDefinition { Label = "Open Visual Studio", Image = "/Images/$sm/vs.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenVisualStudioButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Analyze log files", Image = "/Images/$lg/zoom_vertical.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenLogsButton() }, new ButtonDefinition { Label = "Open log file", Image = "/Images/$sm/console.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenCurrentLogButton() }, new ButtonDefinition { Label = "Open web.config file", Image = "/Images/$sm/document_text.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.OpenWebConfigButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Publish Site", Image = "/Images/$sm/publish.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.PublishButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Backup", Image = "/Images/$sm/box_into.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.BackupInstanceButton() }, new ButtonDefinition { Label = "Restore", Image = "/Images/$sm/box_out.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.RestoreInstanceButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Export", Image = "/Images/$sm/download.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ExportInstanceButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Install modules", Image = "/Images/$sm/install.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.InstallModulesButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Reinstall instance", Image = "/Images/$sm/redo.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.ReinstallInstanceButton() }, new ButtonDefinition(), new ButtonDefinition { Label = "Delete", Image = "/Images/$sm/uninstall.png, SIM.Tool.Windows", Handler = new SIM.Tool.Windows.MainWindowComponents.DeleteInstanceButton() }, }; public static TabDefinition[] Tabs { get; } = { HomeTab, OpenTab, EditTab }; } }
namespace InControl { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using UnityEngine; #if NETFX_CORE using System.Reflection; #endif public class InputManager { public static readonly VersionInfo Version = VersionInfo.InControlVersion(); public static event Action OnSetup; public static event Action<ulong, float> OnUpdate; public static event Action OnReset; public static event Action<InputDevice> OnDeviceAttached; public static event Action<InputDevice> OnDeviceDetached; public static event Action<InputDevice> OnActiveDeviceChanged; internal static event Action<ulong, float> OnUpdateDevices; internal static event Action<ulong, float> OnCommitDevices; static List<InputDeviceManager> deviceManagers = new List<InputDeviceManager>(); static Dictionary<Type, InputDeviceManager> deviceManagerTable = new Dictionary<Type, InputDeviceManager>(); static InputDevice activeDevice = InputDevice.Null; static List<InputDevice> devices = new List<InputDevice>(); static List<PlayerActionSet> playerActionSets = new List<PlayerActionSet>(); /// <summary> /// A readonly collection of devices. /// Not every device in this list is guaranteed to be attached or even a controller. /// This collection should be treated as a pool from which devices may be selected. /// The collection is in no particular order and the order may change at any time. /// Do not treat this collection as a list of players. /// </summary> public static ReadOnlyCollection<InputDevice> Devices; /// <summary> /// Query whether a command button was pressed on any device during the last frame of input. /// </summary> public static bool CommandWasPressed { get; private set; } /// <summary> /// Gets or sets a value indicating whether the Y axis should be inverted for /// two-axis (directional) controls. When false (default), the Y axis will be positive up, /// the same as Unity. /// </summary> public static bool InvertYAxis { get; set; } /// <summary> /// Gets a value indicating whether the InputManager is currently setup and running. /// </summary> public static bool IsSetup { get; private set; } internal static string Platform { get; private set; } static bool applicationIsFocused; static float initialTime; static float currentTime; static float lastUpdateTime; static ulong currentTick; static VersionInfo? unityVersion; [Obsolete( "Use InputManager.CommandWasPressed instead." )] public static bool MenuWasPressed { get { return CommandWasPressed; } } /// <summary> /// DEPRECATED: Use the InControlManager component instead. /// </summary> /// @deprecated /// Calling this method directly is no longer supported. Use the InControlManager component to /// manage the lifecycle of the input manager instead. [Obsolete( "Calling InputManager.Setup() directly is no longer supported. Use the InControlManager component to manage the lifecycle of the input manager instead.", true )] public static void Setup() { SetupInternal(); } internal static bool SetupInternal() { if (IsSetup) { return false; } #if !NETFX_CORE && !UNITY_WEBPLAYER && !UNITY_EDITOR_OSX && (UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN) Platform = Utility.GetWindowsVersion().ToUpper(); #else Platform = (SystemInfo.operatingSystem + " " + SystemInfo.deviceModel).ToUpper(); #endif enabled = true; initialTime = 0.0f; currentTime = 0.0f; lastUpdateTime = 0.0f; currentTick = 0; applicationIsFocused = true; deviceManagers.Clear(); deviceManagerTable.Clear(); devices.Clear(); Devices = new ReadOnlyCollection<InputDevice>( devices ); activeDevice = InputDevice.Null; playerActionSets.Clear(); // TODO: Can this move further down along with the OnSetup callback? IsSetup = true; var enableUnityInput = true; var nativeInputIsEnabled = EnableNativeInput && NativeInputDeviceManager.Enable(); if (nativeInputIsEnabled) { enableUnityInput = false; } #if UNITY_STANDALONE_WIN || UNITY_EDITOR if (EnableXInput && enableUnityInput) { XInputDeviceManager.Enable(); } #endif #if UNITY_IOS if (EnableICade) { ICadeDeviceManager.Enable(); } #endif #if UNITY_XBOXONE if (XboxOneInputDeviceManager.Enable()) { enableUnityInput = false; } #endif #if UNITY_SWITCH if (NintendoSwitchInputDeviceManager.Enable()) { enableUnityInput = false; } #endif // TODO: Can this move further down after the UnityInputDeviceManager is added? // Currently, it allows use of InputManager.HideDevicesWithProfile() if (OnSetup != null) { OnSetup.Invoke(); OnSetup = null; } #if UNITY_ANDROID && INCONTROL_OUYA && !UNITY_EDITOR enableUnityInput = false; #endif if (enableUnityInput) { AddDeviceManager<UnityInputDeviceManager>(); } return true; } /// <summary> /// DEPRECATED: Use the InControlManager component instead. /// </summary> /// @deprecated /// Calling this method directly is no longer supported. Use the InControlManager component to /// manage the lifecycle of the input manager instead. [Obsolete( "Calling InputManager.Reset() method directly is no longer supported. Use the InControlManager component to manage the lifecycle of the input manager instead.", true )] public static void Reset() { ResetInternal(); } internal static void ResetInternal() { if (OnReset != null) { OnReset.Invoke(); } OnSetup = null; OnUpdate = null; OnReset = null; OnActiveDeviceChanged = null; OnDeviceAttached = null; OnDeviceDetached = null; OnUpdateDevices = null; OnCommitDevices = null; DestroyDeviceManagers(); DestroyDevices(); playerActionSets.Clear(); IsSetup = false; } /// <summary> /// DEPRECATED: Use the InControlManager component instead. /// </summary> /// @deprecated /// Calling this method directly is no longer supported. Use the InControlManager component to /// manage the lifecycle of the input manager instead. [Obsolete( "Calling InputManager.Update() directly is no longer supported. Use the InControlManager component to manage the lifecycle of the input manager instead.", true )] public static void Update() { UpdateInternal(); } internal static void UpdateInternal() { AssertIsSetup(); if (OnSetup != null) { OnSetup.Invoke(); OnSetup = null; } if (!enabled) { return; } if (SuspendInBackground && !applicationIsFocused) { return; } currentTick++; UpdateCurrentTime(); var deltaTime = currentTime - lastUpdateTime; UpdateDeviceManagers( deltaTime ); CommandWasPressed = false; UpdateDevices( deltaTime ); CommitDevices( deltaTime ); UpdateActiveDevice(); UpdatePlayerActionSets( deltaTime ); if (OnUpdate != null) { OnUpdate.Invoke( currentTick, deltaTime ); } lastUpdateTime = currentTime; } /// <summary> /// Force the input manager to reset and setup. /// </summary> public static void Reload() { ResetInternal(); SetupInternal(); } static void AssertIsSetup() { if (!IsSetup) { throw new Exception( "InputManager is not initialized. Call InputManager.Setup() first." ); } } static void SetZeroTickOnAllControls() { var deviceCount = devices.Count; for (var i = 0; i < deviceCount; i++) { var controls = devices[i].Controls; var controlCount = controls.Count; for (var j = 0; j < controlCount; j++) { var control = controls[j]; if (control != null) { control.SetZeroTick(); } } } } /// <summary> /// Clears the state of input on all controls. /// The net result here should be that the state on all controls will return /// zero/false for the remainder of the current tick, and during the next update /// tick WasPressed, WasReleased, WasRepeated and HasChanged will return false. /// </summary> public static void ClearInputState() { var deviceCount = devices.Count; for (var i = 0; i < deviceCount; i++) { devices[i].ClearInputState(); } var playerActionSetCount = playerActionSets.Count; for (var i = 0; i < playerActionSetCount; i++) { playerActionSets[i].ClearInputState(); } activeDevice = InputDevice.Null; } internal static void OnApplicationFocus( bool focusState ) { if (!focusState) { if (SuspendInBackground) { ClearInputState(); } SetZeroTickOnAllControls(); } applicationIsFocused = focusState; } internal static void OnApplicationPause( bool pauseState ) { } internal static void OnApplicationQuit() { ResetInternal(); } internal static void OnLevelWasLoaded() { SetZeroTickOnAllControls(); UpdateInternal(); } /// <summary> /// Adds a device manager. /// Only one instance of a given type can be added. An error will be raised if /// you try to add more than one. /// </summary> /// <param name="deviceManager">The device manager to add.</param> public static void AddDeviceManager( InputDeviceManager deviceManager ) { AssertIsSetup(); var type = deviceManager.GetType(); if (deviceManagerTable.ContainsKey( type )) { Logger.LogError( "A device manager of type '" + type.Name + "' already exists; cannot add another." ); return; } deviceManagers.Add( deviceManager ); deviceManagerTable.Add( type, deviceManager ); deviceManager.Update( currentTick, currentTime - lastUpdateTime ); } /// <summary> /// Adds a device manager by type. /// </summary> /// <typeparam name="T">A subclass of InputDeviceManager.</typeparam> public static void AddDeviceManager<T>() where T : InputDeviceManager, new() { AddDeviceManager( new T() ); } /// <summary> /// Get a device manager from the input manager by type if it one is present. /// </summary> /// <typeparam name="T">A subclass of InputDeviceManager.</typeparam> public static T GetDeviceManager<T>() where T : InputDeviceManager { InputDeviceManager deviceManager; if (deviceManagerTable.TryGetValue( typeof( T ), out deviceManager )) { return deviceManager as T; } return null; } /// <summary> /// Query whether a device manager is present by type. /// </summary> /// <typeparam name="T">A subclass of InputDeviceManager.</typeparam> public static bool HasDeviceManager<T>() where T : InputDeviceManager { return deviceManagerTable.ContainsKey( typeof( T ) ); } static void UpdateCurrentTime() { // Have to do this hack since Time.realtimeSinceStartup is not set until AFTER Awake(). if (initialTime < float.Epsilon) { initialTime = Time.realtimeSinceStartup; } currentTime = Mathf.Max( 0.0f, Time.realtimeSinceStartup - initialTime ); } static void UpdateDeviceManagers( float deltaTime ) { var inputDeviceManagerCount = deviceManagers.Count; for (var i = 0; i < inputDeviceManagerCount; i++) { deviceManagers[i].Update( currentTick, deltaTime ); } } static void DestroyDeviceManagers() { var deviceManagerCount = deviceManagers.Count; for (var i = 0; i < deviceManagerCount; i++) { deviceManagers[i].Destroy(); } deviceManagers.Clear(); deviceManagerTable.Clear(); } static void DestroyDevices() { var deviceCount = devices.Count; for (var i = 0; i < deviceCount; i++) { var device = devices[i]; device.OnDetached(); } devices.Clear(); activeDevice = InputDevice.Null; } static void UpdateDevices( float deltaTime ) { var deviceCount = devices.Count; for (var i = 0; i < deviceCount; i++) { var device = devices[i]; device.Update( currentTick, deltaTime ); } if (OnUpdateDevices != null) { OnUpdateDevices.Invoke( currentTick, deltaTime ); } } static void CommitDevices( float deltaTime ) { var deviceCount = devices.Count; for (var i = 0; i < deviceCount; i++) { var device = devices[i]; device.Commit( currentTick, deltaTime ); if (device.CommandWasPressed) { CommandWasPressed = true; } } if (OnCommitDevices != null) { OnCommitDevices.Invoke( currentTick, deltaTime ); } } static void UpdateActiveDevice() { var lastActiveDevice = ActiveDevice; var deviceCount = devices.Count; for (var i = 0; i < deviceCount; i++) { var inputDevice = devices[i]; if (inputDevice.LastChangedAfter( ActiveDevice ) && !inputDevice.Passive) { ActiveDevice = inputDevice; } } if (lastActiveDevice != ActiveDevice) { if (OnActiveDeviceChanged != null) { OnActiveDeviceChanged( ActiveDevice ); } } } /// <summary> /// Attach a device to the input manager. /// </summary> /// <param name="inputDevice">The input device to attach.</param> public static void AttachDevice( InputDevice inputDevice ) { AssertIsSetup(); if (!inputDevice.IsSupportedOnThisPlatform) { return; } if (inputDevice.IsAttached) { return; } if (!devices.Contains( inputDevice )) { devices.Add( inputDevice ); devices.Sort( ( d1, d2 ) => d1.SortOrder.CompareTo( d2.SortOrder ) ); } inputDevice.OnAttached(); if (OnDeviceAttached != null) { OnDeviceAttached( inputDevice ); } } /// <summary> /// Detach a device from the input manager. /// </summary> /// <param name="inputDevice">The input device to attach.</param> public static void DetachDevice( InputDevice inputDevice ) { if (!IsSetup) { return; } if (!inputDevice.IsAttached) { return; } devices.Remove( inputDevice ); if (ActiveDevice == inputDevice) { ActiveDevice = InputDevice.Null; } inputDevice.OnDetached(); if (OnDeviceDetached != null) { OnDeviceDetached( inputDevice ); } } /// <summary> /// Hides the devices with a given profile. /// This must be called before the input manager is initialized. /// </summary> /// <param name="type">Type.</param> public static void HideDevicesWithProfile( Type type ) { #if NETFX_CORE if (type.GetTypeInfo().IsAssignableFrom( typeof( UnityInputDeviceProfile ).GetTypeInfo() )) #else if (type.IsSubclassOf( typeof( UnityInputDeviceProfile ) )) #endif { UnityInputDeviceProfile.Hide( type ); } } internal static void AttachPlayerActionSet( PlayerActionSet playerActionSet ) { if (!playerActionSets.Contains( playerActionSet )) { playerActionSets.Add( playerActionSet ); } } internal static void DetachPlayerActionSet( PlayerActionSet playerActionSet ) { playerActionSets.Remove( playerActionSet ); } internal static void UpdatePlayerActionSets( float deltaTime ) { var playerActionSetCount = playerActionSets.Count; for (var i = 0; i < playerActionSetCount; i++) { playerActionSets[i].Update( currentTick, deltaTime ); } } /// <summary> /// Detects whether any (keyboard) key is currently pressed. /// For more flexibility, see <see cref="KeyCombo.Detect()"/> /// </summary> public static bool AnyKeyIsPressed { get { return KeyCombo.Detect( true ).IncludeCount > 0; } } /// <summary> /// Gets the currently active device if present, otherwise returns a null device which does nothing. /// The currently active device is defined as the last device that provided input events. This is /// a good way to query for a device in single player applications. /// </summary> public static InputDevice ActiveDevice { get { return (activeDevice == null) ? InputDevice.Null : activeDevice; } private set { activeDevice = (value == null) ? InputDevice.Null : value; } } /// <summary> /// Toggle whether input is processed or not. While disabled, all controls will return zero state. /// </summary> public static bool Enabled { get { return enabled; } set { if (enabled != value) { if (value) { SetZeroTickOnAllControls(); UpdateInternal(); } else { ClearInputState(); SetZeroTickOnAllControls(); } enabled = value; } } } static bool enabled; /// <summary> /// Suspend input updates when the application loses focus. /// When enabled and the app loses focus, input will be cleared and no. /// input updates will be processed. Input updates will resume when the app /// regains focus. /// </summary> public static bool SuspendInBackground { get; internal set; } /// <summary> /// Enable Native Input support. /// When enabled on initialization, the input manager will first check /// whether Native Input is supported on this platform and if so, it will add /// a NativeInputDeviceManager. /// </summary> public static bool EnableNativeInput { get; internal set; } /// <summary> /// Enable XInput support (Windows only). /// When enabled on initialization, the input manager will first check /// whether XInput is supported on this platform and if so, it will add /// an XInputDeviceManager. /// </summary> public static bool EnableXInput { get; internal set; } /// <summary> /// Set the XInput background thread polling rate. /// When set to zero (default) it will equal the projects fixed updated rate. /// </summary> public static uint XInputUpdateRate { get; internal set; } /// <summary> /// Set the XInput buffer size. (Experimental) /// Usually you want this to be zero (default). Setting it higher will introduce /// latency, but may smooth out input if querying input on FixedUpdate, which /// tends to cluster calls at the end of a frame. /// </summary> public static uint XInputBufferSize { get; internal set; } /// <summary> /// Set Native Input on Windows to use XInput. /// When set to true (default), XInput will be utilized which better supports /// compatible controllers (such as Xbox 360 and Xbox One gamepads) including /// vibration control and proper separated triggers, but limits the number of /// these controllers to four. Additional XInput-compatible beyond four /// controllers will be ignored. /// DirectInput will be used for all non-XInput-compatible controllers. /// </summary> public static bool NativeInputEnableXInput { get; internal set; } /// <summary> /// Set Native Input to prevent system sleep and screensaver. /// Controller input generally does not prevent the system idle timer and /// the screensaver may come on during extended gameplay. When set to /// true, this will be prevented. /// </summary> public static bool NativeInputPreventSleep { get; internal set; } /// <summary> /// Set the Native Input background thread polling rate. /// When set to zero (default) it will equal the project's fixed update rate. /// </summary> public static uint NativeInputUpdateRate { get; internal set; } /// <summary> /// Enable iCade support (iOS only). /// When enabled on initialization, the input manager will first check /// whether XInput is supported on this platform and if so, it will add /// an XInputDeviceManager. /// </summary> public static bool EnableICade { get; internal set; } internal static VersionInfo UnityVersion { get { if (!unityVersion.HasValue) { unityVersion = VersionInfo.UnityVersion(); } return unityVersion.Value; } } internal static ulong CurrentTick { get { return currentTick; } } } }
// Copyright (c) Valdis Iljuconoks. All rights reserved. // Licensed under Apache-2.0. See the LICENSE file in the project root for more information using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Text.RegularExpressions; using DbLocalizationProvider.Internal; using DbLocalizationProvider.Json; using DbLocalizationProvider.Queries; using Newtonsoft.Json; using JsonConverter = DbLocalizationProvider.Json.JsonConverter; namespace DbLocalizationProvider { /// <summary> /// Main class to use when resource translation is needed. /// </summary> public class LocalizationProvider : ILocalizationProvider { private readonly ResourceKeyBuilder _keyBuilder; private readonly ExpressionHelper _expressionHelper; private readonly FallbackLanguagesCollection _fallbackCollection; internal readonly IQueryExecutor _queryExecutor; /// <summary> /// Creates new localization provider with all the required settings and services injected. /// </summary> /// <param name="keyBuilder">Key builder (with help of <paramref name="expressionHelper"/> this dependency will help to translate from lambda expression to resource key as string).</param> /// <param name="expressionHelper">Can walk lambda expressions and return string representation of the expression.</param> /// <param name="fallbackCollection">Collection of fallback language settings.</param> /// <param name="queryExecutor">Small utility robot to help with queries.</param> public LocalizationProvider( ResourceKeyBuilder keyBuilder, ExpressionHelper expressionHelper, FallbackLanguagesCollection fallbackCollection, IQueryExecutor queryExecutor) { _keyBuilder = keyBuilder; _expressionHelper = expressionHelper; _fallbackCollection = fallbackCollection; _queryExecutor = queryExecutor; } /// <summary> /// Gets translation for the resource with specific key. /// </summary> /// <param name="resourceKey">Key of the resource to look translation for.</param> /// <returns>Translation for the resource with specific key.</returns> /// <remarks><see cref="CultureInfo.CurrentUICulture" /> is used as language.</remarks> public virtual string GetString(string resourceKey) { return GetString(resourceKey, _queryExecutor.Execute(new GetCurrentUICulture.Query())); } /// <summary> /// Gets translation for the resource with specific key. /// </summary> /// <param name="resourceKey">Key of the resource to look translation for.</param> /// <param name="culture"> /// If you want to get translation for other language as <see cref="CultureInfo.CurrentUICulture" />, /// then specify that language here. /// </param> /// <returns>Translation for the resource with specific key.</returns> public virtual string GetString(string resourceKey, CultureInfo culture) { return GetStringByCulture(resourceKey, culture); } /// <summary> /// Gets translation for the resource (reference to the resource is specified as lambda expression). /// </summary> /// <param name="resource">Lambda expression for the resource.</param> /// <param name="formatArguments"> /// If you have placeholders in translation to replace to - use this argument to specify those. /// </param> /// <returns>Translation for the resource with specific key.</returns> /// <remarks><see cref="CultureInfo.CurrentUICulture" /> is used as language.</remarks> public virtual string GetString(Expression<Func<object>> resource, params object[] formatArguments) { return GetStringByCulture(resource, _queryExecutor.Execute(new GetCurrentUICulture.Query()), formatArguments); } /// <summary> /// Gets translation for the resource (reference to the resource is specified as lambda expression). /// </summary> /// <param name="resource">Lambda expression for the resource.</param> /// <param name="culture"> /// If you want to get translation for other language as <see cref="CultureInfo.CurrentUICulture" />, /// then specific that language here. /// </param> /// <param name="formatArguments"> /// If you have placeholders in translation to replace to - use this argument to specify those. /// </param> /// <returns>Translation for the resource with specific key.</returns> public virtual string GetString(Expression<Func<object>> resource, CultureInfo culture, params object[] formatArguments) { return GetStringByCulture(resource, culture, formatArguments); } /// <summary> /// Gets translation for the resource (reference to the resource is specified as lambda expression). /// </summary> /// <param name="resource">Lambda expression for the resource.</param> /// <param name="attribute"> /// Type of the custom attribute (registered in /// <see cref="ConfigurationContext.CustomAttributes" /> collection). /// </param> /// <param name="formatArguments"> /// If you have placeholders in translation to replace to - use this argument to specify /// those. /// </param> /// <returns>Translation for the resource with specific key.</returns> /// <remarks><see cref="CultureInfo.CurrentUICulture" /> is used as language.</remarks> public virtual string GetString(Expression<Func<object>> resource, Type attribute, params object[] formatArguments) { return GetStringByCulture(resource, attribute, _queryExecutor.Execute(new GetCurrentUICulture.Query()), formatArguments); } /// <summary> /// Gets key and translations for the specified culture. /// </summary> /// <param name="culture"> /// If you want to get translation for other language as <see cref="CultureInfo.CurrentUICulture" />, /// then specify that language here. /// </param> /// <returns>Translation for the resource with specific key.</returns> public virtual IDictionary<string, string> GetStringsByCulture(CultureInfo culture) { if (culture == null) { throw new ArgumentNullException(nameof(culture)); } var localizationResources = _queryExecutor.Execute(new GetAllResources.Query()); var translationDictionary = localizationResources.ToDictionary(res => res.ResourceKey, res => res.Translations.ByLanguage(culture, true)); return translationDictionary; } /// <summary> /// Gets translation for the resource (reference to the resource is specified as lambda expression). /// </summary> /// <param name="resource">Lambda expression for the resource.</param> /// <param name="culture"> /// If you want to get translation for other language as <see cref="CultureInfo.CurrentUICulture" />, then specific /// that language here. /// </param> /// <param name="formatArguments"> /// If you have placeholders in translation to replace to - use this argument to specify those. /// </param> /// <returns>Translation for the resource with specific key.</returns> public virtual string GetStringByCulture(Expression<Func<object>> resource, CultureInfo culture, params object[] formatArguments) { if (resource == null) { throw new ArgumentNullException(nameof(resource)); } var resourceKey = _expressionHelper.GetFullMemberName(resource); return GetStringByCulture(resourceKey, culture, formatArguments); } /// <summary> /// Gets translation for the resource with specific key. /// </summary> /// <param name="resourceKey">Key of the resource to look translation for.</param> /// <param name="culture"> /// If you want to get translation for other language as <see cref="CultureInfo.CurrentUICulture" />, /// then specify that language here. /// </param> /// <param name="formatArguments"> /// If you have placeholders in translation to replace to - use this argument to specify /// those. /// </param> /// <returns>Translation for the resource with specific key.</returns> public virtual string GetStringByCulture(string resourceKey, CultureInfo culture, params object[] formatArguments) { if (string.IsNullOrWhiteSpace(resourceKey)) { throw new ArgumentNullException(nameof(resourceKey)); } if (culture == null) { throw new ArgumentNullException(nameof(culture)); } var resourceValue = _queryExecutor.Execute(new GetTranslation.Query(resourceKey, culture)); if (resourceValue == null) { return null; } try { return Format(resourceValue, formatArguments); } catch (Exception) { // TODO: log } return resourceValue; } /// <summary> /// Gets translation for the resource (reference to the resource is specified as lambda expression). /// </summary> /// <param name="resource">Lambda expression for the resource.</param> /// <param name="attribute"> /// Type of the custom attribute (registered in /// <see cref="ConfigurationContext.CustomAttributes" /> collection). /// </param> /// <param name="culture"> /// If you want to get translation for other language as <see cref="CultureInfo.CurrentUICulture" />, /// then specific that language here. /// </param> /// <param name="formatArguments"> /// If you have placeholders in translation to replace to - use this argument to specify /// those. /// </param> /// <returns>Translation for the resource with specific key in language specified in <paramref name="culture" />.</returns> public virtual string GetStringByCulture( Expression<Func<object>> resource, Type attribute, CultureInfo culture, params object[] formatArguments) { if (resource == null) { throw new ArgumentNullException(nameof(resource)); } var resourceKey = _expressionHelper.GetFullMemberName(resource); resourceKey = _keyBuilder.BuildResourceKey(resourceKey, attribute); return GetStringByCulture(resourceKey, culture, formatArguments); } /// <summary> /// Give a type to this method and it will return instance of the type but translated /// </summary> /// <typeparam name="T">Type of the target class you want to translate</typeparam> /// <returns>Translated class based on <see cref="CultureInfo.CurrentUICulture" /> language</returns> public T Translate<T>() { return Translate<T>(_queryExecutor.Execute(new GetCurrentUICulture.Query())); } /// <summary> /// Give a type to this method and it will return instance of the type but translated /// </summary> /// <typeparam name="T">Type of the target class you want to translate</typeparam> /// <param name="language">Language to use during translation</param> /// <returns>Translated class</returns> public T Translate<T>(CultureInfo language) { var converter = new JsonConverter(_queryExecutor); var className = typeof(T).FullName; var json = converter.GetJson(className, language.Name, _fallbackCollection); // get the actual class Json representation (we need to select token through FQN of the class) // to supported nested classes - we need to fix a bit resource key name var jsonToken = json.SelectToken(className.Replace("+", ".")); if (jsonToken == null) { return (T)Activator.CreateInstance(typeof(T), new object[] { }); } return JsonConvert.DeserializeObject<T>(jsonToken.ToString(), new JsonSerializerSettings { ContractResolver = new StaticPropertyContractResolver() }); } /// <summary> /// Translates the specified enum with some formatting arguments (if needed). /// </summary> /// <param name="target">The enum to translate.</param> /// <param name="formatArguments">The format arguments.</param> /// <returns>Translated enum values</returns> public string Translate(Enum target, params object[] formatArguments) { return TranslateByCulture(target, _queryExecutor.Execute(new GetCurrentUICulture.Query()), formatArguments); } /// <summary> /// Translates the specified enum with some formatting arguments (if needed). /// </summary> /// <param name="target">The enum to translate.</param> /// <param name="culture">The culture.</param> /// <param name="formatArguments">The format arguments.</param> /// <returns>Translated enum values</returns> /// <exception cref="ArgumentNullException"> /// target /// or /// culture /// </exception> public string TranslateByCulture(Enum target, CultureInfo culture, params object[] formatArguments) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (culture == null) { throw new ArgumentNullException(nameof(culture)); } var resourceKey = _keyBuilder.BuildResourceKey(target.GetType(), target.ToString()); return GetStringByCulture(resourceKey, culture, formatArguments); } /// <inheritdoc /> public string GetStringWithInvariantFallback(Expression<Func<object>> resource, params object[] formatArguments) { if (resource == null) { throw new ArgumentNullException(nameof(resource)); } var resourceKey = _expressionHelper.GetFullMemberName(resource); var culture = _queryExecutor.Execute(new GetCurrentUICulture.Query()); var resourceValue = _queryExecutor.Execute(new GetTranslation.Query(resourceKey, culture) { FallbackToInvariant = true }); return Format(resourceValue, formatArguments); } internal static string Format(string message, params object[] formatArguments) { if (formatArguments == null || !formatArguments.Any()) { return message; } // check if first element is not scalar - format with named placeholders var first = formatArguments.First(); return !first.GetType().IsSimpleType() ? FormatWithAnonymousObject(message, first) : string.Format(message, formatArguments); } private static string FormatWithAnonymousObject(string message, object model) { var type = model.GetType(); if (type == typeof(string)) { return string.Format(message, model); } var placeHolders = Regex.Matches(message, "{.*?}").Cast<Match>().Select(m => m.Value).ToList(); if (!placeHolders.Any()) { return message; } var placeholderMap = new Dictionary<string, object>(); var properties = type.GetProperties(); foreach (var placeHolder in placeHolders) { var propertyInfo = properties.FirstOrDefault(p => p.Name == placeHolder.Trim('{', '}')); // property found - extract value and add to the map var val = propertyInfo?.GetValue(model); if (val != null && !placeholderMap.ContainsKey(placeHolder)) { placeholderMap.Add(placeHolder, val); } } return placeholderMap.Aggregate(message, (current, pair) => current.Replace(pair.Key, pair.Value.ToString())); } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using CALI.Database.Contracts; using CALI.Database.Contracts.Auth; /////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend.// /////////////////////////////////////////////////////////// // This file contains static implementations of the RoleLogic // Add your own static methods by making a new partial class. // You cannot override static methods, instead override the methods // located in RoleLogicBase by making a partial class of RoleLogic // and overriding the base methods. namespace CALI.Database.Logic.Auth { public partial class RoleLogic { //Put your code in a separate file. This is auto generated. /// <summary> /// Run Role_Insert. /// </summary> /// <param name="fldTitle">Value for Title</param> /// <param name="fldDescription">Value for Description</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldApplyToAnon">Value for ApplyToAnon</param> /// <param name="fldApplyToAllUsers">Value for ApplyToAllUsers</param> /// <param name="fldPreventAddingUsers">Value for PreventAddingUsers</param> /// <param name="fldWINSID">Value for WINSID</param> public static int? InsertNow(string fldTitle , string fldDescription , bool fldIsActive , bool fldApplyToAnon , bool fldApplyToAllUsers , bool fldPreventAddingUsers , string fldWINSID ) { return (new RoleLogic()).Insert(fldTitle , fldDescription , fldIsActive , fldApplyToAnon , fldApplyToAllUsers , fldPreventAddingUsers , fldWINSID ); } /// <summary> /// Run Role_Insert. /// </summary> /// <param name="fldTitle">Value for Title</param> /// <param name="fldDescription">Value for Description</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldApplyToAnon">Value for ApplyToAnon</param> /// <param name="fldApplyToAllUsers">Value for ApplyToAllUsers</param> /// <param name="fldPreventAddingUsers">Value for PreventAddingUsers</param> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> public static int? InsertNow(string fldTitle , string fldDescription , bool fldIsActive , bool fldApplyToAnon , bool fldApplyToAllUsers , bool fldPreventAddingUsers , string fldWINSID , SqlConnection connection, SqlTransaction transaction) { return (new RoleLogic()).Insert(fldTitle , fldDescription , fldIsActive , fldApplyToAnon , fldApplyToAllUsers , fldPreventAddingUsers , fldWINSID , connection, transaction); } /// <summary> /// Insert 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 static int InsertNow(RoleContract row) { return (new RoleLogic()).Insert(row); } /// <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>The number of rows affected.</returns> public static int InsertNow(RoleContract row, SqlConnection connection, SqlTransaction transaction) { return (new RoleLogic()).Insert(row, connection, transaction); } /// <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 static int InsertAllNow(List<RoleContract> rows) { return (new RoleLogic()).InsertAll(rows); } /// <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 static int InsertAllNow(List<RoleContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new RoleLogic()).InsertAll(rows, connection, transaction); } /// <summary> /// Run Role_Update. /// </summary> /// <param name="fldRoleId">Value for RoleId</param> /// <param name="fldTitle">Value for Title</param> /// <param name="fldDescription">Value for Description</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldApplyToAnon">Value for ApplyToAnon</param> /// <param name="fldApplyToAllUsers">Value for ApplyToAllUsers</param> /// <param name="fldPreventAddingUsers">Value for PreventAddingUsers</param> /// <param name="fldWINSID">Value for WINSID</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(int fldRoleId , string fldTitle , string fldDescription , bool fldIsActive , bool fldApplyToAnon , bool fldApplyToAllUsers , bool fldPreventAddingUsers , string fldWINSID ) { return (new RoleLogic()).Update(fldRoleId , fldTitle , fldDescription , fldIsActive , fldApplyToAnon , fldApplyToAllUsers , fldPreventAddingUsers , fldWINSID ); } /// <summary> /// Run Role_Update. /// </summary> /// <param name="fldRoleId">Value for RoleId</param> /// <param name="fldTitle">Value for Title</param> /// <param name="fldDescription">Value for Description</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldApplyToAnon">Value for ApplyToAnon</param> /// <param name="fldApplyToAllUsers">Value for ApplyToAllUsers</param> /// <param name="fldPreventAddingUsers">Value for PreventAddingUsers</param> /// <param name="fldWINSID">Value for WINSID</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 static int UpdateNow(int fldRoleId , string fldTitle , string fldDescription , bool fldIsActive , bool fldApplyToAnon , bool fldApplyToAllUsers , bool fldPreventAddingUsers , string fldWINSID , SqlConnection connection, SqlTransaction transaction) { return (new RoleLogic()).Update(fldRoleId , fldTitle , fldDescription , fldIsActive , fldApplyToAnon , fldApplyToAllUsers , fldPreventAddingUsers , fldWINSID , connection, transaction); } /// <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 static int UpdateNow(RoleContract row) { return (new RoleLogic()).Update(row); } /// <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 static int UpdateNow(RoleContract row, SqlConnection connection, SqlTransaction transaction) { return (new RoleLogic()).Update(row, connection, transaction); } /// <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 static int UpdateAllNow(List<RoleContract> rows) { return (new RoleLogic()).UpdateAll(rows); } /// <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 static int UpdateAllNow(List<RoleContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new RoleLogic()).UpdateAll(rows, connection, transaction); } /// <summary> /// Run Role_Delete. /// </summary> /// <param name="fldRoleId">Value for RoleId</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(int fldRoleId ) { return (new RoleLogic()).Delete(fldRoleId ); } /// <summary> /// Run Role_Delete. /// </summary> /// <param name="fldRoleId">Value for RoleId</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 static int DeleteNow(int fldRoleId , SqlConnection connection, SqlTransaction transaction) { return (new RoleLogic()).Delete(fldRoleId , connection, transaction); } /// <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 static int DeleteNow(RoleContract row) { return (new RoleLogic()).Delete(row); } /// <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 static int DeleteNow(RoleContract row, SqlConnection connection, SqlTransaction transaction) { return (new RoleLogic()).Delete(row, connection, transaction); } /// <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 static int DeleteAllNow(List<RoleContract> rows) { return (new RoleLogic()).DeleteAll(rows); } /// <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 static int DeleteAllNow(List<RoleContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new RoleLogic()).DeleteAll(rows, connection, transaction); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldRoleId">Value for RoleId</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldRoleId ) { return (new RoleLogic()).Exists(fldRoleId ); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldRoleId">Value for RoleId</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 static bool ExistsNow(int fldRoleId , SqlConnection connection, SqlTransaction transaction) { return (new RoleLogic()).Exists(fldRoleId , connection, transaction); } /// <summary> /// Run Role_Search, and return results as a list of RoleRow. /// </summary> /// <param name="fldTitle">Value for Title</param> /// <param name="fldDescription">Value for Description</param> /// <param name="fldWINSID">Value for WINSID</param> /// <returns>A collection of RoleRow.</returns> public static List<RoleContract> SearchNow(string fldTitle , string fldDescription , string fldWINSID ) { var driver = new RoleLogic(); driver.Search(fldTitle , fldDescription , fldWINSID ); return driver.Results; } /// <summary> /// Run Role_Search, and return results as a list of RoleRow. /// </summary> /// <param name="fldTitle">Value for Title</param> /// <param name="fldDescription">Value for Description</param> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of RoleRow.</returns> public static List<RoleContract> SearchNow(string fldTitle , string fldDescription , string fldWINSID , SqlConnection connection, SqlTransaction transaction) { var driver = new RoleLogic(); driver.Search(fldTitle , fldDescription , fldWINSID , connection, transaction); return driver.Results; } /// <summary> /// Run Role_SelectAll, and return results as a list of RoleRow. /// </summary> /// <returns>A collection of RoleRow.</returns> public static List<RoleContract> SelectAllNow() { var driver = new RoleLogic(); driver.SelectAll(); return driver.Results; } /// <summary> /// Run Role_SelectAll, and return results as a list of RoleRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of RoleRow.</returns> public static List<RoleContract> SelectAllNow(SqlConnection connection, SqlTransaction transaction) { var driver = new RoleLogic(); driver.SelectAll(connection, transaction); return driver.Results; } /// <summary> /// Run Role_List, and return results as a list. /// </summary> /// <param name="fldTitle">Value for Title</param> /// <returns>A collection of __ListItemRow.</returns> public static List<ListItemContract> ListNow(string fldTitle ) { return (new RoleLogic()).List(fldTitle ); } /// <summary> /// Run Role_List, and return results as a list. /// </summary> /// <param name="fldTitle">Value for Title</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of __ListItemRow.</returns> public static List<ListItemContract> ListNow(string fldTitle , SqlConnection connection, SqlTransaction transaction) { return (new RoleLogic()).List(fldTitle , connection, transaction); } /// <summary> /// Run Role_SelectBy_RoleId, and return results as a list of RoleRow. /// </summary> /// <param name="fldRoleId">Value for RoleId</param> /// <returns>A collection of RoleRow.</returns> public static List<RoleContract> SelectBy_RoleIdNow(int fldRoleId ) { var driver = new RoleLogic(); driver.SelectBy_RoleId(fldRoleId ); return driver.Results; } /// <summary> /// Run Role_SelectBy_RoleId, and return results as a list of RoleRow. /// </summary> /// <param name="fldRoleId">Value for RoleId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of RoleRow.</returns> public static List<RoleContract> SelectBy_RoleIdNow(int fldRoleId , SqlConnection connection, SqlTransaction transaction) { var driver = new RoleLogic(); driver.SelectBy_RoleId(fldRoleId , connection, transaction); return driver.Results; } /// <summary> /// Read all Role rows from the provided reader into the list structure of RoleRows /// </summary> /// <param name="reader">The result of running a sql command.</param> /// <returns>A populated RoleRows or an empty RoleRows if there are no results.</returns> public static List<RoleContract> ReadAllNow(SqlDataReader reader) { var driver = new RoleLogic(); driver.ReadAll(reader); return driver.Results; } /// <summary>"); /// Advance one, and read values into a Role /// </summary> /// <param name="reader">The result of running a sql command.</param>"); /// <returns>A Role or null if there are no results.</returns> public static RoleContract ReadOneNow(SqlDataReader reader) { var driver = new RoleLogic(); return driver.ReadOne(reader) ? driver.Results[0] : null; } /// <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 static int SaveNow(RoleContract row) { if(row.RoleId == null) { return InsertNow(row); } else { return UpdateNow(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 static int SaveNow(RoleContract row, SqlConnection connection, SqlTransaction transaction) { if(row.RoleId == null) { return InsertNow(row, connection, transaction); } else { return UpdateNow(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 static int SaveAllNow(List<RoleContract> rows) { return (new RoleLogic()).SaveAll(rows); } /// <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 static int SaveAllNow(List<RoleContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new RoleLogic()).SaveAll(rows, connection, transaction); } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmBlockTestFilterSelect { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmBlockTestFilterSelect() : base() { Load += frmBlockTestFilterSelect_Load; KeyPress += frmBlockTestFilterSelect_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.Button _cmdClick_1; public System.Windows.Forms.Button _cmdClick_2; public System.Windows.Forms.Button _cmdClick_3; private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } private System.Windows.Forms.CheckedListBox withEventsField_lstStockItem; public System.Windows.Forms.CheckedListBox lstStockItem { get { return withEventsField_lstStockItem; } set { if (withEventsField_lstStockItem != null) { withEventsField_lstStockItem.SelectedIndexChanged -= lstStockItem_SelectedIndexChanged; } withEventsField_lstStockItem = value; if (withEventsField_lstStockItem != null) { withEventsField_lstStockItem.SelectedIndexChanged += lstStockItem_SelectedIndexChanged; } } } private System.Windows.Forms.TextBox withEventsField_txtSearch; public System.Windows.Forms.TextBox txtSearch { get { return withEventsField_txtSearch; } set { if (withEventsField_txtSearch != null) { withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown; withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress; } withEventsField_txtSearch = value; if (withEventsField_txtSearch != null) { withEventsField_txtSearch.KeyDown += txtSearch_KeyDown; withEventsField_txtSearch.KeyPress += txtSearch_KeyPress; } } } private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button1; public System.Windows.Forms.ToolStripButton _tbStockItem_Button1 { get { return withEventsField__tbStockItem_Button1; } set { if (withEventsField__tbStockItem_Button1 != null) { withEventsField__tbStockItem_Button1.Click -= tbStockItem_ButtonClick; } withEventsField__tbStockItem_Button1 = value; if (withEventsField__tbStockItem_Button1 != null) { withEventsField__tbStockItem_Button1.Click += tbStockItem_ButtonClick; } } } private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button2; public System.Windows.Forms.ToolStripButton _tbStockItem_Button2 { get { return withEventsField__tbStockItem_Button2; } set { if (withEventsField__tbStockItem_Button2 != null) { withEventsField__tbStockItem_Button2.Click -= tbStockItem_ButtonClick; } withEventsField__tbStockItem_Button2 = value; if (withEventsField__tbStockItem_Button2 != null) { withEventsField__tbStockItem_Button2.Click += tbStockItem_ButtonClick; } } } private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button3; public System.Windows.Forms.ToolStripButton _tbStockItem_Button3 { get { return withEventsField__tbStockItem_Button3; } set { if (withEventsField__tbStockItem_Button3 != null) { withEventsField__tbStockItem_Button3.Click -= tbStockItem_ButtonClick; } withEventsField__tbStockItem_Button3 = value; if (withEventsField__tbStockItem_Button3 != null) { withEventsField__tbStockItem_Button3.Click += tbStockItem_ButtonClick; } } } public System.Windows.Forms.ToolStrip tbStockItem; public System.Windows.Forms.ImageList ilSelect; public System.Windows.Forms.Label lblHeading; public System.Windows.Forms.Label _lbl_2; //Public WithEvents cmdClick As Microsoft.VisualBasic.Compatibility.VB6.ButtonArray //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmBlockTestFilterSelect)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this._cmdClick_1 = new System.Windows.Forms.Button(); this._cmdClick_2 = new System.Windows.Forms.Button(); this._cmdClick_3 = new System.Windows.Forms.Button(); this.cmdExit = new System.Windows.Forms.Button(); this.lstStockItem = new System.Windows.Forms.CheckedListBox(); this.txtSearch = new System.Windows.Forms.TextBox(); this.tbStockItem = new System.Windows.Forms.ToolStrip(); this._tbStockItem_Button1 = new System.Windows.Forms.ToolStripButton(); this._tbStockItem_Button2 = new System.Windows.Forms.ToolStripButton(); this._tbStockItem_Button3 = new System.Windows.Forms.ToolStripButton(); this.ilSelect = new System.Windows.Forms.ImageList(); this.lblHeading = new System.Windows.Forms.Label(); this._lbl_2 = new System.Windows.Forms.Label(); //Me.cmdClick = New Microsoft.VisualBasic.Compatibility.VB6.ButtonArray(components) //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) this.tbStockItem.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.cmdClick, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Allocate Stock Items to Price List Group"; this.ClientSize = new System.Drawing.Size(271, 452); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmBlockTestFilterSelect"; this._cmdClick_1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this._cmdClick_1.Text = "&A"; this._cmdClick_1.Size = new System.Drawing.Size(103, 34); this._cmdClick_1.Location = new System.Drawing.Point(303, 162); this._cmdClick_1.TabIndex = 8; this._cmdClick_1.TabStop = false; this._cmdClick_1.BackColor = System.Drawing.SystemColors.Control; this._cmdClick_1.CausesValidation = true; this._cmdClick_1.Enabled = true; this._cmdClick_1.ForeColor = System.Drawing.SystemColors.ControlText; this._cmdClick_1.Cursor = System.Windows.Forms.Cursors.Default; this._cmdClick_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._cmdClick_1.Name = "_cmdClick_1"; this._cmdClick_2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this._cmdClick_2.Text = "&S"; this._cmdClick_2.Size = new System.Drawing.Size(103, 34); this._cmdClick_2.Location = new System.Drawing.Point(306, 210); this._cmdClick_2.TabIndex = 7; this._cmdClick_2.TabStop = false; this._cmdClick_2.BackColor = System.Drawing.SystemColors.Control; this._cmdClick_2.CausesValidation = true; this._cmdClick_2.Enabled = true; this._cmdClick_2.ForeColor = System.Drawing.SystemColors.ControlText; this._cmdClick_2.Cursor = System.Windows.Forms.Cursors.Default; this._cmdClick_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._cmdClick_2.Name = "_cmdClick_2"; this._cmdClick_3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this._cmdClick_3.Text = "&U"; this._cmdClick_3.Size = new System.Drawing.Size(103, 34); this._cmdClick_3.Location = new System.Drawing.Point(297, 261); this._cmdClick_3.TabIndex = 6; this._cmdClick_3.TabStop = false; this._cmdClick_3.BackColor = System.Drawing.SystemColors.Control; this._cmdClick_3.CausesValidation = true; this._cmdClick_3.Enabled = true; this._cmdClick_3.ForeColor = System.Drawing.SystemColors.ControlText; this._cmdClick_3.Cursor = System.Windows.Forms.Cursors.Default; this._cmdClick_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._cmdClick_3.Name = "_cmdClick_3"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Size = new System.Drawing.Size(97, 52); this.cmdExit.Location = new System.Drawing.Point(168, 393); this.cmdExit.TabIndex = 4; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.lstStockItem.Size = new System.Drawing.Size(254, 304); this.lstStockItem.Location = new System.Drawing.Point(9, 81); this.lstStockItem.Sorted = true; this.lstStockItem.TabIndex = 1; this.lstStockItem.Tag = "0"; this.lstStockItem.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lstStockItem.BackColor = System.Drawing.SystemColors.Window; this.lstStockItem.CausesValidation = true; this.lstStockItem.Enabled = true; this.lstStockItem.ForeColor = System.Drawing.SystemColors.WindowText; this.lstStockItem.IntegralHeight = true; this.lstStockItem.Cursor = System.Windows.Forms.Cursors.Default; this.lstStockItem.SelectionMode = System.Windows.Forms.SelectionMode.One; this.lstStockItem.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lstStockItem.TabStop = true; this.lstStockItem.Visible = true; this.lstStockItem.MultiColumn = false; this.lstStockItem.Name = "lstStockItem"; this.txtSearch.AutoSize = false; this.txtSearch.Size = new System.Drawing.Size(215, 19); this.txtSearch.Location = new System.Drawing.Point(48, 57); this.txtSearch.TabIndex = 0; this.txtSearch.AcceptsReturn = true; this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtSearch.BackColor = System.Drawing.SystemColors.Window; this.txtSearch.CausesValidation = true; this.txtSearch.Enabled = true; this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText; this.txtSearch.HideSelection = true; this.txtSearch.ReadOnly = false; this.txtSearch.MaxLength = 0; this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSearch.Multiline = false; this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtSearch.TabStop = true; this.txtSearch.Visible = true; this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSearch.Name = "txtSearch"; this.tbStockItem.ShowItemToolTips = true; this.tbStockItem.Size = new System.Drawing.Size(272, 40); this.tbStockItem.Location = new System.Drawing.Point(0, 18); this.tbStockItem.TabIndex = 2; this.tbStockItem.ImageList = ilSelect; this.tbStockItem.Name = "tbStockItem"; this._tbStockItem_Button1.Size = new System.Drawing.Size(68, 41); this._tbStockItem_Button1.AutoSize = false; this._tbStockItem_Button1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText; this._tbStockItem_Button1.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this._tbStockItem_Button1.Text = "&All"; this._tbStockItem_Button1.Name = "All"; this._tbStockItem_Button1.ImageIndex = 0; this._tbStockItem_Button1.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this._tbStockItem_Button2.Size = new System.Drawing.Size(68, 41); this._tbStockItem_Button2.AutoSize = false; this._tbStockItem_Button2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText; this._tbStockItem_Button2.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this._tbStockItem_Button2.Text = "&Selected"; this._tbStockItem_Button2.Name = "Selected"; this._tbStockItem_Button2.ImageIndex = 1; this._tbStockItem_Button2.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this._tbStockItem_Button3.Size = new System.Drawing.Size(68, 41); this._tbStockItem_Button3.AutoSize = false; this._tbStockItem_Button3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText; this._tbStockItem_Button3.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this._tbStockItem_Button3.Text = "&Unselected"; this._tbStockItem_Button3.Name = "Unselected"; this._tbStockItem_Button3.ImageIndex = 2; this._tbStockItem_Button3.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.ilSelect.ImageSize = new System.Drawing.Size(20, 20); this.ilSelect.TransparentColor = System.Drawing.Color.FromArgb(255, 0, 255); this.ilSelect.ImageStream = (System.Windows.Forms.ImageListStreamer)resources.GetObject("ilSelect.ImageStream"); this.ilSelect.Images.SetKeyName(0, ""); this.ilSelect.Images.SetKeyName(1, ""); this.ilSelect.Images.SetKeyName(2, ""); this.lblHeading.Text = "Label1"; this.lblHeading.Size = new System.Drawing.Size(273, 19); this.lblHeading.Location = new System.Drawing.Point(0, 0); this.lblHeading.TabIndex = 5; this.lblHeading.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblHeading.BackColor = System.Drawing.SystemColors.Control; this.lblHeading.Enabled = true; this.lblHeading.ForeColor = System.Drawing.SystemColors.ControlText; this.lblHeading.Cursor = System.Windows.Forms.Cursors.Default; this.lblHeading.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblHeading.UseMnemonic = true; this.lblHeading.Visible = true; this.lblHeading.AutoSize = false; this.lblHeading.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblHeading.Name = "lblHeading"; this._lbl_2.Text = "Search:"; this._lbl_2.Size = new System.Drawing.Size(40, 13); this._lbl_2.Location = new System.Drawing.Point(6, 60); this._lbl_2.TabIndex = 3; this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_2.BackColor = System.Drawing.Color.Transparent; this._lbl_2.Enabled = true; this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_2.UseMnemonic = true; this._lbl_2.Visible = true; this._lbl_2.AutoSize = false; this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_2.Name = "_lbl_2"; this.Controls.Add(_cmdClick_1); this.Controls.Add(_cmdClick_2); this.Controls.Add(_cmdClick_3); this.Controls.Add(cmdExit); this.Controls.Add(lstStockItem); this.Controls.Add(txtSearch); this.Controls.Add(tbStockItem); this.Controls.Add(lblHeading); this.Controls.Add(_lbl_2); this.tbStockItem.Items.Add(_tbStockItem_Button1); this.tbStockItem.Items.Add(_tbStockItem_Button2); this.tbStockItem.Items.Add(_tbStockItem_Button3); //Me.cmdClick.SetIndex(_cmdClick_1, CType(1, Short)) //Me.cmdClick.SetIndex(_cmdClick_2, CType(2, Short)) //Me.cmdClick.SetIndex(_cmdClick_3, CType(3, Short)) //Me.lbl.SetIndex(_lbl_2, CType(2, Short)) //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.cmdClick, System.ComponentModel.ISupportInitialize).EndInit() this.tbStockItem.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using System; using System.Collections.Generic; using Sce.Pss.Core; using Sce.Pss.Core.Imaging; using Sce.Pss.Core.Environment; using Sce.Pss.HighLevel.UI; using Magnate; enum CurrentScene { First = 1, Second = 2, Third = 3, Fourth = 4, Fifth = 5, Sixth = 6, Seventh = 7, Eighth = 8, Nineth = 9, Tenth = 10 }; namespace MagnateUI { public partial class ChatDialogueUI : Scene { Game game = Game.Instance; TapGestureDetector continueTapGestureDetector; int count = 0; static int currentPhase = 0; bool forceSetUp = false; public ChatDialogueUI () { Aiden = new Sprite (); Kira = new Sprite (); Bear = new Sprite (); Bandit1 = new Sprite (); Bandit2 = new Sprite (); Bandit3 = new Sprite (); LCharBoxL = new ImageBox (); LCharBoxL.Name = "LCharBoxL"; LCharboxR = new ImageBox (); LCharboxR.Name = "LCharboxR"; RCharBoxR = new ImageBox (); RCharBoxR.Name = "RCharBoxR"; RCharBoxL = new ImageBox (); RCharBoxL.Name = "RCharBoxL"; RCharBoxM = new ImageBox (); RCharBoxM.Name = "RCharBoxM"; DialogueText = new Label (); DialogueText.Name = "DialogueText"; screenVignette = new ImageBox (); screenVignette.Name = "ScreenVignette"; ChatBox = new ImageBox (); ChatBox.Name = "ChatBox"; DialogueText = new Label (); DialogueText.Name = "DialogueText"; Aiden.state = (int)CharacterState.Normal; Kira.state = (int)CharacterState.Normal; Bear.state = (int)CharacterState.Normal; Bandit1.state = (int)BanditState.BANDIT1_SMUG; Bandit2.state = (int)BanditState.BANDIT2_SMUG; Bandit3.state = (int)BanditState.BANDIT3_SMUG; currentPhase++; InitializeWidget (); continueTapGestureDetector = new TapGestureDetector (); continueTapGestureDetector.TapDetected += TextTapGestureEventHandler; screenVignette.AddGestureDetector (continueTapGestureDetector); UpdateLanguage (); } void TextTapGestureEventHandler (object sender, TapEventArgs e) { UpdateLanguage (); } public void UpdateLanguage () { switch (currentPhase) { #region Scene One case (int)CurrentScene.First: if (count == 0) { DialogueText.Text = "It has been five years of long conquest for our young \theroes Aiden and Kira, who are trying to restore peace " + "amongst the volatile Kingdoms of Adura."; } if (count == 1) { DialogueText.Text = "Wary from battle our heroes have finally set their" + " eyes on their goal, Cuprille."; } if (count == 2) { DialogueText.Text = "However; feelings of relief were short lived when they realize the town they once " + "knew as a kingdom of prosperity,"; } if (count == 3) DialogueText.Text = "is now a barren rundown ghost town..."; if (count == 4) { Aside = false; game.ChatFinished = true; game.resetCount = true; } if (count == 0 | count == 4) SetUpCharacters (); count++; break; #endregion #region Scene Two case (int)CurrentScene.Second: if (count == 0) { DialogueText.Text = "Aiden and Kira emerge in the town and are filled " + "with grief when the place they once called home is " + "just a mere shadow of its former self. The question of what or whom could have " + "caused this devestation to their beloved town is brought to their minds."; } if (count == 1) { setAiden = true; setKira = true; Aside = false; DialogueText.Text = " Aiden & Kira: Cuprille!?"; setAiden = true; setKira = true; Aiden.state = (int)CharacterState.Shocked; Kira.state = (int)CharacterState.Shocked; SetWidgetLayout (LayoutOrientation.Horizontal); } if (count == 2) { DialogueText.Text = "Aiden: What has happened?! " + "It's deserted!"; } if (count == 3) { DialogueText.Text = "Kira: There are no children playing anymore, or fragrances of hot apple pie at every window."; } if (count == 4) { DialogueText.Text = "Kira: What could have caused this...? We need to get to the bottom of this."; Kira.state = (int)CharacterState.Thinking; Aiden.state = (int)CharacterState.Thinking; } if (count == 5) { DialogueText.Text = "BlackSmith: Hey kids! Get over here!"; } if (count == 6) { DialogueText.Text = "Aiden & Kira: Huh?"; Aiden.state = (int)CharacterState.Shocked; Kira.state = (int)CharacterState.Shocked; } if (count == 7) { DialogueText.Text = "Blacksmith: Hurry, before someone sees you!"; } if (count == 8) { SceneManager.ReplaceScene ((int)GE2D.BLACKSMITH); DialogueText.Text = "Our heroes run towards the door, and the blacksmith shuts it behind them. " + "The blacksmith remains in the shadows."; Aside = true; setKira = false; setAiden = false; SetUpCharacters (Aiden, Kira); SetWidgetLayout (LayoutOrientation.Horizontal); } if (count == 9) { DialogueText.Text = "Kira: Why have you called us in here, blacksmith? What has hap....."; Aside = false; setAiden = true; setKira = true; Aiden.state = (int)CharacterState.Thinking; Kira.state = (int)CharacterState.Thinking; SetWidgetLayout (LayoutOrientation.Horizontal); } if (count == 10) { DialogueText.Text = "BlackSmith: Silence. These times are too dangerous and time too short for chit chat. " + "I saw you and your army coming in from the east."; } if (count == 11) { DialogueText.Text = "So, I'm going to make this short. We need your help to take back this land from an evil knight that " + "sieged our neighbor kingdom from the north"; } if (count == 12) { DialogueText.Text = "Aiden: Rihan has been sieged too!?"; Aiden.state = (int)CharacterState.Shocked; Kira.state = (int)CharacterState.Shocked; } if (count == 13) { DialogueText.Text = "Kira: Things are worse then we thought."; Kira.state = (int)CharacterState.Thinking; Aiden.state = (int)CharacterState.Worried; } if (count == 14) { DialogueText.Text = "Aiden: So where do we start?"; Aiden.state = (int)CharacterState.Thinking; } if (count == 15) { DialogueText.Text = "Blacksmith: I suggest we first take back our mines. " + "Then I may be more of a use in our revolt against our oppressors."; } if (count == 16) { DialogueText.Text = "Aiden: Right. Well, we will be back soon after we reclaim the mines."; Aiden.state = (int)CharacterState.Angry; Kira.state = (int)CharacterState.Normal; } if (count == 17) { DialogueText.Text = "Blacksmith: Oh, and be careful; some say lately that the mines have become... Haunted"; setAiden = false; setKira = false; } if (Aiden.state != Aiden.oldState | Kira.state != Kira.oldState) SetUpCharacters (Aiden, Kira); if (count == 18) { game.ChatFinished = true; game.resetCount = true; SetUpCharacters (); } count++; break; #endregion #region Scene Three case (int)CurrentScene.Third: if (count == 0) { DialogueText.Text = "Our heroes aproach the mines. A sense of unease has filled the air while the " + "blacksmith's grave warning of a haunted mine echoes in their minds"; } if (count == 1) { DialogueText.Text = "Aiden: Well, here we are. At the \"haunted\" mines."; Aiden.state = (int)CharacterState.Normal; setAiden = true; setKira = true; Aside = false; //SetUpCharacters (Aiden, Kira); SetWidgetLayout (LayoutOrientation.Horizontal); } if (count == 2) { DialogueText.Text = "Kira: Haunted mines or not, men, we will not let any make believe ghosts hold us " + "back from glory! Charge in there!"; Kira.state = (int)CharacterState.Angry; } if (count == 3) { DialogueText.Text = "As the men charge into the mine, a few moments pass before shrieks of fear echo out of the cave. " + "Suddenly all sound stops and anxiety slowly creeps in."; Aside = true; setAiden = false; setKira = false; //SetUpCharacters (Aiden, Kira); SetWidgetLayout (LayoutOrientation.Horizontal); } if (count == 4) { DialogueText.Text = "Aiden: We need to help them! All men, I'm at point, charge!"; setAiden = true; setKira = true; Aiden.state = (int)CharacterState.Angry; Kira.state = (int)CharacterState.Worried; Aside = false; SetWidgetLayout (LayoutOrientation.Horizontal); } if (count == 5) { DialogueText.Text = "Aiden and Kira choose to split up and after a few moments of decending deeper into to the mines. " + "They come to the central main shaft."; Aside = true; setAiden = false; setKira = false; SetWidgetLayout (LayoutOrientation.Horizontal); } if (count == 6) { DialogueText.Text = "Kira: Did you see anything?"; setAiden = true; setKira = true; Aside = false; SetWidgetLayout (LayoutOrientation.Horizontal); Kira.state = (int)CharacterState.Normal; Aiden.state = (int)CharacterState.Worried; } if (count == 7) { DialogueText.Text = "Aiden: Nothing. No blood, no weapons, no signs of struggle. It's as if they..."; Aiden.state = (int)CharacterState.Thinking; } if (count == 8) { DialogueText.Text = "Aiden & Kira: Vanished!"; Kira.state = (int)CharacterState.Thinking; } if (count == 9) { DialogueText.Text = "Unknown: Heh heh heh. Combusted and disintegrated to be more precise."; } if (count == 10) { DialogueText.Text = "Aiden: Who said that? Show yourself!"; Aiden.state = (int)CharacterState.Shocked; Kira.state = (int)CharacterState.Shocked; } if (count == 11) { DialogueText.Text = "Unknown: It will be a pleasure. I am Elider the Taint."; setBandit3 = true; kiraOnLeft = true; Bandit3.state = (int)BanditState.BANDIT3_SMUG; Kira.forcevisible = true; } if (count == 12) { DialogueText.Text = "Kira: You did this to my men!? You will pay for what you have done!"; Aiden.state = (int)CharacterState.Angry; Kira.state = (int)CharacterState.Angry; } if (count == 13) { DialogueText.Text = "Elider: If you want to die, little girl, it will be my pleasure to grant your wish."; Bandit3.state = (int)BanditState.BANDIT3_ANNOY; SetUpCharacters (Aiden, Kira, Bandit3); } if (count == 14) { DialogueText.Text = "Kira: Just shut up and draw your sword, old man!"; Kira.state = (int)CharacterState.Angry; } if (count == 15) { game.StartBattle = true; } if (count == 16) { DialogueText.Text = "Kira: Heh. Old man, I didn't even break a sweat. Now to put you out of your misery!"; Kira.forcevisible = true; Aiden.state = (int)CharacterState.Happy; Bandit3.state = (int)BanditState.BANDIT3_MAD; } if (count == 17) { DialogueText.Text = "Elider: Ugghhh, you little nitwits. Do you have any idea of who you are messing with here? " + "Lord Darius will not be pleased to hear of your interference with our plans."; Bandit3.state = (int)BanditState.BANDIT3_MAD; } if (count == 18) { DialogueText.Text = "Aiden: Kira wait, Lord Darius!? It can't be! My father vanquished him and his legion long ago!"; Aiden.state = (int)CharacterState.Shocked; Kira.state = (int)CharacterState.Normal; } if (count == 19) { DialogueText.Text = "Elider: HA HA HA HA! Well well, so you must be the son of Aimes the Magnate? And you are trying to " + "follow in your fathers footsteps too, I see? What a noble way to lead your life... to your death; much like your father did!"; Bandit1.state = (int)BanditState.BANDIT3_SMUG; } if (count == 20) { DialogueText.Text = "Kira: WHY YOU! I will cut out your tongue for insulting the greatest hero in the history of Adura...!"; Aiden.state = (int)CharacterState.Worried; Kira.state = (int)CharacterState.Angry; } if (count == 21) { DialogueText.Text = "Aiden: Kira... back down. Mage, Go tell your master to prepare for war. We end this now."; Aiden.state = (int)CharacterState.Angry; } if (count == 22) { DialogueText.Text = "Kira: We are letting him go?! But my men..."; Kira.state = (int)CharacterState.Shocked; setBandit3 = false; } if (count == 23) { DialogueText.Text = "Aiden: Kira, I'm sorry about your men, but I want to make sure Lord Darius is fully aware of who is at " + "his doorstep ready for battle. Also, the man was clearly defeated. We do not murder unarmed opponenets. " + "Or else we become the same as them."; Aiden.state = (int)CharacterState.Angry; } if (count == 24) { DialogueText.Text = "Kira: But... GRRR! Fine. Stupid men with their morals and egos. I'm out of here!"; Kira.state = (int)CharacterState.Angry; } if (count == 25) { DialogueText.Text = "Aiden: Kira! Wait..."; Aiden.state = (int)CharacterState.Shocked; setKira = false; kiraOnLeft = false; } if (count == 26) { SceneManager.ReplaceScene((int)GE2D.HILL); DialogueText.Text = " Later that evening, Aiden sits ontop of a hill having isolated himself from his men. " + "A lone tear runs down his face as he remembers a dear memory from his youth with his father."; Aiden.state = (int)CharacterState.Worried; } if (count == 27) { DialogueText.Text = " Inside, Aiden believes that if he could even become half the hero his father was, he could pass on " + "from this world completely satisifed he lived a fulfilling life."; } if (count == 28) { DialogueText.Text = "It's been a long five years without his father's guidance, but he is fully aware of what his " + "next move must be. Suddenly, he begins to collect himself as he senses someone approaching."; Aiden.state = (int)CharacterState.Normal; } if (count == 29) { DialogueText.Text = "Kira: Look Aiden. I'm sorry about earlier. You are right considering the fact that, as leaders, " + "we don't kill unarmed defeated men. We must set the example. However, why would you want to give away the element of surprise?"; setKira = true; Kira.state = (int)CharacterState.Worried; } if (count == 30) { DialogueText.Text = "Aiden: The element of surprise against Darius? He knows that our army is here. " + "However, I want him to personally know that I am here. To avenge my fathers death, by defeating his murderer at his best!"; Aiden.state = (int)CharacterState.Angry; } if (count == 31) { DialogueText.Text = "Kira: Darius killed your father? But I thought he died from a rare illness that he caught on " + "during his last campaign that would have unitied all of Adura?"; Aiden.state = (int)CharacterState.Worried; Kira.state = (int)CharacterState.Shocked; } if (count == 32) { DialogueText.Text = "Aiden: My father was poisoned by an unknown agent at the time. Considering that we were so " + "close to reuniting the kingdoms of Adura, my father's last order was to falsify the story of his death"; Aiden.state = (int)CharacterState.Worried; } if (count == 33) { DialogueText.Text = "Kira: So the other kingdoms wouldn't suspect each other of treachery due to the down defense?"; Kira.state = (int)CharacterState.Thinking; } if (count == 34) { DialogueText.Text = "Aiden: Exactly, However, we were under the conclusion that Darius was not alive. So we " + "came to the conclusion it was one of his loyalists avenging his death."; Aiden.state = (int)CharacterState.Thinking; } if (count == 35) { DialogueText.Text = "But considering the current intel that's been brought to my attention, it's obvious the hit " + "was ordered by the coward himself."; Aiden.state = (int)CharacterState.Angry; } if (count == 36) { DialogueText.Text = "Kira: Look Aiden, I am very sorry. Aimes was a real father figure to me as well. " + "He taught us every thing we know. I agree that we must stop him!"; Kira.state = (int)CharacterState.Worried; } if (count == 37) { DialogueText.Text = "Aiden: Indeed... Tomorrow I must gather more resources and report back to the blacksmith in " + "Cuprille, however WE is no longer an option Kira. This is my battle."; Aiden.state = (int)CharacterState.Normal; } if (count == 38) { DialogueText.Text = "Aiden: Therefore, tomorrow at the break of dawn I am ordering you and your men out of this Kingdom."; Aiden.state = (int)CharacterState.Angry; } if (count == 39) { DialogueText.Text = "Kira: AIDEN! You can't send me..."; Kira.state = (int)CharacterState.Shocked; } if (count == 40) { DialogueText.Text = "Aiden: That's an order."; } if (count == 41) { DialogueText.Text = "Kira: But..."; Kira.state = (int)CharacterState.Worried; } if (count == 42) { DialogueText.Text = "Aiden: Soldier! As your commanding officer, my orders are the law in this battalion. Need I strip rank?"; Aiden.state = (int)CharacterState.Angry; } if (count == 43) { DialogueText.Text = "Kira: No sir..."; Kira.state = (int)CharacterState.Normal; } if (count == 44) { DialogueText.Text = "Kira walks away, obviously frustrated and partially hurt that Aiden would humble her with his rank."; setKira = false; } if (count == 45) { DialogueText.Text = "However Aiden cares deeply for Kira and knows that there is a great chance that he may not " + "survive the battle with Darius. Thoughts of her survival is his only source of strength "; Aiden.state = (int)CharacterState.Thinking; } if (count == 46) { game.ChatFinished = true; SetUpCharacters(Aiden); break; } if(count <= 22){ if (Aiden.state != Aiden.oldState | Kira.state != Kira.oldState | Bandit3.state != Bandit3.oldState | forceSetUp) SetUpCharacters (Aiden, Kira, Bandit3);} else { if (Aiden.state != Aiden.oldState | Kira.state != Kira.oldState) SetUpCharacters(Aiden,Kira); } count++; break; #endregion #region Scene Four case (int)CurrentScene.Fourth: if(count == 0){ DialogueText.Text = " The sun rises in the east and Aiden is watching Kira march her army away. How he wishes she " + "would look back at him. Not a single glance."; Aside = true; SetWidgetLayout(LayoutOrientation.Horizontal); } if(count ==1){ SceneManager.ReplaceScene((int)GE2D.BLACKSMITH); DialogueText.Text = "Aiden: Blacksmith! I am back, and we have secured the mine. Now if we are going to take " + "back this land, I will need the finest sword you will ever create."; setAiden = true; Aiden.state = (int)CharacterState.Normal; Aside = false; SetWidgetLayout(LayoutOrientation.Horizontal); } if(count ==2){ DialogueText.Text = "Blacksmith: Ahhh, what happened to the fine lass you had with you yesterday?"; } if(count ==3){ DialogueText.Text = "Aiden: That's of no concern to you. Just tell me what you need."; Aiden.state = (int)CharacterState.Angry; } if(count ==4){ DialogueText.Text = "Blacksmith: No need to be so testy, mate. I'm just wonderin'. Hmmm. Well, we need to secure our " + "other two strongholds first for their mines."; } if(count ==5){ DialogueText.Text = "Aiden: Is that it?"; Aiden.state = (int)CharacterState.Normal; } if(count ==6){ DialogueText.Text = " Blacksmith: Yep, we already got them mills to the east while you were in them mines. " + "You get them resources that we need and I can create a sword that will slay giants."; } if(count ==7){ DialogueText.Text = "Aiden: Alright, I will be back."; Aiden.state = (int)CharacterState.Normal; } if(count ==8){ game.ChatFinished = true; SetUpCharacters(Aiden); break; } if(Aiden.state != Aiden.oldState) { SetUpCharacters(Aiden); } count++; break; #endregion #region Scene Five case (int)CurrentScene.Fifth: if(count ==0){ DialogueText.Text = " Aiden arrives at the the southern strong hold and motions for his army to hold rank."; Aside = true; SetWidgetLayout(LayoutOrientation.Horizontal); } if(count ==1){ DialogueText.Text = "Aiden: Tell whoever leads this fortress to present himself, so that we may negotiate his surrender"; Aside = false; setAiden = true; Aiden.state = (int)CharacterState.Angry; SetUpCharacters(Aiden); SetWidgetLayout(LayoutOrientation.Horizontal); } if(count ==2){ DialogueText.Text = " A few moments pass, and as Aiden's patience begins to wear thin, the front gate is " + "pushed open and a man walks toward Aiden."; } if(count ==3){ DialogueText.Text = "Aiden: Are you the leader of this outpost? If so, surrender..."; Aiden.state = (int)CharacterState.Normal; setBandit2 = true; } if(count ==4){ DialogueText.Text = "Unknown: Surrender? Surrender to whom? A little boy and his army with second rate equipment " + "and armor? Move along, flea; you're not drawing any blood here."; Bandit2.state = (int)BanditState.BANDIT2_SMUG; } if(count ==5){ DialogueText.Text = " Aiden: Do not turn your back on me naively! I am Aiden, son of Aimes the Magnate. And I will cut " + "you down there where you stand."; Aiden.state = (int)CharacterState.Angry; } if(count ==6){ DialogueText.Text = " Unknown: Hmmmmm, As a matter of fact. Maybe this would be interesting after all. There has been a " + "very expensive bounty put on a... Son of Mr. Dead and forgotten."; Bandit2.state = (int)BanditState.BANDIT2_SMUG; } if(count ==7){ DialogueText.Text = " However, I will inform you that my name is Jasz of Bane."; Bandit2.state = (int)BanditState.BANDIT2_SMUG; } if(count ==8){ DialogueText.Text = " Aiden: Less introduction, more battling!"; Aiden.state = (int)CharacterState.Angry; } if(count ==9){ game.StartBattle =true; } if(count ==10){ DialogueText.Text = " Aiden: You are defeated, now surrender your town or my cold steel will be the last thing you " + "ever feel in this life"; Aiden.state = (int)CharacterState.Angry; Bandit2.state = (int)BanditState.BANDIT2_ANNOY; } if(count ==11){ DialogueText.Text = "Jasz of Bane: Alright, just don't kill me."; } if(count ==12){ DialogueText.Text = "Aiden: men take him in chains. We're keeping him prisoner."; Aiden.state = (int)CharacterState.Normal; setBandit2 = false; } if(count ==13){ game.ChatFinished = true; SetUpCharacters(Aiden); break; } if(Aiden.state != Aiden.oldState | Bandit2.state != Bandit2.oldState) SetUpCharacters(Aiden, Bandit2); count++; break; #endregion case (int)CurrentScene.Sixth: if(count ==0){ SceneManager.ReplaceScene((int)GE2D.BLACKSMITH); DialogueText.Text = "A few days pass and plenty of ore is mined from this stronghold. Aiden begins to worry a bit " + "about Kira. He is unsure if she would forgive him, or if he would even see her again."; } if(count ==1){ DialogueText.Text = "Aiden: Alright Blacksmith, just one more stronghold to take. Then I will be back."; setAiden = true; Aiden.state = (int)CharacterState.Normal; Aside = false; SetWidgetLayout(LayoutOrientation.Horizontal); } if(count ==2) { game.ChatFinished = true; } SetUpCharacters(Aiden); count++; break; case(int)CurrentScene.Seventh: if(count ==0){ SceneManager.ReplaceScene((int)GE2D.FORT); DialogueText.Text = "Aiden's army approaches the second stronghold. However, curiously, the front door is wide open."; } if(count ==1){ DialogueText.Text = "Aiden orders his men to hold back as he enters the stronghold himself."; } if(count ==2){ DialogueText.Text = " Aiden: Is anybody in here?! Show yourself! I am Aiden of Ventus and I am here to claim thi..."; setAiden = true; Aside = false; Aiden.state = (int)CharacterState.Angry; SetWidgetLayout(LayoutOrientation.Horizontal); } if(count ==3){ DialogueText.Text = "Unsuspecting to Aiden, a blow to the back of the head had knocked him completely unconscious."; Aiden.state = (int)CharacterState.Hurt; setBandit1 = true; setBandit2 = true; setBandit3 = true; } if(count ==4){ DialogueText.Text = " Jasz of Bane: Lord Arkan will reward us well for taking him alive."; setAiden = false; Bandit1.state = (int)BanditState.BANDIT1_SMUG; Bandit2.state = (int)BanditState.BANDIT2_SMUG; Bandit3.state = (int)BanditState.BANDIT3_SMUG; } if(count ==5){ DialogueText.Text = " Elider: Why must we take him alive.... Why not just say he struggled and we HAD TO KILL HIM."; Bandit3.state = (int)BanditState.BANDIT3_MAD; } if(count ==6){ DialogueText.Text = " Unknown: Shut your face, Elider, before I punch a crater in it."; Bandit1.state = (int)BanditState.BANDIT1_ANNOY; } if(count ==7){ DialogueText.Text = " Elider: But Rasz..."; Bandit3.state = (int)BanditState.BANDIT3_ANNOY; } if(count ==8){ DialogueText.Text = " Rasz snaps back and wrecks his fist against Elider's jaw, knocking him out cold."; setBandit3 = false; Bandit1.state = (int)BanditState.BANDIT1_MAD; } if(count ==9){ DialogueText.Text = " Jasz: Thank you, Brother. His whining was getting on my last nerve."; Bandit2.state = (int)BanditState.BANDIT2_SMUG; } if(count ==10){ DialogueText.Text = " Rasz: Shut it! Just carry the prisoner's body; I will have my quarrel to pick with you later. " + "I'm going to order my men who had sieged his puny force to start executing them immediately."; Bandit1.state = (int)BanditState.BANDIT1_ANNOY; setBandit1 = false; setBandit2 = false; setBandit3 = false; } if(count ==11){ SceneManager.ReplaceScene((int)GE2D.DUNGEON); DialogueText.Text = "Kira: Psst! Aiden, wake up."; setAiden = true; setKira = true; Aiden.forcevisible = true; Kira.state = (int)CharacterState.Worried; kiraOnLeft = true; SetUpCharacters(Aiden,Kira); } if(count ==12){ DialogueText.Text = "Aiden: Uughhhh. K-Kira? Is that you? Nghhh my head. Where are we?"; Aiden.state = (int)CharacterState.Hurt; } if(count ==13){ DialogueText.Text = "Kira: There's no time to explain everything, but right now we are in a dungeon. Now, let's get out of here."; Kira.state = (int)CharacterState.Worried; } if(count ==14){ DialogueText.Text = "Aiden: Where are my men?"; Aiden.state = (int)CharacterState.Hurt; } if(count ==15){ DialogueText.Text = "Kira: Aiden...."; Kira.state = (int)CharacterState.Worried; } if(count ==16){ DialogueText.Text = "Rasz: Your men are dead. I just finished exterminating the last one. He screamed like a little " + "girl before I ripped his throat out."; setBandit1 = true; Bandit1.state = (int)BanditState.BANDIT1_SMUG; } if(count ==17){ DialogueText.Text = "Aiden: YOU BASTARD!"; } if(count ==18){ DialogueText.Text = "Rasz: And in a moment, I'm going to rip your little girlfriend's throat out too. Well hey, she's " + "kind of a cutie, maybe we can have a little personal time first."; Bandit1.state = (int)BanditState.BANDIT1_SMUG; } if(count ==19){ DialogueText.Text = "Aiden: Don't you touch her!"; Aiden.state = (int)CharacterState.Hurt; } if(count ==20){ DialogueText.Text = "As Rasz walks closer to her, Kira roundhouse kicks him in the face and knocks Rasz to the floor"; } if(count ==21){ DialogueText.Text = "Rasz: You will pay for that, wench"; } if(count ==22){ DialogueText.Text = "Aiden: Let me out, Kira. You can't take him alone!"; Aiden.state = (int)CharacterState.Hurt; } if(count ==23){ DialogueText.Text = "Kira: Aiden, I can hold my own against this thug."; Kira.state = (int)CharacterState.Angry; } if(count ==24) { game.StartBattle = true; } if(count ==25){ DialogueText.Text = "Rasz: ughhhh..."; Bandit1.state = (int)BanditState.BANDIT1_MAD; } if(count ==26){ DialogueText.Text = "Kira: Your better stay down. Unless you want my dagger through your gut, you'll stay down and quiet."; Kira.state = (int)CharacterState.Normal; } if(count ==27){ DialogueText.Text = "Kira: Hold on, Aiden, I'll get you out..."; Kira.state = (int)CharacterState.Worried; } if(count ==28){ DialogueText.Text = "Kira frees Aiden from his cell, but as she does so, Rasz seemingly vanishes. Together, " + "the two young heroes return with Kira's men to town."; setBandit1 = false; } if(count ==29){ DialogueText.Text = "Aiden: Tomorrow, we'll go and face Darius."; Aiden.state = (int)CharacterState.Normal; } if(count ==30){ DialogueText.Text = "Kira: Together."; Kira.state = (int)CharacterState.Happy; } if(count ==31){ DialogueText.Text = "Aiden: ...Kira, I'm sorry. For sending you away."; Aiden.state = (int)CharacterState.Worried; } if(count ==32){ DialogueText.Text = "Kira: Just don't do it again, okay? I can't save your ass if I'm not here."; Kira.state = (int)CharacterState.Happy; } if(count ==33) { game.ChatFinished = true; SetUpCharacters(Aiden); break; } if(count <= 17){ if(Aiden.state != Aiden.oldState | Bandit1.state != Bandit1.oldState | Bandit2.state != Bandit2.oldState | Bandit3.state != Bandit3.oldState) { SetUpCharacters(Aiden, null, Bandit2, Bandit1, Bandit3); } } else if(Aiden.state != Aiden.oldState | Bandit1.state != Bandit1.oldState | Kira.state != Kira.oldState) SetUpCharacters(Aiden, Kira, Bandit1); count++; break; case (int)CurrentScene.Eighth: if(count ==0){ SceneManager.ReplaceScene((int)GE2D.BLACKSMITH); DialogueText.Text = "The next morning dawns clear and bright as Kira and Aiden ready themselves " + "for battle. They approach the Blacksmith one more time."; Aside = true; SetWidgetLayout(LayoutOrientation.Horizontal); } if(count ==1){ DialogueText.Text = "Blacksmith: Well, if the little lady ain't back!"; Aside = false; setAiden = true; setKira = true; SetWidgetLayout(LayoutOrientation.Horizontal); } if(count ==2){ DialogueText.Text = "Kira: I hear you have something for Aiden."; Kira.state = (int)CharacterState.Normal; } if(count ==3){ DialogueText.Text = "Blacksmith: You bet! You'll never find a finer sword than this one."; } if(count ==4){ DialogueText.Text = "Kira: Aiden, do you even know how to swing that?"; Kira.state = (int)CharacterState.Shocked; } if(count ==5){ DialogueText.Text = "Aiden: Ha ha ha Very funny Kira. Can you give me a break about what happened yesterday?"; Aiden.state = (int)CharacterState.Normal; } if(count ==6){ DialogueText.Text = "Kira: Oh alright ill stop teasing you. However I do think your father would be proud of you. But please, don't cut your own head off hehe."; Kira.state = (int)CharacterState.Happy; } if(count ==8){ game.ChatFinished = true; SetUpCharacters(); break; } if(Aiden.state != Aiden.oldState | Kira.state != Kira.oldState) SetUpCharacters(Aiden, Kira); count++; break; case (int)CurrentScene.Nineth: if(count ==0){ DialogueText.Text = "With their army, Kira and Aiden approach the northern stronghold. But before they can " + "call out for Lord Arkan to show himself, three very familiar faces appear before them."; } if(count ==1){ DialogueText.Text = "Elider: You thought you'd seen the last of us, didnt you?"; Bandit1.state = (int)BanditState.BANDIT1_SMUG; Bandit2.state = (int)BanditState.BANDIT2_SMUG; Bandit3.state = (int)BanditState.BANDIT3_SMUG; setAiden = true; setKira = true; setBandit1 = true; setBandit2 = true; setBandit3 = true; kiraOnLeft = true; Aside = false; SetWidgetLayout(LayoutOrientation.Horizontal); } if(count ==2){ DialogueText.Text = "Jasz: With Lord Darius on our side, we are undefeatable!"; } if(count ==3){ DialogueText.Text = "Rasz: Face it, brats; you can't win!"; } if(count ==4){ DialogueText.Text = "Aiden: Big talk for a bunch of sore losers! Ready, Kira?"; Aiden.state = (int)CharacterState.Normal; } if(count ==5){ DialogueText.Text = "Kira: Always, Aiden. For Ventus!"; Kira.state = (int)CharacterState.Normal; } if(count ==6){ game.StartBattle = true; } if(count ==7){ DialogueText.Text = "Kira: So much for undefeatable. Now, let's go find Darius!"; Kira.state = (int)CharacterState.Happy; setBandit1 = false; setBandit2 = false; setBandit3 = false; } if(count ==8){ DialogueText.Text = "Aiden: Right!"; Aiden.state = (int)CharacterState.Happy; } if(count ==9){ SceneManager.ReplaceScene((int)GE2D.FINAL); DialogueText.Text = "However, as our heroes set forth, a terrible clattering resounds throughout the room. " + "Aiden pushes Kira away from himself just as a gate slams down between them, separating them."; } if(count ==10){ DialogueText.Text = "Aiden: Kira!"; Aiden.state = (int)CharacterState.Shocked; } if(count ==11){ DialogueText.Text = "Kira: Aiden! Behind you!"; Kira.state = (int)CharacterState.Worried; setKira = false; setBear = true; } if(count ==12){ DialogueText.Text = "Darius: So, the little rat comes scurrying into my keep, does he?"; Bear.state = (int)CharacterState.Normal; } if(count ==13){ DialogueText.Text = "Aiden: Darius!, Your days of inslaving innocent people are over! On my father's honor you will pay"; Aiden.state = (int)CharacterState.Angry; } if(count ==14){ DialogueText.Text = "Darius: I am not as easily beaten as the rats that came before me, boy. Draw your sword only if you have a death wish wanting to be granted"; Bear.state = (int)CharacterState.Angry; } if(count ==15){ DialogueText.Text = "Aiden: I will draw my sword for the sake of all of Audra! For I am Aiden of Ventus, son of Aimes the Magnate. " + "I won't be defeated!"; Aiden.state = (int)CharacterState.Angry; } if(count ==16){ game.StartBattle = true; } if(count ==17){ DialogueText.Text = "As Darius falls, Aiden releases the lock on the gate that seperates him from Kira,"; setKira = true; setBear = false; Aiden.state = (int)CharacterState.Hurt; } if(count ==18){ DialogueText.Text = "Aiden: I...I did it. I avenged my father."; } if(count ==19){ DialogueText.Text = "Kira: You did indeed. And now Adura is safe once more from the likes of Arkan."; Kira.state = (int)CharacterState.Normal; } if(count ==20){ DialogueText.Text = "Aiden: Kira, I..."; } if(count ==21){ SceneManager.ReplaceScene((int)GE2D.GOODTOWN); DialogueText.Text = "Kira: Come on, let's go back to town. I bet we can convince someone to make us some pie."; Kira.state = (int)CharacterState.Happy; } if(count ==22){ DialogueText.Text = "Aiden: Apple?"; Aiden.state = (int)CharacterState.Happy; } if(count ==23){ DialogueText.Text = "Kira: Hot and fresh on the windowsill!"; Kira.state = (int)CharacterState.Happy; } if(count == 24) { DialogueText.Text = "Aiden and Kira have successfully liberated their homeland, and have won the battle. However as always with the ways of war, this is just one battle of many waiting our young heroes. Unknown to them an even greater threat to all of Audra rests on the horizon...."; } if(Aiden.state != Aiden.oldState | Kira.state != Kira.oldState) { SetUpCharacters(Aiden,Kira); } if(Bandit1.state != Bandit1.oldState | Bandit2.state != Bandit2.oldState | Bandit3.state != Bandit3.oldState) { SetUpCharacters(Aiden, Kira, Bandit1, Bandit2, Bandit3); } if(setBear == true | Bear.state != Bear.oldState) { SetUpCharacters(Aiden, Kira, Bear); } count++; break; } } } }
// 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.Net; using System.Text; using System.Linq; using System.Runtime.InteropServices; using Microsoft.Protocols.TestTools.StackSdk.Security.Sspi; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Rsvd { /// <summary> /// RsvdClient is the exposed interface for testing Rsvd server. /// </summary> public sealed class RsvdClient : IDisposable { #region Fields private Smb2ClientTransport transport; private bool disposed; private TimeSpan timeout; #endregion #region Constructor & Dispose /// <summary> /// Constructor /// </summary> public RsvdClient(TimeSpan timeout) { this.timeout = timeout; } /// <summary> /// Release the managed and unmanaged resources. /// </summary> public void Dispose() { Dispose(true); // Take this object out of the finalization queue of the GC: GC.SuppressFinalize(this); } /// <summary> /// Release resources. /// </summary> /// <param name="disposing">If disposing equals true, Managed and unmanaged resources are disposed. /// if false, Only unmanaged resources can be disposed.</param> private void Dispose(bool disposing) { if (!this.disposed) { // If disposing equals true, dispose all managed and unmanaged resources. if (disposing) { // Free managed resources & other reference types: if (this.transport != null) { this.transport.Dispose(); this.transport = null; } } this.disposed = true; } } /// <summary> /// finalizer /// </summary> ~RsvdClient() { Dispose(false); } #endregion /// <summary> /// Set up connection with server. /// Including 4 steps: 1. Tcp connection 2. Negotiation 3. SessionSetup 4. TreeConnect /// </summary> /// <param name="serverName">server name</param> /// <param name="serverIP">server IP address</param> /// <param name="domain">user's domain</param> /// <param name="userName">user's name</param> /// <param name="password">user's password</param> /// <param name="securityPackage">The security package</param> /// <param name="useServerToken">Whether to use token from server</param> /// <param name="shareName">Name of the share when TreeConnect</param> public void Connect( string serverName, IPAddress serverIP, string domain, string userName, string password, SecurityPackageType securityPackage, bool useServerToken, string shareName) { transport = new Smb2ClientTransport(); transport.ConnectShare(serverName, serverIP, domain, userName, password, shareName, securityPackage, useServerToken); } /// <summary> /// Disconnect from server. /// </summary> public void Disconnect() { if (transport != null) { this.transport.Disconnect(timeout); } } /// <summary> /// Open the shared virtual disk file /// Send smb2 create request to server /// </summary> /// <param name="vhdxName">Name of the shared virtual disk file</param> /// <param name="createOption">CreateOption in create request</param> /// <param name="contexts">Create Contexts to be sent together with Create Request</param> /// <param name="status">Status of create response</param> /// <param name="serverContexts">Create contexts returned in create response</param> /// <param name="response">Create Response returned by server</param> /// <returns>Create Response returned by server</returns> public uint OpenSharedVirtualDisk( string vhdxName, FsCreateOption createOption, Smb2CreateContextRequest[] contexts, out Smb2CreateContextResponse[] serverContexts, out CREATE_Response response) { uint status; transport.Create( vhdxName, // The desired access is set the same as Windows client's behavior FsFileDesiredAccess.FILE_READ_DATA | FsFileDesiredAccess.FILE_WRITE_DATA | FsFileDesiredAccess.FILE_READ_ATTRIBUTES | FsFileDesiredAccess.READ_CONTROL, ShareAccess_Values.FILE_SHARE_DELETE | ShareAccess_Values.FILE_SHARE_READ | ShareAccess_Values.FILE_SHARE_WRITE, FsImpersonationLevel.Impersonation, FsFileAttribute.NONE, FsCreateDisposition.FILE_OPEN, createOption, contexts, out status, out serverContexts, out response); return status; } /// <summary> /// Close the shared virtual disk file /// </summary> public void CloseSharedVirtualDisk() { transport.Close(); } /// <summary> /// Read content from the shared virtual disk file /// </summary> /// <param name="offset">In bytes, from the beginning of the virtual disk where data should be read</param> /// <param name="length">The number of bytes to read</param> /// <param name="data">The buffer to receive the data.</param> /// <returns>Status of response packet</returns> public uint Read(ulong offset, uint length, out byte[] data) { return transport.Read(timeout, offset, length, out data); } /// <summary> /// Write content to the shared virtual disk file /// </summary> /// <param name="offset">In bytes, from the beginning of the virtual disk where data should be written</param> /// <param name="data">A buffer containing the bytes to be written.</param> /// <returns>Status of response packet</returns> public uint Write(ulong offset, byte[] data) { return transport.Write(timeout, offset, data); } /// <summary> /// Tunnel operations to the shared virtual disk file /// </summary> /// <typeparam name="ResponseT">Type of the operation response</typeparam> /// <param name="isAsyncOperation">Indicate whether the tunnel operation is async or not</param> /// <param name="code">Operation code</param> /// <param name="requestId">A value that uniquely identifies an operation request and response for all requests sent by this client</param> /// <param name="requestStructure">The marshalled tunnel structure of the request</param> /// <param name="responseHeader">Tunnel operation header of the response packet</param> /// <param name="response">Tunnel operation response of the smb2 response packet</param> /// <returns>Status of the smb2 response packet</returns> public uint TunnelOperation<ResponseT>( bool isAsyncOperation, RSVD_TUNNEL_OPERATION_CODE code, ulong requestId, byte[] requestStructure, out SVHDX_TUNNEL_OPERATION_HEADER? responseHeader, out ResponseT? response) where ResponseT : struct { SVHDX_TUNNEL_OPERATION_HEADER header = new SVHDX_TUNNEL_OPERATION_HEADER(); header.OperationCode = code; header.RequestId = requestId; byte[] payload = TypeMarshal.ToBytes(header); if (null != requestStructure) payload = payload.Concat(requestStructure).ToArray(); CtlCode_Values ctlCode = isAsyncOperation ? CtlCode_Values.FSCTL_SVHDX_ASYNC_TUNNEL_REQUEST : CtlCode_Values.FSCTL_SVHDX_SYNC_TUNNEL_REQUEST; transport.SendIoctlPayload(ctlCode, payload); uint smb2Status; transport.ExpectIoctlPayload(out smb2Status, out payload); response = null; responseHeader = null; if (smb2Status != Smb2Status.STATUS_SUCCESS) { return smb2Status; } responseHeader = TypeMarshal.ToStruct<SVHDX_TUNNEL_OPERATION_HEADER>(payload); // If the response does not contain Header only, parse the resonse body. if (responseHeader.Value.Status == 0 && typeof(ResponseT) != typeof(SVHDX_TUNNEL_OPERATION_HEADER)) { response = TypeMarshal.ToStruct<ResponseT>(payload.Skip(Marshal.SizeOf(responseHeader)).ToArray()); } else { // The operation failed, so no response body. // Or the response only contains header, no response body. } return smb2Status; } /// <summary> /// Create an SVHDX_TUNNEL_FILE_INFO_REQUEST structure and marshal it to a byte array /// </summary> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelFileInfoRequest() { // The SVHDX_TUNNEL_FILE_INFO_REQUEST packet is sent by the client to get the shared virtual disk file information. // The request MUST contain only SVHDX_TUNNEL_OPERATION_HEADER, and MUST NOT contain any payload. return null; } /// <summary> /// Create an SVHDX_TUNNEL_CHECK_CONNECTION_REQUEST structure and marshal it to a byte array /// </summary> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelCheckConnectionStatusRequest() { ///The SVHDX_TUNNEL_CHECK_CONNECTION_REQUEST packet is sent by the client to check the connection status to the shared virtual disk. ///The request MUST contain only SVHDX_TUNNEL_OPERATION_HEADER, and MUST NOT contain any payload. return null; } /// <summary> /// Create an SVHDX_TUNNEL_SRB_STATUS_REQUEST structure and marshal it to a byte array /// </summary> /// <param name="statusKey">The client MUST set this field to the least significant bytes of the status code value given by the server for the failed request.</param> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelSrbStatusRequest(byte statusKey) { SVHDX_TUNNEL_SRB_STATUS_REQUEST srbStatusRequest = new SVHDX_TUNNEL_SRB_STATUS_REQUEST(); srbStatusRequest.StatusKey = statusKey; srbStatusRequest.Reserved = new byte[27]; return TypeMarshal.ToBytes(srbStatusRequest); } /// <summary> /// Create an SVHDX_TUNNEL_DISK_INFO_REQUEST structure and marshal it to a byte array /// </summary> /// <param name="blockSize">The client MUST set this field to zero, and the server MUST ignore it on receipt.</param> /// <param name="linkageID">The client MUST set this field to zero, and the server MUST ignore it on receipt.</param> /// <param name="isMounted">The client MUST set this field to zero, and the server MUST ignore it on receipt.</param> /// <param name="is4kAligned">The client MUST set this field to zero, and the server MUST ignore it on receipt.</param> /// <param name="fileSize">The client MUST set this field to zero, and the server MUST ignore it on receipt.</param> /// <param name="virtualDiskId">This field MUST NOT be used and MUST be reserved. The client MUST set this field to zero, and the server MUST ignore it on receipt.</param> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelDiskInfoRequest(uint blockSize = 0, Guid linkageID = default(Guid), bool isMounted = false, bool is4kAligned = false, ulong fileSize = 0, Guid virtualDiskId = default(Guid)) { SVHDX_TUNNEL_DISK_INFO_REQUEST diskInfoRequest = new SVHDX_TUNNEL_DISK_INFO_REQUEST(); diskInfoRequest.BlockSize = blockSize; diskInfoRequest.LinkageID = linkageID; diskInfoRequest.IsMounted = isMounted; diskInfoRequest.Is4kAligned = is4kAligned; diskInfoRequest.FileSize = fileSize; diskInfoRequest.VirtualDiskId = virtualDiskId; return TypeMarshal.ToBytes(diskInfoRequest); } /// <summary> /// Create an SVHDX_TUNNEL_SCSI_REQUEST structure and marshal it to a byte array /// </summary> /// <param name="length">Specifies the size, in bytes, of the SVHDX_TUNNEL_SCSI_REQUEST structure.</param> /// <param name="cdbLength">The length, in bytes, of the SCSI command descriptor block. This value MUST be less than or equal to RSVD_CDB_GENERIC_LENGTH.</param> /// <param name="senseInfoExLength">The length, in bytes, of the request sense data buffer. This value MUST be less than or equal to RSVD_SCSI_SENSE_BUFFER_SIZE.</param> /// <param name="dataIn">A Boolean, indicating the SCSI command descriptor block transfer type. /// The value TRUE (0x01) indicates that the operation is to store the data onto the disk. /// The value FALSE (0x00) indicates that the operation is to retrieve the data from the disk.</param> /// <param name="srbFlags">An optional, application-provided flag to indicate the options of the SCSI request.</param> /// <param name="dataTransferLength">The length, in bytes, of the additional data placed in the DataBuffer field.</param> /// <param name="cdbBuffer">A buffer that contains the SCSI command descriptor block.</param> /// <param name="dataBuffer">A variable-length buffer that contains the additional buffer, as described by the DataTransferLength field.</param> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelScsiRequest( ushort length, byte cdbLength, byte senseInfoExLength, bool dataIn, SRB_FLAGS srbFlags, uint dataTransferLength, byte[] cdbBuffer, byte[] dataBuffer) { SVHDX_TUNNEL_SCSI_REQUEST scsiRequest = new SVHDX_TUNNEL_SCSI_REQUEST(); scsiRequest.Length = length; scsiRequest.CdbLength = cdbLength; scsiRequest.SenseInfoExLength = senseInfoExLength; scsiRequest.DataIn = dataIn; scsiRequest.SrbFlags = srbFlags; scsiRequest.DataTransferLength = dataTransferLength; scsiRequest.CDBBuffer = cdbBuffer; scsiRequest.DataBuffer = dataBuffer; return TypeMarshal.ToBytes(scsiRequest); } /// <summary> /// Create an SVHDX_TUNNEL_VALIDATE_DISK_REQUEST structure and marshal it to a byte array /// </summary> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelValidateDiskRequest() { ///The SVHDX_TUNNEL_VALIDATE_DISK_REQUEST packet is sent by the client to validate the shared virtual disk. SVHDX_TUNNEL_VALIDATE_DISK_REQUEST validDiskRequest = new SVHDX_TUNNEL_VALIDATE_DISK_REQUEST(); validDiskRequest.Reserved = new byte[56]; return TypeMarshal.ToBytes(validDiskRequest); } /// <summary> /// Create an SVHDX_TUNNEL_VHDSET_FILE_QUERY_INFORMATION_REQUEST structure and marshal it to a byte array /// </summary> /// <param name="setFileInformationType">The set file information type requested</param> /// <param name="snapshotType">The snapshot type queried by this operation</param> /// <param name="snapshotId">The snapshot ID relevant to the particular request</param> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelGetVHDSetFileInfoRequest( SetFile_InformationType setFileInformationType, Snapshot_Type snapshotType, Guid snapshotId) { SVHDX_TUNNEL_VHDSET_FILE_QUERY_INFORMATION_REQUEST getVHDSetFileInfoRequest = new SVHDX_TUNNEL_VHDSET_FILE_QUERY_INFORMATION_REQUEST(); getVHDSetFileInfoRequest.SetFileInformationType = setFileInformationType; getVHDSetFileInfoRequest.SetFileInformationSnapshotType = snapshotType; getVHDSetFileInfoRequest.SnapshotId = snapshotId; return TypeMarshal.ToBytes(getVHDSetFileInfoRequest); } /// <summary> /// Create an SVHDX_META_OPERATION_START_CREATE_SNAPSHOT_REQUEST structure and marshal it to a byte array /// </summary> /// <param name="startRequest">Type SVHDX_META_OPERATION_START_REQUEST includes TransactionId and OperationType</param> /// <param name="createSnapshot">Type of SVHDX_META_OPERATION_CREATE_SNAPSHOT structure</param> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelMetaOperationStartCreateSnapshotRequest( SVHDX_META_OPERATION_START_REQUEST startRequest, SVHDX_META_OPERATION_CREATE_SNAPSHOT createSnapshot) { SVHDX_META_OPERATION_START_CREATE_SNAPSHOT_REQUEST createSnapshotRequest = new SVHDX_META_OPERATION_START_CREATE_SNAPSHOT_REQUEST(); createSnapshotRequest.startRequest = startRequest; createSnapshotRequest.createSnapshot = createSnapshot; return TypeMarshal.ToBytes(createSnapshotRequest); } /// <summary> /// Create an SVHDX_META_OPERATION_START_APPLY_SNAPSHOT_REQUEST structure and marshal it to a byte array /// </summary> /// <param name="startRequest">Type SVHDX_META_OPERATION_START_REQUEST includes TransactionId and OperationType</param> /// <param name="applySnapshot">Type of SVHDX_APPLY_SNAPSHOT_PARAMS structure</param> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelMetaOperationStartApplySnapshotRequest( SVHDX_META_OPERATION_START_REQUEST startRequest, SVHDX_APPLY_SNAPSHOT_PARAMS applySnapshot) { SVHDX_META_OPERATION_START_APPLY_SNAPSHOT_REQUEST applySnapshotRequest = new SVHDX_META_OPERATION_START_APPLY_SNAPSHOT_REQUEST(); applySnapshotRequest.startRequest = startRequest; applySnapshotRequest.applySnapshot = applySnapshot; return TypeMarshal.ToBytes(applySnapshotRequest); } /// <summary> /// Create an SVHDX_META_OPERATION_OPTIMIZE_REQUEST structure and marshal it to a byte array /// </summary> /// <param name="startRequest">Type SVHDX_META_OPERATION_START_REQUEST includes TransactionId and OperationType</param> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelMetaOperationStartOptimizeRequest( SVHDX_META_OPERATION_START_REQUEST startRequest) { SVHDX_META_OPERATION_START_OPTIMIZE_REQUEST optimizeRequest = new SVHDX_META_OPERATION_START_OPTIMIZE_REQUEST(); optimizeRequest.startRequest = startRequest; return TypeMarshal.ToBytes(optimizeRequest); } /// <summary> /// Create an SVHDX_TUNNEL_DELETE_SNAPSHOT_REQUEST structure and marshal it to a byte array /// </summary> /// <param name="request">A SVHDX_TUNNEL_DELETE_SNAPSHOT_REQUEST request</param> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelMetaOperationDeleteSnapshotRequest( SVHDX_TUNNEL_DELETE_SNAPSHOT_REQUEST request) { return TypeMarshal.ToBytes(request); } /// <summary> /// Create an SVHDX_META_OPERATION_START_EXTRACT_REQUEST structure and marshal it to a byte array /// </summary> /// <param name="startRequest">Struct SVHDX_META_OPERATION_START_REQUEST includes TransactionId and OperationType</param> /// <param name="extract">Struct SVHDX_META_OPERATION_EXTRACT</param> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelMetaOperationStartExtractRequest( SVHDX_META_OPERATION_START_REQUEST startRequest, SVHDX_META_OPERATION_EXTRACT extract) { SVHDX_META_OPERATION_START_EXTRACT_REQUEST extractRequest = new SVHDX_META_OPERATION_START_EXTRACT_REQUEST(); extractRequest.startRequest = startRequest; extractRequest.extract = extract; return TypeMarshal.ToBytes(extractRequest); } /// <summary> /// Create an SVHDX_META_OPERATION_START_CONVERT_TO_VHDSET_REQUEST structure and marshal it to a byte array /// </summary> /// <param name="startRequest">Struct SVHDX_META_OPERATION_START_REQUEST includes TransactionId and OperationType</param> /// <param name="convert">Struct SVHDX_META_OPERATION_CONVERT_TO_VHDSET</param> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelMetaOperationStartConvertToVHDSetRequest( SVHDX_META_OPERATION_START_REQUEST startRequest, SVHDX_META_OPERATION_CONVERT_TO_VHDSET convert) { SVHDX_META_OPERATION_START_CONVERT_TO_VHDSET_REQUEST convertRequest = new SVHDX_META_OPERATION_START_CONVERT_TO_VHDSET_REQUEST(); convertRequest.startRequest = startRequest; convertRequest.convert = convert; return TypeMarshal.ToBytes(convertRequest); } /// <summary> /// Create an SVHDX_META_OPERATION_START_RESIZE_REQUEST structure and marshal it to a byte array /// </summary> /// <param name="startRequest">Struct SVHDX_META_OPERATION_START_REQUEST includes TransactionId and OperationType</param> /// <param name="resize">Struct SVHDX_META_OPERATION_RESIZE_VIRTUAL_DISK</param> /// <returns>The marshalled byte array</returns> public byte[] CreateTunnelMetaOperationStartResizeRequest( SVHDX_META_OPERATION_START_REQUEST startRequest, SVHDX_META_OPERATION_RESIZE_VIRTUAL_DISK resize) { SVHDX_META_OPERATION_START_RESIZE_REQUEST resizeVHDSetRequest = new SVHDX_META_OPERATION_START_RESIZE_REQUEST(); resizeVHDSetRequest.startRequest = startRequest; resizeVHDSetRequest.resizeRequest = resize; return TypeMarshal.ToBytes(resizeVHDSetRequest); } /// <summary> /// Marshal an SVHDX_CHANGE_TRACKING_START_REQUEST structure /// </summary> /// <param name="request">SVHDX_CHANGE_TRACKING_START_REQUEST structure</param> /// <returns>The marshalled byte array</returns> public byte[] CreateChangeTrackingStartRequest(SVHDX_CHANGE_TRACKING_START_REQUEST request) { return TypeMarshal.ToBytes(request); } /// <summary> /// Marshal an SVHDX_TUNNEL_QUERY_VIRTUAL_DISK_CHANGES_REQUEST structure /// </summary> /// <param name="request">SVHDX_TUNNEL_QUERY_VIRTUAL_DISK_CHANGES_REQUEST structure</param> /// <returns>The marshalled byte array</returns> public byte[] CreateQueryVirtualDiskChangeRequest(SVHDX_TUNNEL_QUERY_VIRTUAL_DISK_CHANGES_REQUEST request) { return TypeMarshal.ToBytes(request); } /// <summary> /// Marshal a RSVD_BLOCK_DEVICE_TARGET_SPECIFIER structure /// </summary> /// <param name="snapshotId">A GUID that identifies the snapshot to open</param> /// <returns>The marshalled byte array</returns> public byte[] CreateTargetSpecifier(Guid snapshotId) { RSVD_BLOCK_DEVICE_TARGET_SPECIFIER targetSpecifier = new RSVD_BLOCK_DEVICE_TARGET_SPECIFIER(); targetSpecifier.RsvdBlockDeviceTargetNamespace = TargetNamespaceType.SnapshotId; targetSpecifier.TargetInformationSnapshot.SnapshotID = snapshotId; targetSpecifier.TargetInformationSnapshot.SnapshotType = Snapshot_Type.SvhdxSnapshotTypeVM; return TypeMarshal.ToBytes(targetSpecifier); } /// <summary> /// Query shared virtual disk support /// </summary> /// <param name="response">Shared virtual disk support response to receive from RSVD server</param> /// <param name="requestPayload">Payload of the ioctl request, default value is null</param> /// <returns>Status of response packet</returns> public uint QuerySharedVirtualDiskSupport(out SVHDX_SHARED_VIRTUAL_DISK_SUPPORT_RESPONSE? response, byte[] requestPayload = null) { byte[] output; uint status; // FSCTL_QUERY_SHARED_VIRTUAL_DISK_SUPPORT is a fsctl code. // So cast the type from CtlCode_Values to FsCtlCode is to use the correct overloaded function // IoControl(TimeSpan timeout, FsCtlCode controlCode, byte[] input, out byte[] output) status = transport.IoControl(this.timeout, (FsCtlCode)CtlCode_Values.FSCTL_QUERY_SHARED_VIRTUAL_DISK_SUPPORT, requestPayload, out output); if (status != Smb2Status.STATUS_SUCCESS) { response = null; return status; } response = TypeMarshal.ToStruct<SVHDX_SHARED_VIRTUAL_DISK_SUPPORT_RESPONSE>(output); return status; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using Roslyn.Utilities; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.CodeAnalysis.CompilerServer; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// This class defines all of the common stuff that is shared between the Vbc and Csc tasks. /// This class is not instantiatable as a Task just by itself. /// </summary> public abstract class ManagedCompiler : ToolTask { private CancellationTokenSource _sharedCompileCts; internal readonly PropertyDictionary _store = new PropertyDictionary(); public ManagedCompiler() { this.TaskResources = ErrorString.ResourceManager; } #region Properties // Please keep these alphabetized. public string[] AdditionalLibPaths { set { _store[nameof(AdditionalLibPaths)] = value; } get { return (string[])_store[nameof(AdditionalLibPaths)]; } } public string[] AddModules { set { _store[nameof(AddModules)] = value; } get { return (string[])_store[nameof(AddModules)]; } } public ITaskItem[] AdditionalFiles { set { _store[nameof(AdditionalFiles)] = value; } get { return (ITaskItem[])_store[nameof(AdditionalFiles)]; } } public ITaskItem[] Analyzers { set { _store[nameof(Analyzers)] = value; } get { return (ITaskItem[])_store[nameof(Analyzers)]; } } // We do not support BugReport because it always requires user interaction, // which will cause a hang. public string CodeAnalysisRuleSet { set { _store[nameof(CodeAnalysisRuleSet)] = value; } get { return (string)_store[nameof(CodeAnalysisRuleSet)]; } } public int CodePage { set { _store[nameof(CodePage)] = value; } get { return _store.GetOrDefault(nameof(CodePage), 0); } } [Output] public ITaskItem[] CommandLineArgs { set { _store[nameof(CommandLineArgs)] = value; } get { return (ITaskItem[])_store[nameof(CommandLineArgs)]; } } public string DebugType { set { _store[nameof(DebugType)] = value; } get { return (string)_store[nameof(DebugType)]; } } public string DefineConstants { set { _store[nameof(DefineConstants)] = value; } get { return (string)_store[nameof(DefineConstants)]; } } public bool DelaySign { set { _store[nameof(DelaySign)] = value; } get { return _store.GetOrDefault(nameof(DelaySign), false); } } public bool Deterministic { set { _store[nameof(Deterministic)] = value; } get { return _store.GetOrDefault(nameof(Deterministic), false); } } public bool EmitDebugInformation { set { _store[nameof(EmitDebugInformation)] = value; } get { return _store.GetOrDefault(nameof(EmitDebugInformation), false); } } public string ErrorLog { set { _store[nameof(ErrorLog)] = value; } get { return (string)_store[nameof(ErrorLog)]; } } public string Features { set { _store[nameof(Features)] = value; } get { return (string)_store[nameof(Features)]; } } public int FileAlignment { set { _store[nameof(FileAlignment)] = value; } get { return _store.GetOrDefault(nameof(FileAlignment), 0); } } public bool HighEntropyVA { set { _store[nameof(HighEntropyVA)] = value; } get { return _store.GetOrDefault(nameof(HighEntropyVA), false); } } public string KeyContainer { set { _store[nameof(KeyContainer)] = value; } get { return (string)_store[nameof(KeyContainer)]; } } public string KeyFile { set { _store[nameof(KeyFile)] = value; } get { return (string)_store[nameof(KeyFile)]; } } public ITaskItem[] LinkResources { set { _store[nameof(LinkResources)] = value; } get { return (ITaskItem[])_store[nameof(LinkResources)]; } } public string MainEntryPoint { set { _store[nameof(MainEntryPoint)] = value; } get { return (string)_store[nameof(MainEntryPoint)]; } } public bool NoConfig { set { _store[nameof(NoConfig)] = value; } get { return _store.GetOrDefault(nameof(NoConfig), false); } } public bool NoLogo { set { _store[nameof(NoLogo)] = value; } get { return _store.GetOrDefault(nameof(NoLogo), false); } } public bool NoWin32Manifest { set { _store[nameof(NoWin32Manifest)] = value; } get { return _store.GetOrDefault(nameof(NoWin32Manifest), false); } } public bool Optimize { set { _store[nameof(Optimize)] = value; } get { return _store.GetOrDefault(nameof(Optimize), false); } } [Output] public ITaskItem OutputAssembly { set { _store[nameof(OutputAssembly)] = value; } get { return (ITaskItem)_store[nameof(OutputAssembly)]; } } public string Platform { set { _store[nameof(Platform)] = value; } get { return (string)_store[nameof(Platform)]; } } public bool Prefer32Bit { set { _store[nameof(Prefer32Bit)] = value; } get { return _store.GetOrDefault(nameof(Prefer32Bit), false); } } public bool ProvideCommandLineArgs { set { _store[nameof(ProvideCommandLineArgs)] = value; } get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); } } public ITaskItem[] References { set { _store[nameof(References)] = value; } get { return (ITaskItem[])_store[nameof(References)]; } } public bool ReportAnalyzer { set { _store[nameof(ReportAnalyzer)] = value; } get { return _store.GetOrDefault(nameof(ReportAnalyzer), false); } } public ITaskItem[] Resources { set { _store[nameof(Resources)] = value; } get { return (ITaskItem[])_store[nameof(Resources)]; } } public ITaskItem[] ResponseFiles { set { _store[nameof(ResponseFiles)] = value; } get { return (ITaskItem[])_store[nameof(ResponseFiles)]; } } public bool SkipCompilerExecution { set { _store[nameof(SkipCompilerExecution)] = value; } get { return _store.GetOrDefault(nameof(SkipCompilerExecution), false); } } public ITaskItem[] Sources { set { if (UsedCommandLineTool) { NormalizePaths(value); } _store[nameof(Sources)] = value; } get { return (ITaskItem[])_store[nameof(Sources)]; } } public string SubsystemVersion { set { _store[nameof(SubsystemVersion)] = value; } get { return (string)_store[nameof(SubsystemVersion)]; } } public string TargetType { set { _store[nameof(TargetType)] = value.ToLower(CultureInfo.InvariantCulture); } get { return (string)_store[nameof(TargetType)]; } } public bool TreatWarningsAsErrors { set { _store[nameof(TreatWarningsAsErrors)] = value; } get { return _store.GetOrDefault(nameof(TreatWarningsAsErrors), false); } } public bool Utf8Output { set { _store[nameof(Utf8Output)] = value; } get { return _store.GetOrDefault(nameof(Utf8Output), false); } } public string Win32Icon { set { _store[nameof(Win32Icon)] = value; } get { return (string)_store[nameof(Win32Icon)]; } } public string Win32Manifest { set { _store[nameof(Win32Manifest)] = value; } get { return (string)_store[nameof(Win32Manifest)]; } } public string Win32Resource { set { _store[nameof(Win32Resource)] = value; } get { return (string)_store[nameof(Win32Resource)]; } } /// <summary> /// If this property is true then the task will take every C# or VB /// compilation which is queued by MSBuild and send it to the /// VBCSCompiler server instance, starting a new instance if necessary. /// If false, we will use the values from ToolPath/Exe. /// </summary> public bool UseSharedCompilation { set { _store[nameof(UseSharedCompilation)] = value; } get { return _store.GetOrDefault(nameof(UseSharedCompilation), false); } } // Map explicit platform of "AnyCPU" or the default platform (null or ""), since it is commonly understood in the // managed build process to be equivalent to "AnyCPU", to platform "AnyCPU32BitPreferred" if the Prefer32Bit // property is set. internal string PlatformWith32BitPreference { get { string platform = this.Platform; if ((String.IsNullOrEmpty(platform) || platform.Equals("anycpu", StringComparison.OrdinalIgnoreCase)) && this.Prefer32Bit) { platform = "anycpu32bitpreferred"; } return platform; } } /// <summary> /// Overridable property specifying the encoding of the captured task standard output stream /// </summary> protected override Encoding StandardOutputEncoding { get { return (Utf8Output) ? Encoding.UTF8 : base.StandardOutputEncoding; } } #endregion internal abstract BuildProtocolConstants.RequestLanguage Language { get; } protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { if (ProvideCommandLineArgs) { CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands) .Select(arg => new TaskItem(arg)).ToArray(); } if (SkipCompilerExecution) { return 0; } if (!UseSharedCompilation || !String.IsNullOrEmpty(this.ToolPath)) { return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } using (_sharedCompileCts = new CancellationTokenSource()) { try { CompilerServerLogger.Log($"CommandLine = '{commandLineCommands}'"); CompilerServerLogger.Log($"BuildResponseFile = '{responseFileCommands}'"); var responseTask = BuildClient.TryRunServerCompilation( Language, TryGetClientDir() ?? Path.GetDirectoryName(pathToTool), CurrentDirectoryToUse(), GetArguments(commandLineCommands, responseFileCommands), _sharedCompileCts.Token, libEnvVariable: LibDirectoryToUse()); responseTask.Wait(_sharedCompileCts.Token); var response = responseTask.Result; if (response != null) { ExitCode = HandleResponse(response, pathToTool, responseFileCommands, commandLineCommands); } else { ExitCode = base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } } catch (OperationCanceledException) { ExitCode = 0; } catch (Exception e) { Log.LogErrorWithCodeFromResources("Compiler_UnexpectedException"); LogErrorOutput(e.ToString()); ExitCode = -1; } } return ExitCode; } /// <summary> /// Try to get the directory this assembly is in. Returns null if assembly /// was in the GAC. /// </summary> private static string TryGetClientDir() { var assembly = typeof(ManagedCompiler).Assembly; if (assembly.GlobalAssemblyCache) return null; var uri = new Uri(assembly.CodeBase); string assemblyPath = uri.IsFile ? uri.LocalPath : Assembly.GetCallingAssembly().Location; return Path.GetDirectoryName(assemblyPath); } /// <summary> /// Cancel the in-process build task. /// </summary> public override void Cancel() { base.Cancel(); _sharedCompileCts?.Cancel(); } /// <summary> /// Get the current directory that the compiler should run in. /// </summary> private string CurrentDirectoryToUse() { // ToolTask has a method for this. But it may return null. Use the process directory // if ToolTask didn't override. MSBuild uses the process directory. string workingDirectory = GetWorkingDirectory(); if (string.IsNullOrEmpty(workingDirectory)) workingDirectory = Directory.GetCurrentDirectory(); return workingDirectory; } /// <summary> /// Get the "LIB" environment variable, or NULL if none. /// </summary> private string LibDirectoryToUse() { // First check the real environment. string libDirectory = Environment.GetEnvironmentVariable("LIB"); // Now go through additional environment variables. string[] additionalVariables = this.EnvironmentVariables; if (additionalVariables != null) { foreach (string var in this.EnvironmentVariables) { if (var.StartsWith("LIB=", StringComparison.OrdinalIgnoreCase)) { libDirectory = var.Substring(4); } } } return libDirectory; } /// <summary> /// The return code of the compilation. Strangely, this isn't overridable from ToolTask, so we need /// to create our own. /// </summary> [Output] public new int ExitCode { get; private set; } /// <summary> /// Handle a response from the server, reporting messages and returning /// the appropriate exit code. /// </summary> private int HandleResponse(BuildResponse response, string pathToTool, string responseFileCommands, string commandLineCommands) { switch (response.Type) { case BuildResponse.ResponseType.MismatchedVersion: LogErrorOutput(CommandLineParser.MismatchedVersionErrorText); return -1; case BuildResponse.ResponseType.Completed: var completedResponse = (CompletedBuildResponse)response; LogMessages(completedResponse.Output, this.StandardOutputImportanceToUse); if (LogStandardErrorAsError) { LogErrorOutput(completedResponse.ErrorOutput); } else { LogMessages(completedResponse.ErrorOutput, this.StandardErrorImportanceToUse); } return completedResponse.ReturnCode; case BuildResponse.ResponseType.AnalyzerInconsistency: return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); default: throw new InvalidOperationException("Encountered unknown response type"); } } private void LogErrorOutput(string output) { string[] lines = output.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { string trimmedMessage = line.Trim(); if (trimmedMessage != "") { Log.LogError(trimmedMessage); } } } /// <summary> /// Log each of the messages in the given output with the given importance. /// We assume each line is a message to log. /// </summary> /// <remarks> /// Should be "private protected" visibility once it is introduced into C#. /// </remarks> internal abstract void LogMessages(string output, MessageImportance messageImportance); public string GenerateResponseFileContents() { return GenerateResponseFileCommands(); } /// <summary> /// Get the command line arguments to pass to the compiler. /// </summary> private string[] GetArguments(string commandLineCommands, string responseFileCommands) { var commandLineArguments = CommandLineParser.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true); var responseFileArguments = CommandLineParser.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true); return commandLineArguments.Concat(responseFileArguments).ToArray(); } /// <summary> /// Returns the command line switch used by the tool executable to specify the response file /// Will only be called if the task returned a non empty string from GetResponseFileCommands /// Called after ValidateParameters, SkipTaskExecution and GetResponseFileCommands /// </summary> protected override string GenerateResponseFileCommands() { CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension(); AddResponseFileCommands(commandLineBuilder); return commandLineBuilder.ToString(); } protected override string GenerateCommandLineCommands() { CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension(); AddCommandLineCommands(commandLineBuilder); return commandLineBuilder.ToString(); } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and /// must go directly onto the command line. /// </summary> protected internal virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendWhenTrue("/noconfig", this._store, "NoConfig"); } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file. /// </summary> protected internal virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { // If outputAssembly is not specified, then an "/out: <name>" option won't be added to // overwrite the one resulting from the OutputAssembly member of the CompilerParameters class. // In that case, we should set the outputAssembly member based on the first source file. if ( (OutputAssembly == null) && (Sources != null) && (Sources.Length > 0) && (this.ResponseFiles == null) // The response file may already have a /out: switch in it, so don't try to be smart here. ) { try { OutputAssembly = new TaskItem(Path.GetFileNameWithoutExtension(Sources[0].ItemSpec)); } catch (ArgumentException e) { throw new ArgumentException(e.Message, "Sources"); } if (String.Compare(TargetType, "library", StringComparison.OrdinalIgnoreCase) == 0) { OutputAssembly.ItemSpec += ".dll"; } else if (String.Compare(TargetType, "module", StringComparison.OrdinalIgnoreCase) == 0) { OutputAssembly.ItemSpec += ".netmodule"; } else { OutputAssembly.ItemSpec += ".exe"; } } commandLine.AppendSwitchIfNotNull("/addmodule:", this.AddModules, ","); commandLine.AppendSwitchWithInteger("/codepage:", this._store, "CodePage"); ConfigureDebugProperties(); // The "DebugType" parameter should be processed after the "EmitDebugInformation" parameter // because it's more specific. Order matters on the command-line, and the last one wins. // /debug+ is just a shorthand for /debug:full. And /debug- is just a shorthand for /debug:none. commandLine.AppendPlusOrMinusSwitch("/debug", this._store, "EmitDebugInformation"); commandLine.AppendSwitchIfNotNull("/debug:", this.DebugType); commandLine.AppendPlusOrMinusSwitch("/delaysign", this._store, "DelaySign"); commandLine.AppendSwitchWithInteger("/filealign:", this._store, "FileAlignment"); commandLine.AppendSwitchIfNotNull("/keycontainer:", this.KeyContainer); commandLine.AppendSwitchIfNotNull("/keyfile:", this.KeyFile); // If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject. commandLine.AppendSwitchIfNotNull("/linkresource:", this.LinkResources, new string[] { "LogicalName", "Access" }); commandLine.AppendWhenTrue("/nologo", this._store, "NoLogo"); commandLine.AppendWhenTrue("/nowin32manifest", this._store, "NoWin32Manifest"); commandLine.AppendPlusOrMinusSwitch("/optimize", this._store, "Optimize"); commandLine.AppendPlusOrMinusSwitch("/deterministic", this._store, "Deterministic"); commandLine.AppendSwitchIfNotNull("/out:", this.OutputAssembly); commandLine.AppendSwitchIfNotNull("/ruleset:", this.CodeAnalysisRuleSet); commandLine.AppendSwitchIfNotNull("/errorlog:", this.ErrorLog); commandLine.AppendSwitchIfNotNull("/subsystemversion:", this.SubsystemVersion); commandLine.AppendWhenTrue("/reportanalyzer", this._store, "ReportAnalyzer"); // If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject. commandLine.AppendSwitchIfNotNull("/resource:", this.Resources, new string[] { "LogicalName", "Access" }); commandLine.AppendSwitchIfNotNull("/target:", this.TargetType); commandLine.AppendPlusOrMinusSwitch("/warnaserror", this._store, "TreatWarningsAsErrors"); commandLine.AppendWhenTrue("/utf8output", this._store, "Utf8Output"); commandLine.AppendSwitchIfNotNull("/win32icon:", this.Win32Icon); commandLine.AppendSwitchIfNotNull("/win32manifest:", this.Win32Manifest); this.AddFeatures(commandLine); this.AddAnalyzersToCommandLine(commandLine); this.AddAdditionalFilesToCommandLine(commandLine); // Append the sources. commandLine.AppendFileNamesIfNotNull(Sources, " "); } /// <summary> /// Adds a "/features:" switch to the command line for each provided feature. /// </summary> /// <param name="commandLine"></param> private void AddFeatures(CommandLineBuilderExtension commandLine) { var features = Features; if (string.IsNullOrEmpty(features)) { return; } foreach (var feature in CompilerOptionParseUtilities.ParseFeatureFromMSBuild(features)) { commandLine.AppendSwitchIfNotNull("/features:", feature.Trim()); } } /// <summary> /// Adds a "/analyzer:" switch to the command line for each provided analyzer. /// </summary> private void AddAnalyzersToCommandLine(CommandLineBuilderExtension commandLine) { // If there were no analyzers passed in, don't add any /analyzer: switches // on the command-line. if ((this.Analyzers == null) || (this.Analyzers.Length == 0)) { return; } foreach (ITaskItem analyzer in this.Analyzers) { commandLine.AppendSwitchIfNotNull("/analyzer:", analyzer.ItemSpec); } } /// <summary> /// Adds a "/additionalfile:" switch to the command line for each additional file. /// </summary> private void AddAdditionalFilesToCommandLine(CommandLineBuilderExtension commandLine) { // If there were no additional files passed in, don't add any /additionalfile: switches // on the command-line. if ((this.AdditionalFiles == null) || (this.AdditionalFiles.Length == 0)) { return; } foreach (ITaskItem additionalFile in this.AdditionalFiles) { commandLine.AppendSwitchIfNotNull("/additionalfile:", additionalFile.ItemSpec); } } /// <summary> /// Configure the debug switches which will be placed on the compiler command-line. /// The matrix of debug type and symbol inputs and the desired results is as follows: /// /// Debug Symbols DebugType Desired Results /// True Full /debug+ /debug:full /// True PdbOnly /debug+ /debug:PdbOnly /// True None /debug- /// True Blank /debug+ /// False Full /debug- /debug:full /// False PdbOnly /debug- /debug:PdbOnly /// False None /debug- /// False Blank /debug- /// Blank Full /debug:full /// Blank PdbOnly /debug:PdbOnly /// Blank None /debug- /// Debug: Blank Blank /debug+ //Microsoft.common.targets will set this /// Release: Blank Blank "Nothing for either switch" /// /// The logic is as follows: /// If debugtype is none set debugtype to empty and debugSymbols to false /// If debugType is blank use the debugsymbols "as is" /// If debug type is set, use its value and the debugsymbols value "as is" /// </summary> private void ConfigureDebugProperties() { // If debug type is set we need to take some action depending on the value. If debugtype is not set // We don't need to modify the EmitDebugInformation switch as its value will be used as is. if (_store["DebugType"] != null) { // If debugtype is none then only show debug- else use the debug type and the debugsymbols as is. if (string.Compare((string)_store["DebugType"], "none", StringComparison.OrdinalIgnoreCase) == 0) { _store["DebugType"] = null; _store["EmitDebugInformation"] = false; } } } /// <summary> /// Validate parameters, log errors and warnings and return true if /// Execute should proceed. /// </summary> protected override bool ValidateParameters() { return ListHasNoDuplicateItems(this.Resources, "Resources", "LogicalName") && ListHasNoDuplicateItems(this.Sources, "Sources"); } /// <summary> /// Returns true if the provided item list contains duplicate items, false otherwise. /// </summary> protected bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName) { return ListHasNoDuplicateItems(itemList, parameterName, null); } /// <summary> /// Returns true if the provided item list contains duplicate items, false otherwise. /// </summary> /// <param name="itemList"></param> /// <param name="disambiguatingMetadataName">Optional name of metadata that may legitimately disambiguate items. May be null.</param> /// <param name="parameterName"></param> private bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, string disambiguatingMetadataName) { if (itemList == null || itemList.Length == 0) { return true; } Hashtable alreadySeen = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (ITaskItem item in itemList) { string key; string disambiguatingMetadataValue = null; if (disambiguatingMetadataName != null) { disambiguatingMetadataValue = item.GetMetadata(disambiguatingMetadataName); } if (disambiguatingMetadataName == null || String.IsNullOrEmpty(disambiguatingMetadataValue)) { key = item.ItemSpec; } else { key = item.ItemSpec + ":" + disambiguatingMetadataValue; } if (alreadySeen.ContainsKey(key)) { if (disambiguatingMetadataName == null || String.IsNullOrEmpty(disambiguatingMetadataValue)) { Log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupported", item.ItemSpec, parameterName); } else { Log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupportedWithMetadata", item.ItemSpec, parameterName, disambiguatingMetadataValue, disambiguatingMetadataName); } return false; } else { alreadySeen[key] = String.Empty; } } return true; } /// <summary> /// Allows tool to handle the return code. /// This method will only be called with non-zero exitCode. /// </summary> protected override bool HandleTaskExecutionErrors() { // For managed compilers, the compiler should emit the appropriate // error messages before returning a non-zero exit code, so we don't // normally need to emit any additional messages now. // // If somehow the compiler DID return a non-zero exit code and didn't log an error, we'd like to log that exit code. // We can only do this for the command line compiler: if the inproc compiler was used, // we can't tell what if anything it logged as it logs directly to Visual Studio's output window. // if (!Log.HasLoggedErrors && UsedCommandLineTool) { // This will log a message "MSB3093: The command exited with code {0}." base.HandleTaskExecutionErrors(); } return false; } /// <summary> /// Takes a list of files and returns the normalized locations of these files /// </summary> private void NormalizePaths(ITaskItem[] taskItems) { foreach (var item in taskItems) { item.ItemSpec = Utilities.GetFullPathNoThrow(item.ItemSpec); } } /// <summary> /// Whether the command line compiler was invoked, instead /// of the host object compiler. /// </summary> protected bool UsedCommandLineTool { get; set; } private bool _hostCompilerSupportsAllParameters; protected bool HostCompilerSupportsAllParameters { get { return _hostCompilerSupportsAllParameters; } set { _hostCompilerSupportsAllParameters = value; } } /// <summary> /// Checks the bool result from calling one of the methods on the host compiler object to /// set one of the parameters. If it returned false, that means the host object doesn't /// support a particular parameter or variation on a parameter. So we log a comment, /// and set our state so we know not to call the host object to do the actual compilation. /// </summary> /// <owner>RGoel</owner> protected void CheckHostObjectSupport ( string parameterName, bool resultFromHostObjectSetOperation ) { if (!resultFromHostObjectSetOperation) { Log.LogMessageFromResources(MessageImportance.Normal, "General_ParameterUnsupportedOnHostCompiler", parameterName); _hostCompilerSupportsAllParameters = false; } } /// <summary> /// Checks to see whether all of the passed-in references exist on disk before we launch the compiler. /// </summary> /// <owner>RGoel</owner> protected bool CheckAllReferencesExistOnDisk() { if (null == this.References) { // No references return true; } bool success = true; foreach (ITaskItem reference in this.References) { if (!File.Exists(reference.ItemSpec)) { success = false; Log.LogErrorWithCodeFromResources("General_ReferenceDoesNotExist", reference.ItemSpec); } } return success; } /// <summary> /// The IDE and command line compilers unfortunately differ in how win32 /// manifests are specified. In particular, the command line compiler offers a /// "/nowin32manifest" switch, while the IDE compiler does not offer analogous /// functionality. If this switch is omitted from the command line and no win32 /// manifest is specified, the compiler will include a default win32 manifest /// named "default.win32manifest" found in the same directory as the compiler /// executable. Again, the IDE compiler does not offer analogous support. /// /// We'd like to imitate the command line compiler's behavior in the IDE, but /// it isn't aware of the default file, so we must compute the path to it if /// noDefaultWin32Manifest is false and no win32Manifest was provided by the /// project. /// /// This method will only be called during the initialization of the host object, /// which is only used during IDE builds. /// </summary> /// <returns>the path to the win32 manifest to provide to the host object</returns> internal string GetWin32ManifestSwitch ( bool noDefaultWin32Manifest, string win32Manifest ) { if (!noDefaultWin32Manifest) { if (String.IsNullOrEmpty(win32Manifest) && String.IsNullOrEmpty(this.Win32Resource)) { // We only want to consider the default.win32manifest if this is an executable if (!String.Equals(TargetType, "library", StringComparison.OrdinalIgnoreCase) && !String.Equals(TargetType, "module", StringComparison.OrdinalIgnoreCase)) { // We need to compute the path to the default win32 manifest string pathToDefaultManifest = ToolLocationHelper.GetPathToDotNetFrameworkFile ( "default.win32manifest", TargetDotNetFrameworkVersion.VersionLatest ); if (null == pathToDefaultManifest) { // This is rather unlikely, and the inproc compiler seems to log an error anyway. // So just a message is fine. Log.LogMessageFromResources ( "General_ExpectedFileMissing", "default.win32manifest" ); } return pathToDefaultManifest; } } } return win32Manifest; } } }
//============================================================================= // System : Sandcastle Help File Builder Utilities // File : ResolveNameFunction.cs // Author : Eric Woodruff ([email protected]) // Updated : 10/22/2007 // Note : Copyright 2007, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains a custom XPath function used to convert an API name into // its more readable form which is used for searching. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.5.1.0 07/27/2007 EFW Created the code //============================================================================= using System; using System.Globalization; using System.Text; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; namespace SandcastleBuilder.Utils.XPath { /// <summary> /// This class is a custom XPath function used to convert an API name into /// its more readable form used for searching. /// </summary> /// <remarks>The function should be passed an XML node containing the /// necessary information used to obtain the name and convert it into the /// searchable format along with a boolean indicating whether or not the /// name should be fully qualified with the namespace and type.</remarks> /// <example> /// <example> /// Some examples of XPath queries using the function: /// <code lang="none"> /// //apis/api[matches-regex(resolve-name(node(), boolean(false), /// 'utils.*proj', boolean(true)) /// /// //apis/api[matches-regex(resolve-name(node(), boolean(true)), /// 'Proj|Filt|Excep', boolean(false)) /// </code> /// </example> /// </example> internal sealed class ResolveNameFunction : IXsltContextFunction { #region IXsltContextFunction Members //===================================================================== // IXsltContextFunction implementation /// <summary> /// Gets the supplied XPath types for the function's argument list. /// This information can be used to discover the signature of the /// function which allows you to differentiate between overloaded /// functions. /// </summary> /// <value>Always returns an array with a <b>Navigator</b> type /// and a Boolean type entry.</value> public XPathResultType[] ArgTypes { get { return new XPathResultType[] { XPathResultType.Navigator, XPathResultType.Boolean }; } } /// <summary> /// Gets the minimum number of arguments for the function. This enables /// the user to differentiate between overloaded functions. /// </summary> /// <value>Always returns two</value> public int Minargs { get { return 2; } } /// <summary> /// Gets the maximum number of arguments for the function. This enables /// the user to differentiate between overloaded functions. /// </summary> /// <value>Always returns two</value> public int Maxargs { get { return 2; } } /// <summary> /// Gets the XPath type returned by the function /// </summary> /// <value>Always returns String</value> public XPathResultType ReturnType { get { return XPathResultType.String; } } /// <summary> /// This is called to invoke the <b>resolve-name</b> method. /// </summary> /// <param name="xsltContext">The XSLT context for the function call</param> /// <param name="args">The arguments for the function call</param> /// <param name="docContext">The context node for the function call</param> /// <returns>An object representing the return value of the function /// (the name string).</returns> /// <exception cref="ArgumentException">This is thrown if the /// number of arguments for the function is not two.</exception> public object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { XPathNavigator nav; XmlNode apiNode; XmlNodeList templates; StringBuilder sb = new StringBuilder(100); string nodeText; bool fullyQualified; int pos, idx = 1; char nodeType; if(args.Length != 2) throw new ArgumentException("There must be two parameters " + "passed to the 'resolve-name' function", "args"); nav = ((XPathNodeIterator)args[0]).Current; apiNode = ((IHasXmlNode)nav).GetNode(); fullyQualified = Convert.ToBoolean(args[1], CultureInfo.InvariantCulture); if(apiNode.Name == "api") { templates = apiNode.SelectNodes("templates/template"); nodeText = apiNode.Attributes["id"].Value; } else { nodeText = apiNode.Attributes["api"].Value; templates = apiNode.SelectNodes("specialization/template"); if(templates.Count == 0) templates = apiNode.SelectNodes("specialization/type"); } nodeType = nodeText[0]; nodeText = nodeText.Substring(2); if(nodeType == 'N') { if(nodeText.Length == 0 && !fullyQualified) nodeText = "(global)"; } else { // Strip parameters pos = nodeText.IndexOf('('); if(pos != -1) nodeText = nodeText.Substring(0, pos); // Remove the namespace and type if not fully qualified. // Note the last period's position though as we'll need it // to skip generic markers in the name type name. pos = nodeText.LastIndexOf('.'); if(!fullyQualified && pos != -1) { nodeText = nodeText.Substring(pos + 1); pos = 0; } if(nodeType != 'T') { // Replace certain values to make it more readable if(nodeText.IndexOf("#cctor", StringComparison.Ordinal) != -1) nodeText = nodeText.Replace("#cctor", "Static Constructor"); else if(nodeText.IndexOf("#ctor", StringComparison.Ordinal) != -1) nodeText = nodeText.Replace("#ctor", "Constructor"); else { if(nodeText.IndexOf('#') != -1) nodeText = nodeText.Replace('#', '.'); if(pos == 0) { if(nodeText.StartsWith("op_", StringComparison.Ordinal)) nodeText = nodeText.Substring(3) + " Operator"; } else if(nodeText.IndexOf("op_", pos, StringComparison.Ordinal) != -1) nodeText = nodeText.Substring(0, pos + 1) + nodeText.Substring(pos + 4) + " Operator"; } } // Replace generic template markers with the names if(pos != -1) pos = nodeText.IndexOf('`', pos); if(pos != -1) { nodeText = nodeText.Substring(0, pos); foreach(XmlNode template in templates) { if(sb.Length != 0) sb.Append(','); if(template.Name != "type") sb.Append(template.Attributes["name"].Value); else { // For specializations of types, we don't want to // show the type but a generic place holder. sb.Append('T'); if(idx > 1) sb.Append(idx); idx++; } } if(sb.Length != 0) { sb.Insert(0, "<"); sb.Append('>'); nodeText += sb.ToString(); } } // Replace generic template markers in the type name if // fully qualified. if(fullyQualified && nodeText.IndexOf('`') != -1) nodeText = ReplaceTypeTemplateMarker(apiNode, nodeText); } return nodeText; } /// <summary> /// This is used to replace the template marker in a type name /// </summary> /// <param name="apiNode">The API node to use</param> /// <param name="nodeText">The node text to modify</param> /// <returns>The updated node text</returns> public static string ReplaceTypeTemplateMarker(XmlNode apiNode, string nodeText) { XmlNodeList templates; StringBuilder sb = new StringBuilder(100); int idx = 1, pos = nodeText.IndexOf('`'); string typeName = nodeText.Substring(0, nodeText.IndexOf('.', pos)); sb.Append(typeName.Substring(0, pos)); sb.Append('<'); if(apiNode.Name != "element") templates = apiNode.ParentNode.SelectNodes("api[@id='T:" + typeName + "']/templates/template"); else { templates = apiNode.SelectNodes("containers/type/" + "specialization/type"); if(templates.Count == 0) templates = apiNode.SelectNodes("containers/type/" + "specialization/template"); } if(templates.Count == 0) sb.Append("T"); // No info found else foreach(XmlNode template in templates) { if(sb[sb.Length - 1] != '<') sb.Append(','); if(template.Name != "type") sb.Append(template.Attributes["name"].Value); else { // For specializations of types, we don't want to // show the type but a generic place holder. sb.Append('T'); if(idx > 1) sb.Append(idx); idx++; } } sb.Append('>'); sb.Append(nodeText.Substring(typeName.Length)); return sb.ToString(); } #endregion } }
// Copyright 2022 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.Dataflow.V1Beta3.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedMetricsV1Beta3ClientSnippets { /// <summary>Snippet for GetJobMetrics</summary> public void GetJobMetricsRequestObject() { // Snippet: GetJobMetrics(GetJobMetricsRequest, CallSettings) // Create client MetricsV1Beta3Client metricsV1Beta3Client = MetricsV1Beta3Client.Create(); // Initialize request argument(s) GetJobMetricsRequest request = new GetJobMetricsRequest { ProjectId = "", JobId = "", StartTime = new Timestamp(), Location = "", }; // Make the request JobMetrics response = metricsV1Beta3Client.GetJobMetrics(request); // End snippet } /// <summary>Snippet for GetJobMetricsAsync</summary> public async Task GetJobMetricsRequestObjectAsync() { // Snippet: GetJobMetricsAsync(GetJobMetricsRequest, CallSettings) // Additional: GetJobMetricsAsync(GetJobMetricsRequest, CancellationToken) // Create client MetricsV1Beta3Client metricsV1Beta3Client = await MetricsV1Beta3Client.CreateAsync(); // Initialize request argument(s) GetJobMetricsRequest request = new GetJobMetricsRequest { ProjectId = "", JobId = "", StartTime = new Timestamp(), Location = "", }; // Make the request JobMetrics response = await metricsV1Beta3Client.GetJobMetricsAsync(request); // End snippet } /// <summary>Snippet for GetJobExecutionDetails</summary> public void GetJobExecutionDetailsRequestObject() { // Snippet: GetJobExecutionDetails(GetJobExecutionDetailsRequest, CallSettings) // Create client MetricsV1Beta3Client metricsV1Beta3Client = MetricsV1Beta3Client.Create(); // Initialize request argument(s) GetJobExecutionDetailsRequest request = new GetJobExecutionDetailsRequest { ProjectId = "", JobId = "", Location = "", }; // Make the request PagedEnumerable<JobExecutionDetails, StageSummary> response = metricsV1Beta3Client.GetJobExecutionDetails(request); // Iterate over all response items, lazily performing RPCs as required foreach (StageSummary 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 (JobExecutionDetails page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (StageSummary item in page) { // Do something with each item 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<StageSummary> 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 (StageSummary item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetJobExecutionDetailsAsync</summary> public async Task GetJobExecutionDetailsRequestObjectAsync() { // Snippet: GetJobExecutionDetailsAsync(GetJobExecutionDetailsRequest, CallSettings) // Create client MetricsV1Beta3Client metricsV1Beta3Client = await MetricsV1Beta3Client.CreateAsync(); // Initialize request argument(s) GetJobExecutionDetailsRequest request = new GetJobExecutionDetailsRequest { ProjectId = "", JobId = "", Location = "", }; // Make the request PagedAsyncEnumerable<JobExecutionDetails, StageSummary> response = metricsV1Beta3Client.GetJobExecutionDetailsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((StageSummary 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((JobExecutionDetails page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (StageSummary item in page) { // Do something with each item 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<StageSummary> 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 (StageSummary item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetStageExecutionDetails</summary> public void GetStageExecutionDetailsRequestObject() { // Snippet: GetStageExecutionDetails(GetStageExecutionDetailsRequest, CallSettings) // Create client MetricsV1Beta3Client metricsV1Beta3Client = MetricsV1Beta3Client.Create(); // Initialize request argument(s) GetStageExecutionDetailsRequest request = new GetStageExecutionDetailsRequest { ProjectId = "", JobId = "", Location = "", StageId = "", StartTime = new Timestamp(), EndTime = new Timestamp(), }; // Make the request PagedEnumerable<StageExecutionDetails, WorkerDetails> response = metricsV1Beta3Client.GetStageExecutionDetails(request); // Iterate over all response items, lazily performing RPCs as required foreach (WorkerDetails 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 (StageExecutionDetails page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (WorkerDetails item in page) { // Do something with each item 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<WorkerDetails> 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 (WorkerDetails item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetStageExecutionDetailsAsync</summary> public async Task GetStageExecutionDetailsRequestObjectAsync() { // Snippet: GetStageExecutionDetailsAsync(GetStageExecutionDetailsRequest, CallSettings) // Create client MetricsV1Beta3Client metricsV1Beta3Client = await MetricsV1Beta3Client.CreateAsync(); // Initialize request argument(s) GetStageExecutionDetailsRequest request = new GetStageExecutionDetailsRequest { ProjectId = "", JobId = "", Location = "", StageId = "", StartTime = new Timestamp(), EndTime = new Timestamp(), }; // Make the request PagedAsyncEnumerable<StageExecutionDetails, WorkerDetails> response = metricsV1Beta3Client.GetStageExecutionDetailsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((WorkerDetails 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((StageExecutionDetails page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (WorkerDetails item in page) { // Do something with each item 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<WorkerDetails> 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 (WorkerDetails item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
// PendingBuffer.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace PdfSharp.SharpZipLib.Zip.Compression { /// <summary> /// This class is general purpose class for writing data to a buffer. /// /// It allows you to write bits as well as bytes /// Based on DeflaterPending.java /// /// Author of the original java version: Jochen Hoenicke /// </summary> internal class PendingBuffer { #region Instance Fields /// <summary> /// Internal work buffer /// </summary> byte[] buffer_; int start; int end; uint bits; int bitCount; #endregion #region Constructors /// <summary> /// construct instance using default buffer size of 4096 /// </summary> public PendingBuffer() : this(4096) { } /// <summary> /// construct instance using specified buffer size /// </summary> /// <param name="bufferSize"> /// size to use for internal buffer /// </param> public PendingBuffer(int bufferSize) { buffer_ = new byte[bufferSize]; } #endregion /// <summary> /// Clear internal state/buffers /// </summary> public void Reset() { start = end = bitCount = 0; } /// <summary> /// Write a byte to buffer /// </summary> /// <param name="value"> /// The value to write /// </param> public void WriteByte(int value) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte)value); } /// <summary> /// Write a short value to buffer LSB first /// </summary> /// <param name="value"> /// The value to write. /// </param> public void WriteShort(int value) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte)value); buffer_[end++] = unchecked((byte)(value >> 8)); } /// <summary> /// write an integer LSB first /// </summary> /// <param name="value">The value to write.</param> public void WriteInt(int value) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte)value); buffer_[end++] = unchecked((byte)(value >> 8)); buffer_[end++] = unchecked((byte)(value >> 16)); buffer_[end++] = unchecked((byte)(value >> 24)); } /// <summary> /// Write a block of data to buffer /// </summary> /// <param name="block">data to write</param> /// <param name="offset">offset of first byte to write</param> /// <param name="length">number of bytes to write</param> public void WriteBlock(byte[] block, int offset, int length) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif System.Array.Copy(block, offset, buffer_, end, length); end += length; } /// <summary> /// The number of bits written to the buffer /// </summary> public int BitCount { get { return bitCount; } } /// <summary> /// Align internal buffer on a byte boundary /// </summary> public void AlignToByte() { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif if (bitCount > 0) { buffer_[end++] = unchecked((byte)bits); if (bitCount > 8) { buffer_[end++] = unchecked((byte)(bits >> 8)); } } bits = 0; bitCount = 0; } /// <summary> /// Write bits to internal buffer /// </summary> /// <param name="b">source of bits</param> /// <param name="count">number of bits to write</param> public void WriteBits(int b, int count) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("writeBits("+b+","+count+")"); // } #endif bits |= (uint)(b << bitCount); bitCount += count; if (bitCount >= 16) { buffer_[end++] = unchecked((byte)bits); buffer_[end++] = unchecked((byte)(bits >> 8)); bits >>= 16; bitCount -= 16; } } /// <summary> /// Write a short value to internal buffer most significant byte first /// </summary> /// <param name="s">value to write</param> public void WriteShortMSB(int s) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte)(s >> 8)); buffer_[end++] = unchecked((byte)s); } /// <summary> /// Indicates if buffer has been flushed /// </summary> public bool IsFlushed { get { return end == 0; } } /// <summary> /// Flushes the pending buffer into the given output array. If the /// output array is to small, only a partial flush is done. /// </summary> /// <param name="output">The output array.</param> /// <param name="offset">The offset into output array.</param> /// <param name="length">The maximum number of bytes to store.</param> /// <returns>The number of bytes flushed.</returns> public int Flush(byte[] output, int offset, int length) { if (bitCount >= 8) { buffer_[end++] = unchecked((byte)bits); bits >>= 8; bitCount -= 8; } if (length > end - start) { length = end - start; System.Array.Copy(buffer_, start, output, offset, length); start = 0; end = 0; } else { System.Array.Copy(buffer_, start, output, offset, length); start += length; } return length; } /// <summary> /// Convert internal buffer to byte array. /// Buffer is empty on completion /// </summary> /// <returns> /// The internal buffer contents converted to a byte array. /// </returns> public byte[] ToByteArray() { byte[] result = new byte[end - start]; System.Array.Copy(buffer_, start, result, 0, result.Length); start = 0; end = 0; return result; } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.38.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Cloud Runtime Configuration API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://cloud.google.com/deployment-manager/runtime-configurator/'>Cloud Runtime Configuration API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20190107 (1467) * <tr><th>API Docs * <td><a href='https://cloud.google.com/deployment-manager/runtime-configurator/'> * https://cloud.google.com/deployment-manager/runtime-configurator/</a> * <tr><th>Discovery Name<td>runtimeconfig * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Cloud Runtime Configuration API can be found at * <a href='https://cloud.google.com/deployment-manager/runtime-configurator/'>https://cloud.google.com/deployment-manager/runtime-configurator/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.CloudRuntimeConfig.v1 { /// <summary>The CloudRuntimeConfig Service.</summary> public class CloudRuntimeConfigService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public CloudRuntimeConfigService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public CloudRuntimeConfigService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { operations = new OperationsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "runtimeconfig"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://runtimeconfig.googleapis.com/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return ""; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://runtimeconfig.googleapis.com/batch"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch"; } } #endif /// <summary>Available OAuth 2.0 scopes for use with the Cloud Runtime Configuration API.</summary> public class Scope { /// <summary>View and manage your data across Google Cloud Platform services</summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary>Manage your Google Cloud Platform services' runtime configuration</summary> public static string Cloudruntimeconfig = "https://www.googleapis.com/auth/cloudruntimeconfig"; } /// <summary>Available OAuth 2.0 scope constants for use with the Cloud Runtime Configuration API.</summary> public static class ScopeConstants { /// <summary>View and manage your data across Google Cloud Platform services</summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary>Manage your Google Cloud Platform services' runtime configuration</summary> public const string Cloudruntimeconfig = "https://www.googleapis.com/auth/cloudruntimeconfig"; } private readonly OperationsResource operations; /// <summary>Gets the Operations resource.</summary> public virtual OperationsResource Operations { get { return operations; } } } ///<summary>A base abstract class for CloudRuntimeConfig requests.</summary> public abstract class CloudRuntimeConfigBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new CloudRuntimeConfigBaseServiceRequest instance.</summary> protected CloudRuntimeConfigBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes CloudRuntimeConfig parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "operations" collection of methods.</summary> public class OperationsResource { private const string Resource = "operations"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public OperationsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to /// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether /// the cancellation succeeded or whether the operation completed despite cancellation. On successful /// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value /// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.</summary> /// <param name="body">The body of the request.</param> /// <param name="name">The name of the operation resource to be cancelled.</param> public virtual CancelRequest Cancel(Google.Apis.CloudRuntimeConfig.v1.Data.CancelOperationRequest body, string name) { return new CancelRequest(service, body, name); } /// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to /// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether /// the cancellation succeeded or whether the operation completed despite cancellation. On successful /// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value /// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.</summary> public class CancelRequest : CloudRuntimeConfigBaseServiceRequest<Google.Apis.CloudRuntimeConfig.v1.Data.Empty> { /// <summary>Constructs a new Cancel request.</summary> public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudRuntimeConfig.v1.Data.CancelOperationRequest body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary>The name of the operation resource to be cancelled.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudRuntimeConfig.v1.Data.CancelOperationRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "cancel"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}:cancel"; } } /// <summary>Initializes Cancel parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^operations/.+$", }); } } /// <summary>Deletes a long-running operation. This method indicates that the client is no longer interested in /// the operation result. It does not cancel the operation. If the server doesn't support this method, it /// returns `google.rpc.Code.UNIMPLEMENTED`.</summary> /// <param name="name">The name of the operation resource to be deleted.</param> public virtual DeleteRequest Delete(string name) { return new DeleteRequest(service, name); } /// <summary>Deletes a long-running operation. This method indicates that the client is no longer interested in /// the operation result. It does not cancel the operation. If the server doesn't support this method, it /// returns `google.rpc.Code.UNIMPLEMENTED`.</summary> public class DeleteRequest : CloudRuntimeConfigBaseServiceRequest<Google.Apis.CloudRuntimeConfig.v1.Data.Empty> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the operation resource to be deleted.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^operations/.+$", }); } } /// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this /// method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, /// such as `users/operations`. To override the binding, API services can add a binding such as /// `"/v1/{name=users}/operations"` to their service configuration. For backwards compatibility, the default /// name includes the operations collection id, however overriding users must ensure the name binding is the /// parent resource, without the operations collection id.</summary> /// <param name="name">The name of the operation's parent resource.</param> public virtual ListRequest List(string name) { return new ListRequest(service, name); } /// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this /// method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, /// such as `users/operations`. To override the binding, API services can add a binding such as /// `"/v1/{name=users}/operations"` to their service configuration. For backwards compatibility, the default /// name includes the operations collection id, however overriding users must ensure the name binding is the /// parent resource, without the operations collection id.</summary> public class ListRequest : CloudRuntimeConfigBaseServiceRequest<Google.Apis.CloudRuntimeConfig.v1.Data.ListOperationsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the operation's parent resource.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>The standard list filter.</summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary>The standard list page token.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>The standard list page size.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^operations$", }); RequestParameters.Add( "filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.CloudRuntimeConfig.v1.Data { /// <summary>The request message for Operations.CancelOperation.</summary> public class CancelOperationRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A /// typical example is to use it as the request or the response type of an API method. For instance: /// /// service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } /// /// The JSON representation for `Empty` is empty JSON object `{}`.</summary> public class Empty : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The response message for Operations.ListOperations.</summary> public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The standard List next-page token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>A list of operations that matches the specified filter in the request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("operations")] public virtual System.Collections.Generic.IList<Operation> Operations { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>This resource represents a long-running operation that is the result of a network API call.</summary> public class Operation : Google.Apis.Requests.IDirectResponseSchema { /// <summary>If the value is `false`, it means the operation is still in progress. If `true`, the operation is /// completed, and either `error` or `response` is available.</summary> [Newtonsoft.Json.JsonPropertyAttribute("done")] public virtual System.Nullable<bool> Done { get; set; } /// <summary>The error result of the operation in case of failure or cancellation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("error")] public virtual Status Error { get; set; } /// <summary>Service-specific metadata associated with the operation. It typically contains progress /// information and common metadata such as create time. Some services might not provide such metadata. Any /// method that returns a long-running operation should document the metadata type, if any.</summary> [Newtonsoft.Json.JsonPropertyAttribute("metadata")] public virtual System.Collections.Generic.IDictionary<string,object> Metadata { get; set; } /// <summary>The server-assigned name, which is only unique within the same service that originally returns it. /// If you use the default HTTP mapping, the `name` should have the format of /// `operations/some/unique/name`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The normal response of the operation in case of success. If the original method returns no data on /// success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard /// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have /// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name /// is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("response")] public virtual System.Collections.Generic.IDictionary<string,object> Response { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The `Status` type defines a logical error model that is suitable for different programming /// environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model /// is designed to be: /// /// - Simple to use and understand for most users - Flexible enough to meet unexpected needs /// /// # Overview /// /// The `Status` message contains three pieces of data: error code, error message, and error details. The error code /// should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error /// message should be a developer-facing English message that helps developers *understand* and *resolve* the error. /// If a localized user-facing error message is needed, put the localized message in the error details or localize /// it in the client. The optional error details may contain arbitrary information about the error. There is a /// predefined set of error detail types in the package `google.rpc` that can be used for common error conditions. /// /// # Language mapping /// /// The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire /// format. When the `Status` message is exposed in different client libraries and different wire protocols, it can /// be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped /// to some error codes in C. /// /// # Other uses /// /// The error model and the `Status` message can be used in a variety of environments, either with or without APIs, /// to provide a consistent developer experience across different environments. /// /// Example uses of this error model include: /// /// - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the /// normal response to indicate the partial errors. /// /// - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error /// reporting. /// /// - Batch operations. If a client uses batch request and batch response, the `Status` message should be used /// directly inside batch response, one for each error sub-response. /// /// - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of /// those operations should be represented directly using the `Status` message. /// /// - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any /// stripping needed for security/privacy reasons.</summary> public class Status : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The status code, which should be an enum value of google.rpc.Code.</summary> [Newtonsoft.Json.JsonPropertyAttribute("code")] public virtual System.Nullable<int> Code { get; set; } /// <summary>A list of messages that carry the error details. There is a common set of message types for APIs /// to use.</summary> [Newtonsoft.Json.JsonPropertyAttribute("details")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,object>> Details { get; set; } /// <summary>A developer-facing error message, which should be in English. Any user-facing error message should /// be localized and sent in the google.rpc.Status.details field, or localized by the client.</summary> [Newtonsoft.Json.JsonPropertyAttribute("message")] public virtual string Message { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Extensions.Logging; using LoginViewComponent.Models; using LoginViewComponent.Models.AccountViewModels; using LoginViewComponent.Services; namespace LoginViewComponent.Controllers { [Authorize] public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<AccountController>(); } // // GET: /Account/Login [HttpGet] [AllowAnonymous] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { _logger.LogInformation(1, "User logged in."); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); } if (result.IsLockedOut) { _logger.LogWarning(2, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/Register [HttpGet] [AllowAnonymous] public IActionResult Register(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Name = model.Name }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User created a new account with password."); return RedirectToLocal(returnUrl); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LogOff() { await _signInManager.SignOutAsync(); _logger.LogInformation(4, "User logged out."); return RedirectToAction(nameof(HomeController.Index), "Home"); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public IActionResult ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return Challenge(properties, provider); } // // GET: /Account/ExternalLoginCallback [HttpGet] [AllowAnonymous] public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}"); return View(nameof(Login)); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return RedirectToAction(nameof(Login)); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); if (result.Succeeded) { _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }); } if (result.IsLockedOut) { return View("Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.Principal.FindFirstValue(ClaimTypes.Email); return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return View(model); } // GET: /Account/ConfirmEmail [HttpGet] [AllowAnonymous] public async Task<IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return View("Error"); } var result = await _userManager.ConfirmEmailAsync(user, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // GET: /Account/ForgotPassword [HttpGet] [AllowAnonymous] public IActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GeneratePasswordResetTokenAsync(user); //var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Reset Password", // $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>"); //return View("ForgotPasswordConfirmation"); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ForgotPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [HttpGet] [AllowAnonymous] public IActionResult ResetPassword(string code = null) { return code == null ? View("Error") : View(); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ResetPasswordConfirmation() { return View(); } // // GET: /Account/SendCode [HttpGet] [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false) { var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } // Generate the token and send it var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); if (string.IsNullOrWhiteSpace(code)) { return View("Error"); } var message = "Your security code is: " + code; if (model.SelectedProvider == "Email") { await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message); } else if (model.SelectedProvider == "Phone") { await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message); } return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } // // GET: /Account/VerifyCode [HttpGet] [AllowAnonymous] public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null) { // Require that the user has already logged in via username/password or external login var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser); if (result.Succeeded) { return RedirectToLocal(model.ReturnUrl); } if (result.IsLockedOut) { _logger.LogWarning(7, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid code."); return View(model); } } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } private Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction(nameof(HomeController.Index), "Home"); } } #endregion } }
//----------------------------------------------------------------------- // <copyright file="DpRoot.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using Csla.DataPortalClient; using Csla.Serialization; namespace Csla.Test.DataPortal { [Serializable()] public class DpRoot : BusinessBase<DpRoot> { private string _auth = "No value"; #region "Get/Set Private Variables" public static PropertyInfo<string> DataProperty = RegisterProperty<string>(c => c.Data); public string Data { get { return GetProperty(DataProperty); } set { SetProperty(DataProperty, value); } } public string Auth { get { return _auth; } set { //Not allowed } } #endregion #region "Criteria class" [Serializable()] private class Criteria { public string _data; public Criteria() { _data = "<new>"; } public Criteria(string data) { this._data = data; } } #endregion #region "New root + constructor" public static DpRoot NewRoot() { Criteria crit = new Criteria(); return (Csla.DataPortal.Create<DpRoot>(crit)); } public static DpRoot GetRoot(string data) { return (Csla.DataPortal.Fetch<DpRoot>(new Criteria(data))); } #endregion public DpRoot CloneThis() { return this.Clone(); } #region "DataPortal" private void DataPortal_Create(object criteria) { Criteria crit = (Criteria)(criteria); using (BypassPropertyChecks) Data = crit._data; } protected void DataPortal_Fetch(object criteria) { Criteria crit = (Criteria)(criteria); using (BypassPropertyChecks) Data = crit._data; MarkOld(); } protected override void DataPortal_Insert() { //we would insert here } protected override void DataPortal_Update() { //we would update here } protected override void DataPortal_DeleteSelf() { //we would delete here } protected void DataPortal_Delete(object criteria) { //we would delete here } protected override void DataPortal_OnDataPortalInvoke(DataPortalEventArgs e) { Csla.ApplicationContext.GlobalContext["serverinvoke"] = true; } protected override void DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e) { Csla.ApplicationContext.GlobalContext["serverinvokecomplete"] = true; } #endregion #region "Authorization Rules" protected override void AddBusinessRules() { string role = "Admin"; BusinessRules.AddRule(new Csla.Rules.CommonRules.IsNotInRole(Rules.AuthorizationActions.ReadProperty, DenyReadOnPropertyProperty, new List<string> { role })); BusinessRules.AddRule(new Csla.Rules.CommonRules.IsNotInRole(Rules.AuthorizationActions.WriteProperty, DenyWriteOnPropertyProperty, new List<string> { role })); BusinessRules.AddRule(new Csla.Rules.CommonRules.IsNotInRole(Rules.AuthorizationActions.ReadProperty, DenyReadWriteOnPropertyProperty, new List<string> { role })); BusinessRules.AddRule(new Csla.Rules.CommonRules.IsNotInRole(Rules.AuthorizationActions.WriteProperty, DenyReadWriteOnPropertyProperty, new List<string> { role })); BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Rules.AuthorizationActions.ReadProperty, AllowReadWriteOnPropertyProperty, new List<string> { role })); BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Rules.AuthorizationActions.WriteProperty, AllowReadWriteOnPropertyProperty, new List<string> { role })); } public static PropertyInfo<string> DenyReadOnPropertyProperty = RegisterProperty<string>(c => c.DenyReadOnProperty); public string DenyReadOnProperty { get { if (CanReadProperty("DenyReadOnProperty")) throw new Csla.Security.SecurityException("Not allowed 1"); else return "[DenyReadOnProperty] Can't read property"; } set { //Not allowed } } public static PropertyInfo<string> DenyWriteOnPropertyProperty = RegisterProperty<string>(c => c.DenyWriteOnProperty); public string DenyWriteOnProperty { get { return "<No Value>"; } set { if (CanWriteProperty("DenyWriteOnProperty")) throw new Csla.Security.SecurityException("Not allowed 2"); else _auth = "[DenyWriteOnProperty] Can't write variable"; } } public static PropertyInfo<string> DenyReadWriteOnPropertyProperty = RegisterProperty<string>(c => c.DenyReadWriteOnProperty); public string DenyReadWriteOnProperty { get { if (CanReadProperty("DenyReadWriteOnProperty")) throw new Csla.Security.SecurityException("Not allowed 3"); else return "[DenyReadWriteOnProperty] Can't read property"; } set { if (CanWriteProperty("DenyReadWriteOnProperty")) throw new Csla.Security.SecurityException("Not allowed 4"); else _auth = "[DenyReadWriteOnProperty] Can't write variable"; } } public static PropertyInfo<string> AllowReadWriteOnPropertyProperty = RegisterProperty<string>(c => c.AllowReadWriteOnProperty); public string AllowReadWriteOnProperty { get { if (CanReadProperty("AllowReadWriteOnProperty")) return _auth; else throw new Csla.Security.SecurityException("Should be allowed 5"); } set { if (CanWriteProperty("AllowReadWriteOnProperty")) _auth = value; else throw new Csla.Security.SecurityException("Should be allowed 5"); } } #endregion } }
using System.Collections.Generic; using System.IO; using System.Linq; using FluentAssertions; using NuGet.Packaging.Core; using NuGet.Test.Helpers; using NuGet.Versioning; using Xunit; namespace NupkgWrench.Tests { public class UtilTests { [Theory] [InlineData("a.1.0.0.symbols.nupkg", true)] [InlineData("/usr/home/a.1.0.0.symbols.nupkg", true)] [InlineData(".symbols.nupkg", true)] [InlineData("", false)] [InlineData("/usr/home/a.1.0.0.nupkg", false)] [InlineData("a.1.0.0.nupkg", false)] public void GivenAPathVerifySymbolPackage(string path, bool expected) { Util.IsSymbolPackage(path).Should().Be(expected); } [Theory] [InlineData("a", "1.0.0", "a.1.0.0")] [InlineData("a", "1.0", "a.1.0")] [InlineData("a", "1.0.0.0", "a.1.0.0.0")] [InlineData("a", "1.0.0+git", "a.1.0.0")] [InlineData("a", "1.0.0-beta.2+git", "a.1.0.0-beta.2")] [InlineData("a.1", "1.0.0-beta.2+git", "a.1.1.0.0-beta.2")] [InlineData("A", "1.0.0-BETA", "A.1.0.0-BETA")] public void GivenAnIdVersionVerifyNupkgName(string id, string version, string expected) { var identity = new PackageIdentity(id, NuGetVersion.Parse(version)); // non symbol Util.GetNupkgName(identity, isSymbolPackage: false).Should().Be(expected + ".nupkg"); // symbol Util.GetNupkgName(identity, isSymbolPackage: true).Should().Be(expected + ".symbols.nupkg"); } [Fact] public void Util_GetPackagesWithFilter_NoFilters() { using (var workingDir = new TestFolder()) { // Arrange CreatePackages(workingDir.Root); var log = new TestLogger(); // Act var files = Util.GetPackagesWithFilter( idFilter: null, versionFilter: null, excludeSymbols: false, highestVersionFilter: false, inputs: new[] { workingDir.Root }); // Use only the names var names = new List<string>(files.Select(path => Path.GetFileName(path))); // Assert Assert.Equal(6, files.Count); Assert.Equal("a.1.0.nupkg", names[0]); Assert.Equal("a.1.0.symbols.nupkg", names[1]); Assert.Equal("b.2.0.0.0.nupkg", names[2]); Assert.Equal("b.2.0.0.0.symbols.nupkg", names[3]); Assert.Equal("c.2.0.0-beta.1.nupkg", names[4]); Assert.Equal("c.2.0.0-beta.2.nupkg", names[5]); } } [Theory] [InlineData("**/*.nupkg", 6)] [InlineData("subFolder/*.nupkg", 6)] [InlineData("subFolder/*.0.*.nupkg", 5)] [InlineData("*.nupkg", 0)] [InlineData("**", 6)] [InlineData("**/a.*", 2)] [InlineData("**/c.2.0.0-beta.1.nupkg", 1)] [InlineData("subFolder/c.2.0.0-beta.1.*", 1)] [InlineData("subFolder/d.2.0.0-beta.1.*", 0)] public void Util_GetPackagesWithFilter_GlobbingPatterns(string pattern, int count) { using (var workingDir = new TestFolder()) { // Arrange var subFolder = Path.Combine(workingDir.Root, "subFolder"); CreatePackages(subFolder); var log = new TestLogger(); var input = workingDir.Root + Path.DirectorySeparatorChar + pattern; // Act var files = Util.GetPackagesWithFilter( idFilter: null, versionFilter: null, excludeSymbols: false, highestVersionFilter: false, inputs: new[] { input }); // Assert Assert.Equal(count, files.Count); } } [Theory] [InlineData("**/*.nupkg", "/**/*.nupkg")] [InlineData("subFolder/*.nupkg", "/*.nupkg")] [InlineData("subFolder/*.0.*.nupkg", "/*.0.*.nupkg")] [InlineData("*.nupkg", "/*.nupkg")] [InlineData("**", "/**")] [InlineData("**/a.*", "/**/a.*")] [InlineData("**/c.2.0.0-beta.1.nupkg", "/**/c.2.0.0-beta.1.nupkg")] [InlineData("subFolder/c.2.0.0-beta.1.*", "/c.2.0.0-beta.1.*")] [InlineData("subFolder/d.2.0.0-beta.1.*", "/d.2.0.0-beta.1.*")] public void Util_SplitGlobbingPattern(string pattern, string expected) { using (var workingDir = new TestFolder()) { // Arrange var input = workingDir.Root + Path.DirectorySeparatorChar + pattern; // Act var parts = Util.SplitGlobbingPattern(input); // Assert Assert.True(expected == parts.Item2, parts.Item1.ToString() + "|" + parts.Item2); } } [Fact] public void Util_GetPackagesWithFilter_HighestVersion() { using (var workingDir = new TestFolder()) { // Arrange CreatePackages(workingDir.Root); var log = new TestLogger(); // Act var files = Util.GetPackagesWithFilter( idFilter: null, versionFilter: null, excludeSymbols: false, highestVersionFilter: true, inputs: new[] { workingDir.Root }); // Use only the names var names = new List<string>(files.Select(path => Path.GetFileName(path))); // Assert Assert.Equal(5, files.Count); Assert.Equal("a.1.0.nupkg", names[0]); Assert.Equal("a.1.0.symbols.nupkg", names[1]); Assert.Equal("b.2.0.0.0.nupkg", names[2]); Assert.Equal("b.2.0.0.0.symbols.nupkg", names[3]); Assert.Equal("c.2.0.0-beta.2.nupkg", names[4]); } } [Fact] public void Util_GetPackagesWithFilter_ExcludeSymbols() { using (var workingDir = new TestFolder()) { // Arrange CreatePackages(workingDir.Root); var log = new TestLogger(); // Act var files = Util.GetPackagesWithFilter( idFilter: null, versionFilter: null, excludeSymbols: true, highestVersionFilter: false, inputs: new[] { workingDir.Root }); // Use only the names var names = new List<string>(files.Select(path => Path.GetFileName(path))); // Assert Assert.Equal(4, files.Count); Assert.Equal("a.1.0.nupkg", names[0]); Assert.Equal("b.2.0.0.0.nupkg", names[1]); Assert.Equal("c.2.0.0-beta.1.nupkg", names[2]); Assert.Equal("c.2.0.0-beta.2.nupkg", names[3]); } } [Fact] public void Util_GetPackagesWithFilter_ExcludeSymbols_AndId() { using (var workingDir = new TestFolder()) { // Arrange CreatePackages(workingDir.Root); var log = new TestLogger(); // Act var files = Util.GetPackagesWithFilter( idFilter: "c", versionFilter: null, excludeSymbols: true, highestVersionFilter: false, inputs: new[] { workingDir.Root }); // Use only the names var names = new List<string>(files.Select(path => Path.GetFileName(path))); // Assert Assert.Equal(2, files.Count); Assert.Equal("c.2.0.0-beta.1.nupkg", names[0]); Assert.Equal("c.2.0.0-beta.2.nupkg", names[1]); } } [Fact] public void Util_GetPackagesWithFilter_IdFilter() { using (var workingDir = new TestFolder()) { // Arrange CreatePackages(workingDir.Root); var log = new TestLogger(); // Act var files = Util.GetPackagesWithFilter( idFilter: "b", versionFilter: null, excludeSymbols: false, highestVersionFilter: false, inputs: new[] { workingDir.Root }); // Use only the names var names = new List<string>(files.Select(path => Path.GetFileName(path))); // Assert Assert.Equal(2, files.Count); Assert.Equal("b.2.0.0.0.nupkg", names[0]); Assert.Equal("b.2.0.0.0.symbols.nupkg", names[1]); } } [Fact] public void Util_GetPackagesWithFilter_VersionFilter() { using (var workingDir = new TestFolder()) { // Arrange CreatePackages(workingDir.Root); var log = new TestLogger(); // Act var files = Util.GetPackagesWithFilter( idFilter: null, versionFilter: "2.0.*", excludeSymbols: false, highestVersionFilter: false, inputs: new[] { workingDir.Root }); // Use only the names var names = new List<string>(files.Select(path => Path.GetFileName(path))); // Assert Assert.Equal(4, files.Count); Assert.Equal("b.2.0.0.0.nupkg", names[0]); Assert.Equal("b.2.0.0.0.symbols.nupkg", names[1]); Assert.Equal("c.2.0.0-beta.1.nupkg", names[2]); Assert.Equal("c.2.0.0-beta.2.nupkg", names[3]); } } private static void CreatePackages(string workingDir) { var testPackageA = new TestNupkg() { Nuspec = new TestNuspec() { Id = "a", Version = "1.0" } }; var testPackageB = new TestNupkg() { Nuspec = new TestNuspec() { Id = "b", Version = "2.0.0.0" } }; var testPackageC1 = new TestNupkg() { Nuspec = new TestNuspec() { Id = "c", Version = "2.0.0-beta.1" } }; var testPackageC2 = new TestNupkg() { Nuspec = new TestNuspec() { Id = "c", Version = "2.0.0-beta.2" } }; var zipFileA = testPackageA.Save(workingDir); var zipFileB = testPackageB.Save(workingDir); var zipFileC1 = testPackageC1.Save(workingDir); var zipFileC2 = testPackageC2.Save(workingDir); zipFileA.CopyTo(zipFileA.FullName.Replace(".nupkg", ".symbols.nupkg")); zipFileB.CopyTo(zipFileB.FullName.Replace(".nupkg", ".symbols.nupkg")); } } }